@indiegems/gem-web-sdk 13.2.2 → 13.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/dist/function.d.ts +2 -2
- package/dist/game.d.ts +4 -2
- package/dist/gem-web-sdk.bridge.js +2 -1
- package/dist/gem-web-sdk.esm.js +3 -2
- package/dist/gem-web-sdk.function.js +3 -2
- package/dist/gem-web-sdk.game.js +3 -2
- package/dist/gem-web-sdk.min.js +3 -2
- package/dist/gem-web-sdk.sdk.js +3 -2
- package/dist/gem-web-sdk.server.js +2 -2
- package/dist/index.d.ts +6 -2
- package/dist/sdk.d.ts +4 -2
- package/dist/server.d.ts +2 -2
- package/docs/api/api-reference-function.md +1 -1
- package/docs/api/api-reference-game.md +36 -3
- package/docs/api/api-reference-server.md +1 -1
- package/docs/api/reference.json +19 -3
- package/docs/arcade-economy.md +18 -0
- package/docs/changelog.md +19 -0
- package/docs/getting-started.md +1 -1
- package/docs/manifest.json +10 -10
- package/docs/player-text-fields.json +219 -0
- package/docs/server-bundles.md +2 -2
- package/docs/what-a-game-must-do.md +130 -9
- package/package.json +2 -1
- package/schema/bridge.v1.json +25 -4
package/dist/gem-web-sdk.game.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
var $c=Object.defineProperty;var Fc=(n,e)=>{for(var t in e)$c(n,t,{get:e[t],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:13.2.2]";function Xo(){let n=globalThis.__gemWebSdkVersion;if(typeof n!="string")return "";let e=n.lastIndexOf(":"),t=n.lastIndexOf("]");return e<0||t<=e+1?"":n.slice(e+1,t)}var qc={initialDelayMs:2e3,maxDelayMs:6e4};function Nc(n,e){return e!==void 0?!e:n==="chain_exhausted"}var dt=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;retry=null;failures=0;notBefore=0;disposed=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new ie(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.pastChainCeiling())throw new ie("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new ie(this.failure??"unavailable","the embedder asked for no new token yet; one is asked for when that wait is over");return this.refresh(this.nextReason())}pastChainCeiling(){return this.grant===null||this.seconds()<this.grant.chainEndsAt?false:(this.enter("lost","chain_exhausted"),true)}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}dispose(){this.disposed=true,this.cancelRetry();}scheduleRetry(e){if(this.cancelRetry(),this.failures+=1,this.notBefore=e===void 0?0:this.options.clock.now()+e,this.disposed)return;let{initialDelayMs:t,maxDelayMs:r}=qc,i=Math.min(r,t*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 t=this.generation;this.enter("pending");let r=this.options.request(e).then(i=>{if(t!==this.generation)throw new ie("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=jc(i),{retryable:s,retryAfterMs:a}=i??{};throw t===this.generation&&(Nc(o,typeof s=="boolean"?s:void 0)?this.enter("lost",o):(this.scheduleRetry(typeof a=="number"&&Number.isFinite(a)&&a>0?a:void 0),this.enter("degraded",o))),i instanceof ie?i:new ie(o,String(i))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,t){(e==="ready"||e==="lost")&&this.cancelRetry(),e==="ready"&&(this.failures=0,this.notBefore=0),this.failure=t??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,t));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},ie=class n extends Error{constructor(t,r){super(`auth ${t}: ${r}`);this.reason=t;this.name="AuthError";}reason;static isAuthError(t){if(t instanceof n)return true;let r=t;return r?.name==="AuthError"&&typeof r.reason=="string"}};function jc(n){if(n instanceof ie)return n.reason;let e=n?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var se=class n extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof n)return true;let t=e;return t?.name==="TransportRefusal"&&t.retryable===false}},Jr=["if-match","if-none-match"],Qo=4096;function Uc(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n)){let i=t.toLowerCase();if(!Jr.includes(i)||r===void 0)continue;let o=typeof r=="string"?Bc(r):r;if(typeof o!="string"||o.length>Qo||!Wc(o))throw new se(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${Qo} 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 Bc(n){let e=i=>i===32||i===9||i===10||i===13,t=0,r=n.length;for(;t<r&&e(n.charCodeAt(t));)t++;for(;r>t&&e(n.charCodeAt(r-1));)r--;return n.slice(t,r)}function Wc(n){for(let e=0;e<n.length;e++){let t=n.charCodeAt(e);if(t!==9&&(t<32||t===127||t>255))return false}return true}function Vc(n){let{bytes:e}=n;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(n.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 Zo(n,e){let t=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=Uc(i.headers),s=Vc(i),a=Object.freeze({...i,headers:o,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await n(a,l);if(d.status!==401||!t)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),u=await n(a,m);if(u.status===401)throw e.tokenSource.close("unavailable"),new ie("unavailable","the server refused a freshly minted token");return u}}}function zr(n){let e=typeof n=="string"?new TextEncoder().encode(n):n;return btoa(Hc(e))}function En(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function Yr(n){return new TextDecoder().decode(En(n))}function Hc(n){let t="";for(let r=0;r<n.length;r+=32768)t+=String.fromCharCode(...n.subarray(r,r+32768));return t}var O=class extends Error{constructor(t,r,i,o,s){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},ta=new WeakMap;function na(n){return ta.get(n)??{}}var Kc=new Set([408,429,500,502,503,504]),Jc=6e4;function zc(n){if(n===void 0)return 2;if(!Number.isInteger(n)||n<0||n>10)throw new se(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(n)}. This is a configuration fault, not a server failure.`);return n}var We=class{constructor(e){this.options=e;}options;async get(e,t){return this.send({method:"GET",path:e,signal:t},true)}async getWithEtag(e,t={}){let r=await this.sendRaw({method:"GET",path:e,...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{headers:{"if-none-match":t.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,t,r,i={}){return this.send({method:"PUT",path:e,body:t,signal:r,...Mt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async post(e,t,r,i={}){return this.send({method:"POST",path:e,body:t,signal:r,...Mt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async postBytes(e,t,r,i={}){let o=await this.sendRaw({method:"POST",path:e,bytes:t,responseType:"bytes",signal:r,...Mt(i)},i.replaySafe===true,i.retryRateLimited!==false);return {bytes:Yc(o.body),...o.invocationId===void 0?{}:{invocationId:o.invocationId}}}async patch(e,t,r,i={}){return this.send({method:"PATCH",path:e,body:t,signal:r,...Mt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async delete(e,t,r={}){return this.send({method:"DELETE",path:e,signal:t,...Mt(r)},r.replaySafe===true,r.retryRateLimited!==false)}async send(e,t,r=true){return (await this.sendRaw(e,t,r)).body}async sendRaw(e,t,r=true){let i=t?zc(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw ea(e.signal);for(let s=0;s<i;s++){if(s>0&&await this.backoff(s,o,e.signal),e.signal?.aborted)throw ea(e.signal);let a;try{a=await this.options.transport.request(e);}catch(d){if(ie.isAuthError(d)||se.isRefusal(d)||e.signal?.aborted||Xc(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=Qc(a);if(!Kc.has(a.status)||a.status===429&&!r)throw l;o=l;}throw o??new O("unavailable",0,"no attempt was made")}backoff(e,t,r){if(r?.aborted)return Promise.resolve();let i=t?.retryAfterSeconds,o=i!==void 0?i*1e3:2**(e-1)*250,s=2**(e-1)*250,a=Math.min(Math.max(o,s),Jc);return new Promise(l=>{let d=this.options.clock,m=false,u=false,p,g=()=>{m||(m=true,u&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,a),u=true,m&&d.clearTimeout(p);})}};function Yc(n){if(n instanceof Uint8Array)return n;if(n==null)return new Uint8Array(0);let e=typeof n=="string"?n:JSON.stringify(n);return new TextEncoder().encode(e)}function Mt(n){return {...n.keepalive===void 0?{}:{keepalive:n.keepalive},...n.ifMatch===void 0?{}:{headers:{"if-match":n.ifMatch}}}}function ea(n){return n.reason!==void 0?n.reason:new DOMException("The operation was aborted.","AbortError")}function Xc(n){let e=n?.name;return e==="AbortError"||e==="TimeoutError"}function Qc(n){let e=eu(n),t=nu(n.body),r={...t===void 0?{}:{details:t},...n.invocationId===void 0?{}:{invocationId:n.invocationId}};return Object.keys(r).length>0&&ta.set(e,r),e}var Zc=new Map([["insufficient_funds","insufficient_funds"]]);function eu(n){let{status:e,body:t}=n,r=tu(t),i=n.retryAfterSeconds??iu(t),o=ru(t),s=o===void 0?void 0:Zc.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 tu(n){if(typeof n=="string")return n;let e=n?.message;if(typeof e=="string")return e;let t=n?.error;if(typeof t=="string")return t;let r=t?.message;return typeof r=="string"?r:"no detail"}function nu(n){let t=n?.error?.details;return t===null?void 0:t}function ru(n){let t=n?.error?.code;return typeof t=="string"&&t.length>0?t:void 0}function iu(n){let e=n?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function _(n){let e=String(n);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function ra(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function ia(n,e,t,r,i,o){let s=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/add`;return n.client.post(s,i,o?.signal)}async function oa(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function aa(n,e,t){let r=`/v1/games/${_(n.gameId())}/matchmaking/tickets/${_(e)}`;return n.client.delete(r,t?.signal)}async function sa(n,e,t,r,i,o){let s=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/claim`;return n.client.post(s,i,o?.signal)}async function la(n,e,t){return n.client.post("/v1/characters",e,t?.signal)}async function da(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/orders/batch`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ca(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/orders`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ua(n,e,t){let r=`/v1/games/${_(n.gameId())}/matchmaking/tickets`;return n.client.post(r,e,t?.signal)}async function ma(n,e,t,r,i){let o=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.delete(o,i?.signal)}async function pa(n,e,t,r,i){let o=`/v1/saves/${_(e)}/${_(t)}/${_(r)}`;return n.client.delete(o,i?.signal)}async function ga(n,e,t,r){let i=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.delete(i,r?.signal)}async function ya(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/recipes/execute`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function fa(n,e,t,r,i,o){let s=`/v1/saves/${_(e)}/${_(t)}/${_(r)}/finalize`;return n.client.post(s,i,o?.signal)}async function ha(n,e,t){let r=`/v1/games/${_(n.gameId())}/avatars-3d/${_(e)}/owned`;return n.client.get(r,t?.signal)}async function ba(n,e,t){let r=`/v1/games/${_(n.gameId())}/config/channels/${_(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function va(n,e,t){let r=`/v1/characters/${_(e)}`;return n.client.get(r,t?.signal)}async function _a(n,e,t){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function wa(n,e,t,r,i){let o=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function ka(n,e,t,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)}/${_(t)}`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Ra(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/items/${_(r)}`;return n.client.get(o,i?.signal)}async function Sa(n,e,t,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)}/${_(t)}/${_(r)}`+(s?`?${s}`:"");return n.client.get(a,i?.signal)}async function xa(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/orders/${_(r)}`;return n.client.get(o,i?.signal)}async function Aa(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}`;return n.client.get(o,i?.signal)}async function Pa(n,e,t,r,i,o){let s=`/v1/inventory/${_(e)}/${_(t)}/catalogs/${_(r)}/recipes/${_(i)}/availability`;return n.client.get(s,o?.signal)}async function Ta(n,e,t,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(t)}/recipe-usage`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Xr(n,e,t,r,i){let o=`/v1/saves/${_(e)}/${_(t)}/${_(r)}`;return n.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Ea(n,e,t){let r=new URLSearchParams;t?.bucket_1!==void 0&&r.set("bucket_1",String(t?.bucket_1)),t?.bucket_2!==void 0&&r.set("bucket_2",String(t?.bucket_2)),t?.periods_back!==void 0&&r.set("periods_back",String(t?.periods_back)),t?.period!==void 0&&r.set("period",String(t?.period)),t?.player_id!==void 0&&r.set("player_id",String(t?.player_id));let i=r.toString(),o=`/v1/leaderboards/${_(e)}/friends`+(i?`?${i}`:"");return n.client.get(o,t?.signal)}async function Ia(n,e,t){let r=`/v1/showcase/friends/${_(e)}`;return n.client.get(r,t?.signal)}async function Ca(n,e){let t=`/v1/games/${_(n.gameId())}/avatars-3d`;return n.client.get(t,e?.signal)}async function Ma(n,e,t){let r=`/v1/inbox/friend-challenges/${_(e)}`;return n.client.get(r,t?.signal)}async function Oa(n,e,t){let r=new URLSearchParams;t?.bucket_1!==void 0&&r.set("bucket_1",String(t?.bucket_1)),t?.bucket_2!==void 0&&r.set("bucket_2",String(t?.bucket_2)),t?.periods_back!==void 0&&r.set("periods_back",String(t?.periods_back)),t?.period!==void 0&&r.set("period",String(t?.period)),t?.player_id!==void 0&&r.set("player_id",String(t?.player_id));let i=r.toString(),o=`/v1/leaderboards/${_(e)}`+(i?`?${i}`:"");return n.client.get(o,t?.signal)}async function La(n,e){let t=`/v1/games/${_(n.gameId())}/players/me/earn-allowance`;return n.client.get(t,e?.signal)}async function In(n,e){return n.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function Ga(n,e,t){let r=`/v1/profiles/players/${_(e)}`;return n.client.get(r,t?.signal)}async function Da(n,e){let t=new URLSearchParams;e?.config_version!==void 0&&t.set("config_version",String(e?.config_version));let r=t.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function $a(n,e,t){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return n.client.get(r,t?.signal)}async function Fa(n,e,t,r){let i=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.get(i,r?.signal)}async function qa(n,e){return n.client.get("/v1/characters/slots",e?.signal)}async function Na(n,e,t){let r=`/v1/inventory/transfers/${_(e)}`;return n.client.get(r,t?.signal)}async function ja(n,e,t){let r=`/v1/games/${_(n.gameId())}/matchmaking/tickets/${_(e)}/heartbeat`;return n.client.post(r,void 0,t?.signal)}async function Ua(n,e,t){let r=`/v1/games/${_(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{...t?.keepalive===void 0?{}:{keepalive:t.keepalive},replaySafe:true,retryRateLimited:false})}async function Ba(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Wa(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/platform-funded-game-inventory-purchases`;return n.client.post(o,r,i?.signal)}async function Va(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function Ha(n,e){let t=new URLSearchParams;e?.periods_back!==void 0&&t.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&t.set("player_id",String(e?.player_id));let r=t.toString(),i="/v1/challenges"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Ka(n,e){return n.client.get("/v1/characters",e?.signal)}async function Ja(n,e,t,r){let i=`/v1/settings/${_(e)}/${_(t)}`;return n.client.get(i,r?.signal)}async function za(n,e,t,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)}/${_(t)}/orders`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Ya(n,e,t,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)}/${_(t)}`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Xa(n,e){let t=new URLSearchParams;e?.cursor!==void 0&&t.set("cursor",String(e?.cursor)),e?.limit!==void 0&&t.set("limit",String(e?.limit));let r=t.toString(),i="/v1/inbox/friend-challenges"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Qa(n,e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e?.limit)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor));let r=t.toString(),i="/v1/friends"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Za(n,e){let t=new URLSearchParams;e.entity_type!==void 0&&t.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&t.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&t.set("direction",String(e?.direction)),e?.status!==void 0&&t.set("status",String(e?.status)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor)),e?.limit!==void 0&&t.set("limit",String(e?.limit));let r=t.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function es(n,e,t){let r=`/v1/inbox/friend-challenges/${_(e)}/answered`;return n.client.post(r,void 0,t?.signal)}async function ts(n,e,t,r){let i=`/v1/games/${_(n.gameId())}/matches/${_(e)}/end`;return n.client.post(i,t,r?.signal)}async function ns(n,e,t,r,i,o){let s=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/max`;return n.client.post(s,i,o?.signal)}async function rs(n,e,t,r,i,o){let s=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function is(n,e,t,r,i){let o=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.put(o,r,i?.signal)}async function os(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/rewarded-placements/${_(r)}/availability`;return n.client.get(o,i?.signal)}async function as(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function ss(n,e,t,r){let i=`/v1/characters/${_(e)}`;return n.client.patch(i,t,r?.signal)}async function ls(n,e,t,r,i,o){let s=`/v1/saves/${_(e)}/${_(t)}/${_(r)}/upload-url`;return n.client.post(s,i,o?.signal,{replaySafe:true})}async function ds(n,e,t,r,i,o){let s=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/reset`;return n.client.post(s,i,o?.signal)}async function cs(n,e,t){let r=`/v1/characters/${_(e)}`;return n.client.delete(r,t?.signal)}var B="gem-web-bridge",Mn={min:1,max:1},ct=65536,us=8,Cn=5e3,ms=1024;var Ot=Object.create(null),On="__malformed";var Zr=Object.create(null),ou=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"]]);function ps(n){let e=Zr[n];if(e!==void 0)return e;for(let[t,r]of ou)if(n.startsWith(t))return r}function ei(n){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(n);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function au(n){let e;try{e=new URL(n);}catch{return false}return e.username!==""||e.password!==""?false:e.protocol==="https:"?true:e.protocol==="http:"&&(e.hostname==="localhost"||e.hostname==="127.0.0.1")}function su(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function lu(n){return /^[a-z_]+$/.test(n)}function Qr(n,e,t){if(e>us)return `nesting deeper than ${us}`;if(++t.nodes>Cn)return `more than ${Cn} values`;if(t.bytes>ct)return `over the ${ct} byte limit`;if(n==null)return t.bytes+=4,null;let r=typeof n;if(r==="boolean")return t.bytes+=5,null;if(r==="number")return t.bytes+=8,null;if(r==="string")return t.bytes+=n.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=n;if(t.seen.has(i))return "a repeated or cyclic object reference";if(t.seen.add(i),Array.isArray(n)){if(n.length>ms)return `an array of ${n.length} entries, over the ${ms} limit`;t.bytes+=2;for(let a of n){let l=Qr(a,e+1,t);if(l)return l}return null}let o=Object.getPrototypeOf(n);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";t.bytes+=2;let s=n;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++t.nodes>Cn)return `more than ${Cn} values`;if(t.bytes+=a.length*3+4,t.bytes>ct)return `over the ${ct} byte limit`;let l=Qr(s[a],e+1,t);if(l)return l}return null}function du(n){let e={nodes:0,bytes:0,seen:new Set},t=Qr(n,0,e);return t?`message contains ${t}`:e.bytes>ct?`message is over the ${ct} byte limit`:null}var cu={origin:[ei,"not a well-formed origin"],url:[au,"not a safe absolute http(s) URL"],bcp47:[su,"not a well-formed BCP 47 tag"],code:[lu,"not a code of lower-case letters and underscores"]};function gs(n,e,t){for(let r of e){let i=t===""?r.n:`${t}.${r.n}`,o=n[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let s=ys(o,r,i);if(s)return s}return null}function ys(n,e,t){switch(e.k){case "s":{if(typeof n!="string")return `${t}: expected string`;if(n.length>e.max)return `${t}: exceeds ${e.max} characters`;if(e.f){let[r,i]=cu[e.f];if(!r(n))return `${t}: ${i}`}return null}case "i":return typeof n!="number"||!Number.isInteger(n)?`${t}: expected integer`:n<e.lo||n>e.hi?`${t}: out of range ${e.lo}..${e.hi}`:null;case "b":return typeof n=="boolean"?null:`${t}: expected boolean`;case "e":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "o":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:gs(n,e.fs,t);case "j":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "a":{if(!Array.isArray(n))return `${t}: expected array`;if(n.length>e.max)return `${t}: exceeds ${e.max} items`;let r=e.it,i=`${t}[]`;for(let o of n){if(o==null){if(r.o)continue;return `${i}: required`}let s=ys(o,r,i);if(s)return s}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}var fs=Object.create(null);function A(n,e,t,r){return Ot[n]=t,r&&(Zr[n]=r),fs[n]=i=>{let o=du(i);if(o)return o;if(typeof i!="object"||i===null||Array.isArray(i))return "message: expected object";let s=i;return s.gem!==B?"gem: wrong protocol marker":s.type!==n?`type: expected ${n}`:gs(s,e,"")}}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",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}],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:"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}]}}],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",[{n:"requestId",k:"s",max:64},{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",[{n:"requestId",k:"s",max:64}],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",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}],12);A("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}],6,"localHost");A("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}],30,"localHost");A("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{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.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}],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",[{n:"requestId",k:"s",max:64},{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}],12,"purchases");A("gem.requestAvatar3dPurchase",[{n:"requestId",k:"s",max:64},{n:"itemId",k:"s",max:64},{n:"currencySlug",k:"s",max:32}],12,"avatar3dPurchases");A("gem.purchaseResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}],30,"purchases");A("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}],30,"deviceSettings");A("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}],30,"deviceSettings");A("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}],6,"ads");A("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}],12,"ads");A("gem.signalMoment",[{n:"requestId",k:"s",max:64},{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",[{n:"requestId",k:"s",max:64},{n:"shown",k:"b"}],12,"moments");A("gem.requestSignIn",[{n:"requestId",k:"s",max:64}],6,"signIn");A("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}],12,"signIn");A("gem.requestFriendChallenge",[{n:"requestId",k:"s",max:64},{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}],12,"friendChallenges");A("gem.friendChallengeResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}],30,"friendChallenges");var Ln=Object.freeze(fs);Ot.__malformed=60;Object.freeze(Ot);Object.freeze(Zr);var fe={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},Lt=class{constructor(e=fe){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=Ot[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,s=Math.max(0,r-i),a=Math.min(t,o+s*t/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function ti(n,e){return n.toLowerCase()===e.toLowerCase()}function Gn(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function hs(n,e){if(typeof e!="string"||e==="")return false;let t,r;try{t=new URL(n),r=new URL(e);}catch{return false}return t.protocol!=="http:"&&t.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||t.username!==""||t.password!==""||t.pathname!=="/"||t.search!==""||t.hash!==""||t.port===""?false:Gn(t.hostname)&&Gn(r.hostname)}function bs(n,e){if(e.min>e.max)return null;let t=Math.min(n.max,e.max),r=Math.max(n.min,e.min);return t>=r?t:null}var Dn=class{constructor(e,t){this.inventory=e;this.resolveCurrencyId=t;}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,t={}){let i=(await this.inventory.snapshot({buckets:t.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 ri(n){let e=Array.isArray(n.achievements)?n.achievements:[],t=[];for(let r of e){let i=r??{};typeof i.id!="string"||i.id===""||typeof i.threshold!="number"||!Number.isFinite(i.threshold)||t.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 {...t.length>0?{achievements:t}:{},...n.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var vs="inventory",ut=n=>typeof n=="number"?n:0,Gt=n=>typeof n=="string"?n:"";function ni(n,e){let t=n??{},r=typeof t.next_cursor=="string"?t.next_cursor:void 0;return {data:Array.isArray(t.data)?t.data.map(e):[],...r===void 0?{}:{nextCursor:r}}}function _s(n){let e=n??{};return {itemDefinitionId:Gt(e.item_definition_id),instanceId:Gt(e.instance_id),quantity:ut(e.quantity),acquiredAt:ut(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function uu(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {currencies:ni(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(s=>{let a=s??{};return {bucket:Gt(a.bucket),balance:ut(a.balance)}}):void 0;return {currencyId:Gt(i.currency_id),total:ut(i.total),...o===void 0?{}:{buckets:o}}}),items:ni(e.items,_s),progressions:ni(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:Gt(i.progression_definition_id),currentValue:ut(i.current_value),completionCount:ut(i.completion_count),isCompleted:i.is_completed===true,...ri(i)}}),...t===void 0?{}:{etag:t}}}var $n=class{constructor(e,t,r){this.api=e;this.entity=t;this.cache=r;}api;entity;cache;snapshot(e={}){let t=e.buckets?`${vs}#buckets`:vs;return this.cache.read(t,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,t){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 Ra(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Array.isArray(i)?i.map(_s):[]}page(e){return this.fetch(e)}refresh(){this.invalidate();}onChanged(e){return this.cache.onInvalidate(e)}invalidate(){this.cache.invalidate();}async fetch(e){let t=await ka(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 uu(t)}};var mu={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},pu=new Set(Object.keys(mu));function ws(n){return typeof n=="string"&&pu.has(n)?n:"error"}var $e=class extends RangeError{constructor(t,r){super(r);this.code=t;this.name="PurchaseRefusal";}code;retryable=false};var te=n=>typeof n=="string"?n:"",gu=n=>typeof n=="string"?n:te(n&&typeof n=="object"?n.type:void 0),Ae=n=>typeof n=="number"?n:0;function yu(n){let e=n??{};return {prerequisiteType:te(e.prerequisite_type),referenceId:te(e.reference_id),required:Ae(e.required),current:Ae(e.current)}}function Dt(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {orderId:te(e.order_id),status:te(e.status),...t===void 0?{}:{etag:t}}}function Fn(){return crypto.randomUUID()}var fu="recipe-usage",ks=100;function qn(n){let e=n??{};switch(e.type){case "currency":return {kind:"currency",currencyId:te(e.currency_id),bucket:te(e.bucket),delta:Ae(e.delta),balanceAfter:Ae(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:te(e.item_definition_id),instanceId:te(e.instance_id),delta:Ae(e.delta),quantityAfter:Ae(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:te(e.progression_definition_id),delta:Ae(e.delta),valueAfter:Ae(e.value_after),completed:e.completed===true};default:return {kind:"other",type:te(e.type)}}}function hu(n){let e=n??{},t=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:te(e.entry_id),...t===void 0?{}:{rarityTier:t},rollNumber:Ae(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(qn):[]}}function bu(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(hu):void 0;return {orderId:te(e.order_id),status:te(e.status),...t===void 0?{}:{etag:t},granted:Array.isArray(e.granted)?e.granted.map(qn):[],consumed:Array.isArray(e.consumed)?e.consumed.map(qn):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(qn):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function vu(n){let e=n??{},t=e.price??{};return {payment:"platform_currency",orderId:te(e.target_order_id)||te(e.source_order_id),status:te(e.status),purchaseId:te(e.purchase_id),sourceOrderId:te(e.source_order_id),price:{currencyId:te(t.platform_currency_id),amount:Ae(t.price)}}}function _u(n){let e=n??{},t=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:te(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...t===void 0?{}:{lastUsedAt:t},...r===void 0?{}:{cooldownExpiresAt:r}}}function Rs(n){switch(n.type){case "currency_grant":case "currency_consume":return {type:n.type,currency_id:n.currencyId,amount:n.amount};default:return {type:n.type,item_definition_id:n.itemDefinitionId,quantity:n.quantity}}}var Nn=class{constructor(e,t,r){this.api=e;this.entity=t;this.cache=r;}api;entity;cache;async create(e,t={}){let r=await this.write(()=>ca(this.api,this.entity.type,this.entity.id,{operations:e.map(Rs),source:t.source??"play",nonce:Fn()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return Dt(r)}async createMany(e,t={}){return this.write(()=>da(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Rs),nonce:Fn()})),source:t.source??"play"},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}))}async recipeAvailability(e,t,r){let o=await Pa(this.api,this.entity.type,this.entity.id,e,t,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(yu):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>gu(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(fu,[],async()=>{let t=await Ta(this.api,this.entity.type,this.entity.id,{limit:ks})??{},r=Array.isArray(t.usages)?t.usages:[];return {usages:r.map(_u),truncated:r.length>=ks}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,t={}){if(e.payment.kind==="configured"){let u=e,p=await this.write(()=>ya(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:Fn()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return {payment:"configured",...bu(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([Da(this.api,t.signal===void 0?{}:{signal:t.signal}),In(this.api,t.signal===void 0?{}:{signal:t.signal})]),o=e.payment.currencySlug.toLowerCase(),s=i.currencies.find(u=>u.currency_id.toLowerCase()===o||u.slug.toLowerCase()===o);if(s===void 0){let u=i.currencies.map(p=>p.slug);throw new $e("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${u.length===0?"none":u.join(", ")}`)}let a=e.kind==="item"?r.items.find(u=>u.item_id===e.targetId):r.recipes.find(u=>u.recipe_id===e.targetId&&u.catalog_id===e.catalogId);if(a===void 0)throw new $e("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=a.platform_prices.find(u=>u.platform_currency_id===s.currency_id);if(l===void 0){let u=g=>i.currencies.find(y=>y.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${u(g.platform_currency_id)} ${g.price}`);throw new $e("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 $e("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>Wa(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:Fn(),confirmation:"none"},t.signal===void 0?{}:{signal:t.signal}));return vu(m)}async executeRecipe(e,t,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:t,payment:{kind:"configured"}},r)}async addProgression(e,t,r){let i=await this.write(()=>ia(this.api,this.entity.type,this.entity.id,e,{amount:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Dt(i)}async maxProgression(e,t,r){let i=await this.write(()=>ns(this.api,this.entity.type,this.entity.id,e,{value:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Dt(i)}async claimProgression(e,t){let r=await this.write(()=>sa(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return Dt(r)}async resetProgression(e,t){let r=await this.write(()=>ds(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return Dt(r)}async write(e){return this.cache.invalidate(),e()}};var ii=n=>typeof n=="string"?n:"",wu=n=>typeof n=="number"?n:0;function Ss(n){let e=n??{};return {orderId:ii(e.order_id),status:ii(e.status),source:ii(e.source),createdAt:wu(e.created_at)}}var jn=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e={}){let r=await za(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(Ss):[],...i===void 0?{}:{nextCursor:i}}}async get(e,t){let r=await xa(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Ss(r)}};var xs=n=>typeof n=="number"?n:0,ku=n=>typeof n=="string"?n:"";function Ru(n){let e=n??{};return {progressionDefinitionId:ku(e.progression_definition_id),currentValue:xs(e.current_value),completionCount:xs(e.completion_count),isCompleted:e.is_completed===true,...ri(e)}}var Un=class{constructor(e,t,r){this.api=e;this.entity=t;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,t){let i=(await this.inventory.snapshot()).progressions.data.find(o=>o.progressionDefinitionId===e);if(i&&i.achievementsUnavailable!==true)return i;try{let o=await Aa(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Ru(o)}catch{return i??null}}};var Bn=class{constructor(e,t){this.clock=e;this.identity=t;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,t,r,i){this.rebind();let o=t.length===0,s=o?e:e+"\0"+t.join("\0"),a=this.slots.get(s);if(a){let u=a.filledAt;if(u!==void 0&&(i===void 0||this.clock.now()-u<=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(u=>(o&&this.generation===d&&(l.value=u,l.filledAt=this.clock.now()),u)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(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 oi(n){let e=i=>new RegExp(`<${i}>([^<]{0,300})</${i}>`).exec(n)?.[1]?.trim()||void 0,t=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(t.length>0)return t.join(" \u2014 ");let r=n.trim();return r?r.slice(0,300):""}async function ai(n){try{let e=oi(await n.text());return e?`Storage said: ${e}`:""}catch{return ""}}var le=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemSaveError";}reason},Su=3e4,As="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",xu=/^[A-Za-z0-9_]{1,64}$/;function Pe(n){let e=n.length===0?"a save key cannot be empty":n.length>64?`it is ${n.length} characters; a save key is at most 64`:n.startsWith("_")||n.startsWith("$")?`it begins with ${JSON.stringify(n[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(!xu.test(n)||n.startsWith("_"))throw new TypeError(`${JSON.stringify(n)} is not a usable save key: ${e}.`);return n}function Ps(n,e){let t=new AbortController,r=AbortSignal.timeout(e),i=()=>t.abort(r.reason),o=()=>t.abort(n?.reason);return n?.aborted?t.abort(n.reason):(r.addEventListener("abort",i,{once:true}),n?.addEventListener("abort",o,{once:true})),{signal:t.signal,release:()=>{r.removeEventListener("abort",i),n?.removeEventListener("abort",o);}}}function si(n,e){return n.aborted&&e?.aborted!==true}var Au=new Set(["x-ms-blob-type"]),Pu=/^[ -~]+$/;function Tu(n,e){if(n==null)return {};if(typeof n!="object"||Array.isArray(n))throw new le("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(n)?"a list":typeof n}, which is not a set of headers.`);let t={};for(let[r,i]of Object.entries(n)){let o=r.toLowerCase();if(!Au.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"||!Pu.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 t)throw new le("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);t[o]=i;}return t}function li(n){let e=typeof n.metadata=="object"&&n.metadata!==null&&!Array.isArray(n.metadata)?n.metadata:void 0;return {key:n.key,sizeBytes:n.size_bytes,etag:n.etag,...e===void 0?{}:{metadata:e},createdAt:n.created_at,updatedAt:n.updated_at}}function di(n){return n?.reason==="not_found"}var Wn=class{constructor(e,t,r={}){this.api=e;this.entity=t;this.options=r;}api;entity;options;async put(e,t,r={}){let i;try{i=JSON.stringify(t);}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,t,r={}){let i=r.contentType??"application/octet-stream",o=this.budget(r.timeoutMs),s=Ps(r.signal,o);try{let a=await ls(this.api,this.entity.type,this.entity.id,Pe(e),{size_bytes:t.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=Tu(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:t,credentials:"omit",signal:s.signal});}catch(u){throw si(s.signal,r.signal)?this.timeout("upload",o):new le("upload_failed",`${As} for PUT. Underlying error: ${u}`)}if(!d.ok){let u=await ai(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. "+u:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+u)}return li(await fa(this.api,this.entity.type,this.entity.id,Pe(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,t={}){let r=await this.getBytes(e,t);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,t={}){let r=this.budget(t.timeoutMs),i=Ps(t.signal,r);try{let o;try{let l=await Xr(this.api,this.entity.type,this.entity.id,Pe(e),{signal:i.signal});if(!l.modified)return null;o=l.body;}catch(l){if(di(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 si(i.signal,t.signal)?this.timeout("download",r):new le("download_failed",`${As} for GET. Underlying error: ${l}`)}if(!a.ok){let l=await ai(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,t.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,t={}){try{let r=await Xr(this.api,this.entity.type,this.entity.id,Pe(e),{...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}});return r.modified?li(r.body):null}catch(r){if(di(r))return null;throw r}}async list(e={}){let t=await Ya(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=t.next_cursor;return {saves:(t.data??[]).map(li),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,t){try{await pa(this.api,this.entity.type,this.entity.id,Pe(e),{...t===void 0?{}:{signal:t}});}catch(r){if(!di(r))throw r}}budget(e){return e??this.options.timeoutMs??Su}timeout(e,t){return new le("save_timeout",`the save ${e} did not finish within ${t}ms`)}rethrow(e,t,r,i,o){return e instanceof le?e:si(r,t)?this.timeout(i,o):e}};function Eu(n){try{return Yr(n)}catch{return n}}function ci(n,e){let t=n??{},r=typeof t.etag=="string"?t.etag:e;return {key:typeof t.key=="string"?t.key:"",value:typeof t.value=="string"?Eu(t.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof t.updated_at=="number"?t.updated_at:0}}var Vn=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e){let r=(await Ja(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>ci(i)):[]}async get(e,t={}){try{let r=await wa(this.api,this.entity.type,this.entity.id,e,{...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}});return r.modified?ci(r.body,r.etag):null}catch(r){if(Ts(r))return null;throw r}}async put(e,t,r={}){let i=await rs(this.api,this.entity.type,this.entity.id,e,{value:zr(t)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return ci(i)}async delete(e,t){try{await ma(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});}catch(r){if(!Ts(r))throw r}}};function Ts(n){return n?.reason==="not_found"}function Hn(n,e,t={}){let r=new Bn(fe,t.identity);t.onInventoryChanged&&r.onInvalidate(t.onInventoryChanged);let i=new $n(n,e,r);return {settings:new Vn(n,e),inventory:i,saves:new Wn(n,e,t.saves??{}),currencies:new Dn(i,t.resolveCurrencyId),mutations:new Nn(n,e,r),orders:new jn(n,e),progressions:new Un(n,e,i)}}var ui={type:"players",id:"me"};var Ve=n=>typeof n=="string"?n:"",mt=n=>typeof n=="number"?n:0;function Kn(n,e){let t=e??{},r=Ve(t.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...n(r),id:r,playerId:Ve(t.player_id),gameId:Ve(t.game_id),channel:Ve(t.channel)||"release",name:Ve(t.name),slotIndex:mt(t.slot_index),isActive:t.is_active!==false,createdAt:Ve(t.created_at),updatedAt:Ve(t.updated_at)}}var Jn=class{constructor(e,t,r,i){this.api=e;this.saves=t;this.identity=r;this.resolveCurrencyId=i;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let t=this.scopes.get(e);return t||(t=Hn(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,t)),t};async list(e){let r=(await Ka(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>Kn(this.scope,i)):[]}async get(e,t){let r=await va(this.api,e,t===void 0?{}:{signal:t});return Kn(this.scope,r)}async create(e){let t=await la(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Kn(this.scope,t)}async update(e,t,r){let i=await ss(this.api,e,{name:t},r===void 0?{}:{signal:r});return Kn(this.scope,i)}async delete(e,t){await cs(this.api,e,t===void 0?{}:{signal:t});}async slots(e){let r=await qa(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:mt(r?.total_slots),availableSlots:mt(r?.available_slots),activeCharacterCount:mt(r?.active_character_count),defaultMaxSlots:mt(r?.default_max_slots),purchasedExtraSlots:mt(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var he=class{#e;constructor(e){this.#e=e,Object.freeze(this);}toString(){return "[gem: use gem.text.toPlain()]"}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function Ge(n){return new he(n)}var pt={toPlain(n){return he.unwrap(n)},compare(n,e,t){let r=n instanceof he?he.unwrap(n):n,i=e instanceof he?he.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(t);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(n,e){let t=n instanceof he?he.unwrap(n):n,r=e instanceof he?he.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};var gt=n=>typeof n=="string"?n:"";function zn(n){let e=n??{},t=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:gt(e.transfer_id),status:gt(e.status),sourceEntityId:gt(e.source_entity_id),targetEntityId:gt(e.target_entity_id),...t===void 0?{}:{message:Ge(t)},createdAt:gt(e.created_at),expiresAt:gt(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Iu(){return crypto.randomUUID()}var Yn=class{constructor(e,t,r){this.api=e;this.self=t;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let t=await Ba(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:Iu()},e.signal===void 0?{}:{signal:e.signal});return zn(t)}async list(e={}){let r=await Za(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(zn):[],...i===void 0?{}:{nextCursor:i}}}async get(e,t){let r=await Na(this.api,e,t===void 0?{}:{signal:t});return zn(r)}async accept(e,t){return this.resolve(()=>ra(this.api,e,t===void 0?{}:{signal:t}))}async reject(e,t){return this.resolve(()=>as(this.api,e,t===void 0?{}:{signal:t}))}async cancel(e,t){return this.resolve(()=>oa(this.api,e,t===void 0?{}:{signal:t}))}async resolve(e){return this.inventory.invalidate(),zn(await e())}};var Cu=n=>typeof n=="string"?n:"",Mu=n=>typeof n=="string"&&n?n:void 0,Ou=n=>typeof n=="number"?n:void 0;function Es(n){let e=new Map(n.map(r=>[r.id,r])),t=new Map(n.filter(r=>r.slug).map(r=>[r.slug,r]));return r=>e.get(r)??t.get(r)??null}function Lu(n){if(typeof n!="object"||n===null||Array.isArray(n))throw new ue("config_malformed",`the config document is ${n===null?"null":typeof n}, expected a JSON object`);let e=n,t=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=Ou(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 u=Cu(l.id);if(!u)throw new ue("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return u},o=t("items");o.forEach((l,d)=>i(l??{},"items",d));let s=t("currencies");s.forEach((l,d)=>i(l??{},"currencies",d));let a=n;return {...a,version:r,hash:typeof a.hash=="string"?a.hash:"",items:o,currencies:s,catalogs:t("catalogs"),loot_tables:t("loot_tables"),affix_pools:t("affix_pools"),progressions:t("progressions"),game_room_templates:t("game_room_templates"),kv:typeof a.kv=="object"&&a.kv!==null&&!Array.isArray(a.kv)?a.kv:{},item:Es(o),currency:Es(s)}}var ue=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemConfigError";}reason},Is=10*1024*1024,Cs=15e3,Ms=new Set(["dev","test","release"]);function Gu(n){if(!Ms.has(n))throw new ue("config_channel_unknown",`the play token names channel "${n}", which is not one of ${[...Ms].join(", ")}. gem-api would reject the assignment read.`);return n}var Xn=n=>typeof n=="number"?n:0,mi=n=>typeof n=="string"?n:"";function Du(n){let e=n??{},t=Array.isArray(e.entries)?e.entries.map(r=>{let i=r??{},o=typeof i.rarity_tier=="string"?i.rarity_tier:void 0;return {entryId:mi(i.entry_id),weight:Xn(i.weight),dropRate:Xn(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:mi(e.loot_table_id),name:mi(e.name),rollCount:Xn(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Xn(e.total_weight),entries:t}}var Qn=class{constructor(e,t,r={}){this.api=e;this.channel=t;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,t=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===t&&(this.inFlight=null);});return this.inFlight=t,t}refresh(){this.loaded=void 0,this.inFlight=null,this.generation+=1;}async dropRates(e,t){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 _a(this.api,e,t===void 0?{}:{signal:t});return Du(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??Cs),t;try{let l=await ba(this.api,Gu(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");t=l.body;}catch(l){if(l instanceof ue)throw l;if(l?.reason==="not_found")return null;throw l}let r=Mu(t.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??Cs}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=>oi(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>Is)throw new ue("config_too_large",`the config document is ${s.length} bytes, over the ${Is} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new ue("config_malformed",`config document is not JSON: ${String(l)}`)}return Lu(a)}};var Os=400,Te=n=>typeof n=="string"?n:"",$u=/(?:Z|[+-]\d{2}:?\d{2})$/i;function He(n){let e=Te(n);if(!$u.test(e))return 0;let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):0}var Fu=/^[0-9a-f]{1,64}$/,qu=/^[0-9a-f]{16}$/,Nu=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,ju=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function pi(n){let e=Te(n),t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return;let[r,i,o]=[Number(t[1]),Number(t[2]),Number(t[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 Uu=4096,Bu=new TextEncoder;function Wu(n){let e=Te(n.challenge_data),t=Te(n.challenge_data_hash);return e===""||!qu.test(t)?{}:Bu.encode(e).length>Uu?{}:{data:e,dataHash:t}}function Vu(n){let e=n??{},t=He(e.period_start_at),r=He(e.period_ends_at);if(t===0||r===0)return;let i=Te(e.slug),o=Te(e.seed),s=pi(e.period_local_date),a=Te(e.boundary),l=Te(e.reset_time);return {id:Te(e.progression_definition_id),...i===""?{}:{slug:i},window:Te(e.window),periodStartAt:t,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:Nu.test(a)?a:"",resetTime:ju.test(l)?l:"",seed:Fu.test(o)?o:"",...Wu(e)}}function yt(n){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(n)}`)}function Zn(n){let e=n??{};return Array.isArray(e.challenges)?e.challenges.map(Vu).filter(t=>t!==void 0):[]}var $t=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:t}=e;yt(t);let r=await Ha(this.#e,{...t===void 0?{}:{periods_back:t},...e.signal===void 0?{}:{signal:e.signal}});return Zn(r)}};function Ee(n){return typeof n=="string"&&n!==""?n:void 0}var Ls=new Set(["localhost","127.0.0.1","[::1]"]);function Ke(n){return er(n)}function er(n){let e=Ee(n);if(e===void 0)return;let t;try{t=new URL(e);}catch{return}if(!(t.username!==""||t.password!=="")&&(t.protocol==="https:"||t.protocol==="http:"&&Ls.has(t.hostname)))return e}var Hu=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Ku=/^[a-z][a-z0-9_]{0,31}$/;function Ju(n){if(!Array.isArray(n))return;let e=[],t=new Set;for(let r of n.slice(0,8)){let i=r??{},o=Ee(i.family),s=Ee(i.avatar_3d_id),a=Ke(i.model_url),l=Ke(i.icon_url);o===void 0||!Ku.test(o)||t.has(o)||s===void 0||!Hu.test(s)||a===void 0||l===void 0||(t.add(o),e.push({family:o,id:s,modelUrl:a,iconUrl:l}));}return e}function zu(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},i=Ee(r.item_id),o=Ke(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function Re(n){let e=n??{},t=Ee(e.player_id),r=Ee(e.display_name),i=Ee(e.discriminator),o=Ee(e.display_tag),s=Ee(e.avatar_icon_id),a=Ke(e.avatar_icon_url),l=Ee(e.avatar_3d_id),d=Ke(e.avatar_3d_model_url),m=Ke(e.avatar_3d_icon_url),u=Ju(e.avatars_3d);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:Ge(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:Ge(o)},...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},...u===void 0?{}:{avatars3d:u},badges:zu(e.badges)}}var Yu=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Xu(n){if(n===void 0)return;let e=Ke(n);if(e===void 0)return;let t=new URL(e);return Ls.has(t.hostname)||Yu.has(t.origin)?e:void 0}var Gs=100,Fs=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function gi(n){let{periodsBack:e,period:t,playerId:r}=n;if(yt(e),e!==void 0&&t!==void 0)throw new TypeError("pass periodsBack or period, not both");if(t!==void 0&&(typeof t!="string"||!Fs.test(t)))throw new TypeError(`period must be a period id such as 2026-10-02 (a result's period.id), got ${String(t)}`);if(r!==void 0&&(typeof r!="string"||r===""))throw new TypeError("playerId must be a player id");return {...e===void 0?{}:{periods_back:e},...t===void 0?{}:{period:t},...r===void 0?{}:{player_id:r}}}function qs(n){let e=typeof n.period_id=="string"?n.period_id:"";if(!Fs.test(e))return;let t=pi(n.period_local_date),r=He(n.period_start_at),i=He(n.period_ends_at),o=r>0&&i>0;return {id:e,...t===void 0?{}:{localDate:t},...o?{startAt:r,endsAt:i}:{},opensAt:He(n.opens_at),closesAt:He(n.closes_at),final:n.final===true}}var Ft=n=>typeof n=="string"?n:"",ft=n=>typeof n=="number"?n:0,qt=n=>typeof n=="string"?n:void 0,Qu=n=>typeof n=="number"?n:void 0,Ns={player:"players",character:"characters"};function Zu(n,e){let t=n??{},r=qt(t.entity_id),i=typeof t.entity_type=="string"&&Object.hasOwn(Ns,t.entity_type)?t.entity_type:void 0,o=js(t.stats),s=t.properties!==null&&typeof t.properties=="object"?t.properties:void 0,a=e?t.is_viewer===true:void 0;return {...Re(t),rank:ft(t.rank),occurredAt:ft(t.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 Ds(n,e){let t=n??{},r=qt(t.bucket_1),i=qt(t.bucket_2),o=Qu(t.update_frequency_seconds),s=qs(t);return {leaderboardType:Ft(t.leaderboard_type),runType:Ft(t.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(t.entries)?t.entries.map(a=>Zu(a,e)):[],generatedAt:ft(t.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...s===void 0?{}:{period:s}}}function $s(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=n;if(!Number.isFinite(e.rank))return;let t=js(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:ft(e.occurred_at),...t===void 0?{}:{stats:t},...r===void 0?{}:{properties:r}}}function js(n){if(n===null||typeof n!="object")return;let e={};for(let[t,r]of Object.entries(n))typeof r=="number"&&(e[t]=r);return e}function em(n,e,t){let r=n??{},i=qt(r.bucket_1),o=qt(r.bucket_2),s=qs(r);return {leaderboardType:Ft(r.leaderboard_type),runType:Ft(r.run_type),entityType:e,entityId:t,...i===void 0?{}:{bucket1:i},...o===void 0?{}:{bucket2:o},entries:Array.isArray(r.entries)?r.entries.map($s).filter(a=>a!==void 0):[],personalBest:$s(r.personal_best)??null,totalRuns:ft(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:ft(r.generated_at),...s===void 0?{}:{period:s}}}var Nt=class{#e;constructor(e){this.#e=e;}async get(e,t={}){let r=gi(t),i=await Oa(this.#e,e,{...r,...t.bucket1===void 0?{}:{bucket_1:t.bucket1},...t.bucket2===void 0?{}:{bucket_2:t.bucket2},...t.signal===void 0?{}:{signal:t.signal}});return Ds(i,false)}async friends(e,t={}){let r=gi(t),i=await Ea(this.#e,e,{...r,...t.bucket1===void 0?{}:{bucket_1:t.bucket1},...t.bucket2===void 0?{}:{bucket_2:t.bucket2},...t.signal===void 0?{}:{signal:t.signal}});return Ds(i,true)}async mine(e,t={}){return this.#n(e,"player","me",t)}async character(e,t,r={}){return this.#n(e,"character",t,r)}async#n(e,t,r,i){if(i.limit!==void 0){let{limit:l}=i;if(!Number.isInteger(l)||l<1||l>Gs)throw new TypeError(`limit must be an integer between 1 and ${Gs}, got ${String(l)}`)}let o=gi(i),s=await Sa(this.#e,e,Ns[t],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=t==="player"&&r==="me"&&Ft((s??{}).entity_id)||r;return em(s,t,a)}};var tr=n=>typeof n=="string"?n:"",yi=n=>typeof n=="number"?n:0;function Us(n){let e=n??{};return {playerId:tr(e.player_id),key:tr(e.key),value:e.value,updatedAt:yi(e.updated_at)}}function tm(n){let e=n??{};return {...Re(e),playerId:tr(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:yi(e.updated_at)}}function nm(n){return n?.reason==="not_found"}var jt=class{constructor(e,t){this.api=e;this.selfPlayerId=t;}api;selfPlayerId;async friends(e,t={}){let i=await Ia(this.api,Pe(e),{...t.signal===void 0?{}:{signal:t.signal}})??{};return {key:tr(i.key),entries:Array.isArray(i.entries)?i.entries.map(tm):[],generatedAt:yi(i.generated_at)}}async of(e,t,r={}){try{return Us(await Fa(this.api,e,Pe(t),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(nm(i))return null;throw i}}async set(e,t,r={}){if(Pe(e),t===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(t);}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 Us(await is(this.api,i,e,{value:t},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,t={}){let r=await this.selfPlayerId();await ga(this.api,r,Pe(e),{...t.signal===void 0?{}:{signal:t.signal}});}};var rm="gemChallenge",Bs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ws(n){if(!(typeof n!="string"||n===""))try{return new URLSearchParams(n).get(rm)??void 0}catch{return}}var Je=class extends O{constructor(e,t={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,i]of Object.entries(t))i!==void 0&&Object.assign(this,{[r]:i});}},nr=n=>typeof n=="string"?n:void 0;function Vs(n){let e=n??{};return {...Re(e),playerId:nr(e.player_id)??""}}function Hs(n){let e=n.has_more===true?nr(n.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function im(n){let e=n??{};return {friends:Array.isArray(e.data)?e.data.map(Vs):[],...Hs(e)}}var fi=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0;function om(n){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(e=>typeof e[1]=="string"||typeof e[1]=="number"&&Number.isFinite(e[1])))}function Ks(n){let e=n??{},t=fi(e.opened_at),r=fi(e.answered_at);return {id:nr(e.item_id)??"",from:Vs(e.sender),template:nr(e.template)??"",params:om(e.params),createdAt:fi(e.created_at)??0,...t===void 0?{}:{openedAt:t},...r===void 0?{}:{answeredAt:r}}}function am(n){let e=n??{};return {challenges:Array.isArray(e.data)?e.data.map(Ks):[],...Hs(e)}}function sm(n){let e=n;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Ut=class{#e;#n;#o;constructor(e,t={}){this.#e=e,this.#n=t.challenge,this.#o=t.launchedChallengeId;}async list(e={}){let t=await Qa(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return im(t)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let t=await Xa(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return am(t)}async launchedChallenge(e={}){let t=this.#o;if(t===void 0||!Bs.test(t))return null;try{return Ks(await Ma(this.#e,t,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(sm(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!Bs.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 es(this.#e,e);}};var lm=0;function ve(){try{return crypto.randomUUID()}catch{let n=Math.random().toString(36).slice(2,10);return `local-${String(++lm)}-${String(Date.now())}-${n}`}}var dm=12e4,Js=8,cm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,um=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Bt(n,e,t={}){return new Je(new O("invalid",400,e,void 0,n),t)}function mm(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function pm(n){let{playerId:e,template:t,params:r}=n??{};if(typeof e!="string"||!cm.test(e))return {error:Bt("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof t!="string"||!um.test(t))return {error:Bt("unknown_template","template must be a friend_challenge_templates key from this game's config")};if(r===void 0)return {playerId:e,template:t,params:void 0};if(!mm(r))return {error:Bt("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:Bt("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return o.length>Js?{error:Bt("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String(Js)}`)}:{playerId:e,template:t,params:i}}function gm(n){switch(n.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:n.outcome}};case "rate_limited":{let e=n.retryAfterMs,t=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new Je(new O("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",t,"rate_limited"))}}case "invalid":{let e=typeof n.code=="string"?n.code:void 0,t=typeof n.detail=="string"&&n.detail!==""?n.detail:e??"the friend challenge request was refused as invalid";return {error:new Je(new O("invalid",400,t,void 0,e),{...typeof n.param=="string"?{param:n.param}:{},...typeof n.channel=="string"?{channel:n.channel}:{},...typeof n.configVersion=="number"?{configVersion:n.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function ym(n){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(n.outcome)?n.outcome:"unknown"}function zs(n){let e=new Map;return {challenge(t){if(!n.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=pm(t);if("error"in r)return Promise.reject(r.error);let i=`challenge-${ve()}`;return new Promise((o,s)=>{let a={},l=m=>{e.delete(i)&&(n.clock.clearTimeout(a.timer),"error"in m?s(m.error):o(m.outcome));};e.set(i,l),a.timer=n.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},n.timeoutMs??dm);let d=false;try{d=n.bridge.requestFriendChallenge(i,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(t){let r=e.get(t.requestId);if(r===void 0){n.onDropped?.(`gem.friendChallengeResult (${ym(t)}) for an unknown requestId: `+JSON.stringify(t.requestId));return}r(gm(t));}}}var rr=n=>typeof n=="string"?n:void 0;function fm(n){let e=n??{},t=rr(e.currency_id);if(t===void 0||t==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:rr(e.slug)??"",currencyId:t,balance:r,access:e.access==="spend"?"spend":"read"}}var ir=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await In(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=fm(o);s!==void 0&&i.push(s);}return i}},hi=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0?Math.floor(n):0;function hm(n){let e=n??{},t=rr(e.currency_id);if(t===void 0||t==="")return;let r=hi(e.limit),i=Math.min(hi(e.earned),r),o=Math.min(hi(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:rr(e.currency_slug)??"",currencyId:t,limit:r,earned:i,remaining:o,period:e.period==="day"?"day":"window",periodDays:a,...d===void 0?{}:{resetsAt:d}}}function Ys(n){let e=new Set,t=r=>{n?.(`[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,t);}catch(i){t(i);}}}}var or=class{#e;#n;#o;constructor(e,t,r){this.#e=e,this.#n=t,this.#o=r;}async get(e={}){let r=(await La(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=hm(o);s!==void 0&&i.push(s);}return i}on(e,t){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(t)??(()=>{})}},Wt=class{currencies;earnAllowance;constructor(e,t,r){this.currencies=new ir(e),this.earnAllowance=new or(e,t,r);}};var bi=n=>typeof n=="string"?n:"",Xs=n=>typeof n=="number"?n:0;function bm(n){let e=n??{};return {key:bi(e.key),visibility:bi(e.visibility),value:e.value,updatedAt:Xs(e.updated_at)}}function vm(n){let e=n??{};return {...Re(e),playerId:bi(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(bm):[],generatedAt:Xs(e.generated_at)}}function _m(n){return n?.reason==="not_found"}var Vt=class{#e;constructor(e){this.#e=e;}async of(e,t={}){try{return vm(await Ga(this.#e,e,{...t.signal===void 0?{}:{signal:t.signal}}))}catch(r){if(_m(r))return null;throw r}}};var wm=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]]),ar=class extends O{constructor(e,t){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,t);}get retryable(){return (this.code===void 0?void 0:wm.get(this.code))??super.retryable}},ze=class{#e;constructor(e){this.#e=e;}async invoke(e,t={}){let r=km(e),i;try{i=await this.#e(r,t.signal===void 0?{}:{signal:t.signal});}catch(o){throw o instanceof O?Sm(o):o}return Rm(i)}};function km(n){if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);let e;try{e=JSON.stringify(n);}catch(t){throw new se(`the function input could not be serialised to JSON: ${String(t)}. 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 n}, 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 Rm(n){let{bytes:e}=n,t=()=>new TextDecoder("utf-8",{fatal:true}).decode(e);return {bytes:e,...n.invocationId===void 0?{}:{invocationId:n.invocationId},text:t,json:()=>JSON.parse(t())}}function Sm(n){let{details:e,invocationId:t}=na(n),i=e?.untrusted?.message,o=e?.reason;return new ar(n,{...t===void 0?{}:{invocationId:t},...n.code==="function_error"&&typeof i=="string"?{functionMessage:i}:{},...n.code==="function_failed"&&typeof o=="string"?{failure:o}:{}})}function sr(n,e){let t=e?.retryAfterSeconds,r=typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:0,i=1e4*2**Math.min(Math.max(0,n-1),16);return Math.min(Math.max(r,i),3e5)}var xm=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],vi="gem_";function Qs(n){return n.startsWith(vi)}var Zs=1e4,el=50,Am=500,Pm=65536-4*1024,Tm=24*1024;function tl(n){let e={},t={};for(let[r,i]of Object.entries(n))typeof i=="string"?e[r]=i:typeof i=="number"&&Number.isFinite(i)&&(t[r]=i);return {dimensions:e,measures:t}}var nl=n=>typeof n=="number"?n:0,Em=n=>typeof n=="string"?n:"";function lr(n=0){return {accepted:0,rejected:[],dropped:n,duplicate:false}}function Im(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(i=>{let o=i??{};return {index:nl(o.index),code:Em(o.code)}}):[];return {accepted:nl(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function _i(){let n=globalThis.crypto;return typeof n?.randomUUID=="function"?n.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return (e==="x"?t:t&3|8).toString(16)})}function Cm(n){return n?.retryable===true}var Ht=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;#R=false;#S=false;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#o=Math.max(Zs,e.options?.flushIntervalMs??Zs),this.#f=Math.max(1,Math.floor(e.options?.maxQueue??Am));}track(e,t={}){if(!(!this.#n||this.#r)){if(Qs(e)){this.#S||(this.#S=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,tl({...this.#h,...t}));}}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 lr();let t=this.#C();if(t===null||t==="")return this.#t.length>0&&!this.#R&&(this.#R=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.")),lr();if(this.#P(),this.#t.length===0)return lr();let r=e.keepalive===true;if(this.#m>0&&!r)return lr();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:_i(),sent_at_ms:s,events:i.map(d=>rl(d,s))},l={client:this.#e.client(),gameId:()=>t};this.#m+=1;try{let d=await Ua(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=Im(d,o);return this.#_=0,this.#w=0,this.#I(m),m}catch(d){throw Cm(d)?(this.#T(i,o),this.#_+=1,this.#w=this.#e.clock.now()+sr(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,t={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#x(e,tl(t));}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(),t=this.#t.map(r=>({...r,atMs:e}));this.#t=t,this.#p&&(this.#p=false,this.#l=e,this.#c=false,this.#t.unshift({uid:_i(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=el?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 t=this.#l;this.trackPlatform("gem_session_end",{reason:e,...t===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-t))}}),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,t){let{dimensions:r,measures:i}=t;for(this.#P();this.#t.length>=this.#f;)this.#t.shift(),this.#a+=1;this.#t.push({uid:_i(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#t.length>=el?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,t){for(this.#t=[...e,...this.#t],this.#a+=t;this.#t.length>this.#f;)this.#t.shift(),this.#a+=1;}#E(e){let t=e?Tm:Pm,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(rl(s,0)).length+1,i>t)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);}#I(e){for(let t of e.rejected)this.#y(`[gem] analytics: an event was refused (${t.code}). `+Mm(t.code));}#y(e){let t=this.#e.log;t!==null&&(t===void 0?console.warn(e):t(e));}#C(){try{return this.#e.gameId()}catch{return null}}#M(){try{return this.#e.playerId()}catch{return null}}};function rl(n,e){return {event_uid:n.uid,name:n.name,offset_ms:Math.round(n.atMs)-e,dimensions:n.dimensions,measures:n.measures}}function Mm(n){switch(n){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 ge(n){if(typeof n!="string")return;let e=n.trim();return e.length===0?void 0:e}function Kt(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=ge(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Om=2e3,Lm=5e3;function ol(n){let e=[],t=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(t)return Promise.resolve([]);if(!n.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let s,a=new Promise(l=>{let d=false,m=null;s=u=>{d||(d=true,r=null,n.clock.clearTimeout(m),l(u));},m=n.clock.setTimeout(()=>{t=true,s([]);},n.timeoutMs??Om);});return r={promise:a,settle:s},a};return {resolveList:o,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(s=>s[0])},refresh(s){return !il(e,s)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=m=>{i.delete(d)&&(n.clock.clearTimeout(l),a(m));};i.set(d,s),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??Lm);})},accept(s,a){let l=Kt(a),d=ge(s),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[u,p]of [...i])il(m,p)||u(m);}}}}function il(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Gm=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(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="DedicatedServerError",this.retryable=Gm.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var al=["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"],Dm=new Set(al);function ht(n){return typeof n=="string"&&Dm.has(n)?n:"unknown"}var dr="webrtc_dedicated",Si=["universal","mobile","web"];var $m="p2p_unavailable",Fm="capacity_unavailable",qm=2,sl=3e4,ll=1e3,dl=2e4;async function xi(n){let e=ge(n.clusterTargetId),t=n.nextClusterTarget,r=0,i=n.clock??fe,o=n.retry??{},s=o.budgetMs??sl,a=o.maxDelayMs??dl,l=o.initialDelayMs??ll,d=i.now(),m=d+s,u=0;for(;;){u++;try{let p=await Ei(n.signal,"while allocating",()=>n.client.post(`${ml(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Nm(p)||s<=0)throw p;if(p.status===503&&p.code===$m)throw new w("p2p_unavailable",`room ${n.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${p.message}`,{cause:p});if(r=p.code===Fm?r+1:0,t!==void 0&&r>=qm){let x=t;t=void 0;let I=ge(await x());I!==void 0&&(e=I,r=0);}let g=Math.min(a,l*2**(u-1)),y=Math.min(a,(p.retryAfterSeconds??0)*1e3),R=Math.max(g/2,y)+Math.random()*(g/2);if(i.now()+R>m)throw jm(n,p,u,i.now()-d,s);if(o.onWaiting?.({attempt:u,elapsedMs:i.now()-d,budgetMs:s,nextAttemptInMs:R,status:p.status,message:p.message}),await cr(i,R,n.signal),n.signal?.aborted)throw Ri("while waiting to allocate")}}}function Nm(n){return n instanceof O?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function jm(n,e,t,r,i){let o=`${t} attempt${t===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new w("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${o}: ${e.message}`,{cause:e}):new w("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${o}: ${e.message}`,{cause:e})}var Um=12e4,Bm=1e3;async function Ai(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??Bm,i=n.timeoutMs??Um,o=e.now()+i,s=cl(n),a={seen:n.knownToExist===true};for(;;){let l=await ul(n,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new w("timeout",`match ${t} was still ${l.status} after ${i}ms`);await cr(e,r,n.signal);}}async function Pi(n){return (await ul(n,cl(n),{seen:n.knownToExist===true})).outcome}function cl(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${ml(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function ul(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await Ei(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(s){if(s instanceof O&&s.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:Wm(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:ht(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function Ti(n){let e=await Ei(n.signal,"while listing cluster targets",()=>n.client.get("/v1/ping/targets",n.signal)),t=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||t.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return t}async function Ei(n,e,t){if(n?.aborted)throw Ri(e);try{return await t()}catch(r){throw n?.aborted?Ri(e,r):r}}function Ri(n,e){return new w("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function Wm(n,e,t){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:n,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:t+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function ml(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function cr(n,e,t){return t?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{n.clearTimeout(o),t?.removeEventListener("abort",i),r();},o=n.setTimeout(i,e);t?.addEventListener("abort",i);})}function pl(n){return typeof n=="string"&&n.trim()!==""}function ur(n,e){return pl(n)?n.trim():pl(e)?e:null}var mr="0.1.0-beta",gl="0-beta",bt="web",Vm=/^(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 Hm(n){let e=Vm.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function yl(n,e){let t=Km(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:mr};let i=Hm(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 '${mr}' for it.`);if(i!==gl)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${gl}' 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 '${mr}' for it.`);return {...n,platform:t,engineVersion:r}}function Km(n,e){if(n===void 0||n===bt)return bt;if(!Si.includes(n))throw new w("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${Si.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${bt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${bt}' 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.`),bt}function Jt(n){let e=n??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let t=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:fl(e.queued_at),expiresAt:fl(e.expires_at),heartbeatIntervalSeconds:typeof t=="number"&&t>0?t:0}}function fl(n){if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?Math.floor(e/1e3):0}var Jm=3,hl=1e3,pr=class{constructor(e){this.options=e;this.snapshot=e.first;let t=new Promise((o,s)=>{this.resolve=o,this.reject=s;});t.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:t,cancel:()=>(this.requestCancel(),t)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let t=e?hl:Math.max(hl,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},t);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,t=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){t=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(t);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof O&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<Jm){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let t=e instanceof O&&e.code==="matchmaking_unavailable";this.settle({status:t?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let t=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:t});}catch(t){this.busy=false,this.fail(t);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};var zm="join",Ym="welcome",Xm="rejected",bl=25e3,Qm=1e3,Ii=1;function Ci(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var Zm={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 Mi(n){let e=typeof n=="string"?n:"unknown";return new w(Zm[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function zt(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,s=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??bl),a=t.setTimeout(()=>b(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,Qm)),l=R=>{let x=R.data;if(typeof x!="string"){u(x);return}let I;try{I=JSON.parse(x);}catch{u(x);return}if(o){u(x);return}if(I.t===Ym){let h=Ci(I.heartbeat_interval);y({...typeof I.player_id=="string"?{playerId:I.player_id}:{},...typeof I.match_id=="string"?{matchId:I.match_id}:{},...h===void 0?{}:{heartbeatIntervalMs:h}});return}if(I.t===Xm){b(Mi(I.reason));return}u(x);},d=()=>{b(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{b(new w("aborted","the caller aborted during the join exchange"));},u=R=>{o&&n.onMessage?.(R);},p=()=>{t.clearTimeout(a),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=R=>{o=true,p(),n.onMessage===void 0&&g(),r({welcome:R,detach:g});},b=R=>{o||(o=true,p(),g(),i(R));};if(e.addEventListener("message",l),e.addEventListener("close",d),n.signal?.aborted){m();return}n.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:zm,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:Ii}:{}}));}catch(R){b(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(R)}`,{cause:R}));}})}var Ye=1,Yt=2,Oi=4,Di=8,ep=2,tp=1e3,$i="heartbeat timeout",Xt="gem-uu",gr=2,_l="gem_transports";function vt(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!np(r)||e.includes(r)||e.push(r);}return e}function np(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function Qt(n,e){if(typeof n!="object"||n===null)return null;let t=n[_l];if(typeof t!="object"||t===null)return null;let r=t;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function yr(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var wl=new TextEncoder,kl=new TextDecoder;function Fi(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function qi(n){let e=0;return n?.reliable===false&&(e|=Ye),n?.ordered===false&&(e|=Yt),e}function Ni(n){return {reliable:(n&Ye)===0,ordered:(n&Yt)===0}}var ji={reliable:true,ordered:true};function Rl(n){return JSON.stringify({t:"join",credential:n,wire:gr,heartbeat:Ii})}function Sl(n){let e;try{e=JSON.parse(n);}catch{throw new w("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=Ci(e.heartbeat_interval);return {...e.player_id===void 0?{}:{playerId:e.player_id},...e.match_id===void 0?{}:{matchId:e.match_id},...t===void 0?{}:{heartbeatIntervalMs:t}}}throw e.t==="rejected"?Mi(e.reason):new w("join_refused","the server answered the join out of protocol")}function fr(){return typeof globalThis.WebTransport=="function"&&Ui===null}function hr(){return Ui}var Ui=null;var vl="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function rp(n){let e=En(n);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 Li=class{buffered=new Uint8Array(0);push(e){let t=new Uint8Array(this.buffered.byteLength+e.byteLength);t.set(this.buffered,0),t.set(e,this.buffered.byteLength),this.buffered=t;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new 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 Gi(n,e){let t=new Uint8Array(5+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength+1,true),t[4]=n,t.set(e,5),t}async function Zt(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webTransport;if(t===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new w("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new a(n.url):new a(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:rp(n.certHashBase64)}]});}let r=t,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(Ui=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(Gi(Oi,wl.encode(Rl(n.credential))));let u=new Li,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 b of u.push(y.value)){g=Sl(kl.decode(b.payload));break}}return {link:ip(r,m,p,u,n.log??(y=>console.warn(y)),Al(g,n.clock)),welcome:g}}catch(a){return i(a)}}function ip(n,e,t,r,i,o){let s,a,l=false,d=y=>{if(!l){l=true,m.stop();try{n.close();}catch{}a?.(y);}},m=Wi(o,()=>d($i)),u=(y,b)=>{m.heard(),(y&Di)===0&&s!==void 0&&((y&Oi)!==0?s(kl.decode(b),ji):s(b,Ni(y)));};(async()=>{try{for(;;){let y=await t.read();if(y.done||y.value===void 0)break;for(let b of r.push(y.value))u(b.flags,b.payload);}}catch{}d("stream closed");})();let p,g;try{let y=n.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let b=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let R=await b.read();if(R.done||R.value===void 0)break;let x=R.value;x.byteLength!==0&&u((x[0]??0)|Ye|Yt,x.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 (${yr(y)}); unreliable sends ride the stream`);}return n.closed.then(y=>d(xl(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,b){if(l)return;if(typeof y=="string"){e.write(Gi(Oi,wl.encode(y))).catch(()=>d("write failed"));return}let R=qi(b);if((R&Ye)!==0&&g!==void 0){let x=Fi(R,y),I=p?.maxDatagramSize;if(I===void 0||x.byteLength<=I){g.write(x).catch(()=>{});return}}e.write(Gi(R,y)).catch(()=>d("write failed"));},onMessage(y){s=y;},onClose(y){a=y;},close(){d("closed");}}}function Bi(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webSocket;if(t===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new w("connection_failed","this environment has no WebSocket"));t=new i(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new w("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),o(g));},d=()=>{r.send(Rl(n.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=Sl(g.data);}catch(b){l(b);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",u),r.removeEventListener("error",p),i({link:op(r,Al(y,n.clock)),welcome:y});},u=()=>{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",u),r.addEventListener("error",p),r.readyState===1&&d();})}function xl(n){return typeof n=="string"&&n.length>0?n:void 0}function Al(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function Wi(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,tp)*ep,i=t.now(),o=null,s=()=>{o=null;let a=t.now()-i;if(a>=r){e();return}o=t.setTimeout(s,r-a);};return o=t.setTimeout(s,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function op(n,e){let t,r,i=false,o=a=>{if(!i){i=true,s.stop();try{n.close();}catch{}r?.(a);}},s=Wi(e,()=>o($i));return n.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){t?.(a.data,ji);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Di)===0&&t?.(l.slice(1),Ni(d));})),n.addEventListener("close",(a=>o(xl(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!i){if(typeof a=="string"){n.send(a);return}n.send(Fi(qi(l),a));}},onMessage(a){t=a;},onClose(a){r=a;},close(){o("closed");}}}function Vi(n,e,t,r){let i,o,s=false,a=t,l=u=>{if(!s){s=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(u);}},d=Wi(r,()=>l($i)),m=(u,p)=>{if(d.heard(),typeof u=="string"){i?.(u,ji);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let y=g[0]??0;(y&Di)===0&&i?.(g.slice(1),Ni(y|p));};if(n.addEventListener("message",(u=>m(u.data,0))),n.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),a!==void 0){let u=a;u.addEventListener("message",(p=>m(p.data,Ye|Yt))),u.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(u,p){if(s)return;if(typeof u=="string"){n.send(u);return}let g=qi(p),y=Fi(g,u);if((g&Ye)!==0&&a!==void 0&&a.readyState==="open"){a.send(y);return}n.send(y);},onMessage(u){i=u;},onClose(u){o=u;},close(){l("closed");}}}function Ji(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=Hi(r);i!==void 0&&(e[t]=i);}return e}function zi(n){if(Array.isArray(n))return n.map(ap).filter(e=>!!e)}function Hi(n){if(Ki(n)||Array.isArray(n)&&n.every(Ki))return n}function Ki(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function ap(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Hi(e.fixed),r=Hi(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...t===void 0?{}:{fixed:t},...r===void 0?{}:{default:r},..._t("description",sp(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Ki)?{allowed:e.allowed}:{},..._t("min",en(e.min)),..._t("max",en(e.max)),..._t("minItems",en(e.min_items)),..._t("maxItems",en(e.max_items)),..._t("maxLength",en(e.max_length))}}function sp(n){return typeof n=="string"&&n.length>0?n:void 0}function en(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function _t(n,e){return e===void 0?{}:{[n]:e}}function Ce(n){let e=n??{},t=Y(e.id)??Y(e.game_room_id);if(t===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(Pl):[];return {id:t,gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Ie(e.max_players)??0,memberCount:Ie(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,..._e("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},..._e("roomArgs",Ji(e.room_args)),..._e("roomArgsTemplate",zi(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",..._e("region",Y(e.region)),..._e("clusterTargetId",Y(e.cluster_target_id)),selfHosted:e.self_hosted===true,..._e("matchId",Y(e.match_id)),version:Ie(e.version)??0,..._e("templateId",Y(e.template_id)),..._e("templateSlug",Y(e.template_slug)),roomType:Y(e.game_room_type)??"Standard",..._e("transports",vt(e.transports)??void 0),createdAt:Ie(e.created_at)??0,updatedAt:Ie(e.updated_at)??0,..._e("startedAt",Ie(e.started_at))}}function Pl(n){let e=n??{};return {...Re(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:Ie(e.joined_at)??0,..._e("groupId",Y(e.group_id)),..._e("platform",Y(e.platform))}}function br(n){let e=n??{};return {id:Y(e.id)??Y(e.game_room_id)??"",gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Ie(e.max_players)??0,memberCount:Ie(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Y(e.game_channel)??"release",roomType:Y(e.game_room_type)??"Standard",createdAt:Ie(e.created_at)??0}}function Y(n){return typeof n=="string"&&n.length>0?n:void 0}function Ie(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function _e(n,e){return e===void 0?{}:{[n]:e}}var nn=class{constructor(e){this.options=e;}options;list(e){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.templateSlug&&t.set("template_slug",e.templateSlug),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);let r=t.size>0?`?${t.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(br),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(t=>({rooms:(t.game_rooms??[]).map(br)}))}create(e,t,r){return dp(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},...tn(t)},e.signal).then(Ce)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(Ce)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...tn(r)},t.signal).then(Ce)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...tn(r)},t.signal).then(Ce)}quickJoin(e,t,r=[]){let i=this.asksSelfHosted(e.partyId);return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...lp(e.templateSlugs,i),...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...i?{self_hosted:true}:{},...tn(t)},e.signal).then(Ce)}createTicket(e,t,r=[]){return ua(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},...tn(t)},{...e.signal===void 0?{}:{signal:e.signal}}).then(Jt)}heartbeatTicket(e){return ja(this.generated(),e).then(Jt)}cancelTicket(e,t=false){return t?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(Jt):aa(this.generated(),e).then(Jt)}leave(e,t,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}close(e,t){return this.options.client.delete(this.roomV1(e),t).then(()=>{})}update(e,t){return this.options.client.patch(this.roomV2(e),{...t.name===void 0?{}:{name:t.name},...t.maxPlayers===void 0?{}:{max_players:t.maxPlayers},...t.isPublic===void 0?{}:{is_public:t.isPublic},...t.settings===void 0?{}:{settings:t.settings},...t.roomArgs===void 0?{}:{room_args:t.roomArgs}},t.signal).then(Ce)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(Ce)}kick(e,t,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(t)}`,{},r).then(()=>this.get(e,r))}transferHost(e,t,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(t)}`,{},r).then(Ce)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function lp(n,e){return n===void 0?{}:{templates:(e?n.slice(0,1):n).map(r=>({template_slug:r}))}}function tn(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function dp(n){n!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${n}) is deprecated and was not sent. A room's seats come from the room template published in your game config \u2014 name one with templateSlug \u2014 and a room created without a template seats 8. To change a room that already exists, call update({ maxPlayers }) as its host.`);}var rn=class{listeners=new Map;retainedMatch=null;on(e,t){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(t),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(t)&&this.retainedMatch===i&&t(i);});}return ()=>this.off(e,t)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){e==="matchReady"&&(this.retainedMatch=t[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};var vr=class{constructor(e){this.options=e;let t=e.first,r=new Promise(a=>{this.resolve=a;}),i=()=>this.status;this.ticket={id:t.ticketId,get status(){return i()},partySize:t.partySize??0,queuedAt:t.queuedAt??0,expiresAt:t.expiresAt??0,outcome:r};let o=t.queuedAt!==void 0&&t.expiresAt!==void 0?(t.expiresAt-t.queuedAt)*1e3:9e5,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 cp(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var up=1e3,mp=3e3,pp=6e4,gp=2,Tl=new Set(["game_room_closed","game_room_gone"]),yp=12e4,fp=5e3,hp=new Set(["invalid_cluster_target","capacity_unavailable"]),bp=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Xi(n){return new Yi(n)}var Yi=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new nn({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new rn;api;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await t;return this.api.create(r,this.version("create"),o[0]).catch(async s=>{let a=await this.afterRefusedClusters(s,o);if(a[0]===void 0||a[0]===o[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,t={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(t),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(t),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin"),wp(e);let t=this.clusterTargets(),r=await this.attachParty(e),i=s=>this.api.quickJoin(r,this.version("quickJoin"),s).catch(a=>this.retryPastStaleMembership(a,r,s)),o=await this.run("quickJoin",async()=>{let s=await t;return i(s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||Cl(l,s))throw a;return i(l)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}async queueForMatch(e){this.assertNotQueued("queueForMatch"),_p(e?.templateSlugs),this.queueing=true;try{let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let s=await t;return this.api.createTicket(r,this.version("queueForMatch"),s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||Cl(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 pr({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 t=this.heldQueued;this.heldQueued=null,t!==null&&this.showPartyTicket(t);}}async enterMatchedRoom(e){let t=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?t:(this.room!==null&&this.room.id!==t.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(t,"joined"),this.room?.id===t.id?this.room:t)}async list(e={}){let t=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",t),t}async myRooms(e){let t=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",t.rooms),t.rooms}async leave(e={}){let t=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(t.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let t=await this.myRooms(e),r=[];for(let i of t)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let t=this.requireRoom("close");await this.run("close",()=>this.api.close(t.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let t=this.room;if(!t)return null;let r;try{r=await this.track(this.api.get(t.id,e));}catch(i){if(i instanceof 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 t=this.room,r=this.heldMatchId;if(!(t===null||r===null)&&!(t.status==="in_game"&&t.matchId===r)&&!(t.matchId!==void 0&&t.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>Pi({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...t===void 0?{}:{signal:t}})));}catch(s){return s instanceof 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 t=this.pendingHint;if(t===null||t.matchId!==void 0&&t.matchId!==e||(this.pendingHint=null,t.reason===void 0))return null;let r=ht(t.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let t=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=t,this.track(t)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,t){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,t));return this.apply(i),i}async kick(e,t){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,t));return this.apply(i),i}async transferHost(e,t){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,t));return this.apply(i),i}async update(e){let t=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(t.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,t){let r=this.requireRoom("startMatch");if(!this.isHost)throw new 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,t)}finally{this.startsInFlight--;}}async startIn(e,t,r){let i=ge(t.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(m,u)=>xi({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(u)}:{},retry:{...t.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),t.retry?.onWaiting?.(p);}},...t.signal===void 0?{}:{signal:t.signal}}),l=()=>a(o,[s]).catch(async m=>{if(i!==void 0||!Il(m))throw m;let u=await this.nextCluster([s],true);if(u===void 0)throw m;return a(u,[s,u])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new 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 t=this.emitter.retained;return t!==null&&this.session.phase==="ready"?t:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let t=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(t.id,r,e));return this.settleOutcome(i)}chase(e,t,r){return Ai({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:t,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(t),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new w("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!Tl.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,t){this.heldMatchId===e&&(this.abandonReconnect(e,t),this.emitter.emit("matchFailed",e,t),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,t,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:t,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:t,roomReopened:r}),this.abandonReconnect(e,t));}armReconnect(e,t){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),t==="kicked"){r.abandon(e,t);return}let i={matchId:e,cause:t,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,t){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),t());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,t){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,t));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!Xe()){this.park(e,()=>this.reconnectStep(e));return}let t=this.options.autoReconnect;if(t===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=t.attempts||r<up){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:t.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(cp(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Xe()){this.park(e,()=>this.reconnectAttempt(e));return}let t=this.options.autoReconnect,r=this.room;if(t===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>Pi({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,!Tl.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await t.redial(e.matchId,e.deadlineAt);}catch(s){this.reportError("reconcile",s),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let t=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):t&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new w("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let t=this.session.matchId;this.session={phase:"suspended",matchId:t,reason:e},this.emitter.emit("matchSuspended",{matchId:t,cause:e}),this.armReconnect(t,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new w("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let t=this.heldMatchId;if(t===null)throw new w("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:t},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let t=this.heldMatchId;if(t!==null)try{await this.api.leaveMatch(t,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,t){let r=this.emitter.on(e,t);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}handleRoomEvent(e){if(this.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let t=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(t).catch(()=>{}));}handleAutoStartFailed(e,t){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(t);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:t,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!hp.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let t=new vr({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===t&&(this.partyWatch=null);}});this.partyWatch=t,this.emitter.emit("partyQueued",t.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let t=new Set;for(let r of e)r.status!=="closed"&&(t.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])t.has(r)||this.reported.delete(r);}async reportSeat(e){let t=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||t===null||!r.members.some(i=>i.playerId===t)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&Xe())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let t=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(t,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!Xe())){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 _r)e.addEventListener(r,this.visibilityListener);let t=globalThis.document;typeof t?.addEventListener=="function"&&t.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let t=this.inFlight;this.inFlight=[],await Promise.allSettled(t);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of _r)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??fp}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 t=this.options.clientVersion,r=ur(this.options.platformGameVersion?.(),t?.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 yl({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return Kt(await this.options.resolveClusterTargets());let e=ge(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !Il(e)||t.length===0?[]:Kt(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=s=>s.find(a=>!e.includes(a)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!t?o:r(Kt(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let t=this.options.resolveParty;if(t===void 0)return e;let r=await t();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,t,r){if(!(e instanceof O)||e.reason!=="conflict"||!bp.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(t.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.api.quickJoin(t,this.version("quickJoin"),r)}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,t){try{return await this.track(this.onceGameIdKnown(t))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,t){let r=t instanceof O?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof w?t.reason:"unavailable",message:t instanceof Error?t.message:String(t),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let t=this.options.ensureLocalServer;t===void 0||!e.selfHosted||e.status!=="open"||t(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,t){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(t,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let t=this.room;if(t===null||t.id!==e.id)return;let r=new Map(t.members.map(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);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=vp(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let t=this.heldMatchId;t!==null&&t!==e&&this.endMatch(t,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,t=this.heldMatchId;if(e===null||t===null||this.followAbort!==null&&this.followingMatchId===t)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=t,this.track(this.onceGameIdKnown(()=>this.chase(e.id,t,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let t=this.heldMatchId;if(t!==null)return Promise.resolve(t);let r=e.timeoutMs??yp;return new Promise((i,o)=>{let s=u=>{a(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),u();},a=this.emitter.on("matchAllocationStarted",u=>s(()=>i(u))),l=this.emitter.on("matchFailed",(u,p)=>s(()=>o(new w("allocation_failed",`match ${u} 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??mp}pushedInterval(){return this.options.pushedPollIntervalMs??pp}pushed(){return this.options.clock.now()-this.lastPushAt<gp*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=t=>{if(this.ticketWatch?.abandon(true),t?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function Xe(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var _r=["visibilitychange","focus","pageshow","online"];function vp(n,e){return n.version!==e.version||n.status!==e.status||n.matchId!==e.matchId||n.hostPlayerId!==e.hostPlayerId||n.name!==e.name||n.maxPlayers!==e.maxPlayers||n.isPublic!==e.isPublic||El(n)!==El(e)}function El(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Il(n){return n instanceof O&&n.code==="invalid_cluster_target"}var wr=8;function _p(n){if(!(Array.isArray(n)&&n.length>=1&&n.length<=wr&&n.every(t=>typeof t=="string"&&t.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${wr} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function wp(n){let e=n?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=wr&&e.every(r=>typeof r=="string"&&r.length>0)))throw new w("misconfigured",`quickJoin's templateSlugs is an array naming one to ${wr} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(n?.templateSlug!==void 0||n?.templateId!==void 0)throw new 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 Cl(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var kp=["p2p","dedicated","unknown"],Qi=["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 wt=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let i=Rp(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},t);}report(e){this.post(e).catch(()=>{});}};function Rp(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>Qi.includes(i.type)).slice(0,100).map(i=>{let o=Sp(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function Sp(n){if(n!==void 0)return kp.includes(n)?n:"unknown"}var on=class{constructor(e){this.options=e;this.reporter=new wt({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,t,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:kr(i.credential)??"",hostFingerprint:kr(i.host_fingerprint)??"",hostEpoch:Rr(i.host_epoch)??0,expiresAt:(Rr(i.expires_at)??0)*1e3}}async turnLease(e,t,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:t},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(u=>typeof u=="string"&&u.length>0);m.length!==0&&o.push({urls:m,username:kr(d.username)??"",credential:kr(d.credential)??""});}let s=Rr(i.expires_at),a=Rr(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??0)*1e3}}async kick(e,t,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:t},r);}async leave(e,t=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:t});}async telemetry(e,t){await this.reporter.post(e,t);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function kr(n){return typeof n=="string"&&n.length>0?n:void 0}function Rr(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var xp=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),G=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="P2pError",this.retryable=xp.has(t);}reason;retryable};var Ml=10240,Ol=2048,Ap=new TextEncoder;function Ll(n){return Ap.encode(n).length}function Fe(n,e){let t=i=>{throw new w("invalid_sdp",`the ${e} ${i}`)},r=Ll(n);r>=Ml&&t(`is ${r} bytes, over the ${Ml} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),n.startsWith("v=")||t("does not start with 'v=', so it is not SDP"),n.includes("\0")&&t("contains a null byte"),/\r(?!\n)/.test(n)&&t("contains a bare carriage return");for(let i of n.split(/\r\n|\n/)){let o=Ll(i);o>Ol&&t(`has a ${o}-byte line, over the ${Ol} limit`);}}function Sr(n){for(let e of n.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[t,r="0"]=e.slice(2).trim().split(/\s+/);if(!(t!=="audio"&&t!=="video")&&r.split("/")[0]!=="0")return true}return false}var xr=class{listeners=new Map;on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}clear(){this.listeners.clear();}};var Pp=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function kt(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=Ar(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Ar(n){let[e,...t]=n.trim().split(/\s+/);if(e===void 0||t.length===0)return null;let r=`${e.toLowerCase()} ${t.join("").toUpperCase()}`;return Pp.test(r)?r:null}function an(n,e){if(n.length!==e.length)return false;let t=0;for(let r=0;r<n.length;r++)t|=n.charCodeAt(r)^e.charCodeAt(r);return t===0}var Zi=5e3,Tp=12e4+Zi,Ep=1024,Ip=6e4,Cp=1e4,Gl=64*1024,Dl=5;function eo(n){let e=new Map,t=-1/0,r=null,i=(()=>{let a;try{a=new URL(`${n.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=n.subtle??globalThis.crypto?.subtle;if(!a)throw new 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=n.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(Cp)});}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>Gl)throw new G("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Gl} 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>Dl)throw new G("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Dl} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=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 u.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=n.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<t&&(t=-1/0),d-t<Ip?null:(t=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var sn=class{seen=new Map;admit(e,t){for(let[r,i]of this.seen)i<=t&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=Ep){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+Tp),true}};function Fl(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}function $l(n){try{let e=new TextDecoder().decode(Fl(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function to(n,e,t,r,i){let o=j=>{throw new G("peer_unauthenticated",`the peer's join credential is not usable: ${j}`)},s=n.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,l,d]=s,m=$l(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 u=m.kid;(typeof u!="string"||u.length===0)&&o("it names no key");let p=await t.key(u);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}`),b;try{b=Fl(d);}catch{o("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,b,y)||o("its signature does not verify");let x=$l(l);x===null&&o("its payload does not decode");let I=x,h=j=>typeof I[j]=="string"?I[j]:"",k=j=>typeof I[j]=="number"&&Number.isFinite(I[j])?I[j]: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,E=k("nbf")*1e3;(!Number.isFinite(C)||e.now>C+Zi)&&o("it has expired"),Number.isFinite(E)&&e.now<E-Zi&&o("it is not valid yet");let W=h("role");W!=="host"&&W!=="client"&&o("it names no usable role");let D=k("host_epoch");D!==e.hostEpoch&&o("it names a different host epoch");let q=Ar(h("fingerprint"));q===null&&o("its fingerprint claim is malformed"),an(q,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let P=Ar(h("host_fingerprint"));P===null&&o("its host fingerprint claim is malformed"),an(P,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:D,role:W,fingerprint:q,hostFingerprint:P,jti:M,expiresAt:C}}function no(n){let e=new TextEncoder().encode(n.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let t=new ArrayBuffer(3+e.length+4+4),r=new DataView(t);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(t,3,e.length).set(e),r.setUint32(3+e.length,n.protocolVersion,true),r.setUint32(7+e.length,n.assignedPeerId,true),t}function ro(n){let e=new ArrayBuffer(9),t=new DataView(e);return t.setUint8(0,2),t.setUint32(1,n.protocolVersion,true),t.setUint32(5,n.assignedPeerId,true),e}function io(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function oo(n){if(n.byteLength<1)return null;let e=new DataView(n);switch(e.getUint8(0)){case 1:{if(n.byteLength<3)return null;let t=e.getUint16(1,true);return t>8192||n.byteLength<3+t+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(n,3,t)),protocolVersion:e.getUint32(3+t,true),assignedPeerId:e.getUint32(7+t,true)}}case 2:return n.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return n.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function ql(n){switch(n){case 1:return "the host did not accept this credential";case 2:return "the host speaks a different protocol version \u2014 an engine peer refuses a browser peer here, deliberately";case 3:return "the match is full";case 4:return "the host is rate-limiting joins";case 129:return "the host verified this credential but it names a different player than the one who signalled \u2014 the host has its own line saying which";case 130:return "the host has this player on the kicked list for the current host epoch";case 131:return "the host could not fetch the platform's signing keys, so it cannot verify anyone yet \u2014 the host's console says why";default:return `the host refused with an unrecognised code (${n})`}}function Nl(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var ln=class{constructor(e,t,r){this.localPlayerId=e;this.hostPlayerId=t,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,t){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=t,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var ao={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}},De=["reliable","ordered","unreliable"];function so(n){let e=globalThis.RTCPeerConnection;if(!e)throw new Error("[gem] this environment has no RTCPeerConnection. Pass `peerConnectionFactory` to connect against a stand-in, which is how this flow is tested outside a browser.");return new e({iceServers:n.iceServers,...n.certificates===void 0?{}:{certificates:n.certificates}})}async function dn(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Ul=1,Dp=3e4,Bl=2e3,$p=5e3,Wl=6e4,Fp=8,co=class{constructor(e=Fp){this.perMinute=e;}perMinute;sent=[];delayUntilAllowed(e){return this.prune(e),this.sent.length<this.perMinute?0:Math.max(0,(this.sent[0]??e)+6e4-e)}record(e){this.prune(e),this.sent.push(e);}prune(e){let t=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[t++]=r);this.sent.length=t;}},qp=new co,Np=8,jp=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),un=class{constructor(e){this.options=e;this.keys=e.keys??eo({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new xr;links=new Map;replays=new sn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Ul+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let t of this.links.values())t.admitted&&e.push(this.expose(t));return e}peer(e){let t=this.links.get(e);return t&&t.admitted?this.expose(t):null}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}async start(e){let t=this.options.connectTimeoutMs??Dp;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((a,l)=>{this.ready={resolve:a,reject:l};}),i=ge(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: ${lo(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 ${t}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},t),s=()=>this.fail(new 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,t){this.closed||this.route(e,t).catch(r=>this.report_(r));}async route(e,t){switch(e){case "hello":return this.onHello(t);case "offer":return this.onOffer(t);case "answer":return this.onAnswer(t);case "ice":return this.onIce(t);case "peerLeft":return this.onPeerLeft(t);case "migration":return this.onMigration(t);case "matchEnded":return this.onMatchEnded(t);case "error":return this.onSignalingError(t);default:return}}async onHello(e){let t=de(e.playerId),r=de(e.hostPlayerId),i=Pr(e.hostEpoch);if(!(t===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new ln(t,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let t of e)try{await this.onOffer(t);}catch(r){this.report_(r);}}async offerToHost(e){let t=this.hostPlayerId,r=this.openLink(t,Ul),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");Fe(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:kt(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??qp,s=()=>this.closed||e!==this.credentialGeneration,a=$p;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,u;if(m===409)u=Bl;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=a,a=Math.min(a*2,Wl)),u=Math.min(Math.max(u,Bl),Wl);}else throw d;if(!await this.waitForCredential(u,s))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=de(e.fromPlayerId),r=de(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=Np){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=de(e.sessionId);if(i!==null&&this.answeredSessions.get(t)===i)return;Fe(r,"offer"),this.refuseMedia(r,"offer");let o=kt(r);if(o===null)throw new G("invalid_sdp",`the offer from ${t} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(t,i);let s=this.links.get(t);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(t,this.nextPeerId++);a.remoteFingerprint=o,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let 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");Fe(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(t,d,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=de(e.fromPlayerId),r=de(e.sdp);if(t===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||t!==this.hostPlayerId)return;Fe(r,"answer"),this.refuseMedia(r,"answer");let o=kt(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 t=this.credential;return t===null||e.remoteFingerprint===null?false:an(t.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 t=e.pendingAnswer;t!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,t).catch(r=>this.report_(r));}async applyAnswer(e,t){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:t}),this.flushCandidates(e);}async onIce(e){let t=de(e.fromPlayerId),r=de(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=de(e.sdpMid),s=Pr(e.sdpMLineIndex)??Pr(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a);}onPeerLeft(e){let t=de(e.playerId);if(t===null)return;let r=de(e.reason)??"left";if(t===this.localPlayerId){this.fail(new G("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(t);i&&this.dropLink(i,r,true);}async onMigration(e){let t=de(e.hostPlayerId),r=Pr(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,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",t,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",t,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new 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 t=de(e.reason)??"ended";this.ended=t,this.emitter.emit("matchEnded",t),this.ready!==null&&this.fail(new G("match_ended",`the match ended: ${t}`)),this.close();}onSignalingError(e){let t=de(e.code)??"unknown",r=de(e.message)??"the platform refused a signaling message";this.report_(new G("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??so)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of De){let g=i.createDataChannel(p,ao[p]);g.binaryType="arraybuffer",o[p]=g;}let s={playerId:e,assignedPeerId:t,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));},u=()=>{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",u),o.reliable.addEventListener("message",m),s.detachHandshake=()=>{o.reliable.removeEventListener("open",u),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 t=e.pendingCandidates;e.pendingCandidates=[];for(let r of t)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let t=this.credential;if(t===null)throw new G("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=t.expiresAt)throw new G("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(no({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=oo(t);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new G(Nl(r.reason),ql(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,t,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=kt(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 to(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(s){let a=s instanceof G&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",lo(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(ro({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,t,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send(io(t));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let t=e.connection.iceConnectionState;if(!(t!=="failed"&&t!=="disconnected"&&t!=="closed")){if(this.isHost){(t==="failed"||t==="closed")&&this.dropLink(e,t,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,t);}catch(r){this.report_(r);}}}}onConnectionState(e){let t=e.connection.connectionState;t!=="failed"&&t!=="closed"||this.dropLink(e,t,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(t,r="reliable")=>e.channels[r].send(t)}}dropLink(e,t,r){this.links.delete(e.playerId),e.detachAll();for(let i of De)Vl(e.channels[i]);Vl(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,t);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let t=this.ready;this.ready=null,t.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof G?e:new G("connection_failed",lo(e),{cause:e}));}count(e){this.counted||!jp.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(Sr(e))throw new G("media_refused",`the ${t} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(t=>this.options.clock.setTimeout(t,e))}warn(e){let t=this.options.log;t!==null&&(t??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function de(n){return typeof n=="string"&&n.length>0?n:null}function Pr(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function lo(n){return n instanceof Error?n.message:String(n)}function Vl(n){try{n.close();}catch{}}var Up=100,Bp=50,mn=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,t){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:t});}answer(e,t,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:t,assignedPeerId:r});}candidate(e,t,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??Up)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:t,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,t){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:t,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new 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:t,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:t,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let t=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(t),this.dropListener?.(t);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??Bp));}};function H(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function qe(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function Rt(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Hl(n){return typeof n=="boolean"?n:void 0}var be=H(64),pn=qe(0,2147483647);function uo(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=be(t);typeof r=="string"&&e.push(r);}return e}function z(n,e,t){return {to:n,from:e,read:t,required:true}}function K(n,e,t){return {to:n,from:e,read:t,required:false}}var Hp=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=Rt("disconnected","failed","closed")(e.iceState),r=qe(0,4102444800)(e.lastSeenAt);if(!(t===void 0&&r===void 0))return {...t===void 0?{}:{ice_state:t},...r===void 0?{}:{last_seen_timestamp:r}}};Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[z("sdp","sdp",H(10240)),z("signaling_intent","intent",Rt("initial","ice_restart","full_reconnect")),K("sdp_hash","sdpHash",H(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[z("peer_id","peerId",be),z("sdp","sdp",H(10240)),z("assigned_peer_id","assignedPeerId",qe(0,4294967295)),K("sdp_hash","sdpHash",H(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[z("peer_id","peerId",be),z("candidate","candidate",H(512)),K("sdp_mid","sdpMid",H(64)),K("sdp_mline_index","sdpMLineIndex",qe(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[z("host_epoch","hostEpoch",pn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[z("host_epoch","hostEpoch",pn),K("evidence","evidence",Hp)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"}));Object.freeze(Object.assign(Object.create(null),{hello:[z("playerId","player_id",be),z("hostPlayerId","host_player_id",be),z("hostEpoch","host_epoch",pn),K("members","members",uo)],offer:[z("fromPlayerId","from_player_id",be),z("sdp","sdp",H(10240)),K("sessionId","signaling_session_id",H(128)),K("sdpHash","sdp_hash",H(128)),K("iceUfrag","ice_ufrag",H(64)),K("intent","signaling_intent",Rt("initial","ice_restart","full_reconnect"))],answer:[z("fromPlayerId","from_player_id",be),z("sdp","sdp",H(10240)),K("sessionId","signaling_session_id",H(128)),K("sdpHash","sdp_hash",H(128)),K("iceUfrag","ice_ufrag",H(64)),K("assignedPeerId","assigned_peer_id",qe(0,4294967295))],ice:[z("fromPlayerId","from_player_id",be),z("candidate","candidate",H(512)),K("sdpMid","sdp_mid",H(64)),K("sdpMLineIndex","sdp_m_line_index",qe(0,255)),K("sdpMLineIndexAlt","sdp_mline_index",qe(0,255))],peerJoined:[z("playerId","player_id",be)],peerLeft:[z("playerId","player_id",be),K("reason","reason",H(64))],migration:[z("hostPlayerId","new_host_player_id",be),z("hostEpoch","host_epoch",pn),K("reason","reason",H(64)),K("kickedPlayerIds","kicked_player_ids",uo),K("migrationComplete","migration_complete",Hl)],matchEnded:[K("reason","reason",H(64))],error:[K("code","code",H(64)),K("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 Ze="webrtc_p2p";function Jl(n){let e=new on({client:n.client,gameId:n.gameId}),t=new Map;return {handleSignalEvent(r,i,o){t.get(r)?.handleSignal(i,o);},session(r){return t.get(r)??null},async connect(r={}){if(n.bridge===null)throw new 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=ge(r.clusterTargetId),o=i??ge(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let s=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==Ze)throw new G("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${Ze}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new mn({bridge:n.bridge,matchId:s.matchId,clock:n.clock}),l=new un({api:e,clock:n.clock,matchId:s.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:a,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await dn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});a.onDropped(d=>l.notifyCandidatesDropped(d)),t.set(s.matchId,l),l.on("matchEnded",()=>t.delete(s.matchId));try{await l.start(r.signal);}catch(d){throw t.delete(s.matchId),l.close(),d}return l}}}function zl(n){let{analytics:e,rooms:t}=n,r=n.target??globalThis,i=n.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(!Xe());for(let d of _r)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(!Xe());}let s=new Map;return o.push(t.on("matchReady",a=>{let l=a.protocol===Ze?"p2p":"dedicated";s.set(a.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),o.push(t.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 Yl=["pointerdown","keydown"];function Xl(n,e=globalThis){let t=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 Yl)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},a=()=>{if(!(t||r)){t=true,s();try{n();}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(b=>b.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},u=()=>{if(i=null,!(t||r)){if(d()){a();return}m()&&(i=e.requestAnimationFrame?.(u)??null);}};function p(){i===null&&!t&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of Yl)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(i=e.requestAnimationFrame?.(u)??null);}return {get engaged(){return t},stop:s}}async function Tr(n,e,t,r){let i=await t;return n.mark(e)&&r&&r(`[gem] boot: ${n.timeline()}`),i}function mo(n,e){let t=false;return async r=>{let i=await r;return !t&&e&&(t=true,e(`[gem] boot: ${n.timeline()}`)),i}}function po(n={}){let e=n.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),t=[],r=new Set;return {marks:t,mark(i,o){return r.has(i)?false:(r.add(i),t.push({name:i,at:o??e()}),true)},timeline(){let i=[...t].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 Kp="GemWebSdkHandshake";var Jp=()=>Date.now();function Ql(n,e,t={}){let r=n[Kp];if(r===void 0)return null;let i=t.ttlMs??9500,o=t.now??Jp,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,m=false,u=o()-i;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(s[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var go=false;async function nd(n,e,t,r){if(go){e.close(),t("busy",true);return}go=true;let i=null;try{let o=await Yp(n,r);if(typeof o=="string"){e.close(),t(o,zp(o));return}i=o;let a=await(r.encodeRef??(l=>eg(l,r)))(i);if(i.close(),i=null,a===null){e.close(),t("failed",!0);return}if(a.size>Zp){e.close(),t("too_large",!1);return}e.postMessage(a);}catch(o){e.close(),t("failed",true),console.error("[gem] screenshot capture failed",o);}finally{go=false,i?.close();}}function zp(n){switch(n){case "no_source":case "busy":case "failed":return true;case "not_wired":case "unsupported":case "unreadable":case "tainted":case "too_large":case "declined":return false}}async function Yp(n,e){if(e.handler){let o=await e.handler(n);return o===null?"declined":Zl(o,n)}if(!e.useDefaultStrategy)return "not_wired";let t=e.documentRef??globalThis.document;if(!t)return "no_source";let r=Qp(t);if(!r)return "no_source";let i=Xp(r);if(i!==null)return i;try{return Zl(await createImageBitmap(r),n)}catch(o){if(o instanceof DOMException&&o.name==="SecurityError")return "tainted";throw o}}function Xp(n){let e;try{e=n.getContext("webgl2")??n.getContext("webgl");}catch{return "unreadable"}if(e){let t=e.getContextAttributes();return !t||t.preserveDrawingBuffer!==true?"unsupported":null}try{if(n.getContext("2d"))return null}catch{return "unreadable"}return "unreadable"}function Qp(n){let e=null,t=0;for(let r of Array.from(n.querySelectorAll("canvas"))){let i=r.width*r.height;i<=0||r.clientWidth<=0||r.clientHeight<=0||i>t&&(e=r,t=i);}return e}async function Zl(n,e){let{maxWidth:t,maxHeight:r}=e;if(n.width<=t&&n.height<=r)return n;let i=Math.min(t/n.width,r/n.height),o=Math.max(1,Math.floor(n.width*i)),s=Math.max(1,Math.floor(n.height*i));try{let a=await createImageBitmap(n,{resizeWidth:o,resizeHeight:s,resizeQuality:"high"});return n.close(),a}catch{return n.close(),"too_large"}}var Zp=8*1024*1024,ed="image/webp",td=.92;async function eg(n,e){try{if(typeof OffscreenCanvas=="function"){let o=new OffscreenCanvas(n.width,n.height),s=o.getContext("2d");if(s){s.drawImage(n,0,0);let a=await o.convertToBlob({type:ed,quality:td});if(a&&a.size>0)return a}}}catch{}let t=e.documentRef??globalThis.document;if(!t)return null;let r=t.createElement("canvas");r.width=n.width,r.height=n.height;let i=r.getContext("2d");return !i||(i.drawImage(n,0,0),typeof r.toBlob!="function")?null:await new Promise(o=>{r.toBlob(s=>o(s),ed,td);})}async function rd(n,e){if(!e)return;let t;try{t=await tg(e);}catch(r){console.error("[gem] onFeedbackContext threw; sending the report without context",r);return}if(t!=null){if(typeof t!="object"||Array.isArray(t)){console.error("[gem] onFeedbackContext must return a plain object or null; got",t);return}n.sendGameContext(t);}}function tg(n){return new Promise((e,t)=>{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()=>n())().then(o=>{r||(r=true,clearTimeout(i),e(o??null));},o=>{r||(r=true,clearTimeout(i),t(o instanceof Error?o:new Error(String(o))));});})}var id=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function od(n=globalThis){let t=n[id];if(t!==void 0)return t;let r=false,i=()=>r,o=[],s=ng(n,i);s!==null&&o.push(s);let a=rg(n,i);a!==null&&o.push(a);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let u of o)u();}}};return Object.defineProperty(n,id,{value:l,configurable:true}),l}function ng(n,e){let t=n.AudioNode?.prototype,r=n.AudioDestinationNode;if(t===void 0||r===void 0)return null;let i=n.OfflineAudioContext,o=t.connect,s=t.disconnect,a=new Map,l=m=>{let u=m.gain,p=m.context.currentTime;u.cancelScheduledValues(p),e()?u.setValueAtTime(0,p):u.setTargetAtTime(1,p,.01);},d=m=>{let u=m.context;if(i!==void 0&&u instanceof i)return null;let p=a.get(u);return p===void 0&&(p=u.createGain(),p.gain.value=e()?0:1,o.call(p,m),a.set(u,p)),p};return t.connect=function(...u){let[p,...g]=u;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,u)},t.disconnect=function(...u){let[p,...g]=u;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,u)},()=>{for(let[m,u]of a){if(m.state==="closed"){a.delete(m);continue}try{l(u);}catch{}}}}function rg(n,e){let t=n.HTMLMediaElement;if(t===void 0)return null;let r=t.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,u=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),u(this);}}),r.play=function(){try{u(this);}catch{}return a.call(this)},n.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof t)try{u(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 ig=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",og=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',ag=`${ig}${og}`,yo=new WeakSet;function ad(n=globalThis.document){if(n==null||yo.has(n))return null;try{let e=n.defaultView?.CSSStyleSheet??globalThis.CSSStyleSheet;if(Array.isArray(n.adoptedStyleSheets)&&typeof e=="function"){let r=new e;if(typeof r.replaceSync=="function")return r.replaceSync(ag),n.adoptedStyleSheets=[...n.adoptedStyleSheets,r],yo.add(n),"sheet"}let t=n.documentElement?.style;return t===void 0||typeof t.setProperty!="function"?null:(t.setProperty("-webkit-user-select","none"),t.setProperty("user-select","none"),t.setProperty("-webkit-tap-highlight-color","transparent"),yo.add(n),"inline")}catch{return null}}function sd(n){let e=n.windowMs??1e3,t=n.realm??globalThis,r=false,i=false,o=false,s=null,a=null,l=null,d=[],m=()=>r&&!i&&!o,u=()=>{a=null,l=null,d=[];},p=b=>{if(s=null,!m()){u();return}if(l!==null&&d.push(b-l),l=b,a===null)a=b;else {let R=b-a;R>=e&&d.length>0&&(n.report(sg(d,R)),a=b,d=[]);}g();},g=()=>{let b=t.requestAnimationFrame;typeof b=="function"&&(s=b.call(t,p));},y=()=>{if(m()){s===null&&(u(),g());return}s!==null&&(t.cancelAnimationFrame?.call(t,s),s=null),u();};return {setRequested(b){r=b,y();},setPaused(b){i=b,y();},get running(){return s!==null},dispose(){o=true,y();}}}function sg(n,e){let t=[...n].sort((i,o)=>i-o),r=Math.max(1,Math.ceil(t.length*.95));return {fps:n.length*1e3/e,frameTimeP95Ms:t[r-1]}}var Er=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function dd(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function cd(n,e){n!==null&&(n.style.setProperty(Er.top,`${e.top}px`),n.style.setProperty(Er.right,`${e.right}px`),n.style.setProperty(Er.bottom,`${e.bottom}px`),n.style.setProperty(Er.left,`${e.left}px`));}var ld=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height"}});function ud(){let n=globalThis,e=n.innerWidth,t=n.innerHeight;return typeof e=="number"&&e>0&&typeof t=="number"&&t>0?{width:e,height:t}:null}function lg(n,e){let t={tl:{width:0,height:0},tr:{width:0,height:0},bl:{width:0,height:0},br:{width:0,height:0}};for(let r of n){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=t[`${o?"t":"b"}${i?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));}return t}function md(n,e,t){if(n===null)return;let r=lg(e,t);for(let i of ["tl","tr","bl","br"])n.style.setProperty(ld[i].width,`${r[i].width}px`),n.style.setProperty(ld[i].height,`${r[i].height}px`);}var dg=3e4,Ir=class extends Error{retryable;reason;constructor(e,t,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=t;}};function pd(n){let e=n.clock??fe,t=n.timeoutMs??dg,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 n.bridge.parentSupports("localHost")},ensure(a){if(!n.bridge.parentSupports("localHost"))return Promise.resolve();let l=i.get(a);if(l)return l;let d=new Promise((m,u)=>{let p=`ls${++o}`,g=e.setTimeout(()=>{r.delete(p),i.delete(a),u(new Ir("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(t)}ms`));},t);r.set(p,{room:a,resolve:m,reject:u,timer:g}),n.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 Ir(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 gn={url:"https://downloads.indiegems.games/sdk/v13.2.2/gem-web-sdk.devtools.min.js",integrity:"sha384-7EKF4anUfs6zZEL5q8T/wiVysDlKyCZifLknlw/3uREV2M9PaFkA6jvzDigJ1eWd"};var xt=null;function cg(){return xt!==null||(xt=new Promise((n,e)=>{let t=document.createElement("script");t.src=gn.url,t.integrity=gn.integrity,t.crossOrigin="anonymous",t.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){xt=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${gn.url} is not a gem-web-sdk devtools build.`));return}n(r);},t.onerror=()=>{xt=null,e(new Error(`gem devtools: could not load ${gn.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(t);})),xt}function gd(n,e){let t=null,r=0;async function i(o){if(t!==null)return true;let s=++r;if(!e())return false;let a=await cg();return !e()||s!==r?false:(t!==null||(t=a.mount(n(),{openedBy:o,text:pt,onDismiss:()=>{t?.unmount(),t=null;}})),true)}return {get isOpen(){return t!==null},close(){r+=1,t?.unmount(),t=null;},open:()=>i("game"),openFrom:i}}var ug=1e4,yd={reason:"unavailable",retryable:false};function fd(n){let e=new Map,t=null,r=null,i=0,o=(d,m)=>{m.timer=n.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},n.timeoutMs??ug);},s=(d,m)=>{let u=a(d);u&&m(u);},a=d=>{let m=e.get(d);return m?(e.delete(d),n.clock.clearTimeout(m.timer),m):null},l=new dt({clock:n.clock,onStateChange:n.onStateChange,request:d=>new Promise((m,u)=>{let p=n.bridge.currentState;if(p==="refused"||p==="closed"){u(yd);return}let g=`t${++i}`,y={resolve:m,reject:u,reason:d,timer:null,held:p!=="connected"};e.set(g,y),o(g,y),y.held||n.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(t={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){s(d.requestId,u=>u.resolve(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,u]of e)u.held&&(u.held=false,n.clock.clearTimeout(u.timer),o(m,u),n.bridge.requestToken(m,u.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])s(m,u=>u.reject(yd));},get identity(){return t},get gameVersion(){return r}}}function mg(n){let e=n.lastIndexOf("@");return (e===-1?n:`***@${n.slice(e+1)}`).slice(0,200)}var pg=new Set(Jr);function gg(n){if(!n)return {};let e={};for(let[t,r]of Object.entries(n))pg.has(t.toLowerCase())&&(e[t.toLowerCase()]=r);return e}function Cr(n){let e=n.fetch??globalThis.fetch.bind(globalThis);return Zo(async(t,r)=>{let i;try{i=new URL(n.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(/\/+$/,"")+t.path);}catch{throw new se(`${JSON.stringify(typeof t.path=="string"?mg(t.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,b=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new se(`the ${b} puts credentials in the URL, which cannot be fetched (${t.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(n.defaultQuery??{}))o.searchParams.has(g)||o.searchParams.set(g,y);let s=t.bytes,a=t.bytes===void 0?void 0:"application/octet-stream";try{t.body!==void 0&&(s=JSON.stringify(t.body),a="application/json");}catch(g){throw new se(`the body of ${t.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:t.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...gg(t.headers)},body:s,signal:t.signal,...t.keepalive===void 0?{}:{keepalive:t.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(t.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),u=yg(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...u===void 0?{}:{retryAfterSeconds:u},...p===null||p===""?{}:{invocationId:p}}},n)}function yg(n){if(n===null)return;let e=n.trim();if(!/^\d+$/.test(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0}var fg=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),ho="embedder_relay_unavailable",hg="embedder_no_relay",bg=new Set([ho]),bo=new Set([hg]),yn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new fo(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.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){t.refuse(new w("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(vg(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new w("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,t);}release(e,t){this.pending.get(e)===t&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new 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 vg(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new w(_g(n),r,{platformCode:n})}function _g(n){return n===void 0||bg.has(n)?"signaling_failed":bo.has(n)?"offer_refused":fg.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var fo=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){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 t?.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=()=>{t?.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,t?.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 hd="match_ended:",bd="server_shutdown:",vd="kicked:",wg=123;function kg(n){if(typeof n!="string"||n.length===0||n.length>wg)return {kind:"other"};if(n.startsWith(hd)){let e=ht(n.slice(hd.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(bd)?{kind:"server_shutdown",cause:n.slice(bd.length)}:n.startsWith(vd)?{kind:"kicked",detail:n.slice(vd.length)}:{kind:"other"}}function vo(n,e,t){let r=kg(t),i=r.kind==="kicked"?"kicked":"link_closed";n.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&n.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function _o(){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 Rg=3e3,Sg=1e4,xg=15e3;async function Mr(n){let e=n.peerConnection;try{wd(n,"before the handshake started"),wo(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let s of n.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});n.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await Tg(e,n),wo(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new w("invalid_sdp","the offer carried no SDP");Fe(i,"offer"),_d(i,"offer");let o=await Pg(n,i);if(wo(n),typeof o?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return Fe(o.sdp,"answer"),_d(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Eg(t,n),wd(n,"before the channel opened"),t}catch(t){throw e.close(),Ag(t)}}function Ag(n){return n instanceof w?n:Sd(n)?et():new w("connection_failed",xd(n),{cause:n})}function _d(n,e){if(Sr(n))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 Pg(n,e){let t=n.exchangeTimeoutMs??Sg,r=Rd(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof w?o:Sd(o)?et():new w("signaling_failed",xd(o),{cause:o})});return Ig(i,n,r,()=>r.exhausted?ko("while the offer was in flight"):new w("timeout",`no answer arrived within ${t}ms`))}function Tg(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(s),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},s=t.setTimeout(i,e.gatherTimeoutMs??Rg);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Eg(n,e){if(e.signal?.aborted)return Promise.reject(et());if(n.readyState==="open")return Promise.resolve();if(n.readyState!=="connecting")return Promise.reject(new w("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??xg,i=Rd(e,r);return new Promise((o,s)=>{let a=()=>{t.clearTimeout(p),n.removeEventListener("open",l),n.removeEventListener("close",d),n.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",kd(g)===void 0?void 0:{cause:kd(g)}));},m=()=>{a(),s(et());},u=()=>{a(),s(i.exhausted?ko("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},p=t.setTimeout(u,i.ms);n.addEventListener("open",l),n.addEventListener("close",d),n.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Rd(n,e){if(n.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let t=n.credentialExpiresAt-n.clock.now();return t<=e?{ms:Math.max(0,t),exhausted:true}:{ms:e,exhausted:false}}function Ig(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(et()):new Promise((s,a)=>{let l=u=>{i.clearTimeout(m),o?.removeEventListener("abort",d),u();},d=()=>l(()=>a(et())),m=i.setTimeout(()=>l(()=>a(r())),t.ms);o?.addEventListener("abort",d),n.then(u=>l(()=>s(u)),u=>l(()=>a(u)));})}function wd(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw ko(`already ${e}`)}function ko(n){return new w("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function wo(n){if(n.signal?.aborted)throw et()}function et(){return new w("aborted","the caller aborted the connection attempt")}function Sd(n){return n?.name==="AbortError"}function kd(n){return n?.error}function xd(n){return n instanceof Error?n.message:String(n)}Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"}));Object.freeze(Object.assign(Object.create(null),{answer:[z("sdp","sdp",H(10240)),K("sessionId","session_id",H(64))],error:[K("code","code",H(64)),K("message","message",H(256))],matchEnded:[K("reason","reason",H(64))]}));function Od(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??_o,o=n.log??(h=>console.warn(h)),s=new wt({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&&!So(r)&&r.currentRoom?.matchId===void 0){let k=ge(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 Cd(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Ro(h)):await r.awaitMatch(Ro(h)))},u=async h=>Cd(await r.pollMatchStatus(Ro(h))),p=async(h,k)=>{let C=false;try{let E=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 D=h.peerConnection??Md();C=!0;let q=await Mr({peerConnection:D,signaling:k,clock:t,matchId:E.matchId,credentialExpiresAt:E.credentialExpiresAt,...Or(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),P=null;if(h.presentCredential!==!1)try{P=await zt({channel:q,clock:t,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,...Or(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(M){throw Se(q),Se(D),M}return qg(r,E,q,D,k,h.reportDisconnect!==!1,h.reportConnected!==!1,P,{remember:l,forget:d},h.onMatchEnded)}catch(E){throw C&&Id(s,E),Se(k),E}},g=async(h,k,C,E,W,D)=>{if(h==="webtransport"){let U=E?.webtransport;if(U===void 0)throw new w("misconfigured","webtransport is not advertised");let V={credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,clock:t};if(typeof U.named_url=="string"&&U.named_url!==""){let oe=Math.max(Math.floor(D/2),1e3);try{return await Zt({url:U.named_url,timeoutMs:oe,log:o,...V})}catch(ae){if(hr()!==null)throw ae;return o(`[gem] webtransport named dial failed (${yr(ae)}); retrying the pinned dial`),Zt({url:U.url,certHashBase64:U.cert_sha256_b64,timeoutMs:oe,log:o,...V})}}return Zt({url:U.url,certHashBase64:U.cert_sha256_b64,timeoutMs:D,...V})}if(h==="websocket"){let U=E?.websocket;if(U===void 0)throw new w("misconfigured","websocket is not advertised");return Bi({url:U.url,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,clock:t,timeoutMs:D})}let q=k.peerConnection??Md(),P,M=await Mr({peerConnection:q,signaling:W,clock:t,matchId:C.matchId,credentialExpiresAt:C.credentialExpiresAt,extraChannels:[{label:Xt,ordered:false,maxRetransmits:0}],onExtraChannel:(U,V)=>{U===Xt&&(P=V);},...Or(k,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...k.exchangeTimeoutMs===void 0&&k.redial===true?{exchangeTimeoutMs:Og}:{}}),L;try{L=await zt({channel:M,clock:t,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,wire:gr,heartbeat:!0,...Or(k,"signal"),...k.welcomeTimeoutMs===void 0?{}:{ceilingMs:k.welcomeTimeoutMs}});}catch(U){throw Se(M),Se(q),U}let j=L.welcome.heartbeatIntervalMs;return {link:Vi(M,q,P,j===void 0?void 0:{clock:t,intervalMs:j}),welcome:L.welcome,channel:M,peerConnection:q}},y=(h,k,C,E,W)=>{let D=false,q;E.link.onClose(j=>{!D&&h.reportDisconnect!==false&&vo(r,k.matchId,j),q?.(j);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(k.matchId);let P={transport:E.link.transport,send:(j,U)=>E.link.send(j,U),onMessage:j=>E.link.onMessage(j),onClose:j=>{q=j;},close:()=>E.link.close()},M=()=>{D||(D=true,Se(E.link),Se(W));},L=j=>{if(!D){try{h.onMatchEnded?.(j);}catch{}M();}};return l(k.matchId,L),{matchId:k.matchId,transport:C,link:P,joinCredential:k.joinCredential,credentialExpiresAt:k.credentialExpiresAt,welcome:E.welcome,...E.channel===void 0?{}:{channel:E.channel},...E.peerConnection===void 0?{}:{peerConnection:E.peerConnection},close(){d(k.matchId,L),M();}}},b=async(h,k)=>{let C=r.currentRoom?.id,E=r.gameId,W=()=>({advert:Qt(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(C===void 0||E===null)return W();try{let D=await e.get(`/v2/games/${encodeURIComponent(E)}/game-rooms/${encodeURIComponent(C)}`,k);return {advert:Qt(D.settings,h),template:vt(D.transports)??r.currentRoom?.transports??null}}catch{return W()}},R=(h,k)=>{let C=h??Ad;return k.length===0?C:C.filter(E=>k.includes(E))},x=async(h,k,C)=>{try{let E=await m(h),{advert:W,template:D}=await b(E.matchId,h.signal),q=R(D,k),P=q.filter(X=>Dg(X,W)),M=hr();if(M!==null&&q.includes("webtransport")&&W?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${M} (learned on an earlier dial in this page)`),P.length===0){let X=D===null?`the default order (${Ad.join(", ")})`:`the room template's transports (${D.join(", ")||"none"})`;throw new w("misconfigured",`none of ${X}`+(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??Mg,j=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-t.now(),U=X=>n.signalingReady===void 0||X<=0?Promise.resolve(!0):n.signalingReady(X),V=[],oe=[];for(let X of P){if(j()<Td){o(`[gem] ${X} rung not tried: the reconnect budget is spent`);break}oe.length>0&&E.credentialExpiresAt-t.now()<Ed&&(E=await u(h)),oe.push(X);let Ne=!1,me=!1,ke={attempts:0,waitedMs:0};for(;;){if(X==="webrtc"&&h.redial===!0){let Z=Math.min(Pd,j());await U(Z)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Z)}ms; offering anyway`);}let je=Math.max(Math.min(L,j()),Td);try{return y(h,E,X,await g(X,h,E,W,C,je),C)}catch(Z){let J=Z instanceof w?Z:new w("connection_failed",Z instanceof Error?Z.message:String(Z),{cause:Z});if(X==="webrtc"&&Id(s,J),(J.reason==="credential_expired"||J.reason==="credential_reused")&&!Ne){Ne=!0,E=await u(h);continue}if(X==="webrtc"&&J.reason==="signaling_failed"&&J.platformCode===ho&&!me){me=!0;let ee=Math.min(Pd,j());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ee)}ms for the socket before offering again`),await U(ee))continue}if(J.reason==="join_rate_limited"){let ee=Gg(ke,Math.random,j());if(ee!==null){if(ke.attempts+=1,ke.waitedMs+=ee,o(`[gem] ${X} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ee)}ms before presenting again (retry ${ke.attempts} of ${Gd.maxAttempts})`),await cr(t,ee,h.signal),h.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");E.credentialExpiresAt-t.now()<Ed&&(E=await u(h));continue}}if(Lg.has(J.reason)||J.reason==="credential_expired"||X==="webrtc"&&Ld(J)){o(`[gem] ${X} rung failed (${J.reason}): ${yr(J.cause??J)} \u2014 `+(oe.length<P.length?`falling through to ${P[oe.length]}`:"no rungs left")),V.push(J);break}throw o(`[gem] ${X} rung refused the session (${J.reason}): ${J.message}`),J}}}let ae=V[V.length-1];throw ae===void 0?new w("timeout",`the reconnect budget ran out before any transport (${P.join(", ")}) could be tried`):new w(ae.reason,`every transport tried (${oe.join(", ")}) failed; the last said: ${ae.message}`,{cause:V,platformCode:ae.platformCode})}catch(E){throw Se(C),E}};return {listClusterTargets:async(h={})=>Ti({client:e,...h}),handleMatchEnded(h,k){let C=a.get(h);if(C!==void 0){a.delete(h);for(let E of C)E(k);}},connect:(async(h={})=>{let k=h.signaling??i();return h.transports===void 0?p(h,k):x(h,h.transports,k)})}}var Ad=["webtransport","webrtc","websocket"],Mg=1e4,Og=5e3,Pd=3e3,Td=1e3,Ed=1e4,Lg=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Ld(n){return n.platformCode!==void 0&&bo.has(n.platformCode)}var Gd={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Gg(n,e=Math.random,t=1/0){let r=Gd;if(n.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-n.waitedMs,t);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**n.attempts;return Math.min(o+e()*r.jitterMs,i)}function Dg(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&fr():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||$g(e.websocket.url)}function $g(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return Gn(e)}function Ro(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var Fg=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Id(n,e){e instanceof w&&(!Fg.has(e.reason)&&!Ld(e)||n.report([{type:"connection_failures_total",value:1}]));}function qg(n,e,t,r,i,o,s,a,l,d){let m=false,u=()=>{m||vo(n,e.matchId,void 0);};o&&(t.addEventListener("close",u),s&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",u),a?.detach(),Se(t),Se(r),Se(i));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function So(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function Cd(n){if(n.status==="failed")throw new w("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new w("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==dr)throw new w("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${dr}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:t}=n;if(e===void 0||t===void 0)throw new w("connection_failed",`match ${n.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...n,joinCredential:e,credentialExpiresAt:t}}function Md(){let n=globalThis.RTCPeerConnection;if(!n)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 n({iceServers:[]})}function Se(n){try{n.close();}catch{}}function Or(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var Ng=1e4;function Dd(n,e){if(typeof n.serverToken!="function"||typeof n.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 t=s=>({token:s.token,expiresAt:s.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,i=new dt({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??Ng);r={resolve:d=>{e.clock.clearTimeout(l),s(d);},reject:a,timer:l};})}),o=n.onServerToken(s=>{let a=t(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 Ao={};Fc(Ao,{acceptTransfer:()=>jg,addEntityProgression:()=>Ug,adminAction:()=>Bg,cancelInventoryTransfer:()=>Wg,claimEntityProgressionRewards:()=>Vg,closeGameRoom:()=>Hg,createEntityBatchOrder:()=>Kg,createEntityOrder:()=>Jg,createSession:()=>zg,deleteEntityGameSetting:()=>Yg,deleteEntitySave:()=>Xg,deleteSession:()=>Qg,deleteShowcaseValue:()=>Zg,executeEntityRecipe:()=>ey,finalizeSaveUpload:()=>ty,getChannelAssignment:()=>ny,getDropRates:()=>ry,getEntityCurrency:()=>iy,getEntityGameSetting:()=>oy,getEntityInventory:()=>ay,getEntityInventoryItem:()=>sy,getEntityLeaderboard:()=>ly,getEntityOrder:()=>dy,getEntityProgression:()=>cy,getEntityRecipeAvailability:()=>uy,getEntityRecipeUsage:()=>my,getEntitySave:()=>py,getEvent:()=>gy,getGameRoomV2:()=>yy,getLeaderboard:()=>fy,getPlayerGameProfile:()=>hy,getPurchaseCatalog:()=>by,getResolvedTemplate:()=>vy,getRoomArgs:()=>_y,getShowcaseValue:()=>wy,getTransferDetails:()=>ky,ingestAnalyticsEvents:()=>xo,initiateInventoryTransfer:()=>Ry,invokeFunction:()=>Sy,kickPlayer:()=>xy,listChallenges:()=>Ay,listEntityGameSettings:()=>Py,listEntityOrders:()=>Ty,listEntityProgressions:()=>Ey,listEntitySaves:()=>Iy,listEvents:()=>Cy,listGameRooms:()=>My,listResolvedTemplates:()=>Oy,listTransfers:()=>Ly,maxEntityProgression:()=>Gy,putEntityGameSetting:()=>Dy,putRoomArgs:()=>$y,putShowcaseValue:()=>Fy,rejectTransfer:()=>qy,reportMatchPlayers:()=>Ny,requestSaveUploadUrl:()=>jy,resetEntityProgression:()=>Uy,setMatchBackfill:()=>By,simulateEntityOrder:()=>Wy,transferHostV2:()=>Vy,updateGameRoomV2:()=>Hy});function v(n){let e=String(n);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function jg(n,e,t){let r=`/v1/inventory/transfers/${v(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function Ug(n,e,t,r,i,o){let s=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/add`;return n.client.post(s,i,o?.signal)}async function Bg(n,e,t,r){let i=`/v1/voice/sessions/${v(e)}/admin`;return n.client.post(i,t,r?.signal)}async function Wg(n,e,t){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function Vg(n,e,t,r,i,o){let s=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/claim`;return n.client.post(s,i,o?.signal)}async function Hg(n,e,t){let r=`/v1/games/${v(n.gameId())}/game-rooms/${v(e)}`;return n.client.delete(r,t?.signal)}async function Kg(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/orders/batch`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Jg(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/orders`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function zg(n,e,t){return n.client.post("/v1/voice/sessions",e,t?.signal)}async function Yg(n,e,t,r,i){let o=`/v1/settings/${v(e)}/${v(t)}/${v(r)}`;return n.client.delete(o,i?.signal)}async function Xg(n,e,t,r,i){let o=`/v1/saves/${v(e)}/${v(t)}/${v(r)}`;return n.client.delete(o,i?.signal)}async function Qg(n,e,t){let r=`/v1/voice/sessions/${v(e)}`;return n.client.delete(r,t?.signal)}async function Zg(n,e,t,r){let i=`/v1/showcase/players/${v(e)}/${v(t)}`;return n.client.delete(i,r?.signal)}async function ey(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/recipes/execute`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ty(n,e,t,r,i,o){let s=`/v1/saves/${v(e)}/${v(t)}/${v(r)}/finalize`;return n.client.post(s,i,o?.signal)}async function ny(n,e,t){let r=`/v1/games/${v(n.gameId())}/config/channels/${v(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function ry(n,e,t){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function iy(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/currencies/${v(r)}`;return n.client.get(o,i?.signal)}async function oy(n,e,t,r,i){let o=`/v1/settings/${v(e)}/${v(t)}/${v(r)}`;return n.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function ay(n,e,t,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/${v(e)}/${v(t)}`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function sy(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/items/${v(r)}`;return n.client.get(o,i?.signal)}async function ly(n,e,t,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/${v(e)}/${v(t)}/${v(r)}`+(s?`?${s}`:"");return n.client.get(a,i?.signal)}async function dy(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/orders/${v(r)}`;return n.client.get(o,i?.signal)}async function cy(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}`;return n.client.get(o,i?.signal)}async function uy(n,e,t,r,i,o){let s=`/v1/inventory/${v(e)}/${v(t)}/catalogs/${v(r)}/recipes/${v(i)}/availability`;return n.client.get(s,o?.signal)}async function my(n,e,t,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${v(e)}/${v(t)}/recipe-usage`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function py(n,e,t,r,i){let o=`/v1/saves/${v(e)}/${v(t)}/${v(r)}`;return n.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function gy(n,e,t){let r=`/v1/events/${v(e)}`;return n.client.get(r,t?.signal)}async function yy(n,e,t){let r=`/v2/games/${v(n.gameId())}/game-rooms/${v(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function fy(n,e,t){let r=new URLSearchParams;t?.bucket_1!==void 0&&r.set("bucket_1",String(t?.bucket_1)),t?.bucket_2!==void 0&&r.set("bucket_2",String(t?.bucket_2)),t?.periods_back!==void 0&&r.set("periods_back",String(t?.periods_back)),t?.period!==void 0&&r.set("period",String(t?.period)),t?.player_id!==void 0&&r.set("player_id",String(t?.player_id));let i=r.toString(),o=`/v1/leaderboards/${v(e)}`+(i?`?${i}`:"");return n.client.get(o,t?.signal)}async function hy(n,e,t){let r=`/v1/profiles/players/${v(e)}`;return n.client.get(r,t?.signal)}async function by(n,e){let t=new URLSearchParams;e?.config_version!==void 0&&t.set("config_version",String(e?.config_version));let r=t.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function vy(n,e,t){let r=`/v1/game-room-templates/${v(e)}`;return n.client.get(r,t?.signal)}async function _y(n,e,t){let r=`/v1/games/${v(n.gameId())}/game-rooms/${v(e)}/room-args`;return n.client.get(r,t?.signal)}async function wy(n,e,t,r){let i=`/v1/showcase/players/${v(e)}/${v(t)}`;return n.client.get(i,r?.signal)}async function ky(n,e,t){let r=`/v1/inventory/transfers/${v(e)}`;return n.client.get(r,t?.signal)}async function xo(n,e,t){let r=`/v1/games/${v(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{replaySafe:true,retryRateLimited:false})}async function Ry(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Sy(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function xy(n,e,t,r){let i=`/v1/games/${v(n.gameId())}/game-rooms/${v(e)}/kick/${v(t)}`;return n.client.post(i,void 0,r?.signal)}async function Ay(n,e){let t=new URLSearchParams;e?.periods_back!==void 0&&t.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&t.set("player_id",String(e?.player_id));let r=t.toString(),i="/v1/challenges"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Py(n,e,t,r){let i=`/v1/settings/${v(e)}/${v(t)}`;return n.client.get(i,r?.signal)}async function Ty(n,e,t,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/${v(e)}/${v(t)}/orders`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Ey(n,e,t,r){let i=`/v1/inventory/${v(e)}/${v(t)}/progressions`;return n.client.get(i,r?.signal)}async function Iy(n,e,t,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/${v(e)}/${v(t)}`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Cy(n,e){let t=new URLSearchParams;e?.include_inactive!==void 0&&t.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&t.set("limit",String(e?.limit)),e?.offset!==void 0&&t.set("offset",String(e?.offset));let r=t.toString(),i="/v1/events"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function My(n,e){let t=new URLSearchParams;e?.status!==void 0&&t.set("status",String(e?.status)),e?.game_channel!==void 0&&t.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&t.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&t.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&t.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&t.set("limit",String(e?.limit)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor));let r=t.toString(),i=`/v1/games/${v(n.gameId())}/game-rooms`+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Oy(n,e){return n.client.get("/v1/game-room-templates",e?.signal)}async function Ly(n,e){let t=new URLSearchParams;e.entity_type!==void 0&&t.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&t.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&t.set("direction",String(e?.direction)),e?.status!==void 0&&t.set("status",String(e?.status)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor)),e?.limit!==void 0&&t.set("limit",String(e?.limit));let r=t.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Gy(n,e,t,r,i,o){let s=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/max`;return n.client.post(s,i,o?.signal)}async function Dy(n,e,t,r,i,o){let s=`/v1/settings/${v(e)}/${v(t)}/${v(r)}`;return n.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function $y(n,e,t,r){let i=`/v1/games/${v(n.gameId())}/game-rooms/${v(e)}/room-args`;return n.client.put(i,t,r?.signal)}async function Fy(n,e,t,r,i){let o=`/v1/showcase/players/${v(e)}/${v(t)}`;return n.client.put(o,r,i?.signal)}async function qy(n,e,t){let r=`/v1/inventory/transfers/${v(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function Ny(n,e,t,r){let i=`/v1/games/${v(n.gameId())}/matches/${v(e)}/players/report`;return n.client.post(i,t,r?.signal)}async function jy(n,e,t,r,i,o){let s=`/v1/saves/${v(e)}/${v(t)}/${v(r)}/upload-url`;return n.client.post(s,i,o?.signal,{replaySafe:true})}async function Uy(n,e,t,r,i,o){let s=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/reset`;return n.client.post(s,i,o?.signal)}async function By(n,e,t,r){let i=`/v1/games/${v(n.gameId())}/matches/${v(e)}/backfill`;return n.client.put(i,t,r?.signal)}async function Wy(n,e,t,r,i){let o=`/v1/inventory/${v(e)}/${v(t)}/orders/simulate`;return n.client.post(o,r,i?.signal)}async function Vy(n,e,t,r){let i=`/v2/games/${v(n.gameId())}/game-rooms/${v(e)}/transfer/${v(t)}`;return n.client.post(i,void 0,r?.signal)}async function Hy(n,e,t,r){let i=`/v2/games/${v(n.gameId())}/game-rooms/${v(e)}`;return n.client.patch(i,t,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Ky=1e4,Jy=50,zy=1e3,Yy=65536-4*1024,$d=n=>typeof n=="number"?n:0,Xy=n=>typeof n=="string"?n:"";function Fd(){let n=globalThis.crypto;return typeof n?.randomUUID=="function"?n.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return (e==="x"?t:t&3|8).toString(16)})}function Qy(n){return n?.retryable===true}function Zy(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(i=>{let o=i??{};return {index:$d(o.index),code:Xy(o.code)}}):[];return {accepted:$d(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function qd(n,e){return {event_uid:n.uid,name:n.name,offset_ms:Math.round(n.atMs)-e,player_id:n.playerId,dimensions:n.dimensions,measures:n.measures}}function Nd(n){let e=Math.max(1,Math.floor(n.maxQueue??zy)),t={client:n.client,gameId:()=>n.gameId},r=[],i=0,o=null,s=false,a=null,l=0,d=0,m=false,u=false,p=h=>{n.log?.(h);},g=()=>{o!==null&&(n.clock.clearTimeout(o),o=null);},y=()=>Math.max(0,d-n.clock.now()),b=()=>{o!==null||s||a!==null||(o=n.clock.setTimeout(()=>{o=null,x().catch(()=>{});},Math.max(Ky,y())));},R=()=>{let h=Math.min(r.length,100),k=128;for(let C=0;C<h;C+=1){let E=r[C];if(E===void 0)break;if(k+=JSON.stringify(qd(E,0)).length+1,k>Yy)return Math.max(1,C)}return h};async function x(h){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let k=I(h);a=k;try{return await k}finally{a===k&&(a=null),r.length>0&&b();}}async function I(h){g();let k=r.splice(0,R()),C=i;i=0;let E=Math.round(n.clock.now()),W={batch_id:Fd(),sent_at_ms:E,events:k.map(D=>qd(D,E))};try{let D=await xo(t,W,h===void 0?void 0:{signal:h}),q=Zy(D,C);l=0,d=0;for(let P of q.rejected)p(`[gem] analytics: an event was refused (${P.code}). See the analytics_events section of your game config.`);return q}catch(D){if(Qy(D)){for(r=[...k,...r],i+=C;r.length>e;)r.shift(),i+=1;l+=1,d=n.clock.now()+sr(l,D);}else p(`[gem] analytics: ${k.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(D)}`);throw D}}return {track(h,k,C={}){if(s)return;if(typeof h!="string"||h===""){u||(u=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(vi)){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 E={},W={};for(let[D,q]of Object.entries(C))typeof q=="string"?E[D]=q:typeof q=="number"&&Number.isFinite(q)&&(W[D]=q);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:Fd(),playerId:h,name:k,atMs:n.clock.now(),dimensions:E,measures:W}),r.length>=Jy&&a===null&&y()===0?x().catch(()=>{}):b();},flush:h=>x(h),get pending(){return r.length},dispose(){s=true,g(),r=[],i=0;}}}function jd(n){return {async list(e){let{playerId:t,periodsBack:r,signal:i}=e??{};if(typeof t!="string"||t==="")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().");yt(r);let o=await n({player_id:t,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return Zn(o)}}}function ef(n){let e={};for(let[t,r]of Object.entries(Ao))if(typeof r=="function"){let i=r;e[t]=(...o)=>i(n,...o);}return e}function Ud(n,e={}){let t=e.clock??fe,r=e.baseUrl??n.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=Dd(n,{clock:t,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=Cr({baseUrl:r,tokenSource:i.source,defaultQuery:{game_id:n.gameId,channel:n.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new We({transport:o,clock:t}),a={gameId:n.gameId,channel:n.channel,matchId:n.matchId,...n.gameRoomId===void 0?{}:{gameRoomId:n.gameRoomId}},l=ef({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,m=n.endMatch,u=n.log,p=Nd({client:s,clock:t,gameId:a.gameId,...typeof u=="function"?{log:y=>u.call(n,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(n);},setBackfill:async(y,b)=>{let R=await l.setMatchBackfill(a.matchId,{open:y.open,...y.seats===void 0?{}:{seats:y.seats}},b===void 0?{}:{signal:b});return {open:R.open,seats:R.seats??null}},reportPlayers:async(y,b)=>(await l.reportMatchPlayers(a.matchId,{players:y.map(x=>({player_id:x.playerId,state:x.state}))},b===void 0?{}:{signal:b})).players.map(x=>({playerId:x.player_id,outcome:x.outcome}))},analytics:p,functions:new ze(l.invokeFunction),challenges:jd(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let b=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),R=b.modified?b.body:void 0;if(R?.room_args==null||R.room_args_template==null)throw new O("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:R.room_args,room_args_template:R.room_args_template}}}},dispose:()=>{p.dispose(),i.dispose();}}}function tt(n){return n?.reliable!==false?"reliable":n?.ordered!==false?"ordered":"unreliable"}function At(n){return {reliable:n==="reliable",ordered:n!=="unreliable"}}function fn(n){return typeof n=="string"?n:n.slice().buffer}function Lr(n){if(typeof n=="string")return {data:n,isText:true};if(n instanceof ArrayBuffer)return {data:new Uint8Array(n),isText:false};if(ArrayBuffer.isView(n)){let e=n;return {data:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),isText:false}}return null}var tf=5e3,Bd=3e4,Wd=2e3,nf=1e4,rf=3,Vd=1;async function Hd(n,e){let{session:t,localPlayerId:r}=e;if(!t.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 n=="function"?n():n,a=Promise.resolve(),l=true,d=false,m=(f,T)=>{l&&(a=a.then(async()=>{if(!d)try{await T();}catch(F){o(`the bundle's ${f} handler threw: ${nt(F)}. Serving continues.`);}}));},u=true,p,g,y,b=f=>{if(!u)return;u=false,m("leave",()=>s.leave?.(r,{cause:f??"left"}));let T=g;T&&queueMicrotask(()=>T(f));},R={send(f,T){if(!u)return;let F=At(tt(T));m("message",()=>s.message?.(r,f,typeof f=="string",{reliable:F.reliable,ordered:F.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){b("closed");}},x=(f,T)=>{if(!u)return;let F=At(tt(T));queueMicrotask(()=>{u&&p?.(f,F);});},I=new Map,h=f=>{let T=[];for(let F of De){let Q=f.channels[F];try{Q.binaryType="arraybuffer";}catch{}let ye=At(F),$=Rn=>{let Be=Lr(Rn?.data);Be!==null&&m("message",()=>s.message?.(f.playerId,Be.data,Be.isText,{reliable:ye.reliable,ordered:ye.ordered}));};Q.addEventListener("message",$),T.push(()=>Q.removeEventListener("message",$));}I.get(f.playerId)?.forEach(F=>F()),I.set(f.playerId,T);},k=f=>{I.get(f)?.forEach(T=>T()),I.delete(f);},C=new Set,E=new Map,W=(f,T,F)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...T?{rejoin:true}:{},...F?{superseded:true}:{}}),D=f=>{let T=I.has(f.playerId),F=C.has(f.playerId);C.add(f.playerId),h(f),T&&m("leave",()=>s.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>s.join?.(f.playerId,W(f,F,T)));},q=new Set,P=(f,T,F)=>{if(f===r){x(T,F);return}let Q=t.peer(f);if(Q===null){let ye=E.get(f);if(ye!==void 0&&e.clock.now()-ye<Wd)return;q.has(f)||(q.add(f),o(`send to '${f}' dropped: no such connected player`));return}Q.send(fn(T),tt(F));},M={matchId:t.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=u?[r]:[];for(let T of t.peers)f.push(T.playerId);return f},profile(f){let T=e.room()?.members.find(F=>F.playerId===f);if(!(!T||T.displayName===void 0))return {displayName:pt.toPlain(T.displayName),...T.displayTag===void 0?{}:{displayTag:pt.toPlain(T.displayTag)},...T.discriminator===void 0?{}:{discriminator:T.discriminator}}},playerNumber(f){return f===r?Vd:t.peer(f)?.assignedPeerId},send(f,T,F){P(f,T,F);},broadcast(f,T){let F=T?.except;u&&r!==F&&x(f,T);for(let Q of t.peers)Q.playerId!==F&&Q.send(fn(f),tt(T));},async endMatch(){let f=await je();return f.answer!=="ok"&&o(f.cause),f.answer},kick(f,T){if(f===r){b(T??"kicked");return}t.kick(f).catch(F=>{o(`kick of '${f}' failed: ${nt(F)}`);});},log(f){o(f);},warn(f){o(`\u26A0 ${f}`);}},L=()=>{},j=new Promise(f=>{L=f;}),U=[],V=null,oe=async(f,T)=>{l=false;let F=a.then(async()=>{try{await s.shutdown(f);}catch(Q){o(`the bundle's shutdown threw: ${nt(Q)}`);}});a=F,await F,it();for(let Q of U.splice(0))Q();for(let Q of [...I.keys()])k(Q);b(T);},ae=(f,T)=>V||(V=(async()=>{await oe(T,f),t.close(),L();})(),V),X=()=>V||(V=(async()=>{await oe({reason:"signal"},"left"),await t.leave().catch(f=>o(`leaving the match failed: ${nt(f)}`)),L();})(),V),Ne=()=>V||(V=(async()=>{l=false;let f=await je();f.answer==="ok"?(await oe({reason:"match_ended",platform_reason:"explicit"},"match ended"),t.close()):(o(`${f.cause}; leaving instead`),await oe({reason:"signal"},"left"),await t.leave().catch(T=>o(`leaving the match failed: ${nt(T)}`))),L();})(),V),me=null,ke=()=>(me??=Ud(M,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),me),je=async()=>{try{return await ts({client:ke().client,gameId:()=>M.gameId},M.matchId,{},{signal:AbortSignal.timeout(tf)}),{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: ${nt(f)}`}}},Z=null,J=false,ee=0,Le,xe=null,it=()=>{J=true,Z!==null&&(e.clock.clearTimeout(Z),Z=null),xe?.(),xe=null;},Tt=f=>{o(`heartbeats paused: ${f}; they resume when a fresh play token arrives`),ot();let T=Le,F=false,Q=e.tokens.subscribe(ye=>{F||J||ye.token===T||kn(ye)||(F=true,xe?.(),xe=null,ee=0,Le=void 0,ot(),o("a fresh play token arrived; heartbeats resume"),Z=e.clock.setTimeout(()=>{Ue();},0));});F?Q():xe=Q;},ot=()=>{let f=me;me=null,f?.dispose();},kn=f=>f.expiresAt*1e3<=e.clock.now(),Ue=async()=>{if(Z=null,!J){try{await ke().client.post(`/v1/games/${encodeURIComponent(M.gameId)}/matches/${encodeURIComponent(M.matchId)}/heartbeat`,void 0,AbortSignal.timeout(nf)),ee=0,Le=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`),it();return}if(of(f)){if(J)return;ee+=1;let T=e.tokens.current(),F=T===void 0?"this host holds no play token":kn(T)?"this host's play token has expired":T.token===Le?"the platform refused this host's play token again":ee>=rf?`the platform refused this host's play token ${ee} times in a row`:null;if(Le=T?.token,F!==null){Tt(F);return}}else ee=0,Le=void 0;o(`heartbeat failed: ${nt(f)}`);}J||(Z=e.clock.setTimeout(()=>{Ue();},Bd));}},Et=()=>{J||Z!==null||(Z=e.clock.setTimeout(()=>{Ue();},Bd));};{let f=L;L=()=>{it(),me?.dispose(),me=null,f();};}let It=Promise.resolve().then(()=>s.init(M));a=It.then(()=>{},()=>{}),m("join",()=>s.join?.(r,{playerNumber:Vd,transport:"loopback"})),U.push(t.on("peerJoined",D)),U.push(t.on("peerLeft",(f,T)=>{k(f);let F=e.clock.now();for(let[Q,ye]of E)F-ye>=Wd&&E.delete(Q);E.set(f,F),q.delete(f),m("leave",()=>s.leave?.(f,{cause:T}));})),U.push(t.on("error",f=>{o(`\u26A0 session error: ${f.message}`);})),U.push(t.on("matchEnded",f=>{V||Po(y,f),ae("match ended",{reason:"match_ended",platform_reason:f});})),U.push(t.on("hostChanged",f=>{f!==r&&ae("host migrated",{reason:"host_migrated"});}));for(let f of t.peers)D(f);try{await It,Et();}catch(f){l=false,it(),d=true;for(let T of U.splice(0))T();for(let T of [...I.keys()])k(T);throw t.leave().catch(()=>{}),L(),f}return {matchId:t.matchId,localLink:R,onMatchEnded(f){y=f;},end:Ne,leave:X,stop:f=>ae(f,{reason:"stopped"}),done:j}}function Po(n,e){try{n?.(e);}catch{}}function of(n){return n instanceof O&&n.status===401||ie.isAuthError(n)}function nt(n){return n instanceof Error?n.message:String(n)}function To(n,e){let t=async()=>{throw new w("misconfigured",`this seat is \`${n}\`, not the match's authority: `+(n==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:n,matchId:e,end:t,leave:t,stop:async()=>{}}}function Kd(n){let e=new Map,t=n.autoReconnect===true,{rooms:r}=n,i=new Map,o=async a=>{r.isHost&&!So(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!==Ze)return To("dedicated",d.matchId);let m=n.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return To("peer",d.matchId);let u=n.identity();if(u===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await n.p2p.connect(s(l)),g=await Hd(a,{session:p,clock:n.clock,gameId:u.gameId,channel:u.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:n.apiBaseUrl(),tokens:n.tokens,room:n.room,localPlayerId:p.playerId!==""?p.playerId:u.playerId,...n.log===void 0?{}:{log:n.log},...n.fetch===void 0?{}:{fetch:n.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===Ze){let g=i.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),df(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 dn(),b=async()=>n.p2p.connect({...s(a),certificate:y}),R=await b(),x=uf(R,b,d,I=>{r.notifyMatchDisconnected(I).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),t);return t&&(e.set(R.matchId,{redial:x.redial,abandon:x.abandon}),x.onClosed(()=>{e.get(R.matchId)?.abandon===x.abandon&&e.delete(R.matchId);})),x}let m=async(g=null)=>await n.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),u=await m(),p=cf(u,m,r,t);return t&&(e.set(u.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(u.matchId)?.abandon===p.abandon&&e.delete(u.matchId);})),p},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var Jd="link_closed",af="host_unreachable",sf=new Set(["failed","closed"]);function lf(n){return sf.has(n)?Jd:af}function df(n,e,t){let r=e.localLink;e.onMatchEnded(t);let i="connected";r.onClose(()=>{i="closed";});let o;return {matchId:n,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 cf(n,e,t,r){let i=n.matchId,o=n,s="connected",a,l,d=[],m=false,u=false,p=y=>{if(s!=="closed"){s="closed";for(let b of d.splice(0))b();l?.(y);}},g=y=>{y.link.onMessage((b,R)=>a?.(b,R)),y.link.onClose(b=>{if(y!==o||s==="closed")return;if(m||!r){p(b);return}let R=t.matchSession;if(R.phase==="suspended"&&R.matchId===i){s="suspended";return}p(b);});};return g(n),{matchId:i,protocol:"dedicated",get transport(){return o.transport},get state(){return s},send(y,b){s==="connected"&&o.link.send(y,b);},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(u)return "connected";u=true;let b;try{b=await e(y===void 0?{}:{deadlineAt:y});}finally{u=false;}return m||s==="closed"?(b.close(),"closed"):(o=b,g(b),s="connected",t.notifyMatchConnected(i),"connected")},abandon(y){s!=="closed"&&(s==="connected"&&o.close(),p(y));},onClosed(y){s==="closed"?y():d.push(y);}}}function uf(n,e,t,r,i,o=false){let s=n.matchId,a=n,l,d,m=[],u=[],p=[],g=false,y=false,b=false,R=false,x="connected",I=P=>{if(g)return;g=true,x="closed";for(let L of m.splice(0))L();for(let L of u.splice(0))L();for(let L of p.splice(0))L();let M=d;M&&queueMicrotask(()=>M(P));},h=P=>{for(let M of m.splice(0))M();for(let M of De){let L=P.channels[M];try{L.binaryType="arraybuffer";}catch{}let j=At(M),U=V=>{let oe=Lr(V?.data);oe!==null&&l?.(oe.data,j);};L.addEventListener("message",U),m.push(()=>L.removeEventListener("message",U));}},k=()=>a.peer(a.hostPlayerId),C=P=>{if(!(g||a.isHost)&&x!=="suspended"){if(r?.(P),o){x="suspended";return}I(P);}},E=P=>{for(let M of De){let L=P.channels[M];if(typeof L.addEventListener!="function")continue;let j=()=>{k()===P&&C(Jd);};L.addEventListener("close",j),m.push(()=>L.removeEventListener?.("close",j));}},W=P=>{h(P),E(P),!g&&(x="connected",i?.());},D=P=>{for(let M of u.splice(0))M();u.push(P.on("migrating",()=>{R=true;})),u.push(P.on("hostChanged",M=>{if(R=false,M===P.playerId){I("host_migrated_here");return}let L=k();L!==null&&W(L);})),u.push(P.on("peerJoined",M=>{M.playerId===P.hostPlayerId&&W(M);})),u.push(P.on("matchEnded",M=>{g||Po(t,M),I(M);})),u.push(P.on("peerLeft",(M,L)=>{M===P.hostPlayerId&&C(lf(L));}));};D(a);let q=k();return q!==null&&W(q),{matchId:s,protocol:"p2p",get state(){return x},send(P,M){x==="connected"&&k()?.send(fn(P),tt(M));},onMessage(P){l=P;},onClose(P){d=P;},close(){y=true,I("closed"),a.leave().catch(()=>{});},async redial(){if(x==="closed")return "closed";if(x==="connected"||b)return "connected";if(R)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");b=true;let P;try{for(let L of m.splice(0))L();for(let L of u.splice(0))L();a.close(),P=await e();}finally{b=false;}if(g)return y?P.leave().catch(()=>{}):P.close(),"closed";a=P,D(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(P){I(P);},onClosed(P){g?P():p.push(P);}}}function Eo(n){let e=0,t=new Map;return {resolve(){if(!n.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},s=l=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(l));};t.set(r,s),o.timer=n.clock.setTimeout(()=>s(void 0),n.timeoutMs??2e3);let a=false;try{a=n.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){t.get(r)?.(i);}}}var mf=12e4;function rt(n,e){return {outcome:n,reason:e}}function zd(n){let e=false,t=new Map,r=(i,o,s,a)=>{if(!n.bridge.parentSupports(i))return Promise.resolve(rt("unavailable","error"));if(e)return Promise.resolve(rt("declined","busy"));let l=`purchase-${ve()}`;return new Promise(d=>{let m={},u=g=>{t.delete(l)&&(e=false,n.clock.clearTimeout(m.timer),d(g));};e=true,t.set(l,{finish:u,check:s,label:a}),m.timer=n.clock.setTimeout(()=>u(rt("unavailable","error")),n.timeoutMs??mf);let p=false;try{p=o(l);}catch{}p||u(rt("unavailable","error"));})};return {api:{request(i){return r("purchases",o=>n.bridge.requestPurchase(o,i.kind,i.targetId,i.currencySlug,i.quantity,i.catalogId),o=>o===void 0?null:n.confirm(o),o=>`purchase ${JSON.stringify(o)}`)}},requestAvatar3d(i){return r("avatar3dPurchases",o=>n.bridge.requestAvatar3dPurchase(o,i.itemId,i.currencySlug),()=>n.confirmAvatar3d(i.itemId),()=>`3D avatar ${JSON.stringify(i.itemId)}`)},settle(i){let o=i.outcome==="ok"||i.outcome==="declined"?i.outcome:"unavailable",s=t.get(i.requestId);if(s===void 0){n.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(i.requestId));return}let{finish:a}=s;if(o!=="ok"){a(rt(o,ws(i.reason)));return}let l=i.purchaseId,d;try{d=s.check(l);}catch{d=Promise.resolve("unknown");}if(d===null){n.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),a(rt("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"&&n.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+s.label(l)),a(rt("unavailable","error"));})();}}}async function Yd(n,e){try{return (await $a(n,e)).granted?"granted":"absent"}catch(t){return t instanceof O&&t.reason==="not_found"?"absent":"unknown"}}var pf="small_human",Xd=/^[a-z][a-z0-9_]{0,31}$/,Qd=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,gf=8;function Io(n){if(n===null)return [];if(n.avatars3d!==void 0)return n.avatars3d;let{avatar3dId:e,avatar3dModelUrl:t,avatar3dIconUrl:r}=n;return e===void 0||t===void 0||r===void 0?[]:[{family:pf,id:e,modelUrl:t,iconUrl:r}]}function yf(n,e){return n.length===e.length&&n.every((t,r)=>{let i=e[r];return t.family===i.family&&t.id===i.id&&t.modelUrl===i.modelUrl})}function ff(n){let e=n??{},t=typeof e.item_id=="string"&&Qd.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&Xd.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=er(e.icon_url),l=er(e.model_url),d=[];for(let m of Array.isArray(e.prices)?e.prices:[]){let u=m??{};typeof u.currency_slug=="string"&&u.currency_slug!==""&&typeof u.price=="number"&&Number.isSafeInteger(u.price)&&u.price>0&&d.push({currencySlug:u.currency_slug,price:u.price});}if(!(t===void 0||r===void 0||i===void 0||o===void 0||a===void 0||l===void 0||d.length===0))return {itemId:t,slug:i,family:r,displayName:o,...s===void 0?{}:{description:s},iconUrl:a,modelUrl:l,prices:d}}function hf(n){if(!Array.isArray(n))return [];let e=[];for(let t of n)if(typeof t=="string"&&Xd.test(t)&&!e.includes(t)&&e.push(t),e.length===gf)break;return e}function Zd(n){let e=new Set,t=Io(n.player()),r=i=>{n.log?.(`[gem] an avatars3d onChange listener threw: ${i instanceof Error?i.message:String(i)}`);};return n.subscribe(i=>{let o=Io(i);if(!yf(t,o)){t=o;for(let s of [...e])try{s(o);}catch(a){r(a);}}}),{async families(){return hf(await n.configFamilies())},worn(i){let o=Io(n.player());if(i!==void 0)return o.find(l=>l.family===i);let a=n.player()?.avatar3dId;return (a===void 0?void 0:o.find(l=>l.id===a))??o[0]},async offers(){let i=await n.readOffers(),o=[];for(let s of Array.isArray(i?.offers)?i.offers:[]){let a=ff(s);a!==void 0&&o.push(a);}return o},purchase(i){let o=i?.itemId,s=i?.currencySlug;return typeof o!="string"||!Qd.test(o)?Promise.resolve({outcome:"declined",reason:"not_purchasable"}):typeof s!="string"||s===""?Promise.resolve({outcome:"declined",reason:"unknown_currency"}):n.purchase({itemId:o,currencySlug:s})},onChange(i){return e.add(i),()=>{e.delete(i);}}}}async function ec(n,e){try{return (await ha(n,e))?.owned===!0?"granted":"absent"}catch(t){return t instanceof O&&t.reason==="not_found"?"absent":"unknown"}}function tc(n){return Ca(n)}var bf=6e5;function nc(n){let e=null,t=new Map;return {api:{requestSignIn(){if(!n.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${ve()}`;return e=new Promise(i=>{let o={},s=l=>{t.delete(r)&&(e=null,n.clock.clearTimeout(o.timer),i(l));};t.set(r,s),o.timer=n.clock.setTimeout(()=>{s({outcome:"unavailable"});},n.timeoutMs??bf);let a=false;try{a=n.bridge.requestSignIn(r);}catch{}a||s({outcome:"unavailable"});}),e}},settle(r){let i=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",o=t.get(r.requestId);if(o===void 0){n.onDropped?.(`gem.signInResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}o({outcome:i});}}}var vf=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),_f=["utm_"];function rc(n){return vf.has(n)||_f.some(e=>n.startsWith(e))}var ic=16,oc=512,wf=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,kf=/[\p{Cc}\p{Cf}]/u,Rf=/\p{Cs}/u,Me="[gem] gem.share.request:";function ac(n){let{frame:e,log:t}=n,r=false,i=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,o=s=>{t!==null&&(t===void 0?console.warn(s):t(s));};return {get available(){return i()!==null},request(s){let a=i();if(a===null)throw new Error(`${Me} 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(`${Me} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!Sf(l))throw new TypeError(`${Me} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>ic)throw new TypeError(`${Me} at most ${ic} params; got ${d.length}`);let m=[];for(let[u,p]of d){let g=JSON.stringify(u);if(!wf.test(u))throw new TypeError(`${Me} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(rc(u))throw new TypeError(`${Me} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Me} param ${g}: values must be strings`);if(p.length>oc)throw new TypeError(`${Me} param ${g}: a value is at most ${oc} characters`);if(kf.test(p))throw new TypeError(`${Me} param ${g}: control and format characters are not allowed`);if(Rf.test(p))throw new TypeError(`${Me} param ${g}: a value must be well-formed text`);m.push({key:u,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 Sf(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var Tf="(any-pointer: coarse)";function Ef(n){let e=Array.isArray(n)?n:[n],t=[],r=1e4;for(let i of e){if(typeof i!="number"||!Number.isFinite(i)||i<0)return null;if(t.length===99||r===0)continue;let o=Math.min(Math.trunc(i),1e4,r);t.push(o),r-=o;}return t.length%2===0&&t.pop(),t.every(i=>i===0)?[]:t}function sc(n){let{frame:e,log:t}=n,r=n.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(Tf),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,u)=>{s.has(m)||(s.add(m),t!==null&&(t===void 0?console.warn(u):t(u)));};return {get available(){return a()||l()},vibrate(m){let u=a();if(!u&&!l())return false;let p=Ef(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(u)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 Pt=Math.PI/180,Oe=Object.freeze({touch:Object.freeze({yaw:1*Pt,pitch:.66*Pt}),mouse:Object.freeze({yaw:.5*Pt,pitch:.5*.77*Pt}),stick:Object.freeze({yaw:240*Pt,pitch:240*.77*Pt}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),Co="[gem.controls]",Mo=Object.freeze({yaw:0,pitch:0}),Gr=n=>Number.isFinite(n)?n:0,lc=(n,e)=>({yaw:n+0,pitch:e+0});function dc(n){let e=Gr(n),t=(Math.abs(e)-Oe.stickDeadzone)/(1-Oe.stickDeadzone),r=Oe.stickCurve,i=(Math.exp(r*t)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,i))+0}function If(n){let e=Math.min(1,2*Math.abs(n)/Math.PI);return (1-Math.pow(e,.75))*(1-Oe.touchPitchMin)+Oe.touchPitchMin}function cc(n,e){if(n===void 0)return {};if(typeof n!="object"||n===null)throw new TypeError(`${Co} ${e} takes an options object`);let t=n;for(let r of ["sensitivity","gamepadSensitivity"]){let i=t[r];if(i!==void 0&&!(typeof i=="number"&&Number.isFinite(i)&&i>0))throw new TypeError(`${Co} ${e}: ${r} must be a finite number above 0 (1 = the base speed); got ${String(i)}`)}if(t.invertY!==void 0&&typeof t.invertY!="boolean")throw new TypeError(`${Co} ${e}: invertY must be a boolean; got ${String(t.invertY)}`);return t}function Cf(n,e){let t=cc(e,"look()"),r=t.sensitivity,i=t.gamepadSensitivity,o=t.invertY,s=a=>o??a?.invertLookY??false;return {fromPointer(a,l,d,m){let u=Gr(a),p=Gr(l);if(u===0&&p===0)return Mo;let g=n(),y=r??(g===null?void 0:g.lookSensitivity/100)??1,b=d==="touch"||d==="pen",R=b?Oe.touch:Oe.mouse,x=u*R.yaw*y,I=-p*R.pitch*y;return s(g)&&(I=-I),b&&m!==void 0&&Number.isFinite(m)&&I*m>0&&(I*=If(m)),lc(x,I)},fromStick(a,l,d){let m=Gr(d);if(m<=0)return Mo;let u=dc(a),p=dc(l);if(u===0&&p===0)return Mo;let g=n(),y=i??(g===null?void 0:g.gamepadLookSensitivity/100)??1,b=u*Oe.stick.yaw*m*y,R=-p*Oe.stick.pitch*m*y;return s(g)&&(R=-R),lc(b,R)},set(a){let l=cc(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(i=l.gamepadSensitivity),"invertY"in l&&(o=l.invertY);}}}function uc(n){return {look:e=>Cf(n.recommended,e),LOOK_BASE:Oe}}function mc(n,e){return n==null?e?"low":"medium":n==="low"||n==="high"?n:"medium"}var Mf=/(?:Z|[+-]\d{2}:?\d{2})$/i;function pc(n){if(typeof n!="string"||!Mf.test(n))return;let e=Date.parse(n);return Number.isFinite(e)&&e>0?e:void 0}function hn(){return {declared:false,grantable:false,heldLimitReached:false}}function gc(n,e){let t=typeof n=="object"&&n!==null?n:{},r=pc(t.resets_at),i=r===void 0?{}:{resetsAt:r};if(t.declared!==true)return {...hn(),...i};let o=t.remaining_today,s=typeof o=="number"&&Number.isFinite(o)&&o>=0?Math.floor(o):void 0,a=t.next_eligible_at,l=pc(a),d=t.held_limit_reached===true,m=a!=null,u=o!=null&&s===void 0;return {declared:true,grantable:t.grantable===true&&e&&s!==0&&!u&&!m&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var Of=18e4,Oo=32,Lf=/^[a-z0-9_-]+$/,Gf="rewarded_requires_user_gesture";function Df(){let n=globalThis.navigator?.userActivation?.isActive;return typeof n=="boolean"?n:void 0}var $f=1e3;function Ff(){let n=globalThis,e=n.navigator?.getGamepads,t=n.performance?.now;if(typeof e!="function"||typeof t!="function")return;let r=t.call(n.performance),i=e.call(n.navigator);for(let o=0;o<i.length;o+=1){let s=i[o]?.timestamp;if(typeof s=="number"&&r-s>=0&&r-s<=$f)return true}return false}var yc=1e4;function qf(n){return n==="interstitial"||n==="rewarded"}function fc(n){return typeof n=="string"&&n!==""&&n.length<=Oo&&Lf.test(n)}function Nf(n){let e=typeof n=="object"&&n!==null?n:{};return [e.name,e.reason,e.status].join()}function Dr(n){return typeof n=="string"?JSON.stringify(n):typeof n}function hc(n){let e=false,t=new Map,r=new Map,i=new Set,o=d=>{try{n.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let m=n.log;if(m!==null)try{m===void 0?console.warn(`[gem] ${d}`):m(`[gem] ${d}`);}catch{}},l=d=>{let m=n.readAvailability;if(m===void 0)return Promise.resolve(hn());let u=r.get(d);if(u!==void 0)return u;let p=new Promise(g=>{let y={},b=h=>y.done===true?false:(y.done=true,n.clock.clearTimeout(y.timer),g(h),true),R=(h,k)=>{!b(hn())||i.has(h)||(i.add(h),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${k}. Said once.`));},x=h=>{R(Nf(h),`the read failed (${h instanceof Error?h.message:Dr(h)})`);},I;try{I=Promise.resolve(m(d,AbortSignal.timeout(yc)));}catch(h){I=Promise.reject(h);}y.timer=n.clock.setTimeout(()=>{R("timeout","no answer within 10 s");},yc),I.then(h=>{try{b(gc(h,n.bridge.parentSupports("ads")));}catch(k){x(k);}},x);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return fc(d)?l(d):(o(`gem.ads.rewardedStatus(${Dr(d)}) answered not grantable: a placement is 1..${String(Oo)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(hn()))},requestAd(d){if(!n.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let m=d?.placement,u=d?.format;if(!fc(m)||!qf(u))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${Dr(m)}, format ${Dr(u)}. A placement is 1..${String(Oo)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});if(u==="rewarded"){let g;try{g=(n.userActivation??Df)();}catch{g=void 0;}if(g===false)try{(n.recentGamepadInput??Ff)()===!0&&(g=!0);}catch{}if(g===false){let y=`${Gf}: 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-${ve()}`;return new Promise(g=>{let y={},b=x=>{t.delete(p)&&(e=false,n.clock.clearTimeout(y.timer),g(x));};e=true,t.set(p,b),y.timer=n.clock.setTimeout(()=>{b({outcome:"unavailable"});},n.timeoutMs??Of);let R=false;try{R=n.bridge.requestAd(p,m,u);}catch{}R||b({outcome:"no_ad"});})}},settle(d){let m=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",u=t.get(d.requestId);if(u===void 0){n.onDropped?.(`gem.adResult (${m}) for an unknown requestId: `+JSON.stringify(d.requestId));return}u({outcome:m});}}}var bc=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),vc=18e4,jf=1e4,Uf=/^[a-z0-9_-]{1,32}$/;function _c(n){return typeof n=="string"?JSON.stringify(n):typeof n}var bn=Object.freeze({shown:false});function wc(n){let e=new Map,t,r=false,i=o=>{try{n.onDropped?.(o);}catch{}return bn};return {api:{signal(o){try{if(!n.bridge.parentSupports("moments"))return r?Promise.resolve(bn):(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(!bc.includes(s)||a!==void 0&&(typeof a!="string"||!Uf.test(a)))return Promise.resolve(i(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${_c(s)}, placement ${_c(a)}. A kind is one of ${bc.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'. Answering shown: false.`));if(!n.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=n.clock.now();if(t!==void 0&&l-t<jf)return Promise.resolve(i(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(l-t)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let d=`moment-${ve()}`;return new Promise(m=>{let u={},p=(y,b)=>{e.delete(d)&&(n.clock.clearTimeout(u.timer),b&&(t=n.clock.now()),m(y));};e.set(d,y=>p(y,!0)),u.timer=n.clock.setTimeout(()=>{e.has(d)&&(p(bn,!0),i(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((n.timeoutMs??vc)/1e3)} s. Answering shown: false.`));},n.timeoutMs??vc);let g=!1;try{g=n.bridge.signalMoment(d,s,a);}catch{}g||p(bn,!1);})}catch{return Promise.resolve(bn)}}},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 Lo=16384;function kc(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e;try{e=JSON.stringify(n);}catch{return null}return typeof e!="string"?null:Bf(e)}function Bf(n){let e=0;for(let t=0;t<n.length;t+=1){let r=n.charCodeAt(t);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=n.charCodeAt(t+1);i>=56320&&i<=57343?(e+=4,t+=1):e+=3;}else e+=3;}return e}var Wf=1e4,Vf=5e3;function Rc(n){let e=null,t=false,r=[],i=new Map,o=()=>{for(let s of r.splice(0))s();};return {api:{get current(){return e},wait(s=Vf){return t?Promise.resolve(e):new Promise(a=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,1);},d=()=>{n.clock.clearTimeout(m),l(),a(e);},m=n.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!n.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=kc(s);if(a===null)return n.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-${ve()}`;return new Promise(m=>{let u={},p=y=>{i.delete(d)&&(n.clock.clearTimeout(u.timer),y==="stored"&&(e=l,t=true,o()),m(y));};i.set(d,p),u.timer=n.clock.setTimeout(()=>p("unavailable"),n.timeoutMs??Wf);let g=false;try{g=n.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,t=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){n.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var vn=class extends Error{constructor(){super("createGem: this game is not framed (window.parent === window), so nothing can hand it a player, saves, config or rooms. Play it in the Gem Arcade or the Gem Editor, or through the Gem dev host on this machine: `npm run dev` (`gemctl serve start . --dev`) while editing, `gemctl serve start .` for a build, signed in to gemctl. Do not open the dev server's own address."),this.name="GemUnframedError";}};var Hf=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Kf(n){return typeof n=="string"&&Hf.test(n)}function $r(n){if(n===null||Kf(n))return n;let e=typeof n=="string"?JSON.stringify(n.length>48?`${n.slice(0,48)}\u2026`:n):`a value of type ${typeof n}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}function Sc(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Go(n,e){if(n!==true)return {visible:false};let t=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!t.includes(i)&&t.push(i);return !r&&t.length===0?{visible:true}:{visible:true,currencies:t.slice(0,8),score:r}}function Fr(n){let e=[];for(let t of Array.isArray(n)?n:[]){if(e.length===4)break;if(typeof t!="object"||t===null)continue;let{id:r,label:i}=t;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 xc(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Jf(n){let e=n.untrusted,t=Ge(e.displayName),r=e.displayTag||e.displayHandle,i=r?Ge(r):void 0,o=n.discriminator||n.displayTag,s=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,a=n.avatarIconUrl||n.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=n.avatarIconId,m=n.avatar3dId,u={displayName:t,displayHandle:i??t,badges:(n.badges??[]).map(b=>({itemId:b.itemId,iconUrl:b.iconUrl}))};n.playerId&&(u.playerId=n.playerId),s&&(u.discriminator=s),i&&(u.displayTag=i),a&&(u.avatarIconUrl=u.avatarUrl=a),d&&l.test(d)&&(u.avatarIconId=d),m&&l.test(m)&&(u.avatar3dId=m),n.avatar3dModelUrl&&(u.avatar3dModelUrl=n.avatar3dModelUrl),n.avatar3dIconUrl&&(u.avatar3dIconUrl=n.avatar3dIconUrl),n.avatars3d&&(u.avatars3d=n.avatars3d.filter(b=>l.test(b.id)&&/^[a-z][a-z0-9_]*$/.test(b.family)).filter((b,R,x)=>x.findIndex(I=>I.family==b.family)==R).map(({family:b,id:R,modelUrl:x,iconUrl:I})=>({family:b,id:R,modelUrl:x,iconUrl:I})));let p=n.boost,g=(p?.multipliers??[]).map(b=>({currencyId:b.currencyId,currencySlug:b.currencySlug,multiplier:b.multiplierBp/1e4})),y=g.some(b=>b.multiplier>1);return u.boost=y&&p?.expiresInDays?{active:y,multipliers:g,expiresInDays:p.expiresInDays}:{active:y,multipliers:g},u}var zf=1e4,_n=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??fe,this.inbound=new Lt(this.clock),this.outbound=new Lt(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=>ti(a,e.origin))||hs(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=Ln["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!ti(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=bs(Mn,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:B,type:"gem.error",code:"version_mismatch",message:`frame supports v${Mn.min}..v${Mn.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:B,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:B,type:"gem.ready"});}settled(e=zf){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(t=>{let r=o=>{this.clock.clearTimeout(i),t(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),t(this.state);},e);this.settleWaiters.push(r);})}progress(e,t){this.send({gem:B,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:B,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:B,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:B,type:"gem.exit"}:{gem:B,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:B,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:B,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:B,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:B,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let t={gem:B,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(t.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(t.origin={x:Sc(e.origin.x),y:Sc(e.origin.y)}),this.send(t),true}showPortraitBorders(e){let t=$r(e);return t===void 0||!this.gated("portraitBorders")?false:this.send(t===null?{gem:B,type:"gem.portraitBorders"}:{gem:B,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.gated("walletDisplay")?this.send({gem:B,type:"gem.walletDisplay",...Go(e,t?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:B,type:"gem.menu",...Fr(e)}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:B,type:"gem.gemCorner",corner:e}):false}requestShare(e){return this.gated("share")?this.send({gem:B,type:"gem.requestShare",params:e.map(({key:t,value:r})=>({key:t,value:r}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:B,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:B,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:B,type:"gem.frameStats",fps:xc(e.fps,1e3),frameTimeP95Ms:xc(e.frameTimeP95Ms,1e5)}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:B,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:B,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:B,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:B,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,s){return this.send({gem:B,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s}})}requestAvatar3dPurchase(e,t,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:B,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:t,currencySlug:r}):false}putDeviceSettings(e,t){return this.send({gem:B,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:B,type:"gem.requestAd",requestId:e,placement:t,format:r})}signalMoment(e,t,r){return this.send({gem:B,type:"gem.signalMoment",requestId:e,kind:t,...r===void 0?{}:{placement:r}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:B,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,i){return this.send({gem:B,type:"gem.requestFriendChallenge",requestId:e,playerId:t,template:r,...i===void 0?{}:{params:i}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let t of this.settleWaiters.splice(0))t(e);this.options.onStateChange?.(e);}}refuseMalformed(e,t){if(!this.inbound.allow(On)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(On)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(On)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:B,type:"gem.error",code:e,...t===void 0?{}:{message:t}});}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 t=e.type;if(!this.outbound.allow(t))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${t}`),false;let r=Ln[t]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${t}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,t=[]){let r=false;try{r=this.dispatchInbound(e,t);}finally{r||Ac(t);}}dispatchInbound(e,t){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let i=Ln[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=ps(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=t[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 Ac(t.slice(1)),this.options.onScreenshot(d,l,(m,u)=>this.screenshotDenied(m,u)),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?.(Jf(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,t){this.send({gem:B,type:"gem.screenshot.denied",reason:e,retryable:t});}};function Ac(n){for(let e of n)try{e?.close?.();}catch{}}var Pc="https://api.gemarcade.com";function Do(n){let e;try{e=new URL(n);}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 Yf=new Set(["localhost","127.0.0.1","[::1]"]);function Tc(n){let e=Do(n);if(e!==null)return e;let t=new URL(n);return t.protocol==="http:"&&!Yf.has(t.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 Ec(n){return Object.freeze(n.map(([e,t])=>Object.freeze({node:e,parent:t})))}function Xf(){let n=[["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 t=r=>`${r}_${e}`;n.push([t("shoulder"),"upper_chest"],[t("upper_arm"),t("shoulder")],[t("lower_arm"),t("upper_arm")],[t("hand"),t("lower_arm")],[t("hand_socket"),t("hand")]);for(let r of ["thumb","index","middle","ring","little"])for(let i=1;i<=3;i++)n.push([t(`${r}_${i}`),t(i===1?"hand":`${r}_${i-1}`)]);}for(let e of ["l","r"]){let t=r=>`${r}_${e}`;n.push([t("upper_leg"),"hips"],[t("lower_leg"),t("upper_leg")],[t("foot"),t("lower_leg")],[t("toes"),t("foot")]);}return n}var Qf=Object.freeze({small_human:Ec([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:Ec(Xf())});var eh=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),th=Pc,nh=["top-left","top-right","bottom-left","bottom-right"],Ic=8e3,$o=15e3,rh=9e4,ih=1/0,oh=8e3,ah=5e3,sh=5e3;async function lh(n,e,t,r){if(n.isInRoom)try{await n.leave();}catch{}r?.endSession("session_ended"),e!==null&&e.currentState==="connected"&&e.exit(t);}function wn(n){let e=null,t=false,r=[];return {get current(){return e},set(i){e=i;for(let o of r.splice(0))o(i);},release(){t=true;for(let i of r.splice(0))i(e);},wait(i){return e!==null||t?Promise.resolve(e):new Promise(o=>{let s=()=>{let d=r.indexOf(a);d>=0&&r.splice(d,1);},a=d=>{n.clearTimeout(l),s(),o(d);},l=n.setTimeout(()=>{s(),o(e);},i);r.push(a);})}}}function Ex(n={}){let e=n.clock??fe,t=n.log===void 0?c=>console.info(c):n.log,r=n.baseUrl??void 0;if(r!=null){let c=Do(r);if(c!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${c}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=Ws(typeof window>"u"?void 0:window.location?.search),o=po();o.mark("sdk created");let s=()=>ur(ne.gameVersion,n.clientVersion?.gameVersion),a=new Ht({client:()=>st,clock:e,gameId:()=>ne.identity?.gameId??null,playerId:()=>ne.identity?.playerId??null,environment:()=>{let c=s();return {sdk_version:Xo(),...c===null?{}:{game_version:c}}},...n.analytics===void 0?{}:{options:n.analytics},log:t}),l=Xl(()=>{o.mark("engaged"),a.release(),$.reportEngaged();},typeof window>"u"?{}:window),d=c=>{if(c===false)return null;let S=c?.attempts??ih,N=c?.budgetMs??rh;return !(S>0)||!(N>0)?null:{attempts:S,budgetMs:N,maxDelayMs:c?.maxDelayMs??oh}},m=c=>{c.on("created",()=>{o.mark("room created");}),c.on("joined",()=>{o.mark("room joined");}),c.on("matchAllocationStarted",()=>{o.mark("allocation started");}),c.on("matchReady",()=>{o.mark("match ready");}),c.on("matchFailed",()=>{o.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new vn;let u=n.allowedEmbedders;if(u!=null&&!Array.isArray(u))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 p=Array.from(u??[]),g=p.filter(c=>typeof c!="string"||!ei(c));if(g.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${g.length===1?"an entry":"entries"} that ${g.length===1?"is":"are"} not an origin: ${g.map(c=>typeof c=="string"?JSON.stringify(c):String(c)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let y=Object.freeze([...new Set([...eh,...p])]),b=wn(e),R=new Set,x=wn(e),I=false,h=wn(e),k=Ys(t),C=wn(e),E=n.manageAudio===false?null:od();n.selectableText!==true&&ad();let W=null,D=()=>{W!==null&&(x.current!==null&&x.current.muted===W||$.reportMuted(W));},q,P,M=-1/0,L=null,j=()=>{if(q===void 0||L!==null||q===P)return;let c=M+1e3-e.now();if(c>0){L=e.setTimeout(()=>{L=null,j();},c);return}$.showPortraitBorders(q)&&(P=q,M=e.now());},U=null,V=null,oe=()=>{if(U===null)return false;let c=JSON.stringify(Go(U.visible,U.only));return c===V?$.parentSupports("walletDisplay"):$.setWalletVisible(U.visible,U)?(V=c,true):false},ae=null,X=null,Ne=()=>{if(ae===null)return false;let c=JSON.stringify(Fr(ae.items));return c===X?$.parentSupports("gameMenu"):$.setMenu(ae.items)?(X=c,true):false},me=null,ke=null,je=()=>me===null?false:me===ke?$.parentSupports("gemCorner"):$.setGemCorner(me)?(ke=me,true):false,Z=sd({report:c=>$.reportFrameStats(c)}),J=false,ee=gd(()=>Yo,()=>J),Le=c=>{let S=J&&!c,N=J!==c;if(J=c,S&&ee.close(),!!N)try{n.onDevToolsPermissionChange?.(c);}catch(re){t?.(`[gem] onDevToolsPermissionChange threw: ${re instanceof Error?re.message:String(re)}`),queueMicrotask(()=>{throw re});}},xe=r??th,it=r!==void 0,Tt,ot=c=>(t?.(`[gem] token refused: ${c}`),n.onError?.("internal",c),false),kn=(c,S)=>{if(c===void 0)return S!==void 0?ot("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 N=Tc(c);return N!==null?ot(`the embedder named an API root that cannot be used: ${N}. Its value is withheld here rather than written to logs.`):Tt!==void 0&&Tt!==c?ot("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."):(Tt=c,it||(xe=c),true)},Ue=window.location?.origin,Et=null,It=-1/0,f=2e3,T=new Set,F=c=>Et!==false?Promise.resolve(true):new Promise(S=>{let N=e.setTimeout(()=>{T.delete(re),S(false);},c),re=()=>{e.clearTimeout(N),T.delete(re),S(true);};T.add(re);}),Q=()=>{},ye=null,$=new _n({allowedEmbedders:y,...typeof Ue=="string"&&Ue!==""?{selfOrigin:Ue}:{},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","engagement","reservedAreas","viewport","purchases","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges",...n.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:c=>{ye=c,n.onRefused?.(c);},...n.onError===void 0?{}:{onError:n.onError},onStateChange:c=>{ne.onBridgeState(c),c!=="connected"&&Z.setRequested(false),V=null,X=null,ke=null,P=void 0,c==="refused"&&(console.error("[gem] this game refused the page that framed it"+(ye===null?"":` (${ye})`)+", 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."),Q()),c==="connected"&&(o.mark("bridge connected"),Cc(),D(),j(),oe(),Ne(),je(),$.unbiddenLaunch&&!l.engaged&&a.hold(),a.startSession(),l.engaged&&$.reportEngaged()),n.onStateChange?.(c);},onPlayer:c=>{b.set(c);for(let S of [...R])S(c);n.onPlayer?.(c);},onPrefs:c=>{let S={reducedMotion:c.reducedMotion,muted:c.muted,locale:c.locale,showFrameStats:c.showFrameStats===true,recommended:c.recommended===void 0?null:Object.freeze({volume:c.recommended.volume,batterySaver:c.recommended.batterySaver,keyboardLayout:c.recommended.keyboardLayout,gamepadConfirm:c.recommended.gamepadConfirm,vibration:c.recommended.vibration,lookSensitivity:c.recommended.lookSensitivity??100,gamepadLookSensitivity:c.recommended.gamepadLookSensitivity??100,invertLookY:c.recommended.invertLookY??false,touchMovement:c.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:mc(c.recommended.graphicsQuality,c.recommended.batterySaver),graphicsQualityAuto:c.recommended.graphicsQualityAuto??true})};x.set(S),E?.setMuted(S.muted),Z.setRequested(S.showFrameStats&&$.parentSupports("frameStats")),n.onPrefs?.(S);},onCohorts:c=>{let S=Object.freeze(c.cohorts.map(N=>Object.freeze({experimentId:N.experimentId,variantKey:N.variantKey})));h.set(S),n.onCohorts?.(S);},onEarnAllowanceChanged:()=>k.emit(),onViewport:c=>{let S=Object.freeze({insets:Object.freeze({top:c.insets.top,right:c.insets.right,bottom:c.insets.bottom,left:c.insets.left}),reserved:Object.freeze((c.reserved??[]).map(re=>Object.freeze({x:re.x,y:re.y,width:re.width,height:re.height})))});C.set(S);let N=dd();cd(N,S.insets),md(N,S.reserved,ud()),n.onViewport?.(S);},onPause:c=>{I=c.paused,a.setPaused(c.paused),Z.setPaused(c.paused),n.onPause?.(c.paused);},onMenuSelect:c=>{ae===null||c.entry!=="item"||!(Fr(ae.items).items??[]).some(N=>N.id===c.id)||ae.items?.find(N=>N.id===c.id)?.onSelect?.();},onWillTerminate:c=>{a.endSession(c.reason),n.onWillTerminate?.({reason:c.reason,graceMs:c.graceMs});},onToken:c=>{let S=c.garden;if(Le(c.allowDevTools===true),!kn(c.apiBaseUrl,S))return;let N=c;ne.onToken(N);let re=ne.identity;re&&(Be.set(re),Fo||(Fo=true,ce.reconcileSeats().catch(()=>{}))),qo.push({token:N.token,expiresAt:N.expiresAt});},onTokenDenied:c=>{Le(false),ne.onDenied(c);},onScreenshot:(c,S,N)=>{nd(c,S,N,{...n.onScreenshot===void 0?{}:{handler:n.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{rd($,n.onFeedbackContext);},onDevtools:c=>{c==="close"?ee.close():c==="open"?ee.openFrom("platform").catch(()=>{}):ee.isOpen?ee.close():ee.openFrom("platform").catch(()=>{});},onRoomEvent:c=>ce.handleRoomEvent({event:c.event,roomId:c.roomId,...c.matchId===void 0?{}:{matchId:c.matchId},...c.version===void 0?{}:{version:c.version},...c.reason===void 0?{}:{reason:c.reason},...c.platform===void 0?{}:{platform:c.platform}}),onSeatedEvent:c=>ce.handleSeated(c.roomId),onAutoStartFailedEvent:c=>ce.handleAutoStartFailed(c.roomId,c.code),onTicketEvent:c=>ce.handleTicketEvent({event:c.event,ticketId:c.ticketId,...c.partySize===void 0?{}:{partySize:c.partySize},...c.queuedAt===void 0?{}:{queuedAt:c.queuedAt},...c.expiresAt===void 0?{}:{expiresAt:c.expiresAt},...c.reason===void 0?{}:{reason:c.reason},...c.roomId===void 0?{}:{roomId:c.roomId}}),onSocketState:c=>{let S=Et;if(Et=c.connected,c.connected)for(let re of [...T])re();if(!c.connected||S===true)return;let N=e.now();N-It<f||(It=N,ce.reconcile().catch(()=>{}));},onSignalEvent:c=>{let S=typeof c.data=="object"&&c.data!==null&&!Array.isArray(c.data)?c.data:{};lt.handleSignalEvent(c.matchId,c.event,S),c.event==="matchEnded"&&ce.reconcile({matchId:c.matchId,...typeof S.reason=="string"?{reason:S.reason}:{}}).catch(()=>{});},onDedicatedEvent:c=>{c.event==="matchEnded"&&(Ct.handleMatchEnded(c.matchId,c.reason),ce.reconcile({matchId:c.matchId,...c.reason===void 0?{}:{reason:c.reason}}).catch(()=>{})),Rn.handleEvent(c);},onClusterTarget:c=>Pn.accept(c.clusterTargetId,c.clusterTargetIds),onLocalServer:c=>Tn.accept(c),onLocalServerDenied:c=>Tn.refuse(c),onPartyResult:c=>jo.settle(c.requestId,c.partyId),onPurchaseResult:c=>Nr.settle(c),onDeviceSettings:c=>{An.receive(c),n.onDeviceSettings?.(An.api.current);},onDeviceSettingsResult:c=>An.settle(c),onAdResult:c=>Bo.settle(c),onMomentResult:c=>Wo.settle(c),onSignInResult:c=>Vo.settle(c),onFriendChallengeResult:c=>Ho.settle(c)}),Rn=new yn({bridge:$}),Be=wn(e);Q=()=>{Be.release(),b.release(),h.release();},$.currentState==="refused"&&Q();let Fo=false,qr=new Set,Sn,qo={current:()=>Sn,subscribe:c=>(qr.add(c),Sn!==void 0&&c(Sn),()=>qr.delete(c)),push:c=>{Sn=c;for(let S of [...qr])try{S(c);}catch(N){t?.(`[gem] a server-token listener threw: ${N instanceof Error?N.message:String(N)}`);}}},ne=fd({bridge:$,clock:e,onStateChange:(c,S)=>{if(c==="ready"){if(o.mark("token ready")){let N=o.marks.find(re=>re.name==="token ready")?.at;a.trackPlatform("gem_boot_ready",N===void 0?{}:{boot_ms:Math.max(0,Math.round(N))});}}else c==="lost"&&(o.mark("token lost"),a.trackPlatform("gem_auth_lost"));n.onAuthStateChange?.(c,S);}}),No=()=>{let c=ne.identity;return !c||ne.source.currentState==="lost"?null:`${c.playerId}\0${c.gameId}\0${c.channel}`},Cc=()=>{o.mark("token requested"),ne.source.get().catch(()=>{});},jo=Eo({bridge:$,clock:e}),xn={},Nr=zd({bridge:$,clock:e,onDropped:c=>n.onError?.("internal",c),confirm:async c=>xn.confirm?.(c)??"unknown",confirmAvatar3d:async c=>xn.confirmAvatar3d?.(c)??"unknown"}),An=Rc({bridge:$,clock:e,onDropped:c=>n.onError?.("internal",c)}),Uo={},Bo=hc({bridge:$,clock:e,onDropped:c=>n.onError?.("internal",c),readAvailability:(c,S)=>Uo.read?.(c,S)??Promise.reject(new Error("the gem-api client is not built yet")),log:n.log}),Wo=wc({bridge:$,clock:e,onDropped:c=>n.onError?.("internal",c)}),Vo=nc({bridge:$,clock:e,onDropped:c=>n.onError?.("internal",c)}),Ho=zs({bridge:$,clock:e,onDropped:c=>n.onError?.("internal",c)}),Pn=ol({bridge:$,clock:e}),Tn=pd({bridge:$,clock:e}),jr=c=>{let S=$.handleWindowMessage({data:c.data,origin:c.origin,source:c.source,ports:c.ports});return S&&window.removeEventListener("message",jr),S};window.addEventListener("message",jr);let at=Ql(window,jr),Mc=at?.capture,Ur=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Ur?.domInteractive!==void 0&&Ur.domInteractive>0&&o.mark("document parsed",Ur.domInteractive),Mc?.late&&t?.("[gem] the early-handshake capture installed after this document finished loading, so a handshake posted at iframe load may already have been missed. Load the capture script ahead of everything else in the document.");let Br=n.handshakeWarningMs;Br!==null&&t&&e.setTimeout(()=>{let c=at===null?"no capture script ran":`capture: ${at.delivered} offer(s) delivered, ${at.stale} stale, ${at.capture.dropped} evicted${at.capture.late?", installed late":""}`;if($.currentState==="connected"){t(`[gem] handshake connected. boot: ${o.timeline()} \xB7 ${c}`);return}t(`[gem] no completed handshake after ${Br??Ic}ms (bridge state: ${$.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${o.timeline()} \xB7 `+c);},Br??Ic);let Oc=Cr({get baseUrl(){return xe},tokenSource:ne.source,get defaultQuery(){let c=ne.identity;return c?{game_id:c.gameId,channel:c.channel}:{}}}),st=new We({transport:Oc,clock:e}),pe={client:st,gameId:()=>ne.identity?.gameId??""};xn.confirm=c=>Yd(pe,c),xn.confirmAvatar3d=c=>ec(pe,c),Uo.read=(c,S)=>os(pe,"players","me",c,{signal:S});let Lc=()=>ne.identity?.channel??"release",Wr=new Qn(pe,Lc),Gc=Zd({player:()=>b.current,subscribe:c=>(R.add(c),()=>{R.delete(c);}),configFamilies:async()=>(await Wr.load())?.avatar_3d_families,readOffers:()=>tc(pe),purchase:c=>Nr.requestAvatar3d(c),log:n.log}),Ko=async c=>(await Wr.load())?.currency(c)?.id??void 0,Jo=Hn(pe,ui,{identity:No,resolveCurrencyId:Ko}),Vr=async c=>{let S=await Be.wait(c);if(S)return S;throw $.currentState==="refused"?new ie("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new ie("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},Hr=d(n.autoReconnect),ce=Xi({client:st,clock:e,gameId:()=>ne.identity?.gameId??null,playerId:()=>ne.identity?.playerId??null,awaitGameId:async()=>(await Vr($o)).gameId,resolveParty:jo.resolve,resolveClusterTargets:Pn.resolveList,refreshClusterTargets:Pn.refresh,ensureLocalServer:Tn.ensure,localHostAvailable:Tn.available,...n.clientVersion===void 0?{}:{clientVersion:n.clientVersion},platformGameVersion:()=>ne.gameVersion,...n.pollRooms===void 0?{}:{poll:n.pollRooms},...n.recoverStaleMembership===void 0?{}:{recoverStaleMembership:n.recoverStaleMembership},...n.retryAutoStart===void 0?{}:{retryAutoStart:n.retryAutoStart},...n.watchSeats===void 0?{}:{watchSeats:n.watchSeats},...n.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:n.seatPollIntervalMs},...Hr===null?{}:{autoReconnect:{...Hr,redial:(c,S)=>Kr.redialMatch(c,S),abandon:(c,S)=>Kr.abandonMatch(c,S)}}});m(ce),zl({analytics:a,rooms:ce});let lt=Jl({client:st,clock:e,rooms:ce,bridge:$,gameId:()=>ne.identity?.gameId??"",baseUrl:()=>xe,resolveClusterTarget:Pn.resolve,boot:o,...n.log===void 0?{}:{log:n.log}}),zo=mo(o,t),Ct=Od({client:st,clock:e,rooms:ce,signaling:()=>Rn.channel(),signalingReady:F,log:t??(()=>{})}),Kr=Kd({rooms:ce,p2p:{connect:c=>zo(lt.connect(c)),session:c=>lt.session(c)},dedicated:{connect:(c=>Tr(o,"welcome",Ct.connect(c),t))},clock:e,identity:()=>ne.identity,apiBaseUrl:()=>xe,tokens:qo,room:()=>ce.currentRoom,autoReconnect:Hr!==null,...n.log===void 0?{}:{log:n.log}}),Dc=async()=>(await Vr($o)).playerId,Yo={client:st,boot:o,get identity(){return ne.identity},awaitIdentity:(c=$o)=>Vr(c),awaitBridge:c=>$.settled(c),get player(){return b.current},awaitPlayer:(c=ah)=>b.wait(c),me:Jo,characters:new Jn(pe,void 0,No,Ko),transfers:new Yn(pe,ui,Jo.inventory),gameConfig:Wr,purchases:Nr.api,deviceSettings:An.api,moments:Wo.api,ads:Bo.api,account:Vo.api,share:ac({frame:$,log:n.log}),vibration:sc({frame:$,log:n.log}),get avatarPickerAvailable(){return $.currentState==="connected"&&$.parentSupports("avatarPicker")},openAvatarPicker:c=>$.requestAvatarPicker(c?.tab),avatars3d:Gc,controls:uc({recommended:()=>x.current?.recommended??null}),analytics:a,leaderboards:new Nt(pe),challenges:new $t(pe),showcase:new jt(pe,Dc),friends:new Ut(pe,{challenge:Ho.challenge,...i===void 0?{}:{launchedChallengeId:i}}),platform:new Wt(pe,k,t),profiles:new Vt(pe),functions:new ze((c,S)=>Va(pe,c,S)),get prefs(){return x.current},get paused(){return I},get cohorts(){return h.current},get viewport(){return C.current},awaitCohorts:(c=sh)=>h.wait(c),reportMuted:c=>{W=!!c,D();},showPortraitBorders:c=>{let S=$r(c);S!==void 0&&(q=S,j());},cueReward:c=>$.cueReward(c),setWalletVisible:(c,S)=>{let N=Array.isArray(S?.only)?[...S.only]:void 0;return U=N===void 0?{visible:c===true}:{visible:c===true,only:N},oe()},setMenu:c=>(ae=Array.isArray(c?.items)?{items:c.items.map(S=>({...S}))}:{},Ne()),setGemCorner:c=>{if(!nh.includes(c)){let S=typeof c=="string"?JSON.stringify(c.slice(0,48)):`a value of type ${typeof c}`;return console.warn(`[gem] setGemCorner: ${S} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return me=c,je()},exit:c=>lh(ce,$,c,a),frame:$,devtools:ee,rooms:ce,dedicatedServer:{listClusterTargets:c=>Ct.listClusterTargets(c),connect:(c=>Tr(o,"welcome",Ct.connect(c),t)),handleMatchEnded:(c,S)=>Ct.handleMatchEnded(c,S)},p2p:{handleSignalEvent:(c,S,N)=>lt.handleSignalEvent(c,S,N),session:c=>lt.session(c),connect:c=>zo(lt.connect(c))},match:Kr};return Yo}
|
|
2
|
-
export{eh as ARCADE_EMBEDDERS,Qf as AVATAR_RIGS,Ht as AnalyticsApi,ie as AuthError,$t as ChallengesApi,Lo as DEVICE_SETTINGS_MAX_BYTES,w as DedicatedServerError,Je as FriendChallengeError,Ut as FriendsApi,ze as FunctionsApi,O as GemApiError,We as GemClient,ue as GemConfigError,_n as GemFrame,ar as GemFunctionError,le as GemSaveError,vn as GemUnframedError,Nt as LeaderboardsApi,Os as MAX_PERIODS_BACK,xm as PLATFORM_EVENTS,Wt as PlatformApi,ir as PlatformCurrenciesApi,or as PlatformEarnAllowanceApi,he as PlayerText,Vt as ProfilesApi,$e as PurchaseRefusal,jt as ShowcaseApi,se as TransportRefusal,Xt as UNRELIABLE_CHANNEL_LABEL,Ge as asPlayerText,po as createBootTimeline,Ex as createGem,lh as leaveAndExit,Re as mapIdentity,Tr as markOnResolve,Xu as platformIconUrl,zt as presentJoinCredential,vt as readTemplateTransports,Qt as readTransportAdvert,mo as reportOnResolve,pt as text,fr as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.game.js.map
|
|
1
|
+
var Uc=Object.defineProperty;var Bc=(n,e)=>{for(var t in e)Uc(n,t,{get:e[t],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:13.3.1]";function Qo(){let n=globalThis.__gemWebSdkVersion;if(typeof n!="string")return "";let e=n.lastIndexOf(":"),t=n.lastIndexOf("]");return e<0||t<=e+1?"":n.slice(e+1,t)}var Wc={initialDelayMs:2e3,maxDelayMs:6e4};function Vc(n,e){return e!==void 0?!e:n==="chain_exhausted"}var ut=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;retry=null;failures=0;notBefore=0;disposed=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new ie(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.pastChainCeiling())throw new ie("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new ie(this.failure??"unavailable","the embedder asked for no new token yet; one is asked for when that wait is over");return this.refresh(this.nextReason())}pastChainCeiling(){return this.grant===null||this.seconds()<this.grant.chainEndsAt?false:(this.enter("lost","chain_exhausted"),true)}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}dispose(){this.disposed=true,this.cancelRetry();}scheduleRetry(e){if(this.cancelRetry(),this.failures+=1,this.notBefore=e===void 0?0:this.options.clock.now()+e,this.disposed)return;let{initialDelayMs:t,maxDelayMs:r}=Wc,i=Math.min(r,t*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 t=this.generation;this.enter("pending");let r=this.options.request(e).then(i=>{if(t!==this.generation)throw new ie("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=Hc(i),{retryable:s,retryAfterMs:a}=i??{};throw t===this.generation&&(Vc(o,typeof s=="boolean"?s:void 0)?this.enter("lost",o):(this.scheduleRetry(typeof a=="number"&&Number.isFinite(a)&&a>0?a:void 0),this.enter("degraded",o))),i instanceof ie?i:new ie(o,String(i))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,t){(e==="ready"||e==="lost")&&this.cancelRetry(),e==="ready"&&(this.failures=0,this.notBefore=0),this.failure=t??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,t));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},ie=class n extends Error{constructor(t,r){super(`auth ${t}: ${r}`);this.reason=t;this.name="AuthError";}reason;static isAuthError(t){if(t instanceof n)return true;let r=t;return r?.name==="AuthError"&&typeof r.reason=="string"}};function Hc(n){if(n instanceof ie)return n.reason;let e=n?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var ae=class n extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof n)return true;let t=e;return t?.name==="TransportRefusal"&&t.retryable===false}},zr=["if-match","if-none-match"],Zo=4096;function Kc(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n)){let i=t.toLowerCase();if(!zr.includes(i)||r===void 0)continue;let o=typeof r=="string"?Jc(r):r;if(typeof o!="string"||o.length>Zo||!zc(o))throw new ae(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${Zo} 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 Jc(n){let e=i=>i===32||i===9||i===10||i===13,t=0,r=n.length;for(;t<r&&e(n.charCodeAt(t));)t++;for(;r>t&&e(n.charCodeAt(r-1));)r--;return n.slice(t,r)}function zc(n){for(let e=0;e<n.length;e++){let t=n.charCodeAt(e);if(t!==9&&(t<32||t===127||t>255))return false}return true}function Yc(n){let{bytes:e}=n;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new ae("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(n.body!==void 0)throw new ae("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 ea(n,e){let t=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=Kc(i.headers),s=Yc(i),a=Object.freeze({...i,headers:o,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await n(a,l);if(d.status!==401||!t)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),u=await n(a,m);if(u.status===401)throw e.tokenSource.close("unavailable"),new ie("unavailable","the server refused a freshly minted token");return u}}}function Yr(n){let e=typeof n=="string"?new TextEncoder().encode(n):n;return btoa(Xc(e))}function En(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function Xr(n){return new TextDecoder().decode(En(n))}function Xc(n){let t="";for(let r=0;r<n.length;r+=32768)t+=String.fromCharCode(...n.subarray(r,r+32768));return t}var O=class extends Error{constructor(t,r,i,o,s){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},na=new WeakMap;function ra(n){return na.get(n)??{}}var Qc=new Set([408,429,500,502,503,504]),Zc=6e4;function eu(n){if(n===void 0)return 2;if(!Number.isInteger(n)||n<0||n>10)throw new ae(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(n)}. This is a configuration fault, not a server failure.`);return n}var Be=class{constructor(e){this.options=e;}options;async get(e,t){return this.send({method:"GET",path:e,signal:t},true)}async getWithEtag(e,t={}){let r=await this.sendRaw({method:"GET",path:e,...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{headers:{"if-none-match":t.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,t,r,i={}){return this.send({method:"PUT",path:e,body:t,signal:r,...Lt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async post(e,t,r,i={}){return this.send({method:"POST",path:e,body:t,signal:r,...Lt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async postBytes(e,t,r,i={}){let o=await this.sendRaw({method:"POST",path:e,bytes:t,responseType:"bytes",signal:r,...Lt(i)},i.replaySafe===true,i.retryRateLimited!==false);return {bytes:tu(o.body),...o.invocationId===void 0?{}:{invocationId:o.invocationId}}}async patch(e,t,r,i={}){return this.send({method:"PATCH",path:e,body:t,signal:r,...Lt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async delete(e,t,r={}){return this.send({method:"DELETE",path:e,signal:t,...Lt(r)},r.replaySafe===true,r.retryRateLimited!==false)}async send(e,t,r=true){return (await this.sendRaw(e,t,r)).body}async sendRaw(e,t,r=true){let i=t?eu(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw ta(e.signal);for(let s=0;s<i;s++){if(s>0&&await this.backoff(s,o,e.signal),e.signal?.aborted)throw ta(e.signal);let a;try{a=await this.options.transport.request(e);}catch(d){if(ie.isAuthError(d)||ae.isRefusal(d)||e.signal?.aborted||nu(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=ru(a);if(!Qc.has(a.status)||a.status===429&&!r)throw l;o=l;}throw o??new O("unavailable",0,"no attempt was made")}backoff(e,t,r){if(r?.aborted)return Promise.resolve();let i=t?.retryAfterSeconds,o=i!==void 0?i*1e3:2**(e-1)*250,s=2**(e-1)*250,a=Math.min(Math.max(o,s),Zc);return new Promise(l=>{let d=this.options.clock,m=false,u=false,p,g=()=>{m||(m=true,u&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,a),u=true,m&&d.clearTimeout(p);})}};function tu(n){if(n instanceof Uint8Array)return n;if(n==null)return new Uint8Array(0);let e=typeof n=="string"?n:JSON.stringify(n);return new TextEncoder().encode(e)}function Lt(n){return {...n.keepalive===void 0?{}:{keepalive:n.keepalive},...n.ifMatch===void 0?{}:{headers:{"if-match":n.ifMatch}}}}function ta(n){return n.reason!==void 0?n.reason:new DOMException("The operation was aborted.","AbortError")}function nu(n){let e=n?.name;return e==="AbortError"||e==="TimeoutError"}function ru(n){let e=ou(n),t=su(n.body),r={...t===void 0?{}:{details:t},...n.invocationId===void 0?{}:{invocationId:n.invocationId}};return Object.keys(r).length>0&&na.set(e,r),e}var iu=new Map([["insufficient_funds","insufficient_funds"]]);function ou(n){let{status:e,body:t}=n,r=au(t),i=n.retryAfterSeconds??du(t),o=lu(t),s=o===void 0?void 0:iu.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 au(n){if(typeof n=="string")return n;let e=n?.message;if(typeof e=="string")return e;let t=n?.error;if(typeof t=="string")return t;let r=t?.message;return typeof r=="string"?r:"no detail"}function su(n){let t=n?.error?.details;return t===null?void 0:t}function lu(n){let t=n?.error?.code;return typeof t=="string"&&t.length>0?t:void 0}function du(n){let e=n?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function _(n){let e=String(n);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function ia(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function oa(n,e,t,r,i,o){let s=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/add`;return n.client.post(s,i,o?.signal)}async function aa(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function sa(n,e,t){let r=`/v1/games/${_(n.gameId())}/matchmaking/tickets/${_(e)}`;return n.client.delete(r,t?.signal)}async function la(n,e,t,r,i,o){let s=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/claim`;return n.client.post(s,i,o?.signal)}async function da(n,e,t){return n.client.post("/v1/characters",e,t?.signal)}async function ca(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/orders/batch`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ua(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/orders`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ma(n,e,t){let r=`/v1/games/${_(n.gameId())}/matchmaking/tickets`;return n.client.post(r,e,t?.signal)}async function pa(n,e,t,r,i){let o=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.delete(o,i?.signal)}async function ga(n,e,t,r,i){let o=`/v1/saves/${_(e)}/${_(t)}/${_(r)}`;return n.client.delete(o,i?.signal)}async function ya(n,e,t,r){let i=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.delete(i,r?.signal)}async function fa(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/recipes/execute`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ha(n,e,t,r,i,o){let s=`/v1/saves/${_(e)}/${_(t)}/${_(r)}/finalize`;return n.client.post(s,i,o?.signal)}async function ba(n,e,t){let r=`/v1/games/${_(n.gameId())}/avatars-3d/${_(e)}/owned`;return n.client.get(r,t?.signal)}async function va(n,e,t){let r=`/v1/games/${_(n.gameId())}/config/channels/${_(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function _a(n,e,t){let r=`/v1/characters/${_(e)}`;return n.client.get(r,t?.signal)}async function wa(n,e,t){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function ka(n,e,t,r,i){let o=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Ra(n,e,t,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)}/${_(t)}`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Sa(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/items/${_(r)}`;return n.client.get(o,i?.signal)}async function xa(n,e,t,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)}/${_(t)}/${_(r)}`+(s?`?${s}`:"");return n.client.get(a,i?.signal)}async function Aa(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/orders/${_(r)}`;return n.client.get(o,i?.signal)}async function Pa(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}`;return n.client.get(o,i?.signal)}async function Ta(n,e,t,r,i,o){let s=`/v1/inventory/${_(e)}/${_(t)}/catalogs/${_(r)}/recipes/${_(i)}/availability`;return n.client.get(s,o?.signal)}async function Ea(n,e,t,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(t)}/recipe-usage`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Qr(n,e,t,r,i){let o=`/v1/saves/${_(e)}/${_(t)}/${_(r)}`;return n.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Ia(n,e,t){let r=new URLSearchParams;t?.bucket_1!==void 0&&r.set("bucket_1",String(t?.bucket_1)),t?.bucket_2!==void 0&&r.set("bucket_2",String(t?.bucket_2)),t?.periods_back!==void 0&&r.set("periods_back",String(t?.periods_back)),t?.period!==void 0&&r.set("period",String(t?.period)),t?.player_id!==void 0&&r.set("player_id",String(t?.player_id));let i=r.toString(),o=`/v1/leaderboards/${_(e)}/friends`+(i?`?${i}`:"");return n.client.get(o,t?.signal)}async function Ca(n,e,t){let r=`/v1/showcase/friends/${_(e)}`;return n.client.get(r,t?.signal)}async function Ma(n,e){let t=`/v1/games/${_(n.gameId())}/avatars-3d`;return n.client.get(t,e?.signal)}async function Oa(n,e,t){let r=`/v1/inbox/friend-challenges/${_(e)}`;return n.client.get(r,t?.signal)}async function La(n,e,t){let r=new URLSearchParams;t?.bucket_1!==void 0&&r.set("bucket_1",String(t?.bucket_1)),t?.bucket_2!==void 0&&r.set("bucket_2",String(t?.bucket_2)),t?.periods_back!==void 0&&r.set("periods_back",String(t?.periods_back)),t?.period!==void 0&&r.set("period",String(t?.period)),t?.player_id!==void 0&&r.set("player_id",String(t?.player_id));let i=r.toString(),o=`/v1/leaderboards/${_(e)}`+(i?`?${i}`:"");return n.client.get(o,t?.signal)}async function Ga(n,e){let t=`/v1/games/${_(n.gameId())}/players/me/earn-allowance`;return n.client.get(t,e?.signal)}async function In(n,e){return n.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function Da(n,e,t){let r=`/v1/profiles/players/${_(e)}`;return n.client.get(r,t?.signal)}async function $a(n,e){let t=new URLSearchParams;e?.config_version!==void 0&&t.set("config_version",String(e?.config_version));let r=t.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Fa(n,e,t){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return n.client.get(r,t?.signal)}async function qa(n,e,t,r){let i=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.get(i,r?.signal)}async function Na(n,e){return n.client.get("/v1/characters/slots",e?.signal)}async function ja(n,e,t){let r=`/v1/inventory/transfers/${_(e)}`;return n.client.get(r,t?.signal)}async function Ua(n,e,t){let r=`/v1/games/${_(n.gameId())}/matchmaking/tickets/${_(e)}/heartbeat`;return n.client.post(r,void 0,t?.signal)}async function Ba(n,e,t){let r=`/v1/games/${_(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{...t?.keepalive===void 0?{}:{keepalive:t.keepalive},replaySafe:true,retryRateLimited:false})}async function Wa(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Va(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/platform-funded-game-inventory-purchases`;return n.client.post(o,r,i?.signal)}async function Ha(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function Ka(n,e){let t=new URLSearchParams;e?.periods_back!==void 0&&t.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&t.set("player_id",String(e?.player_id));let r=t.toString(),i="/v1/challenges"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Ja(n,e){return n.client.get("/v1/characters",e?.signal)}async function za(n,e,t,r){let i=`/v1/settings/${_(e)}/${_(t)}`;return n.client.get(i,r?.signal)}async function Ya(n,e,t,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)}/${_(t)}/orders`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Xa(n,e,t,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)}/${_(t)}`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Qa(n,e){let t=new URLSearchParams;e?.cursor!==void 0&&t.set("cursor",String(e?.cursor)),e?.limit!==void 0&&t.set("limit",String(e?.limit));let r=t.toString(),i="/v1/inbox/friend-challenges"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Za(n,e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e?.limit)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor));let r=t.toString(),i="/v1/friends"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function es(n,e){let t=new URLSearchParams;e.entity_type!==void 0&&t.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&t.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&t.set("direction",String(e?.direction)),e?.status!==void 0&&t.set("status",String(e?.status)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor)),e?.limit!==void 0&&t.set("limit",String(e?.limit));let r=t.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function ts(n,e,t){let r=`/v1/inbox/friend-challenges/${_(e)}/answered`;return n.client.post(r,void 0,t?.signal)}async function ns(n,e,t,r){let i=`/v1/games/${_(n.gameId())}/matches/${_(e)}/end`;return n.client.post(i,t,r?.signal)}async function rs(n,e,t,r,i,o){let s=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/max`;return n.client.post(s,i,o?.signal)}async function is(n,e,t,r,i,o){let s=`/v1/settings/${_(e)}/${_(t)}/${_(r)}`;return n.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function os(n,e,t,r,i){let o=`/v1/showcase/players/${_(e)}/${_(t)}`;return n.client.put(o,r,i?.signal)}async function as(n,e,t,r,i){let o=`/v1/inventory/${_(e)}/${_(t)}/rewarded-placements/${_(r)}/availability`;return n.client.get(o,i?.signal)}async function ss(n,e,t){let r=`/v1/inventory/transfers/${_(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function ls(n,e,t,r){let i=`/v1/characters/${_(e)}`;return n.client.patch(i,t,r?.signal)}async function ds(n,e,t,r,i,o){let s=`/v1/saves/${_(e)}/${_(t)}/${_(r)}/upload-url`;return n.client.post(s,i,o?.signal,{replaySafe:true})}async function cs(n,e,t,r,i,o){let s=`/v1/inventory/${_(e)}/${_(t)}/progressions/${_(r)}/reset`;return n.client.post(s,i,o?.signal)}async function us(n,e,t){let r=`/v1/characters/${_(e)}`;return n.client.delete(r,t?.signal)}var U="gem-web-bridge",Mn={min:1,max:1},mt=65536,ms=8,Cn=5e3,ps=1024;var Gt=Object.create(null),On="__malformed";var ei=Object.create(null),cu=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"]]);function gs(n){let e=ei[n];if(e!==void 0)return e;for(let[t,r]of cu)if(n.startsWith(t))return r}function ti(n){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(n);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function uu(n){let e;try{e=new URL(n);}catch{return false}return e.username!==""||e.password!==""?false:e.protocol==="https:"?true:e.protocol==="http:"&&(e.hostname==="localhost"||e.hostname==="127.0.0.1")}function mu(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function pu(n){return /^[a-z_]+$/.test(n)}function Zr(n,e,t){if(e>ms)return `nesting deeper than ${ms}`;if(++t.nodes>Cn)return `more than ${Cn} values`;if(t.bytes>mt)return `over the ${mt} byte limit`;if(n==null)return t.bytes+=4,null;let r=typeof n;if(r==="boolean")return t.bytes+=5,null;if(r==="number")return t.bytes+=8,null;if(r==="string")return t.bytes+=n.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=n;if(t.seen.has(i))return "a repeated or cyclic object reference";if(t.seen.add(i),Array.isArray(n)){if(n.length>ps)return `an array of ${n.length} entries, over the ${ps} limit`;t.bytes+=2;for(let a of n){let l=Zr(a,e+1,t);if(l)return l}return null}let o=Object.getPrototypeOf(n);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";t.bytes+=2;let s=n;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++t.nodes>Cn)return `more than ${Cn} values`;if(t.bytes+=a.length*3+4,t.bytes>mt)return `over the ${mt} byte limit`;let l=Zr(s[a],e+1,t);if(l)return l}return null}function gu(n){let e={nodes:0,bytes:0,seen:new Set},t=Zr(n,0,e);return t?`message contains ${t}`:e.bytes>mt?`message is over the ${mt} byte limit`:null}var yu={origin:[ti,"not a well-formed origin"],url:[uu,"not a safe absolute http(s) URL"],bcp47:[mu,"not a well-formed BCP 47 tag"],code:[pu,"not a code of lower-case letters and underscores"]};function ys(n,e,t){for(let r of e){let i=t===""?r.n:`${t}.${r.n}`,o=n[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let s=fs(o,r,i);if(s)return s}return null}function fs(n,e,t){switch(e.k){case "s":{if(typeof n!="string")return `${t}: expected string`;if(n.length>e.max)return `${t}: exceeds ${e.max} characters`;if(e.f){let[r,i]=yu[e.f];if(!r(n))return `${t}: ${i}`}return null}case "i":return typeof n!="number"||!Number.isInteger(n)?`${t}: expected integer`:n<e.lo||n>e.hi?`${t}: out of range ${e.lo}..${e.hi}`:null;case "b":return typeof n=="boolean"?null:`${t}: expected boolean`;case "e":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "o":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:ys(n,e.fs,t);case "j":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "a":{if(!Array.isArray(n))return `${t}: expected array`;if(n.length>e.max)return `${t}: exceeds ${e.max} items`;let r=e.it,i=`${t}[]`;for(let o of n){if(o==null){if(r.o)continue;return `${i}: required`}let s=fs(o,r,i);if(s)return s}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}var hs=Object.create(null);function P(n,e,t,r){return Gt[n]=t,r&&(ei[n]=r),hs[n]=i=>{let o=gu(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!==n?`type: expected ${n}`:ys(s,e,"")}}P("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);P("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);P("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);P("gem.token.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}],30);P("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);P("gem.pause",[{n:"paused",k:"b"}],120);P("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"},{n:"lookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"gamepadLookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"invertLookY",k:"b",o:1},{n:"touchMovement",k:"s",o:1,max:16,f:"code"},{n:"graphicsQuality",k:"s",o:1,max:16,f:"code"},{n:"graphicsQualityAuto",k:"b",o:1}]}],60);P("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");P("gem.earnAllowanceChanged",[],30,"earnAllowance");P("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}]}}],60,"viewport");P("gem.deviceSettings",[{n:"settings",k:"j",o:1}],12,"deviceSettings");P("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}],10);P("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");P("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}],12,"socketState");P("gem.seatedEvent",[{n:"roomId",k:"s",max:64}],60,"partySeating");P("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}],30,"autoStartFailure");P("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");P("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");P("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");P("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}],30,"parties");P("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}],12,"clusterTarget");P("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}],30,"devtools");P("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}],6,"screenshot");P("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");P("gem.requestContext",[],12,"feedbackContext");P("gem.gameContext",[{n:"context",k:"j"}],12,"feedbackContext");P("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");P("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");P("gem.partyRequest",[{n:"requestId",k:"s",max:64}],12,"parties");P("gem.ready",[],5);P("gem.engaged",[],5,"engagement");P("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}],600);P("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}],12);P("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}],6,"localHost");P("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}],30,"localHost");P("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}],30,"localHost");P("gem.exit",[{n:"reason",k:"s",o:1,max:64}],5);P("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}],6);P("gem.requestFullscreen",[{n:"enabled",k:"b"}],30);P("gem.audioState",[{n:"muted",k:"b"}],120,"audioState");P("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");P("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");P("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");P("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");P("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}],60,"gameMenu");P("gem.gemCorner",[{n:"corner",k:"e",v:["top-left","top-right","bottom-left","bottom-right"]}],12,"gemCorner");P("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");P("gem.requestAvatarPicker",[{n:"tab",k:"e",o:1,v:["2d","3d"]}],6,"avatarPicker");P("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}],600,"vibration");P("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");P("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}],60,"portraitBorders");P("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);P("gem.requestPurchase",[{n:"requestId",k:"s",max:64},{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}],12,"purchases");P("gem.requestAvatar3dPurchase",[{n:"requestId",k:"s",max:64},{n:"itemId",k:"s",max:64},{n:"currencySlug",k:"s",max:32}],12,"avatar3dPurchases");P("gem.purchaseResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}],30,"purchases");P("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}],30,"deviceSettings");P("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}],30,"deviceSettings");P("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}],6,"ads");P("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}],12,"ads");P("gem.signalMoment",[{n:"requestId",k:"s",max:64},{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");P("gem.momentResult",[{n:"requestId",k:"s",max:64},{n:"shown",k:"b"}],12,"moments");P("gem.requestSignIn",[{n:"requestId",k:"s",max:64}],6,"signIn");P("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}],12,"signIn");P("gem.requestFriendChallenge",[{n:"requestId",k:"s",max:64},{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}],12,"friendChallenges");P("gem.friendChallengeResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}],30,"friendChallenges");var Ln=Object.freeze(hs);Gt.__malformed=60;Object.freeze(Gt);Object.freeze(ei);var he={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},Dt=class{constructor(e=he){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=Gt[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,s=Math.max(0,r-i),a=Math.min(t,o+s*t/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function ni(n,e){return n.toLowerCase()===e.toLowerCase()}function pt(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function bs(n,e){if(typeof e!="string"||e==="")return false;let t,r;try{t=new URL(n),r=new URL(e);}catch{return false}return t.protocol!=="http:"&&t.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||t.username!==""||t.password!==""||t.pathname!=="/"||t.search!==""||t.hash!==""||t.port===""?false:pt(t.hostname)&&pt(r.hostname)}function vs(n,e){if(e.min>e.max)return null;let t=Math.min(n.max,e.max),r=Math.max(n.min,e.min);return t>=r?t:null}var Gn=class{constructor(e,t){this.inventory=e;this.resolveCurrencyId=t;}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,t={}){let i=(await this.inventory.snapshot({buckets:t.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 ii(n){let e=Array.isArray(n.achievements)?n.achievements:[],t=[];for(let r of e){let i=r??{};typeof i.id!="string"||i.id===""||typeof i.threshold!="number"||!Number.isFinite(i.threshold)||t.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 {...t.length>0?{achievements:t}:{},...n.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var _s="inventory",gt=n=>typeof n=="number"?n:0,$t=n=>typeof n=="string"?n:"";function ri(n,e){let t=n??{},r=typeof t.next_cursor=="string"?t.next_cursor:void 0;return {data:Array.isArray(t.data)?t.data.map(e):[],...r===void 0?{}:{nextCursor:r}}}function ws(n){let e=n??{};return {itemDefinitionId:$t(e.item_definition_id),instanceId:$t(e.instance_id),quantity:gt(e.quantity),acquiredAt:gt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function fu(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {currencies:ri(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(s=>{let a=s??{};return {bucket:$t(a.bucket),balance:gt(a.balance)}}):void 0;return {currencyId:$t(i.currency_id),total:gt(i.total),...o===void 0?{}:{buckets:o}}}),items:ri(e.items,ws),progressions:ri(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:$t(i.progression_definition_id),currentValue:gt(i.current_value),completionCount:gt(i.completion_count),isCompleted:i.is_completed===true,...ii(i)}}),...t===void 0?{}:{etag:t}}}var Dn=class{constructor(e,t,r){this.api=e;this.entity=t;this.cache=r;}api;entity;cache;snapshot(e={}){let t=e.buckets?`${_s}#buckets`:_s;return this.cache.read(t,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,t){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 Sa(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Array.isArray(i)?i.map(ws):[]}page(e){return this.fetch(e)}refresh(){this.invalidate();}onChanged(e){return this.cache.onInvalidate(e)}invalidate(){this.cache.invalidate();}async fetch(e){let t=await Ra(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 fu(t)}};var hu={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},bu=new Set(Object.keys(hu));function ks(n){return typeof n=="string"&&bu.has(n)?n:"error"}var Ne=class extends RangeError{constructor(t,r){super(r);this.code=t;this.name="PurchaseRefusal";}code;retryable=false};var ee=n=>typeof n=="string"?n:"",vu=n=>typeof n=="string"?n:ee(n&&typeof n=="object"?n.type:void 0),Ae=n=>typeof n=="number"?n:0;function _u(n){let e=n??{};return {prerequisiteType:ee(e.prerequisite_type),referenceId:ee(e.reference_id),required:Ae(e.required),current:Ae(e.current)}}function Ft(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {orderId:ee(e.order_id),status:ee(e.status),...t===void 0?{}:{etag:t}}}function $n(){return crypto.randomUUID()}var wu="recipe-usage",Rs=100;function Fn(n){let e=n??{};switch(e.type){case "currency":return {kind:"currency",currencyId:ee(e.currency_id),bucket:ee(e.bucket),delta:Ae(e.delta),balanceAfter:Ae(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:ee(e.item_definition_id),instanceId:ee(e.instance_id),delta:Ae(e.delta),quantityAfter:Ae(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:ee(e.progression_definition_id),delta:Ae(e.delta),valueAfter:Ae(e.value_after),completed:e.completed===true};default:return {kind:"other",type:ee(e.type)}}}function ku(n){let e=n??{},t=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:ee(e.entry_id),...t===void 0?{}:{rarityTier:t},rollNumber:Ae(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(Fn):[]}}function Ru(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(ku):void 0;return {orderId:ee(e.order_id),status:ee(e.status),...t===void 0?{}:{etag:t},granted:Array.isArray(e.granted)?e.granted.map(Fn):[],consumed:Array.isArray(e.consumed)?e.consumed.map(Fn):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(Fn):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function Su(n){let e=n??{},t=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(t.platform_currency_id),amount:Ae(t.price)}}}function xu(n){let e=n??{},t=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,...t===void 0?{}:{lastUsedAt:t},...r===void 0?{}:{cooldownExpiresAt:r}}}function Ss(n){switch(n.type){case "currency_grant":case "currency_consume":return {type:n.type,currency_id:n.currencyId,amount:n.amount};default:return {type:n.type,item_definition_id:n.itemDefinitionId,quantity:n.quantity}}}var qn=class{constructor(e,t,r){this.api=e;this.entity=t;this.cache=r;}api;entity;cache;async create(e,t={}){let r=await this.write(()=>ua(this.api,this.entity.type,this.entity.id,{operations:e.map(Ss),source:t.source??"play",nonce:$n()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return Ft(r)}async createMany(e,t={}){return this.write(()=>ca(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Ss),nonce:$n()})),source:t.source??"play"},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}))}async recipeAvailability(e,t,r){let o=await Ta(this.api,this.entity.type,this.entity.id,e,t,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(_u):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>vu(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(wu,[],async()=>{let t=await Ea(this.api,this.entity.type,this.entity.id,{limit:Rs})??{},r=Array.isArray(t.usages)?t.usages:[];return {usages:r.map(xu),truncated:r.length>=Rs}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,t={}){if(e.payment.kind==="configured"){let u=e,p=await this.write(()=>fa(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:$n()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return {payment:"configured",...Ru(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([$a(this.api,t.signal===void 0?{}:{signal:t.signal}),In(this.api,t.signal===void 0?{}:{signal:t.signal})]),o=e.payment.currencySlug.toLowerCase(),s=i.currencies.find(u=>u.currency_id.toLowerCase()===o||u.slug.toLowerCase()===o);if(s===void 0){let u=i.currencies.map(p=>p.slug);throw new Ne("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${u.length===0?"none":u.join(", ")}`)}let a=e.kind==="item"?r.items.find(u=>u.item_id===e.targetId):r.recipes.find(u=>u.recipe_id===e.targetId&&u.catalog_id===e.catalogId);if(a===void 0)throw new Ne("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=a.platform_prices.find(u=>u.platform_currency_id===s.currency_id);if(l===void 0){let u=g=>i.currencies.find(y=>y.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${u(g.platform_currency_id)} ${g.price}`);throw new Ne("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 Ne("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>Va(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:$n(),confirmation:"none"},t.signal===void 0?{}:{signal:t.signal}));return Su(m)}async executeRecipe(e,t,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:t,payment:{kind:"configured"}},r)}async addProgression(e,t,r){let i=await this.write(()=>oa(this.api,this.entity.type,this.entity.id,e,{amount:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Ft(i)}async maxProgression(e,t,r){let i=await this.write(()=>rs(this.api,this.entity.type,this.entity.id,e,{value:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Ft(i)}async claimProgression(e,t){let r=await this.write(()=>la(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return Ft(r)}async resetProgression(e,t){let r=await this.write(()=>cs(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return Ft(r)}async write(e){return this.cache.invalidate(),e()}};var oi=n=>typeof n=="string"?n:"",Au=n=>typeof n=="number"?n:0;function xs(n){let e=n??{};return {orderId:oi(e.order_id),status:oi(e.status),source:oi(e.source),createdAt:Au(e.created_at)}}var Nn=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e={}){let r=await Ya(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(xs):[],...i===void 0?{}:{nextCursor:i}}}async get(e,t){let r=await Aa(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return xs(r)}};var As=n=>typeof n=="number"?n:0,Pu=n=>typeof n=="string"?n:"";function Tu(n){let e=n??{};return {progressionDefinitionId:Pu(e.progression_definition_id),currentValue:As(e.current_value),completionCount:As(e.completion_count),isCompleted:e.is_completed===true,...ii(e)}}var jn=class{constructor(e,t,r){this.api=e;this.entity=t;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,t){let i=(await this.inventory.snapshot()).progressions.data.find(o=>o.progressionDefinitionId===e);if(i&&i.achievementsUnavailable!==true)return i;try{let o=await Pa(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Tu(o)}catch{return i??null}}};var Un=class{constructor(e,t){this.clock=e;this.identity=t;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,t,r,i){this.rebind();let o=t.length===0,s=o?e:e+"\0"+t.join("\0"),a=this.slots.get(s);if(a){let u=a.filledAt;if(u!==void 0&&(i===void 0||this.clock.now()-u<=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(u=>(o&&this.generation===d&&(l.value=u,l.filledAt=this.clock.now()),u)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(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 ai(n){let e=i=>new RegExp(`<${i}>([^<]{0,300})</${i}>`).exec(n)?.[1]?.trim()||void 0,t=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(t.length>0)return t.join(" \u2014 ");let r=n.trim();return r?r.slice(0,300):""}async function si(n){try{let e=ai(await n.text());return e?`Storage said: ${e}`:""}catch{return ""}}var se=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemSaveError";}reason},Eu=3e4,Ps="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",Iu=/^[A-Za-z0-9_]{1,64}$/;function Pe(n){let e=n.length===0?"a save key cannot be empty":n.length>64?`it is ${n.length} characters; a save key is at most 64`:n.startsWith("_")||n.startsWith("$")?`it begins with ${JSON.stringify(n[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(!Iu.test(n)||n.startsWith("_"))throw new TypeError(`${JSON.stringify(n)} is not a usable save key: ${e}.`);return n}function Ts(n,e){let t=new AbortController,r=AbortSignal.timeout(e),i=()=>t.abort(r.reason),o=()=>t.abort(n?.reason);return n?.aborted?t.abort(n.reason):(r.addEventListener("abort",i,{once:true}),n?.addEventListener("abort",o,{once:true})),{signal:t.signal,release:()=>{r.removeEventListener("abort",i),n?.removeEventListener("abort",o);}}}function li(n,e){return n.aborted&&e?.aborted!==true}var Cu=new Set(["x-ms-blob-type"]),Mu=/^[ -~]+$/;function Ou(n,e){if(n==null)return {};if(typeof n!="object"||Array.isArray(n))throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(n)?"a list":typeof n}, which is not a set of headers.`);let t={};for(let[r,i]of Object.entries(n)){let o=r.toLowerCase();if(!Cu.has(o))throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof i!="string"||!Mu.test(i))throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(o in t)throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);t[o]=i;}return t}function di(n){let e=typeof n.metadata=="object"&&n.metadata!==null&&!Array.isArray(n.metadata)?n.metadata:void 0;return {key:n.key,sizeBytes:n.size_bytes,etag:n.etag,...e===void 0?{}:{metadata:e},createdAt:n.created_at,updatedAt:n.updated_at}}function ci(n){return n?.reason==="not_found"}var Bn=class{constructor(e,t,r={}){this.api=e;this.entity=t;this.options=r;}api;entity;options;async put(e,t,r={}){let i;try{i=JSON.stringify(t);}catch(o){throw new se("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 se("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(i),{...r,contentType:"application/json"})}async putBytes(e,t,r={}){let i=r.contentType??"application/octet-stream",o=this.budget(r.timeoutMs),s=Ts(r.signal,o);try{let a=await ds(this.api,this.entity.type,this.entity.id,Pe(e),{size_bytes:t.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 se("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=Ou(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:t,credentials:"omit",signal:s.signal});}catch(u){throw li(s.signal,r.signal)?this.timeout("upload",o):new se("upload_failed",`${Ps} for PUT. Underlying error: ${u}`)}if(!d.ok){let u=await si(d);throw new se("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+u:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+u)}return di(await ha(this.api,this.entity.type,this.entity.id,Pe(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,t={}){let r=await this.getBytes(e,t);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(i){throw new se("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${i}`)}}async getBytes(e,t={}){let r=this.budget(t.timeoutMs),i=Ts(t.signal,r);try{let o;try{let l=await Qr(this.api,this.entity.type,this.entity.id,Pe(e),{signal:i.signal});if(!l.modified)return null;o=l.body;}catch(l){if(ci(l))return null;throw l}if(typeof o.download_url!="string")throw new se("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 li(i.signal,t.signal)?this.timeout("download",r):new se("download_failed",`${Ps} for GET. Underlying error: ${l}`)}if(!a.ok){let l=await si(a);throw new se("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,t.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,t={}){try{let r=await Qr(this.api,this.entity.type,this.entity.id,Pe(e),{...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}});return r.modified?di(r.body):null}catch(r){if(ci(r))return null;throw r}}async list(e={}){let t=await Xa(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=t.next_cursor;return {saves:(t.data??[]).map(di),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,t){try{await ga(this.api,this.entity.type,this.entity.id,Pe(e),{...t===void 0?{}:{signal:t}});}catch(r){if(!ci(r))throw r}}budget(e){return e??this.options.timeoutMs??Eu}timeout(e,t){return new se("save_timeout",`the save ${e} did not finish within ${t}ms`)}rethrow(e,t,r,i,o){return e instanceof se?e:li(r,t)?this.timeout(i,o):e}};function Lu(n){try{return Xr(n)}catch{return n}}function ui(n,e){let t=n??{},r=typeof t.etag=="string"?t.etag:e;return {key:typeof t.key=="string"?t.key:"",value:typeof t.value=="string"?Lu(t.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof t.updated_at=="number"?t.updated_at:0}}var Wn=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e){let r=(await za(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>ui(i)):[]}async get(e,t={}){try{let r=await ka(this.api,this.entity.type,this.entity.id,e,{...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}});return r.modified?ui(r.body,r.etag):null}catch(r){if(Es(r))return null;throw r}}async put(e,t,r={}){let i=await is(this.api,this.entity.type,this.entity.id,e,{value:Yr(t)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return ui(i)}async delete(e,t){try{await pa(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});}catch(r){if(!Es(r))throw r}}};function Es(n){return n?.reason==="not_found"}function Vn(n,e,t={}){let r=new Un(he,t.identity);t.onInventoryChanged&&r.onInvalidate(t.onInventoryChanged);let i=new Dn(n,e,r);return {settings:new Wn(n,e),inventory:i,saves:new Bn(n,e,t.saves??{}),currencies:new Gn(i,t.resolveCurrencyId),mutations:new qn(n,e,r),orders:new Nn(n,e),progressions:new jn(n,e,i)}}var mi={type:"players",id:"me"};var We=n=>typeof n=="string"?n:"",yt=n=>typeof n=="number"?n:0;function Hn(n,e){let t=e??{},r=We(t.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...n(r),id:r,playerId:We(t.player_id),gameId:We(t.game_id),channel:We(t.channel)||"release",name:We(t.name),slotIndex:yt(t.slot_index),isActive:t.is_active!==false,createdAt:We(t.created_at),updatedAt:We(t.updated_at)}}var Kn=class{constructor(e,t,r,i){this.api=e;this.saves=t;this.identity=r;this.resolveCurrencyId=i;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let t=this.scopes.get(e);return t||(t=Vn(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,t)),t};async list(e){let r=(await Ja(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>Hn(this.scope,i)):[]}async get(e,t){let r=await _a(this.api,e,t===void 0?{}:{signal:t});return Hn(this.scope,r)}async create(e){let t=await da(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Hn(this.scope,t)}async update(e,t,r){let i=await ls(this.api,e,{name:t},r===void 0?{}:{signal:r});return Hn(this.scope,i)}async delete(e,t){await us(this.api,e,t===void 0?{}:{signal:t});}async slots(e){let r=await Na(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:yt(r?.total_slots),availableSlots:yt(r?.available_slots),activeCharacterCount:yt(r?.active_character_count),defaultMaxSlots:yt(r?.default_max_slots),purchasedExtraSlots:yt(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var Ms="[gem: use gem.text.toPlain()]",Is=new Set,Cs;function Gu(n){try{if(Is.has(n))return;let e=globalThis.location;if(Cs??=!!e?.port&&pt(e.hostname??""),!Cs)return;Is.add(n),console.warn(`[gem] ${n} is PlayerText, turned into a string: players see ${Ms}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
|
|
2
|
+
${new Error().stack}`);}catch{}}var be=class{#e;#n;constructor(e,t="player text"){this.#e=e,this.#n=t,Object.freeze(this);}toString(){return Gu(this.#n),Ms}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function Ge(n,e){return new be(n,e)}var ft={toPlain(n){return be.unwrap(n)},compare(n,e,t){let r=n instanceof be?be.unwrap(n):n,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(t);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(n,e){let t=n instanceof be?be.unwrap(n):n,r=e instanceof be?be.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};var ht=n=>typeof n=="string"?n:"";function Jn(n){let e=n??{},t=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:ht(e.transfer_id),status:ht(e.status),sourceEntityId:ht(e.source_entity_id),targetEntityId:ht(e.target_entity_id),...t===void 0?{}:{message:Ge(t,"transfer.message")},createdAt:ht(e.created_at),expiresAt:ht(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Du(){return crypto.randomUUID()}var zn=class{constructor(e,t,r){this.api=e;this.self=t;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let t=await Wa(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:Du()},e.signal===void 0?{}:{signal:e.signal});return Jn(t)}async list(e={}){let r=await es(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(Jn):[],...i===void 0?{}:{nextCursor:i}}}async get(e,t){let r=await ja(this.api,e,t===void 0?{}:{signal:t});return Jn(r)}async accept(e,t){return this.resolve(()=>ia(this.api,e,t===void 0?{}:{signal:t}))}async reject(e,t){return this.resolve(()=>ss(this.api,e,t===void 0?{}:{signal:t}))}async cancel(e,t){return this.resolve(()=>aa(this.api,e,t===void 0?{}:{signal:t}))}async resolve(e){return this.inventory.invalidate(),Jn(await e())}};var $u=n=>typeof n=="string"?n:"",Fu=n=>typeof n=="string"&&n?n:void 0,qu=n=>typeof n=="number"?n:void 0;function Os(n){let e=new Map(n.map(r=>[r.id,r])),t=new Map(n.filter(r=>r.slug).map(r=>[r.slug,r]));return r=>e.get(r)??t.get(r)??null}function Nu(n){if(typeof n!="object"||n===null||Array.isArray(n))throw new ce("config_malformed",`the config document is ${n===null?"null":typeof n}, expected a JSON object`);let e=n,t=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new ce("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=qu(e.version);if(r===void 0)throw new ce("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let i=(l,d,m)=>{let u=$u(l.id);if(!u)throw new ce("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return u},o=t("items");o.forEach((l,d)=>i(l??{},"items",d));let s=t("currencies");s.forEach((l,d)=>i(l??{},"currencies",d));let a=n;return {...a,version:r,hash:typeof a.hash=="string"?a.hash:"",items:o,currencies:s,catalogs:t("catalogs"),loot_tables:t("loot_tables"),affix_pools:t("affix_pools"),progressions:t("progressions"),game_room_templates:t("game_room_templates"),kv:typeof a.kv=="object"&&a.kv!==null&&!Array.isArray(a.kv)?a.kv:{},item:Os(o),currency:Os(s)}}var ce=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemConfigError";}reason},Ls=10*1024*1024,Gs=15e3,Ds=new Set(["dev","test","release"]);function ju(n){if(!Ds.has(n))throw new ce("config_channel_unknown",`the play token names channel "${n}", which is not one of ${[...Ds].join(", ")}. gem-api would reject the assignment read.`);return n}var Yn=n=>typeof n=="number"?n:0,pi=n=>typeof n=="string"?n:"";function Uu(n){let e=n??{},t=Array.isArray(e.entries)?e.entries.map(r=>{let i=r??{},o=typeof i.rarity_tier=="string"?i.rarity_tier:void 0;return {entryId:pi(i.entry_id),weight:Yn(i.weight),dropRate:Yn(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:pi(e.loot_table_id),name:pi(e.name),rollCount:Yn(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Yn(e.total_weight),entries:t}}var Xn=class{constructor(e,t,r={}){this.api=e;this.channel=t;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,t=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===t&&(this.inFlight=null);});return this.inFlight=t,t}refresh(){this.loaded=void 0,this.inFlight=null,this.generation+=1;}async dropRates(e,t){let r=await this.load();if(r===null)throw new ce("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let 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 wa(this.api,e,t===void 0?{}:{signal:t});return Uu(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??Gs),t;try{let l=await va(this.api,ju(this.channel()),{signal:e});if(!l.modified)throw new ce("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");t=l.body;}catch(l){if(l instanceof ce)throw l;if(l?.reason==="not_found")return null;throw l}let r=Fu(t.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 ce("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??Gs}ms`):new ce("config_unreachable",`could not fetch the game config document. From a browser this is almost always the storage CORS rule: the storage account must allow this game origin for GET. It is NOT a CSP problem \u2014 game origins carry no fetch directives by design. Underlying error: ${String(l)}`)}if(!o.ok){let l=await o.text().then(d=>ai(d)).catch(()=>"");throw new ce("config_unreachable",`the config document answered ${o.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await o.text();if(s.length>Ls)throw new ce("config_too_large",`the config document is ${s.length} bytes, over the ${Ls} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new ce("config_malformed",`config document is not JSON: ${String(l)}`)}return Nu(a)}};var $s=400,Te=n=>typeof n=="string"?n:"",Bu=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Ve(n){let e=Te(n);if(!Bu.test(e))return 0;let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):0}var Wu=/^[0-9a-f]{1,64}$/,Vu=/^[0-9a-f]{16}$/,Hu=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Ku=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function gi(n){let e=Te(n),t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return;let[r,i,o]=[Number(t[1]),Number(t[2]),Number(t[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 Ju=4096,zu=new TextEncoder;function Yu(n){let e=Te(n.challenge_data),t=Te(n.challenge_data_hash);return e===""||!Vu.test(t)?{}:zu.encode(e).length>Ju?{}:{data:e,dataHash:t}}function Xu(n){let e=n??{},t=Ve(e.period_start_at),r=Ve(e.period_ends_at);if(t===0||r===0)return;let i=Te(e.slug),o=Te(e.seed),s=gi(e.period_local_date),a=Te(e.boundary),l=Te(e.reset_time);return {id:Te(e.progression_definition_id),...i===""?{}:{slug:i},window:Te(e.window),periodStartAt:t,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:Hu.test(a)?a:"",resetTime:Ku.test(l)?l:"",seed:Wu.test(o)?o:"",...Yu(e)}}function bt(n){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(n)}`)}function Qn(n){let e=n??{};return Array.isArray(e.challenges)?e.challenges.map(Xu).filter(t=>t!==void 0):[]}var qt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:t}=e;bt(t);let r=await Ka(this.#e,{...t===void 0?{}:{periods_back:t},...e.signal===void 0?{}:{signal:e.signal}});return Qn(r)}};function Ee(n){return typeof n=="string"&&n!==""?n:void 0}var Fs=new Set(["localhost","127.0.0.1","[::1]"]);function He(n){return Zn(n)}function Zn(n){let e=Ee(n);if(e===void 0)return;let t;try{t=new URL(e);}catch{return}if(!(t.username!==""||t.password!=="")&&(t.protocol==="https:"||t.protocol==="http:"&&Fs.has(t.hostname)))return e}var Qu=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Zu=/^[a-z][a-z0-9_]{0,31}$/;function em(n){if(!Array.isArray(n))return;let e=[],t=new Set;for(let r of n.slice(0,8)){let i=r??{},o=Ee(i.family),s=Ee(i.avatar_3d_id),a=He(i.model_url),l=He(i.icon_url);o===void 0||!Zu.test(o)||t.has(o)||s===void 0||!Qu.test(s)||a===void 0||l===void 0||(t.add(o),e.push({family:o,id:s,modelUrl:a,iconUrl:l}));}return e}function tm(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},i=Ee(r.item_id),o=He(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function Se(n){let e=n??{},t=Ee(e.player_id),r=Ee(e.display_name),i=Ee(e.discriminator),o=Ee(e.display_tag),s=Ee(e.avatar_icon_id),a=He(e.avatar_icon_url),l=Ee(e.avatar_3d_id),d=He(e.avatar_3d_model_url),m=He(e.avatar_3d_icon_url),u=em(e.avatars_3d);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:Ge(r,"displayName")},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:Ge(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},...u===void 0?{}:{avatars3d:u},badges:tm(e.badges)}}var nm=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function rm(n){if(n===void 0)return;let e=He(n);if(e===void 0)return;let t=new URL(e);return Fs.has(t.hostname)||nm.has(t.origin)?e:void 0}var qs=100,Us=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function yi(n){let{periodsBack:e,period:t,playerId:r}=n;if(bt(e),e!==void 0&&t!==void 0)throw new TypeError("pass periodsBack or period, not both");if(t!==void 0&&(typeof t!="string"||!Us.test(t)))throw new TypeError(`period must be a period id such as 2026-10-02 (a result's period.id), got ${String(t)}`);if(r!==void 0&&(typeof r!="string"||r===""))throw new TypeError("playerId must be a player id");return {...e===void 0?{}:{periods_back:e},...t===void 0?{}:{period:t},...r===void 0?{}:{player_id:r}}}function Bs(n){let e=typeof n.period_id=="string"?n.period_id:"";if(!Us.test(e))return;let t=gi(n.period_local_date),r=Ve(n.period_start_at),i=Ve(n.period_ends_at),o=r>0&&i>0;return {id:e,...t===void 0?{}:{localDate:t},...o?{startAt:r,endsAt:i}:{},opensAt:Ve(n.opens_at),closesAt:Ve(n.closes_at),final:n.final===true}}var Nt=n=>typeof n=="string"?n:"",vt=n=>typeof n=="number"?n:0,jt=n=>typeof n=="string"?n:void 0,im=n=>typeof n=="number"?n:void 0,Ws={player:"players",character:"characters"};function om(n,e){let t=n??{},r=jt(t.entity_id),i=typeof t.entity_type=="string"&&Object.hasOwn(Ws,t.entity_type)?t.entity_type:void 0,o=Vs(t.stats),s=t.properties!==null&&typeof t.properties=="object"?t.properties:void 0,a=e?t.is_viewer===true:void 0;return {...Se(t),rank:vt(t.rank),occurredAt:vt(t.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 Ns(n,e){let t=n??{},r=jt(t.bucket_1),i=jt(t.bucket_2),o=im(t.update_frequency_seconds),s=Bs(t);return {leaderboardType:Nt(t.leaderboard_type),runType:Nt(t.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(t.entries)?t.entries.map(a=>om(a,e)):[],generatedAt:vt(t.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...s===void 0?{}:{period:s}}}function js(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=n;if(!Number.isFinite(e.rank))return;let t=Vs(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:vt(e.occurred_at),...t===void 0?{}:{stats:t},...r===void 0?{}:{properties:r}}}function Vs(n){if(n===null||typeof n!="object")return;let e={};for(let[t,r]of Object.entries(n))typeof r=="number"&&(e[t]=r);return e}function am(n,e,t){let r=n??{},i=jt(r.bucket_1),o=jt(r.bucket_2),s=Bs(r);return {leaderboardType:Nt(r.leaderboard_type),runType:Nt(r.run_type),entityType:e,entityId:t,...i===void 0?{}:{bucket1:i},...o===void 0?{}:{bucket2:o},entries:Array.isArray(r.entries)?r.entries.map(js).filter(a=>a!==void 0):[],personalBest:js(r.personal_best)??null,totalRuns:vt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:vt(r.generated_at),...s===void 0?{}:{period:s}}}var Ut=class{#e;constructor(e){this.#e=e;}async get(e,t={}){let r=yi(t),i=await La(this.#e,e,{...r,...t.bucket1===void 0?{}:{bucket_1:t.bucket1},...t.bucket2===void 0?{}:{bucket_2:t.bucket2},...t.signal===void 0?{}:{signal:t.signal}});return Ns(i,false)}async friends(e,t={}){let r=yi(t),i=await Ia(this.#e,e,{...r,...t.bucket1===void 0?{}:{bucket_1:t.bucket1},...t.bucket2===void 0?{}:{bucket_2:t.bucket2},...t.signal===void 0?{}:{signal:t.signal}});return Ns(i,true)}async mine(e,t={}){return this.#n(e,"player","me",t)}async character(e,t,r={}){return this.#n(e,"character",t,r)}async#n(e,t,r,i){if(i.limit!==void 0){let{limit:l}=i;if(!Number.isInteger(l)||l<1||l>qs)throw new TypeError(`limit must be an integer between 1 and ${qs}, got ${String(l)}`)}let o=yi(i),s=await xa(this.#e,e,Ws[t],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=t==="player"&&r==="me"&&Nt((s??{}).entity_id)||r;return am(s,t,a)}};var er=n=>typeof n=="string"?n:"",fi=n=>typeof n=="number"?n:0;function Hs(n){let e=n??{};return {playerId:er(e.player_id),key:er(e.key),value:e.value,updatedAt:fi(e.updated_at)}}function sm(n){let e=n??{};return {...Se(e),playerId:er(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:fi(e.updated_at)}}function lm(n){return n?.reason==="not_found"}var Bt=class{constructor(e,t){this.api=e;this.selfPlayerId=t;}api;selfPlayerId;async friends(e,t={}){let i=await Ca(this.api,Pe(e),{...t.signal===void 0?{}:{signal:t.signal}})??{};return {key:er(i.key),entries:Array.isArray(i.entries)?i.entries.map(sm):[],generatedAt:fi(i.generated_at)}}async of(e,t,r={}){try{return Hs(await qa(this.api,e,Pe(t),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(lm(i))return null;throw i}}async set(e,t,r={}){if(Pe(e),t===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(t);}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 Hs(await os(this.api,i,e,{value:t},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,t={}){let r=await this.selfPlayerId();await ya(this.api,r,Pe(e),{...t.signal===void 0?{}:{signal:t.signal}});}};var dm="gemChallenge",Ks=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Js(n){if(!(typeof n!="string"||n===""))try{return new URLSearchParams(n).get(dm)??void 0}catch{return}}var Ke=class extends O{constructor(e,t={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,i]of Object.entries(t))i!==void 0&&Object.assign(this,{[r]:i});}},tr=n=>typeof n=="string"?n:void 0;function zs(n){let e=n??{};return {...Se(e),playerId:tr(e.player_id)??""}}function Ys(n){let e=n.has_more===true?tr(n.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function cm(n){let e=n??{};return {friends:Array.isArray(e.data)?e.data.map(zs):[],...Ys(e)}}var hi=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0;function um(n){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(e=>typeof e[1]=="string"||typeof e[1]=="number"&&Number.isFinite(e[1])))}function Xs(n){let e=n??{},t=hi(e.opened_at),r=hi(e.answered_at);return {id:tr(e.item_id)??"",from:zs(e.sender),template:tr(e.template)??"",params:um(e.params),createdAt:hi(e.created_at)??0,...t===void 0?{}:{openedAt:t},...r===void 0?{}:{answeredAt:r}}}function mm(n){let e=n??{};return {challenges:Array.isArray(e.data)?e.data.map(Xs):[],...Ys(e)}}function pm(n){let e=n;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Wt=class{#e;#n;#o;constructor(e,t={}){this.#e=e,this.#n=t.challenge,this.#o=t.launchedChallengeId;}async list(e={}){let t=await Za(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return cm(t)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let t=await Qa(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return mm(t)}async launchedChallenge(e={}){let t=this.#o;if(t===void 0||!Ks.test(t))return null;try{return Xs(await Oa(this.#e,t,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(pm(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!Ks.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 ts(this.#e,e);}};var gm=0;function we(){try{return crypto.randomUUID()}catch{let n=Math.random().toString(36).slice(2,10);return `local-${String(++gm)}-${String(Date.now())}-${n}`}}var ym=12e4,Qs=8,fm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,hm=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Vt(n,e,t={}){return new Ke(new O("invalid",400,e,void 0,n),t)}function bm(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function vm(n){let{playerId:e,template:t,params:r}=n??{};if(typeof e!="string"||!fm.test(e))return {error:Vt("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof t!="string"||!hm.test(t))return {error:Vt("unknown_template","template must be a friend_challenge_templates key from this game's config")};if(r===void 0)return {playerId:e,template:t,params:void 0};if(!bm(r))return {error:Vt("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:Vt("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return o.length>Qs?{error:Vt("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String(Qs)}`)}:{playerId:e,template:t,params:i}}function _m(n){switch(n.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:n.outcome}};case "rate_limited":{let e=n.retryAfterMs,t=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new Ke(new O("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",t,"rate_limited"))}}case "invalid":{let e=typeof n.code=="string"?n.code:void 0,t=typeof n.detail=="string"&&n.detail!==""?n.detail:e??"the friend challenge request was refused as invalid";return {error:new Ke(new O("invalid",400,t,void 0,e),{...typeof n.param=="string"?{param:n.param}:{},...typeof n.channel=="string"?{channel:n.channel}:{},...typeof n.configVersion=="number"?{configVersion:n.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function wm(n){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(n.outcome)?n.outcome:"unknown"}function Zs(n){let e=new Map;return {challenge(t){if(!n.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=vm(t);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)&&(n.clock.clearTimeout(a.timer),"error"in m?s(m.error):o(m.outcome));};e.set(i,l),a.timer=n.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},n.timeoutMs??ym);let d=false;try{d=n.bridge.requestFriendChallenge(i,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(t){let r=e.get(t.requestId);if(r===void 0){n.onDropped?.(`gem.friendChallengeResult (${wm(t)}) for an unknown requestId: `+JSON.stringify(t.requestId));return}r(_m(t));}}}var nr=n=>typeof n=="string"?n:void 0;function km(n){let e=n??{},t=nr(e.currency_id);if(t===void 0||t==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:nr(e.slug)??"",currencyId:t,balance:r,access:e.access==="spend"?"spend":"read"}}var rr=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await In(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=km(o);s!==void 0&&i.push(s);}return i}},bi=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0?Math.floor(n):0;function Rm(n){let e=n??{},t=nr(e.currency_id);if(t===void 0||t==="")return;let r=bi(e.limit),i=Math.min(bi(e.earned),r),o=Math.min(bi(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:nr(e.currency_slug)??"",currencyId:t,limit:r,earned:i,remaining:o,period:e.period==="day"?"day":"window",periodDays:a,...d===void 0?{}:{resetsAt:d}}}function el(n){let e=new Set,t=r=>{n?.(`[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,t);}catch(i){t(i);}}}}var ir=class{#e;#n;#o;constructor(e,t,r){this.#e=e,this.#n=t,this.#o=r;}async get(e={}){let r=(await Ga(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=Rm(o);s!==void 0&&i.push(s);}return i}on(e,t){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(t)??(()=>{})}},Ht=class{currencies;earnAllowance;constructor(e,t,r){this.currencies=new rr(e),this.earnAllowance=new ir(e,t,r);}};var vi=n=>typeof n=="string"?n:"",tl=n=>typeof n=="number"?n:0;function Sm(n){let e=n??{};return {key:vi(e.key),visibility:vi(e.visibility),value:e.value,updatedAt:tl(e.updated_at)}}function xm(n){let e=n??{};return {...Se(e),playerId:vi(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Sm):[],generatedAt:tl(e.generated_at)}}function Am(n){return n?.reason==="not_found"}var Kt=class{#e;constructor(e){this.#e=e;}async of(e,t={}){try{return xm(await Da(this.#e,e,{...t.signal===void 0?{}:{signal:t.signal}}))}catch(r){if(Am(r))return null;throw r}}};var Pm=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]]),or=class extends O{constructor(e,t){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,t);}get retryable(){return (this.code===void 0?void 0:Pm.get(this.code))??super.retryable}},Je=class{#e;constructor(e){this.#e=e;}async invoke(e,t={}){let r=Tm(e),i;try{i=await this.#e(r,t.signal===void 0?{}:{signal:t.signal});}catch(o){throw o instanceof O?Im(o):o}return Em(i)}};function Tm(n){if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);let e;try{e=JSON.stringify(n);}catch(t){throw new ae(`the function input could not be serialised to JSON: ${String(t)}. 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 ae(`the function input is ${typeof n}, 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 Em(n){let{bytes:e}=n,t=()=>new TextDecoder("utf-8",{fatal:true}).decode(e);return {bytes:e,...n.invocationId===void 0?{}:{invocationId:n.invocationId},text:t,json:()=>JSON.parse(t())}}function Im(n){let{details:e,invocationId:t}=ra(n),i=e?.untrusted?.message,o=e?.reason;return new or(n,{...t===void 0?{}:{invocationId:t},...n.code==="function_error"&&typeof i=="string"?{functionMessage:i}:{},...n.code==="function_failed"&&typeof o=="string"?{failure:o}:{}})}function ar(n,e){let t=e?.retryAfterSeconds,r=typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:0,i=1e4*2**Math.min(Math.max(0,n-1),16);return Math.min(Math.max(r,i),3e5)}var Cm=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],_i="gem_";function nl(n){return n.startsWith(_i)}var rl=1e4,il=50,Mm=500,Om=65536-4*1024,Lm=24*1024;function ol(n){let e={},t={};for(let[r,i]of Object.entries(n))typeof i=="string"?e[r]=i:typeof i=="number"&&Number.isFinite(i)&&(t[r]=i);return {dimensions:e,measures:t}}var al=n=>typeof n=="number"?n:0,Gm=n=>typeof n=="string"?n:"";function sr(n=0){return {accepted:0,rejected:[],dropped:n,duplicate:false}}function Dm(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(i=>{let o=i??{};return {index:al(o.index),code:Gm(o.code)}}):[];return {accepted:al(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function wi(){let n=globalThis.crypto;return typeof n?.randomUUID=="function"?n.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return (e==="x"?t:t&3|8).toString(16)})}function $m(n){return n?.retryable===true}var Jt=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;#R=false;#S=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??Mm));}track(e,t={}){if(!(!this.#n||this.#r)){if(nl(e)){this.#S||(this.#S=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,ol({...this.#h,...t}));}}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 sr();let t=this.#C();if(t===null||t==="")return this.#t.length>0&&!this.#R&&(this.#R=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.")),sr();if(this.#P(),this.#t.length===0)return sr();let r=e.keepalive===true;if(this.#m>0&&!r)return sr();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:wi(),sent_at_ms:s,events:i.map(d=>sl(d,s))},l={client:this.#e.client(),gameId:()=>t};this.#m+=1;try{let d=await Ba(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=Dm(d,o);return this.#_=0,this.#w=0,this.#I(m),m}catch(d){throw $m(d)?(this.#T(i,o),this.#_+=1,this.#w=this.#e.clock.now()+ar(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,t={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#x(e,ol(t));}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(),t=this.#t.map(r=>({...r,atMs:e}));this.#t=t,this.#p&&(this.#p=false,this.#l=e,this.#c=false,this.#t.unshift({uid:wi(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=il?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 t=this.#l;this.trackPlatform("gem_session_end",{reason:e,...t===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-t))}}),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,t){let{dimensions:r,measures:i}=t;for(this.#P();this.#t.length>=this.#f;)this.#t.shift(),this.#a+=1;this.#t.push({uid:wi(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#t.length>=il?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,t){for(this.#t=[...e,...this.#t],this.#a+=t;this.#t.length>this.#f;)this.#t.shift(),this.#a+=1;}#E(e){let t=e?Lm:Om,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(sl(s,0)).length+1,i>t)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);}#I(e){for(let t of e.rejected)this.#y(`[gem] analytics: an event was refused (${t.code}). `+Fm(t.code));}#y(e){let t=this.#e.log;t!==null&&(t===void 0?console.warn(e):t(e));}#C(){try{return this.#e.gameId()}catch{return null}}#M(){try{return this.#e.playerId()}catch{return null}}};function sl(n,e){return {event_uid:n.uid,name:n.name,offset_ms:Math.round(n.atMs)-e,dimensions:n.dimensions,measures:n.measures}}function Fm(n){switch(n){case "analytics_not_declared":return "This channel has no analytics_events section at all \u2014 promote a game config that declares one. The gem_* events in the same batch were still recorded.";case "unknown_event":return "This channel declares a set of events and this name is not in it \u2014 check the spelling, or declare it in analytics_events.";case "unknown_dimension":return "A string property on this event is not declared as one of its dimensions.";case "missing_dimension":return "A dimension this event declares was not supplied.";case "dimension_value_not_declared":return "A dimension value is outside the closed set the config declares for it.";case "unknown_measure":return "A numeric property on this event is not declared as one of its measures.";case "measure_wrong_type":return "A measure was the wrong shape \u2014 an int measure refuses a fractional value.";case "source_not_permitted":return "This event is declared for the server only, so a client may not emit it.";default:return "See the analytics_events section of your game config."}}function me(n){if(typeof n!="string")return;let e=n.trim();return e.length===0?void 0:e}function zt(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=me(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var qm=2e3,Nm=5e3;function dl(n){let e=[],t=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(t)return Promise.resolve([]);if(!n.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let s,a=new Promise(l=>{let d=false,m=null;s=u=>{d||(d=true,r=null,n.clock.clearTimeout(m),l(u));},m=n.clock.setTimeout(()=>{t=true,s([]);},n.timeoutMs??qm);});return r={promise:a,settle:s},a};return {resolveList:o,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(s=>s[0])},refresh(s){return !ll(e,s)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=m=>{i.delete(d)&&(n.clock.clearTimeout(l),a(m));};i.set(d,s),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??Nm);})},accept(s,a){let l=zt(a),d=me(s),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[u,p]of [...i])ll(m,p)||u(m);}}}}function ll(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var jm=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(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="DedicatedServerError",this.retryable=jm.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var cl=["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"],Um=new Set(cl);function _t(n){return typeof n=="string"&&Um.has(n)?n:"unknown"}var lr="webrtc_dedicated",xi=["universal","mobile","web"];var Bm="p2p_unavailable",Wm="capacity_unavailable",Vm=2,ul=3e4,ml=1e3,pl=2e4;async function Ai(n){let e=me(n.clusterTargetId),t=n.nextClusterTarget,r=0,i=n.clock??he,o=n.retry??{},s=o.budgetMs??ul,a=o.maxDelayMs??pl,l=o.initialDelayMs??ml,d=i.now(),m=d+s,u=0;for(;;){u++;try{let p=await Ii(n.signal,"while allocating",()=>n.client.post(`${fl(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Hm(p)||s<=0)throw p;if(p.status===503&&p.code===Bm)throw new w("p2p_unavailable",`room ${n.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${p.message}`,{cause:p});if(r=p.code===Wm?r+1:0,t!==void 0&&r>=Vm){let x=t;t=void 0;let I=me(await x());I!==void 0&&(e=I,r=0);}let g=Math.min(a,l*2**(u-1)),y=Math.min(a,(p.retryAfterSeconds??0)*1e3),R=Math.max(g/2,y)+Math.random()*(g/2);if(i.now()+R>m)throw Km(n,p,u,i.now()-d,s);if(o.onWaiting?.({attempt:u,elapsedMs:i.now()-d,budgetMs:s,nextAttemptInMs:R,status:p.status,message:p.message}),await dr(i,R,n.signal),n.signal?.aborted)throw Si("while waiting to allocate")}}}function Hm(n){return n instanceof O?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function Km(n,e,t,r,i){let o=`${t} attempt${t===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new w("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${o}: ${e.message}`,{cause:e}):new w("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${o}: ${e.message}`,{cause:e})}var Jm=12e4,zm=1e3;async function Pi(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??zm,i=n.timeoutMs??Jm,o=e.now()+i,s=gl(n),a={seen:n.knownToExist===true};for(;;){let l=await yl(n,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new w("timeout",`match ${t} was still ${l.status} after ${i}ms`);await dr(e,r,n.signal);}}async function Ti(n){return (await yl(n,gl(n),{seen:n.knownToExist===true})).outcome}function gl(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${fl(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function yl(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await Ii(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(s){if(s instanceof O&&s.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:Ym(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:_t(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function Ei(n){let e=await Ii(n.signal,"while listing cluster targets",()=>n.client.get("/v1/ping/targets",n.signal)),t=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||t.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return t}async function Ii(n,e,t){if(n?.aborted)throw Si(e);try{return await t()}catch(r){throw n?.aborted?Si(e,r):r}}function Si(n,e){return new w("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function Ym(n,e,t){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:n,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:t+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function fl(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function dr(n,e,t){return t?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{n.clearTimeout(o),t?.removeEventListener("abort",i),r();},o=n.setTimeout(i,e);t?.addEventListener("abort",i);})}function hl(n){return typeof n=="string"&&n.trim()!==""}function cr(n,e){return hl(n)?n.trim():hl(e)?e:null}var ur="0.1.0-beta",bl="0-beta",wt="web",Xm=/^(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 Qm(n){let e=Xm.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function vl(n,e){let t=Zm(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:ur};let i=Qm(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 '${ur}' for it.`);if(i!==bl)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${bl}' 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 '${ur}' for it.`);return {...n,platform:t,engineVersion:r}}function Zm(n,e){if(n===void 0||n===wt)return wt;if(!xi.includes(n))throw new w("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${xi.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${wt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${wt}' 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.`),wt}function Yt(n){let e=n??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let t=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:_l(e.queued_at),expiresAt:_l(e.expires_at),heartbeatIntervalSeconds:typeof t=="number"&&t>0?t:0}}function _l(n){if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?Math.floor(e/1e3):0}var ep=3,wl=1e3,mr=class{constructor(e){this.options=e;this.snapshot=e.first;let t=new Promise((o,s)=>{this.resolve=o,this.reject=s;});t.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:t,cancel:()=>(this.requestCancel(),t)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let t=e?wl:Math.max(wl,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},t);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,t=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){t=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(t);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof O&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<ep){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let t=e instanceof O&&e.code==="matchmaking_unavailable";this.settle({status:t?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let t=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:t});}catch(t){this.busy=false,this.fail(t);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};var tp="join",np="welcome",rp="rejected",kl=25e3,ip=1e3,Ci=1;function Mi(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var op={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 Oi(n){let e=typeof n=="string"?n:"unknown";return new w(op[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Xt(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,s=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??kl),a=t.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,ip)),l=R=>{let x=R.data;if(typeof x!="string"){u(x);return}let I;try{I=JSON.parse(x);}catch{u(x);return}if(o){u(x);return}if(I.t===np){let h=Mi(I.heartbeat_interval);y({...typeof I.player_id=="string"?{playerId:I.player_id}:{},...typeof I.match_id=="string"?{matchId:I.match_id}:{},...h===void 0?{}:{heartbeatIntervalMs:h}});return}if(I.t===rp){v(Oi(I.reason));return}u(x);},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"));},u=R=>{o&&n.onMessage?.(R);},p=()=>{t.clearTimeout(a),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=R=>{o=true,p(),n.onMessage===void 0&&g(),r({welcome:R,detach:g});},v=R=>{o||(o=true,p(),g(),i(R));};if(e.addEventListener("message",l),e.addEventListener("close",d),n.signal?.aborted){m();return}n.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:tp,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:Ci}:{}}));}catch(R){v(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(R)}`,{cause:R}));}})}var ze=1,Qt=2,Li=4,$i=8,ap=2,sp=1e3,Fi="heartbeat timeout",Zt="gem-uu",pr=2,Sl="gem_transports";function kt(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!lp(r)||e.includes(r)||e.push(r);}return e}function lp(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function en(n,e){if(typeof n!="object"||n===null)return null;let t=n[Sl];if(typeof t!="object"||t===null)return null;let r=t;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function gr(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var xl=new TextEncoder,Al=new TextDecoder;function qi(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function Ni(n){let e=0;return n?.reliable===false&&(e|=ze),n?.ordered===false&&(e|=Qt),e}function ji(n){return {reliable:(n&ze)===0,ordered:(n&Qt)===0}}var Ui={reliable:true,ordered:true};function Pl(n){return JSON.stringify({t:"join",credential:n,wire:pr,heartbeat:Ci})}function Tl(n){let e;try{e=JSON.parse(n);}catch{throw new w("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=Mi(e.heartbeat_interval);return {...e.player_id===void 0?{}:{playerId:e.player_id},...e.match_id===void 0?{}:{matchId:e.match_id},...t===void 0?{}:{heartbeatIntervalMs:t}}}throw e.t==="rejected"?Oi(e.reason):new w("join_refused","the server answered the join out of protocol")}function yr(){return typeof globalThis.WebTransport=="function"&&Bi===null}function fr(){return Bi}var Bi=null;var Rl="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function dp(n){let e=En(n);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 Gi=class{buffered=new Uint8Array(0);push(e){let t=new Uint8Array(this.buffered.byteLength+e.byteLength);t.set(this.buffered,0),t.set(e,this.buffered.byteLength),this.buffered=t;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new 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 Di(n,e){let t=new Uint8Array(5+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength+1,true),t[4]=n,t.set(e,5),t}async function tn(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webTransport;if(t===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new w("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new a(n.url):new a(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:dp(n.certHashBase64)}]});}let r=t,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(Bi=Rl,i(new w("connection_failed",`${Rl}; 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(Di(Li,xl.encode(Pl(n.credential))));let u=new Gi,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 u.push(y.value)){g=Tl(Al.decode(v.payload));break}}return {link:cp(r,m,p,u,n.log??(y=>console.warn(y)),Il(g,n.clock)),welcome:g}}catch(a){return i(a)}}function cp(n,e,t,r,i,o){let s,a,l=false,d=y=>{if(!l){l=true,m.stop();try{n.close();}catch{}a?.(y);}},m=Vi(o,()=>d(Fi)),u=(y,v)=>{m.heard(),(y&$i)===0&&s!==void 0&&((y&Li)!==0?s(Al.decode(v),Ui):s(v,ji(y)));};(async()=>{try{for(;;){let y=await t.read();if(y.done||y.value===void 0)break;for(let v of r.push(y.value))u(v.flags,v.payload);}}catch{}d("stream closed");})();let p,g;try{let y=n.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 R=await v.read();if(R.done||R.value===void 0)break;let x=R.value;x.byteLength!==0&&u((x[0]??0)|ze|Qt,x.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 (${gr(y)}); unreliable sends ride the stream`);}return n.closed.then(y=>d(El(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,v){if(l)return;if(typeof y=="string"){e.write(Di(Li,xl.encode(y))).catch(()=>d("write failed"));return}let R=Ni(v);if((R&ze)!==0&&g!==void 0){let x=qi(R,y),I=p?.maxDatagramSize;if(I===void 0||x.byteLength<=I){g.write(x).catch(()=>{});return}}e.write(Di(R,y)).catch(()=>d("write failed"));},onMessage(y){s=y;},onClose(y){a=y;},close(){d("closed");}}}function Wi(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webSocket;if(t===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new w("connection_failed","this environment has no WebSocket"));t=new i(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new w("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),o(g));},d=()=>{r.send(Pl(n.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=Tl(g.data);}catch(v){l(v);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",u),r.removeEventListener("error",p),i({link:up(r,Il(y,n.clock)),welcome:y});},u=()=>{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",u),r.addEventListener("error",p),r.readyState===1&&d();})}function El(n){return typeof n=="string"&&n.length>0?n:void 0}function Il(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function Vi(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,sp)*ap,i=t.now(),o=null,s=()=>{o=null;let a=t.now()-i;if(a>=r){e();return}o=t.setTimeout(s,r-a);};return o=t.setTimeout(s,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function up(n,e){let t,r,i=false,o=a=>{if(!i){i=true,s.stop();try{n.close();}catch{}r?.(a);}},s=Vi(e,()=>o(Fi));return n.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){t?.(a.data,Ui);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&$i)===0&&t?.(l.slice(1),ji(d));})),n.addEventListener("close",(a=>o(El(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!i){if(typeof a=="string"){n.send(a);return}n.send(qi(Ni(l),a));}},onMessage(a){t=a;},onClose(a){r=a;},close(){o("closed");}}}function Hi(n,e,t,r){let i,o,s=false,a=t,l=u=>{if(!s){s=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(u);}},d=Vi(r,()=>l(Fi)),m=(u,p)=>{if(d.heard(),typeof u=="string"){i?.(u,Ui);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let y=g[0]??0;(y&$i)===0&&i?.(g.slice(1),ji(y|p));};if(n.addEventListener("message",(u=>m(u.data,0))),n.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),a!==void 0){let u=a;u.addEventListener("message",(p=>m(p.data,ze|Qt))),u.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(u,p){if(s)return;if(typeof u=="string"){n.send(u);return}let g=Ni(p),y=qi(g,u);if((g&ze)!==0&&a!==void 0&&a.readyState==="open"){a.send(y);return}n.send(y);},onMessage(u){i=u;},onClose(u){o=u;},close(){l("closed");}}}function zi(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=Ki(r);i!==void 0&&(e[t]=i);}return e}function Yi(n){if(Array.isArray(n))return n.map(mp).filter(e=>!!e)}function Ki(n){if(Ji(n)||Array.isArray(n)&&n.every(Ji))return n}function Ji(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function mp(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Ki(e.fixed),r=Ki(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...t===void 0?{}:{fixed:t},...r===void 0?{}:{default:r},...Rt("description",pp(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Ji)?{allowed:e.allowed}:{},...Rt("min",nn(e.min)),...Rt("max",nn(e.max)),...Rt("minItems",nn(e.min_items)),...Rt("maxItems",nn(e.max_items)),...Rt("maxLength",nn(e.max_length))}}function pp(n){return typeof n=="string"&&n.length>0?n:void 0}function nn(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Rt(n,e){return e===void 0?{}:{[n]:e}}function Ce(n){let e=n??{},t=X(e.id)??X(e.game_room_id);if(t===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(Cl):[];return {id:t,gameId:X(e.game_id)??"",name:X(e.name)??"",status:X(e.status)??"open",hostPlayerId:X(e.host_player_id)??"",maxPlayers:Ie(e.max_players)??0,memberCount:Ie(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",zi(e.room_args)),...ke("roomArgsTemplate",Yi(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:Ie(e.version)??0,...ke("templateId",X(e.template_id)),...ke("templateSlug",X(e.template_slug)),roomType:X(e.game_room_type)??"Standard",...ke("transports",kt(e.transports)??void 0),createdAt:Ie(e.created_at)??0,updatedAt:Ie(e.updated_at)??0,...ke("startedAt",Ie(e.started_at))}}function Cl(n){let e=n??{};return {...Se(e),playerId:X(e.player_id)??"",isReady:e.is_ready===true,role:X(e.role)??"member",joinedAt:Ie(e.joined_at)??0,...ke("groupId",X(e.group_id)),...ke("platform",X(e.platform))}}function hr(n){let e=n??{};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:Ie(e.max_players)??0,memberCount:Ie(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:X(e.game_channel)??"release",roomType:X(e.game_room_type)??"Standard",createdAt:Ie(e.created_at)??0}}function X(n){return typeof n=="string"&&n.length>0?n:void 0}function Ie(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ke(n,e){return e===void 0?{}:{[n]:e}}var on=class{constructor(e){this.options=e;}options;list(e){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.templateSlug&&t.set("template_slug",e.templateSlug),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);let r=t.size>0?`?${t.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(hr),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(t=>({rooms:(t.game_rooms??[]).map(hr)}))}create(e,t,r){return yp(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},...rn(t)},e.signal).then(Ce)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(Ce)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...rn(r)},t.signal).then(Ce)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...rn(r)},t.signal).then(Ce)}quickJoin(e,t,r=[]){let i=this.asksSelfHosted(e.partyId);return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...gp(e.templateSlugs,i),...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...i?{self_hosted:true}:{},...rn(t)},e.signal).then(Ce)}createTicket(e,t,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},...rn(t)},{...e.signal===void 0?{}:{signal:e.signal}}).then(Yt)}heartbeatTicket(e){return Ua(this.generated(),e).then(Yt)}cancelTicket(e,t=false){return t?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(Yt):sa(this.generated(),e).then(Yt)}leave(e,t,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}close(e,t){return this.options.client.delete(this.roomV1(e),t).then(()=>{})}update(e,t){return this.options.client.patch(this.roomV2(e),{...t.name===void 0?{}:{name:t.name},...t.maxPlayers===void 0?{}:{max_players:t.maxPlayers},...t.isPublic===void 0?{}:{is_public:t.isPublic},...t.settings===void 0?{}:{settings:t.settings},...t.roomArgs===void 0?{}:{room_args:t.roomArgs}},t.signal).then(Ce)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(Ce)}kick(e,t,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(t)}`,{},r).then(()=>this.get(e,r))}transferHost(e,t,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(t)}`,{},r).then(Ce)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function gp(n,e){return n===void 0?{}:{templates:(e?n.slice(0,1):n).map(r=>({template_slug:r}))}}function rn(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function yp(n){n!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${n}) is deprecated and was not sent. A room's seats come from the room template published in your game config \u2014 name one with templateSlug \u2014 and a room created without a template seats 8. To change a room that already exists, call update({ maxPlayers }) as its host.`);}var an=class{listeners=new Map;retainedMatch=null;on(e,t){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(t),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(t)&&this.retainedMatch===i&&t(i);});}return ()=>this.off(e,t)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){e==="matchReady"&&(this.retainedMatch=t[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};var br=class{constructor(e){this.options=e;let t=e.first,r=new Promise(a=>{this.resolve=a;}),i=()=>this.status;this.ticket={id:t.ticketId,get status(){return i()},partySize:t.partySize??0,queuedAt:t.queuedAt??0,expiresAt:t.expiresAt??0,outcome:r};let o=t.queuedAt!==void 0&&t.expiresAt!==void 0?(t.expiresAt-t.queuedAt)*1e3:9e5,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 fp(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var hp=1e3,bp=3e3,vp=6e4,_p=2,Ml=new Set(["game_room_closed","game_room_gone"]),wp=12e4,kp=5e3,Rp=new Set(["invalid_cluster_target","capacity_unavailable"]),Sp=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Qi(n){return new Xi(n)}var Xi=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new on({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new an;api;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await t;return this.api.create(r,this.version("create"),o[0]).catch(async s=>{let a=await this.afterRefusedClusters(s,o);if(a[0]===void 0||a[0]===o[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,t={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(t),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(t),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin"),Pp(e);let t=this.clusterTargets(),r=await this.attachParty(e),i=s=>this.api.quickJoin(r,this.version("quickJoin"),s).catch(a=>this.retryPastStaleMembership(a,r,s)),o=await this.run("quickJoin",async()=>{let s=await t;return i(s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||Gl(l,s))throw a;return i(l)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Ap(e?.templateSlugs),this.queueing=true;try{let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let s=await t;return this.api.createTicket(r,this.version("queueForMatch"),s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||Gl(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 mr({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 t=this.heldQueued;this.heldQueued=null,t!==null&&this.showPartyTicket(t);}}async enterMatchedRoom(e){let t=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?t:(this.room!==null&&this.room.id!==t.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(t,"joined"),this.room?.id===t.id?this.room:t)}async list(e={}){let t=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",t),t}async myRooms(e){let t=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",t.rooms),t.rooms}async leave(e={}){let t=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(t.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let t=await this.myRooms(e),r=[];for(let i of t)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let t=this.requireRoom("close");await this.run("close",()=>this.api.close(t.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let t=this.room;if(!t)return null;let r;try{r=await this.track(this.api.get(t.id,e));}catch(i){if(i instanceof 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 t=this.room,r=this.heldMatchId;if(!(t===null||r===null)&&!(t.status==="in_game"&&t.matchId===r)&&!(t.matchId!==void 0&&t.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>Ti({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...t===void 0?{}:{signal:t}})));}catch(s){return s instanceof 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 t=this.pendingHint;if(t===null||t.matchId!==void 0&&t.matchId!==e||(this.pendingHint=null,t.reason===void 0))return null;let r=_t(t.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let t=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=t,this.track(t)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,t){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,t));return this.apply(i),i}async kick(e,t){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,t));return this.apply(i),i}async transferHost(e,t){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,t));return this.apply(i),i}async update(e){let t=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(t.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,t){let r=this.requireRoom("startMatch");if(!this.isHost)throw new 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,t)}finally{this.startsInFlight--;}}async startIn(e,t,r){let i=me(t.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(m,u)=>Ai({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(u)}:{},retry:{...t.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),t.retry?.onWaiting?.(p);}},...t.signal===void 0?{}:{signal:t.signal}}),l=()=>a(o,[s]).catch(async m=>{if(i!==void 0||!Ll(m))throw m;let u=await this.nextCluster([s],true);if(u===void 0)throw m;return a(u,[s,u])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new 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 t=this.emitter.retained;return t!==null&&this.session.phase==="ready"?t:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let t=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(t.id,r,e));return this.settleOutcome(i)}chase(e,t,r){return Pi({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:t,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(t),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new w("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!Ml.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,t){this.heldMatchId===e&&(this.abandonReconnect(e,t),this.emitter.emit("matchFailed",e,t),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,t,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:t,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:t,roomReopened:r}),this.abandonReconnect(e,t));}armReconnect(e,t){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),t==="kicked"){r.abandon(e,t);return}let i={matchId:e,cause:t,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,t){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),t());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,t){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,t));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!Ye()){this.park(e,()=>this.reconnectStep(e));return}let t=this.options.autoReconnect;if(t===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=t.attempts||r<hp){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:t.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(fp(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Ye()){this.park(e,()=>this.reconnectAttempt(e));return}let t=this.options.autoReconnect,r=this.room;if(t===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>Ti({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,!Ml.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await t.redial(e.matchId,e.deadlineAt);}catch(s){this.reportError("reconcile",s),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let t=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):t&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new w("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let t=this.session.matchId;this.session={phase:"suspended",matchId:t,reason:e},this.emitter.emit("matchSuspended",{matchId:t,cause:e}),this.armReconnect(t,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new w("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let t=this.heldMatchId;if(t===null)throw new w("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:t},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let t=this.heldMatchId;if(t!==null)try{await this.api.leaveMatch(t,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,t){let r=this.emitter.on(e,t);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}handleRoomEvent(e){if(this.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let t=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(t).catch(()=>{}));}handleAutoStartFailed(e,t){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(t);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:t,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Rp.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let t=new br({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===t&&(this.partyWatch=null);}});this.partyWatch=t,this.emitter.emit("partyQueued",t.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let t=new Set;for(let r of e)r.status!=="closed"&&(t.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])t.has(r)||this.reported.delete(r);}async reportSeat(e){let t=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||t===null||!r.members.some(i=>i.playerId===t)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&Ye())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let t=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(t,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!Ye())){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 vr)e.addEventListener(r,this.visibilityListener);let t=globalThis.document;typeof t?.addEventListener=="function"&&t.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let t=this.inFlight;this.inFlight=[],await Promise.allSettled(t);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of vr)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??kp}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 t=this.options.clientVersion,r=cr(this.options.platformGameVersion?.(),t?.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 vl({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return zt(await this.options.resolveClusterTargets());let e=me(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !Ll(e)||t.length===0?[]:zt(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=s=>s.find(a=>!e.includes(a)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!t?o:r(zt(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let t=this.options.resolveParty;if(t===void 0)return e;let r=await t();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,t,r){if(!(e instanceof O)||e.reason!=="conflict"||!Sp.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(t.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.api.quickJoin(t,this.version("quickJoin"),r)}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,t){try{return await this.track(this.onceGameIdKnown(t))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,t){let r=t instanceof O?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof w?t.reason:"unavailable",message:t instanceof Error?t.message:String(t),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let t=this.options.ensureLocalServer;t===void 0||!e.selfHosted||e.status!=="open"||t(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,t){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(t,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let t=this.room;if(t===null||t.id!==e.id)return;let r=new Map(t.members.map(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);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=xp(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let t=this.heldMatchId;t!==null&&t!==e&&this.endMatch(t,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,t=this.heldMatchId;if(e===null||t===null||this.followAbort!==null&&this.followingMatchId===t)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=t,this.track(this.onceGameIdKnown(()=>this.chase(e.id,t,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let t=this.heldMatchId;if(t!==null)return Promise.resolve(t);let r=e.timeoutMs??wp;return new Promise((i,o)=>{let s=u=>{a(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),u();},a=this.emitter.on("matchAllocationStarted",u=>s(()=>i(u))),l=this.emitter.on("matchFailed",(u,p)=>s(()=>o(new w("allocation_failed",`match ${u} 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??bp}pushedInterval(){return this.options.pushedPollIntervalMs??vp}pushed(){return this.options.clock.now()-this.lastPushAt<_p*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=t=>{if(this.ticketWatch?.abandon(true),t?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function Ye(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var vr=["visibilitychange","focus","pageshow","online"];function xp(n,e){return n.version!==e.version||n.status!==e.status||n.matchId!==e.matchId||n.hostPlayerId!==e.hostPlayerId||n.name!==e.name||n.maxPlayers!==e.maxPlayers||n.isPublic!==e.isPublic||Ol(n)!==Ol(e)}function Ol(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Ll(n){return n instanceof O&&n.code==="invalid_cluster_target"}var _r=8;function Ap(n){if(!(Array.isArray(n)&&n.length>=1&&n.length<=_r&&n.every(t=>typeof t=="string"&&t.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${_r} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function Pp(n){let e=n?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=_r&&e.every(r=>typeof r=="string"&&r.length>0)))throw new w("misconfigured",`quickJoin's templateSlugs is an array naming one to ${_r} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(n?.templateSlug!==void 0||n?.templateId!==void 0)throw new 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 Gl(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Tp=["p2p","dedicated","unknown"],Zi=["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 St=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let i=Ep(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},t);}report(e){this.post(e).catch(()=>{});}};function Ep(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>Zi.includes(i.type)).slice(0,100).map(i=>{let o=Ip(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function Ip(n){if(n!==void 0)return Tp.includes(n)?n:"unknown"}var sn=class{constructor(e){this.options=e;this.reporter=new St({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,t,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:wr(i.credential)??"",hostFingerprint:wr(i.host_fingerprint)??"",hostEpoch:kr(i.host_epoch)??0,expiresAt:(kr(i.expires_at)??0)*1e3}}async turnLease(e,t,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:t},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(u=>typeof u=="string"&&u.length>0);m.length!==0&&o.push({urls:m,username:wr(d.username)??"",credential:wr(d.credential)??""});}let s=kr(i.expires_at),a=kr(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??0)*1e3}}async kick(e,t,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:t},r);}async leave(e,t=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:t});}async telemetry(e,t){await this.reporter.post(e,t);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function wr(n){return typeof n=="string"&&n.length>0?n:void 0}function kr(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var Cp=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),L=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="P2pError",this.retryable=Cp.has(t);}reason;retryable};var Dl=10240,$l=2048,Mp=new TextEncoder;function Fl(n){return Mp.encode(n).length}function je(n,e){let t=i=>{throw new w("invalid_sdp",`the ${e} ${i}`)},r=Fl(n);r>=Dl&&t(`is ${r} bytes, over the ${Dl} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),n.startsWith("v=")||t("does not start with 'v=', so it is not SDP"),n.includes("\0")&&t("contains a null byte"),/\r(?!\n)/.test(n)&&t("contains a bare carriage return");for(let i of n.split(/\r\n|\n/)){let o=Fl(i);o>$l&&t(`has a ${o}-byte line, over the ${$l} limit`);}}function Rr(n){for(let e of n.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[t,r="0"]=e.slice(2).trim().split(/\s+/);if(!(t!=="audio"&&t!=="video")&&r.split("/")[0]!=="0")return true}return false}var Sr=class{listeners=new Map;on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}clear(){this.listeners.clear();}};var Op=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function xt(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=xr(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function xr(n){let[e,...t]=n.trim().split(/\s+/);if(e===void 0||t.length===0)return null;let r=`${e.toLowerCase()} ${t.join("").toUpperCase()}`;return Op.test(r)?r:null}function ln(n,e){if(n.length!==e.length)return false;let t=0;for(let r=0;r<n.length;r++)t|=n.charCodeAt(r)^e.charCodeAt(r);return t===0}var eo=5e3,Lp=12e4+eo,Gp=1024,Dp=6e4,$p=1e4,ql=64*1024,Nl=5;function to(n){let e=new Map,t=-1/0,r=null,i=(()=>{let a;try{a=new URL(`${n.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=n.subtle??globalThis.crypto?.subtle;if(!a)throw new L("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return a},s=async()=>{if(!i.ok)throw new L("keys_unavailable",i.reason);let a=n.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($p)});}catch{throw new L("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 L("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>ql)throw new L("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${ql} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof L?p:new L("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>Nl)throw new L("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Nl} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=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 u.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 L("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let d=n.now();if(!Number.isFinite(d))throw new L("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<t&&(t=-1/0),d-t<Dp?null:(t=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var dn=class{seen=new Map;admit(e,t){for(let[r,i]of this.seen)i<=t&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=Gp){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+Lp),true}};function Ul(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}function jl(n){try{let e=new TextDecoder().decode(Ul(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function no(n,e,t,r,i){let o=N=>{throw new L("peer_unauthenticated",`the peer's join credential is not usable: ${N}`)},s=n.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,l,d]=s,m=jl(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 u=m.kid;(typeof u!="string"||u.length===0)&&o("it names no key");let p=await t.key(u);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=Ul(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 x=jl(l);x===null&&o("its payload does not decode");let I=x,h=N=>typeof I[N]=="string"?I[N]:"",k=N=>typeof I[N]=="number"&&Number.isFinite(I[N])?I[N]: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 E=k("exp")*1e3,T=k("nbf")*1e3;(!Number.isFinite(E)||e.now>E+eo)&&o("it has expired"),Number.isFinite(T)&&e.now<T-eo&&o("it is not valid yet");let B=h("role");B!=="host"&&B!=="client"&&o("it names no usable role");let G=k("host_epoch");G!==e.hostEpoch&&o("it names a different host epoch");let j=xr(h("fingerprint"));j===null&&o("its fingerprint claim is malformed"),ln(j,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let A=xr(h("host_fingerprint"));A===null&&o("its host fingerprint claim is malformed"),ln(A,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 D=h("sub");return D.length===0&&o("it names no player"),{playerId:D.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:G,role:B,fingerprint:j,hostFingerprint:A,jti:M,expiresAt:E}}function ro(n){let e=new TextEncoder().encode(n.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let t=new ArrayBuffer(3+e.length+4+4),r=new DataView(t);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(t,3,e.length).set(e),r.setUint32(3+e.length,n.protocolVersion,true),r.setUint32(7+e.length,n.assignedPeerId,true),t}function io(n){let e=new ArrayBuffer(9),t=new DataView(e);return t.setUint8(0,2),t.setUint32(1,n.protocolVersion,true),t.setUint32(5,n.assignedPeerId,true),e}function oo(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function ao(n){if(n.byteLength<1)return null;let e=new DataView(n);switch(e.getUint8(0)){case 1:{if(n.byteLength<3)return null;let t=e.getUint16(1,true);return t>8192||n.byteLength<3+t+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(n,3,t)),protocolVersion:e.getUint32(3+t,true),assignedPeerId:e.getUint32(7+t,true)}}case 2:return n.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return n.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function Bl(n){switch(n){case 1:return "the host did not accept this credential";case 2:return "the host speaks a different protocol version \u2014 an engine peer refuses a browser peer here, deliberately";case 3:return "the match is full";case 4:return "the host is rate-limiting joins";case 129:return "the host verified this credential but it names a different player than the one who signalled \u2014 the host has its own line saying which";case 130:return "the host has this player on the kicked list for the current host epoch";case 131:return "the host could not fetch the platform's signing keys, so it cannot verify anyone yet \u2014 the host's console says why";default:return `the host refused with an unrecognised code (${n})`}}function Wl(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var cn=class{constructor(e,t,r){this.localPlayerId=e;this.hostPlayerId=t,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,t){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=t,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var so={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}},De=["reliable","ordered","unreliable"];function lo(n){let e=globalThis.RTCPeerConnection;if(!e)throw new Error("[gem] this environment has no RTCPeerConnection. Pass `peerConnectionFactory` to connect against a stand-in, which is how this flow is tested outside a browser.");return new e({iceServers:n.iceServers,...n.certificates===void 0?{}:{certificates:n.certificates}})}async function un(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Hl=1,Up=3e4,Kl=2e3,Bp=5e3,Jl=6e4,Wp=8,uo=class{constructor(e=Wp){this.perMinute=e;}perMinute;sent=[];delayUntilAllowed(e){return this.prune(e),this.sent.length<this.perMinute?0:Math.max(0,(this.sent[0]??e)+6e4-e)}record(e){this.prune(e),this.sent.push(e);}prune(e){let t=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[t++]=r);this.sent.length=t;}},Vp=new uo,Hp=8,Kp=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),pn=class{constructor(e){this.options=e;this.keys=e.keys??to({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Sr;links=new Map;replays=new dn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Hl+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let t of this.links.values())t.admitted&&e.push(this.expose(t));return e}peer(e){let t=this.links.get(e);return t&&t.admitted?this.expose(t):null}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}async start(e){let t=this.options.connectTimeoutMs??Up;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((a,l)=>{this.ready={resolve:a,reject:l};}),i=me(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: ${co(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 L("timeout",`no usable P2P connection after ${t}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},t),s=()=>this.fail(new L("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 L("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,t){this.closed||this.route(e,t).catch(r=>this.report_(r));}async route(e,t){switch(e){case "hello":return this.onHello(t);case "offer":return this.onOffer(t);case "answer":return this.onAnswer(t);case "ice":return this.onIce(t);case "peerLeft":return this.onPeerLeft(t);case "migration":return this.onMigration(t);case "matchEnded":return this.onMatchEnded(t);case "error":return this.onSignalingError(t);default:return}}async onHello(e){let t=le(e.playerId),r=le(e.hostPlayerId),i=Ar(e.hostEpoch);if(!(t===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new cn(t,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let t of e)try{await this.onOffer(t);}catch(r){this.report_(r);}}async offerToHost(e){let t=this.hostPlayerId,r=this.openLink(t,Hl),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new L("invalid_sdp","the browser produced an offer with no SDP");je(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:xt(r);if(i===null)throw new L("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let o=this.options.credentialPacing??Vp,s=()=>this.closed||e!==this.credentialGeneration,a=Bp;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,u;if(m===409)u=Kl;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=a,a=Math.min(a*2,Jl)),u=Math.min(Math.max(u,Kl),Jl);}else throw d;if(!await this.waitForCredential(u,s))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=le(e.fromPlayerId),r=le(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=Hp){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=le(e.sessionId);if(i!==null&&this.answeredSessions.get(t)===i)return;je(r,"offer"),this.refuseMedia(r,"offer");let o=xt(r);if(o===null)throw new L("invalid_sdp",`the offer from ${t} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(t,i);let s=this.links.get(t);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(t,this.nextPeerId++);a.remoteFingerprint=o,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let l=await a.connection.createAnswer();await a.connection.setLocalDescription(l);let d=a.connection.localDescription?.sdp??l.sdp;if(!d)throw new L("invalid_sdp","the browser produced an answer with no SDP");je(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(t,d,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=le(e.fromPlayerId),r=le(e.sdp);if(t===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||t!==this.hostPlayerId)return;je(r,"answer"),this.refuseMedia(r,"answer");let o=xt(r);if(o===null)throw new L("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let t=this.credential;return t===null||e.remoteFingerprint===null?false:ln(t.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new L("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let t=e.pendingAnswer;t!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,t).catch(r=>this.report_(r));}async applyAnswer(e,t){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:t}),this.flushCandidates(e);}async onIce(e){let t=le(e.fromPlayerId),r=le(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=le(e.sdpMid),s=Ar(e.sdpMLineIndex)??Ar(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a);}onPeerLeft(e){let t=le(e.playerId);if(t===null)return;let r=le(e.reason)??"left";if(t===this.localPlayerId){this.fail(new L("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(t);i&&this.dropLink(i,r,true);}async onMigration(e){let t=le(e.hostPlayerId),r=Ar(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,hostEpoch:r,...le(e.reason)===null?{}:{reason:le(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",t,r);return}if(i.kind==="refused"){this.report_(new L("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",t,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new L("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let t=le(e.reason)??"ended";this.ended=t,this.emitter.emit("matchEnded",t),this.ready!==null&&this.fail(new L("match_ended",`the match ended: ${t}`)),this.close();}onSignalingError(e){let t=le(e.code)??"unknown",r=le(e.message)??"the platform refused a signaling message";this.report_(new L("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??lo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of De){let g=i.createDataChannel(p,so[p]);g.binaryType="arraybuffer",o[p]=g;}let s={playerId:e,assignedPeerId:t,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));},u=()=>{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",u),o.reliable.addEventListener("message",m),s.detachHandshake=()=>{o.reliable.removeEventListener("open",u),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 t=e.pendingCandidates;e.pendingCandidates=[];for(let r of t)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let t=this.credential;if(t===null)throw new L("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=t.expiresAt)throw new L("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(ro({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=ao(t);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new L(Wl(r.reason),Bl(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,t,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=xt(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 no(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(s){let a=s instanceof L&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",co(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(io({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,t,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send(oo(t));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let t=e.connection.iceConnectionState;if(!(t!=="failed"&&t!=="disconnected"&&t!=="closed")){if(this.isHost){(t==="failed"||t==="closed")&&this.dropLink(e,t,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,t);}catch(r){this.report_(r);}}}}onConnectionState(e){let t=e.connection.connectionState;t!=="failed"&&t!=="closed"||this.dropLink(e,t,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(t,r="reliable")=>e.channels[r].send(t)}}dropLink(e,t,r){this.links.delete(e.playerId),e.detachAll();for(let i of De)zl(e.channels[i]);zl(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,t);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let t=this.ready;this.ready=null,t.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof L?e:new L("connection_failed",co(e),{cause:e}));}count(e){this.counted||!Kp.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(Rr(e))throw new L("media_refused",`the ${t} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(t=>this.options.clock.setTimeout(t,e))}warn(e){let t=this.options.log;t!==null&&(t??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function le(n){return typeof n=="string"&&n.length>0?n:null}function Ar(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function co(n){return n instanceof Error?n.message:String(n)}function zl(n){try{n.close();}catch{}}var Jp=100,zp=50,gn=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,t){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:t});}answer(e,t,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:t,assignedPeerId:r});}candidate(e,t,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??Jp)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:t,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,t){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:t,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new L("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new L("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:t,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:t,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let t=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(t),this.dropListener?.(t);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??zp));}};function H(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function Ue(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function At(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Yl(n){return typeof n=="boolean"?n:void 0}var ve=H(64),yn=Ue(0,2147483647);function mo(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=ve(t);typeof r=="string"&&e.push(r);}return e}function Y(n,e,t){return {to:n,from:e,read:t,required:true}}function K(n,e,t){return {to:n,from:e,read:t,required:false}}var Qp=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=At("disconnected","failed","closed")(e.iceState),r=Ue(0,4102444800)(e.lastSeenAt);if(!(t===void 0&&r===void 0))return {...t===void 0?{}:{ice_state:t},...r===void 0?{}:{last_seen_timestamp:r}}};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",At("initial","ice_restart","full_reconnect")),K("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",Ue(0,4294967295)),K("sdp_hash","sdpHash",H(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[Y("peer_id","peerId",ve),Y("candidate","candidate",H(512)),K("sdp_mid","sdpMid",H(64)),K("sdp_mline_index","sdpMLineIndex",Ue(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[Y("host_epoch","hostEpoch",yn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[Y("host_epoch","hostEpoch",yn),K("evidence","evidence",Qp)]}}));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",yn),K("members","members",mo)],offer:[Y("fromPlayerId","from_player_id",ve),Y("sdp","sdp",H(10240)),K("sessionId","signaling_session_id",H(128)),K("sdpHash","sdp_hash",H(128)),K("iceUfrag","ice_ufrag",H(64)),K("intent","signaling_intent",At("initial","ice_restart","full_reconnect"))],answer:[Y("fromPlayerId","from_player_id",ve),Y("sdp","sdp",H(10240)),K("sessionId","signaling_session_id",H(128)),K("sdpHash","sdp_hash",H(128)),K("iceUfrag","ice_ufrag",H(64)),K("assignedPeerId","assigned_peer_id",Ue(0,4294967295))],ice:[Y("fromPlayerId","from_player_id",ve),Y("candidate","candidate",H(512)),K("sdpMid","sdp_mid",H(64)),K("sdpMLineIndex","sdp_m_line_index",Ue(0,255)),K("sdpMLineIndexAlt","sdp_mline_index",Ue(0,255))],peerJoined:[Y("playerId","player_id",ve)],peerLeft:[Y("playerId","player_id",ve),K("reason","reason",H(64))],migration:[Y("hostPlayerId","new_host_player_id",ve),Y("hostEpoch","host_epoch",yn),K("reason","reason",H(64)),K("kickedPlayerIds","kicked_player_ids",mo),K("migrationComplete","migration_complete",Yl)],matchEnded:[K("reason","reason",H(64))],error:[K("code","code",H(64)),K("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 Qe="webrtc_p2p";function Ql(n){let e=new sn({client:n.client,gameId:n.gameId}),t=new Map;return {handleSignalEvent(r,i,o){t.get(r)?.handleSignal(i,o);},session(r){return t.get(r)??null},async connect(r={}){if(n.bridge===null)throw new L("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let i=me(r.clusterTargetId),o=i??me(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let s=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==Qe)throw new L("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${Qe}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new gn({bridge:n.bridge,matchId:s.matchId,clock:n.clock}),l=new pn({api:e,clock:n.clock,matchId:s.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:a,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await un(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});a.onDropped(d=>l.notifyCandidatesDropped(d)),t.set(s.matchId,l),l.on("matchEnded",()=>t.delete(s.matchId));try{await l.start(r.signal);}catch(d){throw t.delete(s.matchId),l.close(),d}return l}}}function Zl(n){let{analytics:e,rooms:t}=n,r=n.target??globalThis,i=n.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(!Ye());for(let d of vr)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(!Ye());}let s=new Map;return o.push(t.on("matchReady",a=>{let l=a.protocol===Qe?"p2p":"dedicated";s.set(a.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),o.push(t.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 ed=["pointerdown","keydown"];function td(n,e=globalThis){let t=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 ed)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},a=()=>{if(!(t||r)){t=true,s();try{n();}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}},u=()=>{if(i=null,!(t||r)){if(d()){a();return}m()&&(i=e.requestAnimationFrame?.(u)??null);}};function p(){i===null&&!t&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of ed)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(i=e.requestAnimationFrame?.(u)??null);}return {get engaged(){return t},stop:s}}async function Pr(n,e,t,r){let i=await t;return n.mark(e)&&r&&r(`[gem] boot: ${n.timeline()}`),i}function po(n,e){let t=false;return async r=>{let i=await r;return !t&&e&&(t=true,e(`[gem] boot: ${n.timeline()}`)),i}}function go(n={}){let e=n.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),t=[],r=new Set;return {marks:t,mark(i,o){return r.has(i)?false:(r.add(i),t.push({name:i,at:o??e()}),true)},timeline(){let i=[...t].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 Zp="GemWebSdkHandshake";var eg=()=>Date.now();function nd(n,e,t={}){let r=n[Zp];if(r===void 0)return null;let i=t.ttlMs??9500,o=t.now??eg,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,m=false,u=o()-i;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(s[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var yo=false;async function ad(n,e,t,r){if(yo){e.close(),t("busy",true);return}yo=true;let i=null;try{let o=await ng(n,r);if(typeof o=="string"){e.close(),t(o,tg(o));return}i=o;let a=await(r.encodeRef??(l=>ag(l,r)))(i);if(i.close(),i=null,a===null){e.close(),t("failed",!0);return}if(a.size>og){e.close(),t("too_large",!1);return}e.postMessage(a);}catch(o){e.close(),t("failed",true),console.error("[gem] screenshot capture failed",o);}finally{yo=false,i?.close();}}function tg(n){switch(n){case "no_source":case "busy":case "failed":return true;case "not_wired":case "unsupported":case "unreadable":case "tainted":case "too_large":case "declined":return false}}async function ng(n,e){if(e.handler){let o=await e.handler(n);return o===null?"declined":rd(o,n)}if(!e.useDefaultStrategy)return "not_wired";let t=e.documentRef??globalThis.document;if(!t)return "no_source";let r=ig(t);if(!r)return "no_source";let i=rg(r);if(i!==null)return i;try{return rd(await createImageBitmap(r),n)}catch(o){if(o instanceof DOMException&&o.name==="SecurityError")return "tainted";throw o}}function rg(n){let e;try{e=n.getContext("webgl2")??n.getContext("webgl");}catch{return "unreadable"}if(e){let t=e.getContextAttributes();return !t||t.preserveDrawingBuffer!==true?"unsupported":null}try{if(n.getContext("2d"))return null}catch{return "unreadable"}return "unreadable"}function ig(n){let e=null,t=0;for(let r of Array.from(n.querySelectorAll("canvas"))){let i=r.width*r.height;i<=0||r.clientWidth<=0||r.clientHeight<=0||i>t&&(e=r,t=i);}return e}async function rd(n,e){let{maxWidth:t,maxHeight:r}=e;if(n.width<=t&&n.height<=r)return n;let i=Math.min(t/n.width,r/n.height),o=Math.max(1,Math.floor(n.width*i)),s=Math.max(1,Math.floor(n.height*i));try{let a=await createImageBitmap(n,{resizeWidth:o,resizeHeight:s,resizeQuality:"high"});return n.close(),a}catch{return n.close(),"too_large"}}var og=8*1024*1024,id="image/webp",od=.92;async function ag(n,e){try{if(typeof OffscreenCanvas=="function"){let o=new OffscreenCanvas(n.width,n.height),s=o.getContext("2d");if(s){s.drawImage(n,0,0);let a=await o.convertToBlob({type:id,quality:od});if(a&&a.size>0)return a}}}catch{}let t=e.documentRef??globalThis.document;if(!t)return null;let r=t.createElement("canvas");r.width=n.width,r.height=n.height;let i=r.getContext("2d");return !i||(i.drawImage(n,0,0),typeof r.toBlob!="function")?null:await new Promise(o=>{r.toBlob(s=>o(s),id,od);})}async function sd(n,e){if(!e)return;let t;try{t=await sg(e);}catch(r){console.error("[gem] onFeedbackContext threw; sending the report without context",r);return}if(t!=null){if(typeof t!="object"||Array.isArray(t)){console.error("[gem] onFeedbackContext must return a plain object or null; got",t);return}n.sendGameContext(t);}}function sg(n){return new Promise((e,t)=>{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()=>n())().then(o=>{r||(r=true,clearTimeout(i),e(o??null));},o=>{r||(r=true,clearTimeout(i),t(o instanceof Error?o:new Error(String(o))));});})}var ld=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function dd(n=globalThis){let t=n[ld];if(t!==void 0)return t;let r=false,i=()=>r,o=[],s=lg(n,i);s!==null&&o.push(s);let a=dg(n,i);a!==null&&o.push(a);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let u of o)u();}}};return Object.defineProperty(n,ld,{value:l,configurable:true}),l}function lg(n,e){let t=n.AudioNode?.prototype,r=n.AudioDestinationNode;if(t===void 0||r===void 0)return null;let i=n.OfflineAudioContext,o=t.connect,s=t.disconnect,a=new Map,l=m=>{let u=m.gain,p=m.context.currentTime;u.cancelScheduledValues(p),e()?u.setValueAtTime(0,p):u.setTargetAtTime(1,p,.01);},d=m=>{let u=m.context;if(i!==void 0&&u instanceof i)return null;let p=a.get(u);return p===void 0&&(p=u.createGain(),p.gain.value=e()?0:1,o.call(p,m),a.set(u,p)),p};return t.connect=function(...u){let[p,...g]=u;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,u)},t.disconnect=function(...u){let[p,...g]=u;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,u)},()=>{for(let[m,u]of a){if(m.state==="closed"){a.delete(m);continue}try{l(u);}catch{}}}}function dg(n,e){let t=n.HTMLMediaElement;if(t===void 0)return null;let r=t.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,u=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),u(this);}}),r.play=function(){try{u(this);}catch{}return a.call(this)},n.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof t)try{u(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 cg=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",ug=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',mg=`${cg}${ug}`,fo=new WeakSet;function cd(n=globalThis.document){if(n==null||fo.has(n))return null;try{let e=n.defaultView?.CSSStyleSheet??globalThis.CSSStyleSheet;if(Array.isArray(n.adoptedStyleSheets)&&typeof e=="function"){let r=new e;if(typeof r.replaceSync=="function")return r.replaceSync(mg),n.adoptedStyleSheets=[...n.adoptedStyleSheets,r],fo.add(n),"sheet"}let t=n.documentElement?.style;return t===void 0||typeof t.setProperty!="function"?null:(t.setProperty("-webkit-user-select","none"),t.setProperty("user-select","none"),t.setProperty("-webkit-tap-highlight-color","transparent"),fo.add(n),"inline")}catch{return null}}function ud(n){let e=n.windowMs??1e3,t=n.realm??globalThis,r=n.now??(()=>globalThis.performance?.now()??Date.now()),i=false,o=false,s=false,a=null,l=null,d=null,m=[],u=false,p=0,g=null,y=[],v=()=>i&&!o&&!s,R=()=>{l=null,d=null,m=[],p=0,g=null,y=[];},x=k=>{if(a=null,!v()){R();return}if(d!==null&&m.push(k-d),d=k,l===null)l=k;else {let E=k-l;if(E>=e&&m.length>0){if(u){let T=g===null?E:r()-g;n.report(gg(p,y,E,T));}else n.report(pg(m,E));l=k,m=[],p=0,y=[];}}I();},I=()=>{let k=t.requestAnimationFrame;typeof k=="function"&&(a=k.call(t,x));},h=()=>{if(v()){a===null&&(R(),I());return}a!==null&&(t.cancelAnimationFrame?.call(t,a),a=null),R();};return {setRequested(k){i=k,h();},setPaused(k){o=k,h();},draw(){if(!u){u=true,a!==null&&R();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 pg(n,e){return {fps:n.length*1e3/e,frameTimeP95Ms:md(n),counts:"pageFrames"}}function gg(n,e,t,r){let i=r;return e.length>0&&(i=md(r>Math.max(...e)?[...e,r]:e)),{fps:n*1e3/t,frameTimeP95Ms:i,counts:"gameDraws"}}function md(n){let e=[...n].sort((r,i)=>r-i),t=Math.max(1,Math.ceil(e.length*.95));return e[t-1]}var Tr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function gd(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function yd(n,e){n!==null&&(n.style.setProperty(Tr.top,`${e.top}px`),n.style.setProperty(Tr.right,`${e.right}px`),n.style.setProperty(Tr.bottom,`${e.bottom}px`),n.style.setProperty(Tr.left,`${e.left}px`));}var pd=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height"}});function fd(){let n=globalThis,e=n.innerWidth,t=n.innerHeight;return typeof e=="number"&&e>0&&typeof t=="number"&&t>0?{width:e,height:t}:null}function yg(n,e){let t={tl:{width:0,height:0},tr:{width:0,height:0},bl:{width:0,height:0},br:{width:0,height:0}};for(let r of n){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=t[`${o?"t":"b"}${i?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));}return t}function hd(n,e,t){if(n===null)return;let r=yg(e,t);for(let i of ["tl","tr","bl","br"])n.style.setProperty(pd[i].width,`${r[i].width}px`),n.style.setProperty(pd[i].height,`${r[i].height}px`);}var fg=3e4,Er=class extends Error{retryable;reason;constructor(e,t,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=t;}};function bd(n){let e=n.clock??he,t=n.timeoutMs??fg,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 n.bridge.parentSupports("localHost")},ensure(a){if(!n.bridge.parentSupports("localHost"))return Promise.resolve();let l=i.get(a);if(l)return l;let d=new Promise((m,u)=>{let p=`ls${++o}`,g=e.setTimeout(()=>{r.delete(p),i.delete(a),u(new Er("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(t)}ms`));},t);r.set(p,{room:a,resolve:m,reject:u,timer:g}),n.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 Er(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 fn={url:"https://downloads.indiegems.games/sdk/v13.3.1/gem-web-sdk.devtools.min.js",integrity:"sha384-ZbwUID1f7DNEqHFHG8Sz6V6SsrUoq8n8mppI6ck6z2iXC+V40TTI5P86E3yrEcI/"};var Tt=null;function hg(){return Tt!==null||(Tt=new Promise((n,e)=>{let t=document.createElement("script");t.src=fn.url,t.integrity=fn.integrity,t.crossOrigin="anonymous",t.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Tt=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${fn.url} is not a gem-web-sdk devtools build.`));return}n(r);},t.onerror=()=>{Tt=null,e(new Error(`gem devtools: could not load ${fn.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(t);})),Tt}function vd(n,e){let t=null,r=0;async function i(o){if(t!==null)return true;let s=++r;if(!e())return false;let a=await hg();return !e()||s!==r?false:(t!==null||(t=a.mount(n(),{openedBy:o,text:ft,onDismiss:()=>{t?.unmount(),t=null;}})),true)}return {get isOpen(){return t!==null},close(){r+=1,t?.unmount(),t=null;},open:()=>i("game"),openFrom:i}}var bg=1e4,_d={reason:"unavailable",retryable:false};function wd(n){let e=new Map,t=null,r=null,i=0,o=(d,m)=>{m.timer=n.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},n.timeoutMs??bg);},s=(d,m)=>{let u=a(d);u&&m(u);},a=d=>{let m=e.get(d);return m?(e.delete(d),n.clock.clearTimeout(m.timer),m):null},l=new ut({clock:n.clock,onStateChange:n.onStateChange,request:d=>new Promise((m,u)=>{let p=n.bridge.currentState;if(p==="refused"||p==="closed"){u(_d);return}let g=`t${++i}`,y={resolve:m,reject:u,reason:d,timer:null,held:p!=="connected"};e.set(g,y),o(g,y),y.held||n.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(t={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){s(d.requestId,u=>u.resolve(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,u]of e)u.held&&(u.held=false,n.clock.clearTimeout(u.timer),o(m,u),n.bridge.requestToken(m,u.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])s(m,u=>u.reject(_d));},get identity(){return t},get gameVersion(){return r}}}function vg(n){let e=n.lastIndexOf("@");return (e===-1?n:`***@${n.slice(e+1)}`).slice(0,200)}var _g=new Set(zr);function wg(n){if(!n)return {};let e={};for(let[t,r]of Object.entries(n))_g.has(t.toLowerCase())&&(e[t.toLowerCase()]=r);return e}function Ir(n){let e=n.fetch??globalThis.fetch.bind(globalThis);return ea(async(t,r)=>{let i;try{i=new URL(n.baseUrl.replace(/\/+$/,""));}catch{throw new ae("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(/\/+$/,"")+t.path);}catch{throw new ae(`${JSON.stringify(typeof t.path=="string"?vg(t.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 ae(`${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 ae(`the ${v} puts credentials in the URL, which cannot be fetched (${t.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(n.defaultQuery??{}))o.searchParams.has(g)||o.searchParams.set(g,y);let s=t.bytes,a=t.bytes===void 0?void 0:"application/octet-stream";try{t.body!==void 0&&(s=JSON.stringify(t.body),a="application/json");}catch(g){throw new ae(`the body of ${t.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:t.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...wg(t.headers)},body:s,signal:t.signal,...t.keepalive===void 0?{}:{keepalive:t.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(t.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),u=kg(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...u===void 0?{}:{retryAfterSeconds:u},...p===null||p===""?{}:{invocationId:p}}},n)}function kg(n){if(n===null)return;let e=n.trim();if(!/^\d+$/.test(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0}var Rg=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),bo="embedder_relay_unavailable",Sg="embedder_no_relay",xg=new Set([bo]),vo=new Set([Sg]),hn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new ho(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.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){t.refuse(new w("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(Ag(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new w("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,t);}release(e,t){this.pending.get(e)===t&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new 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 Ag(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new w(Pg(n),r,{platformCode:n})}function Pg(n){return n===void 0||xg.has(n)?"signaling_failed":vo.has(n)?"offer_refused":Rg.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var ho=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){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 t?.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=()=>{t?.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,t?.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 kd="match_ended:",Rd="server_shutdown:",Sd="kicked:",Tg=123;function Eg(n){if(typeof n!="string"||n.length===0||n.length>Tg)return {kind:"other"};if(n.startsWith(kd)){let e=_t(n.slice(kd.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(Rd)?{kind:"server_shutdown",cause:n.slice(Rd.length)}:n.startsWith(Sd)?{kind:"kicked",detail:n.slice(Sd.length)}:{kind:"other"}}function _o(n,e,t){let r=Eg(t),i=r.kind==="kicked"?"kicked":"link_closed";n.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&n.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function wo(){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 Ig=3e3,Cg=1e4,Mg=15e3;async function Cr(n){let e=n.peerConnection;try{Ad(n,"before the handshake started"),ko(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let s of n.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});n.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await Gg(e,n),ko(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new w("invalid_sdp","the offer carried no SDP");je(i,"offer"),xd(i,"offer");let o=await Lg(n,i);if(ko(n),typeof o?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return je(o.sdp,"answer"),xd(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Dg(t,n),Ad(n,"before the channel opened"),t}catch(t){throw e.close(),Og(t)}}function Og(n){return n instanceof w?n:Ed(n)?Ze():new w("connection_failed",Id(n),{cause:n})}function xd(n,e){if(Rr(n))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 Lg(n,e){let t=n.exchangeTimeoutMs??Cg,r=Td(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof w?o:Ed(o)?Ze():new w("signaling_failed",Id(o),{cause:o})});return $g(i,n,r,()=>r.exhausted?Ro("while the offer was in flight"):new w("timeout",`no answer arrived within ${t}ms`))}function Gg(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(s),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},s=t.setTimeout(i,e.gatherTimeoutMs??Ig);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Dg(n,e){if(e.signal?.aborted)return Promise.reject(Ze());if(n.readyState==="open")return Promise.resolve();if(n.readyState!=="connecting")return Promise.reject(new w("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??Mg,i=Td(e,r);return new Promise((o,s)=>{let a=()=>{t.clearTimeout(p),n.removeEventListener("open",l),n.removeEventListener("close",d),n.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",Pd(g)===void 0?void 0:{cause:Pd(g)}));},m=()=>{a(),s(Ze());},u=()=>{a(),s(i.exhausted?Ro("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},p=t.setTimeout(u,i.ms);n.addEventListener("open",l),n.addEventListener("close",d),n.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Td(n,e){if(n.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let t=n.credentialExpiresAt-n.clock.now();return t<=e?{ms:Math.max(0,t),exhausted:true}:{ms:e,exhausted:false}}function $g(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(Ze()):new Promise((s,a)=>{let l=u=>{i.clearTimeout(m),o?.removeEventListener("abort",d),u();},d=()=>l(()=>a(Ze())),m=i.setTimeout(()=>l(()=>a(r())),t.ms);o?.addEventListener("abort",d),n.then(u=>l(()=>s(u)),u=>l(()=>a(u)));})}function Ad(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw Ro(`already ${e}`)}function Ro(n){return new w("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function ko(n){if(n.signal?.aborted)throw Ze()}function Ze(){return new w("aborted","the caller aborted the connection attempt")}function Ed(n){return n?.name==="AbortError"}function Pd(n){return n?.error}function Id(n){return n instanceof Error?n.message:String(n)}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)),K("sessionId","session_id",H(64))],error:[K("code","code",H(64)),K("message","message",H(256))],matchEnded:[K("reason","reason",H(64))]}));function Fd(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??wo,o=n.log??(h=>console.warn(h)),s=new St({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(h,k)=>{let E=a.get(h)??new Set;E.add(k),a.set(h,E);},d=(h,k)=>{let E=a.get(h);E!==void 0&&(E.delete(k),E.size===0&&a.delete(h));},m=async h=>{if(r.isHost&&!xo(r)&&r.currentRoom?.matchId===void 0){let k=me(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 Dd(r.matchConnectionState==="suspended"?await r.reconnectToMatch(So(h)):await r.awaitMatch(So(h)))},u=async h=>Dd(await r.pollMatchStatus(So(h))),p=async(h,k)=>{let E=false;try{let T=await m(h),B=r.currentRoom?.transports;if(B!==void 0&&!B.includes("webrtc"))throw new w("misconfigured",`the room template offers (${B.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 G=h.peerConnection??$d();E=!0;let j=await Cr({peerConnection:G,signaling:k,clock:t,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...Mr(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),A=null;if(h.presentCredential!==!1)try{A=await Xt({channel:j,clock:t,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...Mr(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(M){throw xe(j),xe(G),M}return Hg(r,T,j,G,k,h.reportDisconnect!==!1,h.reportConnected!==!1,A,{remember:l,forget:d},h.onMatchEnded)}catch(T){throw E&&Gd(s,T),xe(k),T}},g=async(h,k,E,T,B,G)=>{if(h==="webtransport"){let W=T?.webtransport;if(W===void 0)throw new w("misconfigured","webtransport is not advertised");let V={credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:t};if(typeof W.named_url=="string"&&W.named_url!==""){let te=Math.max(Math.floor(G/2),1e3);try{return await tn({url:W.named_url,timeoutMs:te,log:o,...V})}catch(pe){if(fr()!==null)throw pe;return o(`[gem] webtransport named dial failed (${gr(pe)}); retrying the pinned dial`),tn({url:W.url,certHashBase64:W.cert_sha256_b64,timeoutMs:te,log:o,...V})}}return tn({url:W.url,certHashBase64:W.cert_sha256_b64,timeoutMs:G,...V})}if(h==="websocket"){let W=T?.websocket;if(W===void 0)throw new w("misconfigured","websocket is not advertised");return Wi({url:W.url,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:t,timeoutMs:G})}let j=k.peerConnection??$d(),A,M=await Cr({peerConnection:j,signaling:B,clock:t,matchId:E.matchId,credentialExpiresAt:E.credentialExpiresAt,extraChannels:[{label:Zt,ordered:false,maxRetransmits:0}],onExtraChannel:(W,V)=>{W===Zt&&(A=V);},...Mr(k,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...k.exchangeTimeoutMs===void 0&&k.redial===true?{exchangeTimeoutMs:Ng}:{}}),D;try{D=await Xt({channel:M,clock:t,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,wire:pr,heartbeat:!0,...Mr(k,"signal"),...k.welcomeTimeoutMs===void 0?{}:{ceilingMs:k.welcomeTimeoutMs}});}catch(W){throw xe(M),xe(j),W}let N=D.welcome.heartbeatIntervalMs;return {link:Hi(M,j,A,N===void 0?void 0:{clock:t,intervalMs:N}),welcome:D.welcome,channel:M,peerConnection:j}},y=(h,k,E,T,B)=>{let G=false,j;T.link.onClose(N=>{!G&&h.reportDisconnect!==false&&_o(r,k.matchId,N),j?.(N);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(k.matchId);let A={transport:T.link.transport,send:(N,W)=>T.link.send(N,W),onMessage:N=>T.link.onMessage(N),onClose:N=>{j=N;},close:()=>T.link.close()},M=()=>{G||(G=true,xe(T.link),xe(B));},D=N=>{if(!G){try{h.onMatchEnded?.(N);}catch{}M();}};return l(k.matchId,D),{matchId:k.matchId,transport:E,link:A,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,D),M();}}},v=async(h,k)=>{let E=r.currentRoom?.id,T=r.gameId,B=()=>({advert:en(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(E===void 0||T===null)return B();try{let G=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(E)}`,k);return {advert:en(G.settings,h),template:kt(G.transports)??r.currentRoom?.transports??null}}catch{return B()}},R=(h,k)=>{let E=h??Cd;return k.length===0?E:E.filter(T=>k.includes(T))},x=async(h,k,E)=>{try{let T=await m(h),{advert:B,template:G}=await v(T.matchId,h.signal),j=R(G,k),A=j.filter(J=>Bg(J,B)),M=fr();if(M!==null&&j.includes("webtransport")&&B?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${M} (learned on an earlier dial in this page)`),A.length===0){let J=G===null?`the default order (${Cd.join(", ")})`:`the room template's transports (${G.join(", ")||"none"})`;throw new w("misconfigured",`none of ${J}`+(k.length>0?`, narrowed to (${k.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let D=h.transportAttemptTimeoutMs??qg,N=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-t.now(),W=J=>n.signalingReady===void 0||J<=0?Promise.resolve(!0):n.signalingReady(J),V=[],te=[];for(let J of A){if(N()<Od){o(`[gem] ${J} rung not tried: the reconnect budget is spent`);break}te.length>0&&T.credentialExpiresAt-t.now()<Ld&&(T=await u(h)),te.push(J);let $e=!1,_e=!1,fe={attempts:0,waitedMs:0};for(;;){if(J==="webrtc"&&h.redial===!0){let Z=Math.min(Md,N());await W(Z)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Z)}ms; offering anyway`);}let Fe=Math.max(Math.min(D,N()),Od);try{return y(h,T,J,await g(J,h,T,B,E,Fe),E)}catch(Z){let z=Z instanceof w?Z:new w("connection_failed",Z instanceof Error?Z.message:String(Z),{cause:Z});if(J==="webrtc"&&Gd(s,z),(z.reason==="credential_expired"||z.reason==="credential_reused")&&!$e){$e=!0,T=await u(h);continue}if(J==="webrtc"&&z.reason==="signaling_failed"&&z.platformCode===bo&&!_e){_e=!0;let oe=Math.min(Md,N());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 W(oe))continue}if(z.reason==="join_rate_limited"){let oe=Ug(fe,Math.random,N());if(oe!==null){if(fe.attempts+=1,fe.waitedMs+=oe,o(`[gem] ${J} rung: the server is rate-limiting this player's joins; waiting ${Math.round(oe)}ms before presenting again (retry ${fe.attempts} of ${Nd.maxAttempts})`),await dr(t,oe,h.signal),h.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-t.now()<Ld&&(T=await u(h));continue}}if(jg.has(z.reason)||z.reason==="credential_expired"||J==="webrtc"&&qd(z)){o(`[gem] ${J} rung failed (${z.reason}): ${gr(z.cause??z)} \u2014 `+(te.length<A.length?`falling through to ${A[te.length]}`:"no rungs left")),V.push(z);break}throw o(`[gem] ${J} rung refused the session (${z.reason}): ${z.message}`),z}}}let pe=V[V.length-1];throw pe===void 0?new w("timeout",`the reconnect budget ran out before any transport (${A.join(", ")}) could be tried`):new w(pe.reason,`every transport tried (${te.join(", ")}) failed; the last said: ${pe.message}`,{cause:V,platformCode:pe.platformCode})}catch(T){throw xe(E),T}};return {listClusterTargets:async(h={})=>Ei({client:e,...h}),handleMatchEnded(h,k){let E=a.get(h);if(E!==void 0){a.delete(h);for(let T of E)T(k);}},connect:(async(h={})=>{let k=h.signaling??i();return h.transports===void 0?p(h,k):x(h,h.transports,k)})}}var Cd=["webtransport","webrtc","websocket"],qg=1e4,Ng=5e3,Md=3e3,Od=1e3,Ld=1e4,jg=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function qd(n){return n.platformCode!==void 0&&vo.has(n.platformCode)}var Nd={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Ug(n,e=Math.random,t=1/0){let r=Nd;if(n.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-n.waitedMs,t);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**n.attempts;return Math.min(o+e()*r.jitterMs,i)}function Bg(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&yr():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||Wg(e.websocket.url)}function Wg(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return pt(e)}function So(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var Vg=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Gd(n,e){e instanceof w&&(!Vg.has(e.reason)&&!qd(e)||n.report([{type:"connection_failures_total",value:1}]));}function Hg(n,e,t,r,i,o,s,a,l,d){let m=false,u=()=>{m||_o(n,e.matchId,void 0);};o&&(t.addEventListener("close",u),s&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",u),a?.detach(),xe(t),xe(r),xe(i));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function xo(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function Dd(n){if(n.status==="failed")throw new w("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new w("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==lr)throw new w("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${lr}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:t}=n;if(e===void 0||t===void 0)throw new w("connection_failed",`match ${n.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...n,joinCredential:e,credentialExpiresAt:t}}function $d(){let n=globalThis.RTCPeerConnection;if(!n)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 n({iceServers:[]})}function xe(n){try{n.close();}catch{}}function Mr(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var Kg=1e4;function jd(n,e){if(typeof n.serverToken!="function"||typeof n.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 t=s=>({token:s.token,expiresAt:s.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,i=new ut({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??Kg);r={resolve:d=>{e.clock.clearTimeout(l),s(d);},reject:a,timer:l};})}),o=n.onServerToken(s=>{let a=t(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 Po={};Bc(Po,{acceptTransfer:()=>Jg,addEntityProgression:()=>zg,adminAction:()=>Yg,cancelInventoryTransfer:()=>Xg,claimEntityProgressionRewards:()=>Qg,closeGameRoom:()=>Zg,createEntityBatchOrder:()=>ey,createEntityOrder:()=>ty,createSession:()=>ny,deleteEntityGameSetting:()=>ry,deleteEntitySave:()=>iy,deleteSession:()=>oy,deleteShowcaseValue:()=>ay,executeEntityRecipe:()=>sy,finalizeSaveUpload:()=>ly,getChannelAssignment:()=>dy,getDropRates:()=>cy,getEntityCurrency:()=>uy,getEntityGameSetting:()=>my,getEntityInventory:()=>py,getEntityInventoryItem:()=>gy,getEntityLeaderboard:()=>yy,getEntityOrder:()=>fy,getEntityProgression:()=>hy,getEntityRecipeAvailability:()=>by,getEntityRecipeUsage:()=>vy,getEntitySave:()=>_y,getEvent:()=>wy,getGameRoomV2:()=>ky,getLeaderboard:()=>Ry,getPlayerGameProfile:()=>Sy,getPurchaseCatalog:()=>xy,getResolvedTemplate:()=>Ay,getRoomArgs:()=>Py,getShowcaseValue:()=>Ty,getTransferDetails:()=>Ey,ingestAnalyticsEvents:()=>Ao,initiateInventoryTransfer:()=>Iy,invokeFunction:()=>Cy,kickPlayer:()=>My,listChallenges:()=>Oy,listEntityGameSettings:()=>Ly,listEntityOrders:()=>Gy,listEntityProgressions:()=>Dy,listEntitySaves:()=>$y,listEvents:()=>Fy,listGameRooms:()=>qy,listResolvedTemplates:()=>Ny,listTransfers:()=>jy,maxEntityProgression:()=>Uy,putEntityGameSetting:()=>By,putRoomArgs:()=>Wy,putShowcaseValue:()=>Vy,rejectTransfer:()=>Hy,reportMatchPlayers:()=>Ky,requestSaveUploadUrl:()=>Jy,resetEntityProgression:()=>zy,setMatchBackfill:()=>Yy,simulateEntityOrder:()=>Xy,transferHostV2:()=>Qy,updateGameRoomV2:()=>Zy});function b(n){let e=String(n);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function Jg(n,e,t){let r=`/v1/inventory/transfers/${b(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function zg(n,e,t,r,i,o){let s=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}/add`;return n.client.post(s,i,o?.signal)}async function Yg(n,e,t,r){let i=`/v1/voice/sessions/${b(e)}/admin`;return n.client.post(i,t,r?.signal)}async function Xg(n,e,t){let r=`/v1/inventory/transfers/${b(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function Qg(n,e,t,r,i,o){let s=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}/claim`;return n.client.post(s,i,o?.signal)}async function Zg(n,e,t){let r=`/v1/games/${b(n.gameId())}/game-rooms/${b(e)}`;return n.client.delete(r,t?.signal)}async function ey(n,e,t,r,i){let o=`/v1/inventory/${b(e)}/${b(t)}/orders/batch`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ty(n,e,t,r,i){let o=`/v1/inventory/${b(e)}/${b(t)}/orders`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ny(n,e,t){return n.client.post("/v1/voice/sessions",e,t?.signal)}async function ry(n,e,t,r,i){let o=`/v1/settings/${b(e)}/${b(t)}/${b(r)}`;return n.client.delete(o,i?.signal)}async function iy(n,e,t,r,i){let o=`/v1/saves/${b(e)}/${b(t)}/${b(r)}`;return n.client.delete(o,i?.signal)}async function oy(n,e,t){let r=`/v1/voice/sessions/${b(e)}`;return n.client.delete(r,t?.signal)}async function ay(n,e,t,r){let i=`/v1/showcase/players/${b(e)}/${b(t)}`;return n.client.delete(i,r?.signal)}async function sy(n,e,t,r,i){let o=`/v1/inventory/${b(e)}/${b(t)}/recipes/execute`;return n.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ly(n,e,t,r,i,o){let s=`/v1/saves/${b(e)}/${b(t)}/${b(r)}/finalize`;return n.client.post(s,i,o?.signal)}async function dy(n,e,t){let r=`/v1/games/${b(n.gameId())}/config/channels/${b(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function cy(n,e,t){let r=`/v1/inventory/loot-tables/${b(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function uy(n,e,t,r,i){let o=`/v1/inventory/${b(e)}/${b(t)}/currencies/${b(r)}`;return n.client.get(o,i?.signal)}async function my(n,e,t,r,i){let o=`/v1/settings/${b(e)}/${b(t)}/${b(r)}`;return n.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function py(n,e,t,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(t)}`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function gy(n,e,t,r,i){let o=`/v1/inventory/${b(e)}/${b(t)}/items/${b(r)}`;return n.client.get(o,i?.signal)}async function yy(n,e,t,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(t)}/${b(r)}`+(s?`?${s}`:"");return n.client.get(a,i?.signal)}async function fy(n,e,t,r,i){let o=`/v1/inventory/${b(e)}/${b(t)}/orders/${b(r)}`;return n.client.get(o,i?.signal)}async function hy(n,e,t,r,i){let o=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}`;return n.client.get(o,i?.signal)}async function by(n,e,t,r,i,o){let s=`/v1/inventory/${b(e)}/${b(t)}/catalogs/${b(r)}/recipes/${b(i)}/availability`;return n.client.get(s,o?.signal)}async function vy(n,e,t,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(t)}/recipe-usage`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function _y(n,e,t,r,i){let o=`/v1/saves/${b(e)}/${b(t)}/${b(r)}`;return n.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function wy(n,e,t){let r=`/v1/events/${b(e)}`;return n.client.get(r,t?.signal)}async function ky(n,e,t){let r=`/v2/games/${b(n.gameId())}/game-rooms/${b(e)}`;return n.client.getWithEtag(r,{...t?.signal===void 0?{}:{signal:t.signal},...t?.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}})}async function Ry(n,e,t){let r=new URLSearchParams;t?.bucket_1!==void 0&&r.set("bucket_1",String(t?.bucket_1)),t?.bucket_2!==void 0&&r.set("bucket_2",String(t?.bucket_2)),t?.periods_back!==void 0&&r.set("periods_back",String(t?.periods_back)),t?.period!==void 0&&r.set("period",String(t?.period)),t?.player_id!==void 0&&r.set("player_id",String(t?.player_id));let i=r.toString(),o=`/v1/leaderboards/${b(e)}`+(i?`?${i}`:"");return n.client.get(o,t?.signal)}async function Sy(n,e,t){let r=`/v1/profiles/players/${b(e)}`;return n.client.get(r,t?.signal)}async function xy(n,e){let t=new URLSearchParams;e?.config_version!==void 0&&t.set("config_version",String(e?.config_version));let r=t.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Ay(n,e,t){let r=`/v1/game-room-templates/${b(e)}`;return n.client.get(r,t?.signal)}async function Py(n,e,t){let r=`/v1/games/${b(n.gameId())}/game-rooms/${b(e)}/room-args`;return n.client.get(r,t?.signal)}async function Ty(n,e,t,r){let i=`/v1/showcase/players/${b(e)}/${b(t)}`;return n.client.get(i,r?.signal)}async function Ey(n,e,t){let r=`/v1/inventory/transfers/${b(e)}`;return n.client.get(r,t?.signal)}async function Ao(n,e,t){let r=`/v1/games/${b(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{replaySafe:true,retryRateLimited:false})}async function Iy(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Cy(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function My(n,e,t,r){let i=`/v1/games/${b(n.gameId())}/game-rooms/${b(e)}/kick/${b(t)}`;return n.client.post(i,void 0,r?.signal)}async function Oy(n,e){let t=new URLSearchParams;e?.periods_back!==void 0&&t.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&t.set("player_id",String(e?.player_id));let r=t.toString(),i="/v1/challenges"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Ly(n,e,t,r){let i=`/v1/settings/${b(e)}/${b(t)}`;return n.client.get(i,r?.signal)}async function Gy(n,e,t,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(t)}/orders`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Dy(n,e,t,r){let i=`/v1/inventory/${b(e)}/${b(t)}/progressions`;return n.client.get(i,r?.signal)}async function $y(n,e,t,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(t)}`+(o?`?${o}`:"");return n.client.get(s,r?.signal)}async function Fy(n,e){let t=new URLSearchParams;e?.include_inactive!==void 0&&t.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&t.set("limit",String(e?.limit)),e?.offset!==void 0&&t.set("offset",String(e?.offset));let r=t.toString(),i="/v1/events"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function qy(n,e){let t=new URLSearchParams;e?.status!==void 0&&t.set("status",String(e?.status)),e?.game_channel!==void 0&&t.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&t.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&t.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&t.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&t.set("limit",String(e?.limit)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor));let r=t.toString(),i=`/v1/games/${b(n.gameId())}/game-rooms`+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Ny(n,e){return n.client.get("/v1/game-room-templates",e?.signal)}async function jy(n,e){let t=new URLSearchParams;e.entity_type!==void 0&&t.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&t.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&t.set("direction",String(e?.direction)),e?.status!==void 0&&t.set("status",String(e?.status)),e?.cursor!==void 0&&t.set("cursor",String(e?.cursor)),e?.limit!==void 0&&t.set("limit",String(e?.limit));let r=t.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return n.client.get(i,e?.signal)}async function Uy(n,e,t,r,i,o){let s=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}/max`;return n.client.post(s,i,o?.signal)}async function By(n,e,t,r,i,o){let s=`/v1/settings/${b(e)}/${b(t)}/${b(r)}`;return n.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Wy(n,e,t,r){let i=`/v1/games/${b(n.gameId())}/game-rooms/${b(e)}/room-args`;return n.client.put(i,t,r?.signal)}async function Vy(n,e,t,r,i){let o=`/v1/showcase/players/${b(e)}/${b(t)}`;return n.client.put(o,r,i?.signal)}async function Hy(n,e,t){let r=`/v1/inventory/transfers/${b(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function Ky(n,e,t,r){let i=`/v1/games/${b(n.gameId())}/matches/${b(e)}/players/report`;return n.client.post(i,t,r?.signal)}async function Jy(n,e,t,r,i,o){let s=`/v1/saves/${b(e)}/${b(t)}/${b(r)}/upload-url`;return n.client.post(s,i,o?.signal,{replaySafe:true})}async function zy(n,e,t,r,i,o){let s=`/v1/inventory/${b(e)}/${b(t)}/progressions/${b(r)}/reset`;return n.client.post(s,i,o?.signal)}async function Yy(n,e,t,r){let i=`/v1/games/${b(n.gameId())}/matches/${b(e)}/backfill`;return n.client.put(i,t,r?.signal)}async function Xy(n,e,t,r,i){let o=`/v1/inventory/${b(e)}/${b(t)}/orders/simulate`;return n.client.post(o,r,i?.signal)}async function Qy(n,e,t,r){let i=`/v2/games/${b(n.gameId())}/game-rooms/${b(e)}/transfer/${b(t)}`;return n.client.post(i,void 0,r?.signal)}async function Zy(n,e,t,r){let i=`/v2/games/${b(n.gameId())}/game-rooms/${b(e)}`;return n.client.patch(i,t,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var ef=1e4,tf=50,nf=1e3,rf=65536-4*1024,Ud=n=>typeof n=="number"?n:0,of=n=>typeof n=="string"?n:"";function Bd(){let n=globalThis.crypto;return typeof n?.randomUUID=="function"?n.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return (e==="x"?t:t&3|8).toString(16)})}function af(n){return n?.retryable===true}function sf(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(i=>{let o=i??{};return {index:Ud(o.index),code:of(o.code)}}):[];return {accepted:Ud(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function Wd(n,e){return {event_uid:n.uid,name:n.name,offset_ms:Math.round(n.atMs)-e,player_id:n.playerId,dimensions:n.dimensions,measures:n.measures}}function Vd(n){let e=Math.max(1,Math.floor(n.maxQueue??nf)),t={client:n.client,gameId:()=>n.gameId},r=[],i=0,o=null,s=false,a=null,l=0,d=0,m=false,u=false,p=h=>{n.log?.(h);},g=()=>{o!==null&&(n.clock.clearTimeout(o),o=null);},y=()=>Math.max(0,d-n.clock.now()),v=()=>{o!==null||s||a!==null||(o=n.clock.setTimeout(()=>{o=null,x().catch(()=>{});},Math.max(ef,y())));},R=()=>{let h=Math.min(r.length,100),k=128;for(let E=0;E<h;E+=1){let T=r[E];if(T===void 0)break;if(k+=JSON.stringify(Wd(T,0)).length+1,k>rf)return Math.max(1,E)}return h};async function x(h){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let k=I(h);a=k;try{return await k}finally{a===k&&(a=null),r.length>0&&v();}}async function I(h){g();let k=r.splice(0,R()),E=i;i=0;let T=Math.round(n.clock.now()),B={batch_id:Bd(),sent_at_ms:T,events:k.map(G=>Wd(G,T))};try{let G=await Ao(t,B,h===void 0?void 0:{signal:h}),j=sf(G,E);l=0,d=0;for(let A of j.rejected)p(`[gem] analytics: an event was refused (${A.code}). See the analytics_events section of your game config.`);return j}catch(G){if(af(G)){for(r=[...k,...r],i+=E;r.length>e;)r.shift(),i+=1;l+=1,d=n.clock.now()+ar(l,G);}else p(`[gem] analytics: ${k.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(G)}`);throw G}}return {track(h,k,E={}){if(s)return;if(typeof h!="string"||h===""){u||(u=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(_i)){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={},B={};for(let[G,j]of Object.entries(E))typeof j=="string"?T[G]=j:typeof j=="number"&&Number.isFinite(j)&&(B[G]=j);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:Bd(),playerId:h,name:k,atMs:n.clock.now(),dimensions:T,measures:B}),r.length>=tf&&a===null&&y()===0?x().catch(()=>{}):v();},flush:h=>x(h),get pending(){return r.length},dispose(){s=true,g(),r=[],i=0;}}}function Hd(n){return {async list(e){let{playerId:t,periodsBack:r,signal:i}=e??{};if(typeof t!="string"||t==="")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().");bt(r);let o=await n({player_id:t,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return Qn(o)}}}function lf(n){let e={};for(let[t,r]of Object.entries(Po))if(typeof r=="function"){let i=r;e[t]=(...o)=>i(n,...o);}return e}function Kd(n,e={}){let t=e.clock??he,r=e.baseUrl??n.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=jd(n,{clock:t,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=Ir({baseUrl:r,tokenSource:i.source,defaultQuery:{game_id:n.gameId,channel:n.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new Be({transport:o,clock:t}),a={gameId:n.gameId,channel:n.channel,matchId:n.matchId,...n.gameRoomId===void 0?{}:{gameRoomId:n.gameRoomId}},l=lf({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,m=n.endMatch,u=n.log,p=Vd({client:s,clock:t,gameId:a.gameId,...typeof u=="function"?{log:y=>u.call(n,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(n);},setBackfill:async(y,v)=>{let R=await l.setMatchBackfill(a.matchId,{open:y.open,...y.seats===void 0?{}:{seats:y.seats}},v===void 0?{}:{signal:v});return {open:R.open,seats:R.seats??null}},reportPlayers:async(y,v)=>(await l.reportMatchPlayers(a.matchId,{players:y.map(x=>({player_id:x.playerId,state:x.state}))},v===void 0?{}:{signal:v})).players.map(x=>({playerId:x.player_id,outcome:x.outcome}))},analytics:p,functions:new Je(l.invokeFunction),challenges:Hd(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}),R=v.modified?v.body:void 0;if(R?.room_args==null||R.room_args_template==null)throw new O("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:R.room_args,room_args_template:R.room_args_template}}}},dispose:()=>{p.dispose(),i.dispose();}}}function et(n){return n?.reliable!==false?"reliable":n?.ordered!==false?"ordered":"unreliable"}function Et(n){return {reliable:n==="reliable",ordered:n!=="unreliable"}}function bn(n){return typeof n=="string"?n:n.slice().buffer}function Or(n){if(typeof n=="string")return {data:n,isText:true};if(n instanceof ArrayBuffer)return {data:new Uint8Array(n),isText:false};if(ArrayBuffer.isView(n)){let e=n;return {data:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),isText:false}}return null}var df=5e3,Jd=3e4,zd=2e3,cf=1e4,uf=3,Yd=1;async function Xd(n,e){let{session:t,localPlayerId:r}=e;if(!t.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 n=="function"?n():n,a=Promise.resolve(),l=true,d=false,m=(f,C)=>{l&&(a=a.then(async()=>{if(!d)try{await C();}catch($){o(`the bundle's ${f} handler threw: ${tt($)}. Serving continues.`);}}));},u=true,p,g,y,v=f=>{if(!u)return;u=false,m("leave",()=>s.leave?.(r,{cause:f??"left"}));let C=g;C&&queueMicrotask(()=>C(f));},R={send(f,C){if(!u)return;let $=Et(et(C));m("message",()=>s.message?.(r,f,typeof f=="string",{reliable:$.reliable,ordered:$.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){v("closed");}},x=(f,C)=>{if(!u)return;let $=Et(et(C));queueMicrotask(()=>{u&&p?.(f,$);});},I=new Map,h=f=>{let C=[];for(let $ of De){let Q=f.channels[$];try{Q.binaryType="arraybuffer";}catch{}let ye=Et($),at=F=>{let st=Or(F?.data);st!==null&&m("message",()=>s.message?.(f.playerId,st.data,st.isText,{reliable:ye.reliable,ordered:ye.ordered}));};Q.addEventListener("message",at),C.push(()=>Q.removeEventListener("message",at));}I.get(f.playerId)?.forEach($=>$()),I.set(f.playerId,C);},k=f=>{I.get(f)?.forEach(C=>C()),I.delete(f);},E=new Set,T=new Map,B=(f,C,$)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...C?{rejoin:true}:{},...$?{superseded:true}:{}}),G=f=>{let C=I.has(f.playerId),$=E.has(f.playerId);E.add(f.playerId),h(f),C&&m("leave",()=>s.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>s.join?.(f.playerId,B(f,$,C)));},j=new Set,A=(f,C,$)=>{if(f===r){x(C,$);return}let Q=t.peer(f);if(Q===null){let ye=T.get(f);if(ye!==void 0&&e.clock.now()-ye<zd)return;j.has(f)||(j.add(f),o(`send to '${f}' dropped: no such connected player`));return}Q.send(bn(C),et($));},M={matchId:t.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=u?[r]:[];for(let C of t.peers)f.push(C.playerId);return f},profile(f){let C=e.room()?.members.find($=>$.playerId===f);if(!(!C||C.displayName===void 0))return {displayName:ft.toPlain(C.displayName),...C.displayTag===void 0?{}:{displayTag:ft.toPlain(C.displayTag)},...C.discriminator===void 0?{}:{discriminator:C.discriminator}}},playerNumber(f){return f===r?Yd:t.peer(f)?.assignedPeerId},send(f,C,$){A(f,C,$);},broadcast(f,C){let $=C?.except;u&&r!==$&&x(f,C);for(let Q of t.peers)Q.playerId!==$&&Q.send(bn(f),et(C));},async endMatch(){let f=await Fe();return f.answer!=="ok"&&o(f.cause),f.answer},kick(f,C){if(f===r){v(C??"kicked");return}t.kick(f).catch($=>{o(`kick of '${f}' failed: ${tt($)}`);});},log(f){o(f);},warn(f){o(`\u26A0 ${f}`);}},D=()=>{},N=new Promise(f=>{D=f;}),W=[],V=null,te=async(f,C)=>{l=false;let $=a.then(async()=>{try{await s.shutdown(f);}catch(Q){o(`the bundle's shutdown threw: ${tt(Q)}`);}});a=$,await $,Le();for(let Q of W.splice(0))Q();for(let Q of [...I.keys()])k(Q);v(C);},pe=(f,C)=>V||(V=(async()=>{await te(C,f),t.close(),D();})(),V),J=()=>V||(V=(async()=>{await te({reason:"signal"},"left"),await t.leave().catch(f=>o(`leaving the match failed: ${tt(f)}`)),D();})(),V),$e=()=>V||(V=(async()=>{l=false;let f=await Fe();f.answer==="ok"?(await te({reason:"match_ended",platform_reason:"explicit"},"match ended"),t.close()):(o(`${f.cause}; leaving instead`),await te({reason:"signal"},"left"),await t.leave().catch(C=>o(`leaving the match failed: ${tt(C)}`))),D();})(),V),_e=null,fe=()=>(_e??=Kd(M,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),_e),Fe=async()=>{try{return await ns({client:fe().client,gameId:()=>M.gameId},M.matchId,{},{signal:AbortSignal.timeout(df)}),{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: ${tt(f)}`}}},Z=null,z=false,oe=0,ge,qe=null,Le=()=>{z=true,Z!==null&&(e.clock.clearTimeout(Z),Z=null),qe?.(),qe=null;},Fr=f=>{o(`heartbeats paused: ${f}; they resume when a fresh play token arrives`),rt();let C=ge,$=false,Q=e.tokens.subscribe(ye=>{$||z||ye.token===C||it(ye)||($=true,qe?.(),qe=null,oe=0,ge=void 0,rt(),o("a fresh play token arrived; heartbeats resume"),Z=e.clock.setTimeout(()=>{Ct();},0));});$?Q():qe=Q;},rt=()=>{let f=_e;_e=null,f?.dispose();},it=f=>f.expiresAt*1e3<=e.clock.now(),Ct=async()=>{if(Z=null,!z){try{await fe().client.post(`/v1/games/${encodeURIComponent(M.gameId)}/matches/${encodeURIComponent(M.matchId)}/heartbeat`,void 0,AbortSignal.timeout(cf)),oe=0,ge=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(mf(f)){if(z)return;oe+=1;let C=e.tokens.current(),$=C===void 0?"this host holds no play token":it(C)?"this host's play token has expired":C.token===ge?"the platform refused this host's play token again":oe>=uf?`the platform refused this host's play token ${oe} times in a row`:null;if(ge=C?.token,$!==null){Fr($);return}}else oe=0,ge=void 0;o(`heartbeat failed: ${tt(f)}`);}z||(Z=e.clock.setTimeout(()=>{Ct();},Jd));}},Mt=()=>{z||Z!==null||(Z=e.clock.setTimeout(()=>{Ct();},Jd));};{let f=D;D=()=>{Le(),_e?.dispose(),_e=null,f();};}let ot=Promise.resolve().then(()=>s.init(M));a=ot.then(()=>{},()=>{}),m("join",()=>s.join?.(r,{playerNumber:Yd,transport:"loopback"})),W.push(t.on("peerJoined",G)),W.push(t.on("peerLeft",(f,C)=>{k(f);let $=e.clock.now();for(let[Q,ye]of T)$-ye>=zd&&T.delete(Q);T.set(f,$),j.delete(f),m("leave",()=>s.leave?.(f,{cause:C}));})),W.push(t.on("error",f=>{o(`\u26A0 session error: ${f.message}`);})),W.push(t.on("matchEnded",f=>{V||To(y,f),pe("match ended",{reason:"match_ended",platform_reason:f});})),W.push(t.on("hostChanged",f=>{f!==r&&pe("host migrated",{reason:"host_migrated"});}));for(let f of t.peers)G(f);try{await ot,Mt();}catch(f){l=false,Le(),d=true;for(let C of W.splice(0))C();for(let C of [...I.keys()])k(C);throw t.leave().catch(()=>{}),D(),f}return {matchId:t.matchId,localLink:R,onMatchEnded(f){y=f;},end:$e,leave:J,stop:f=>pe(f,{reason:"stopped"}),done:N}}function To(n,e){try{n?.(e);}catch{}}function mf(n){return n instanceof O&&n.status===401||ie.isAuthError(n)}function tt(n){return n instanceof Error?n.message:String(n)}function Eo(n,e){let t=async()=>{throw new w("misconfigured",`this seat is \`${n}\`, not the match's authority: `+(n==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:n,matchId:e,end:t,leave:t,stop:async()=>{}}}function Qd(n){let e=new Map,t=n.autoReconnect===true,{rooms:r}=n,i=new Map,o=async a=>{r.isHost&&!xo(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!==Qe)return Eo("dedicated",d.matchId);let m=n.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return Eo("peer",d.matchId);let u=n.identity();if(u===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await n.p2p.connect(s(l)),g=await Xd(a,{session:p,clock:n.clock,gameId:u.gameId,channel:u.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:n.apiBaseUrl(),tokens:n.tokens,room:n.room,localPlayerId:p.playerId!==""?p.playerId:u.playerId,...n.log===void 0?{}:{log:n.log},...n.fetch===void 0?{}:{fetch:n.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===Qe){let g=i.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),ff(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 un(),v=async()=>n.p2p.connect({...s(a),certificate:y}),R=await v(),x=bf(R,v,d,I=>{r.notifyMatchDisconnected(I).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),t);return t&&(e.set(R.matchId,{redial:x.redial,abandon:x.abandon}),x.onClosed(()=>{e.get(R.matchId)?.abandon===x.abandon&&e.delete(R.matchId);})),x}let m=async(g=null)=>await n.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),u=await m(),p=hf(u,m,r,t);return t&&(e.set(u.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(u.matchId)?.abandon===p.abandon&&e.delete(u.matchId);})),p},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var Zd="link_closed",pf="host_unreachable",gf=new Set(["failed","closed"]);function yf(n){return gf.has(n)?Zd:pf}function ff(n,e,t){let r=e.localLink;e.onMatchEnded(t);let i="connected";r.onClose(()=>{i="closed";});let o;return {matchId:n,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 hf(n,e,t,r){let i=n.matchId,o=n,s="connected",a,l,d=[],m=false,u=false,p=y=>{if(s!=="closed"){s="closed";for(let v of d.splice(0))v();l?.(y);}},g=y=>{y.link.onMessage((v,R)=>a?.(v,R)),y.link.onClose(v=>{if(y!==o||s==="closed")return;if(m||!r){p(v);return}let R=t.matchSession;if(R.phase==="suspended"&&R.matchId===i){s="suspended";return}p(v);});};return g(n),{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(u)return "connected";u=true;let v;try{v=await e(y===void 0?{}:{deadlineAt:y});}finally{u=false;}return m||s==="closed"?(v.close(),"closed"):(o=v,g(v),s="connected",t.notifyMatchConnected(i),"connected")},abandon(y){s!=="closed"&&(s==="connected"&&o.close(),p(y));},onClosed(y){s==="closed"?y():d.push(y);}}}function bf(n,e,t,r,i,o=false){let s=n.matchId,a=n,l,d,m=[],u=[],p=[],g=false,y=false,v=false,R=false,x="connected",I=A=>{if(g)return;g=true,x="closed";for(let D of m.splice(0))D();for(let D of u.splice(0))D();for(let D of p.splice(0))D();let M=d;M&&queueMicrotask(()=>M(A));},h=A=>{for(let M of m.splice(0))M();for(let M of De){let D=A.channels[M];try{D.binaryType="arraybuffer";}catch{}let N=Et(M),W=V=>{let te=Or(V?.data);te!==null&&l?.(te.data,N);};D.addEventListener("message",W),m.push(()=>D.removeEventListener("message",W));}},k=()=>a.peer(a.hostPlayerId),E=A=>{if(!(g||a.isHost)&&x!=="suspended"){if(r?.(A),o){x="suspended";return}I(A);}},T=A=>{for(let M of De){let D=A.channels[M];if(typeof D.addEventListener!="function")continue;let N=()=>{k()===A&&E(Zd);};D.addEventListener("close",N),m.push(()=>D.removeEventListener?.("close",N));}},B=A=>{h(A),T(A),!g&&(x="connected",i?.());},G=A=>{for(let M of u.splice(0))M();u.push(A.on("migrating",()=>{R=true;})),u.push(A.on("hostChanged",M=>{if(R=false,M===A.playerId){I("host_migrated_here");return}let D=k();D!==null&&B(D);})),u.push(A.on("peerJoined",M=>{M.playerId===A.hostPlayerId&&B(M);})),u.push(A.on("matchEnded",M=>{g||To(t,M),I(M);})),u.push(A.on("peerLeft",(M,D)=>{M===A.hostPlayerId&&E(yf(D));}));};G(a);let j=k();return j!==null&&B(j),{matchId:s,protocol:"p2p",get state(){return x},send(A,M){x==="connected"&&k()?.send(bn(A),et(M));},onMessage(A){l=A;},onClose(A){d=A;},close(){y=true,I("closed"),a.leave().catch(()=>{});},async redial(){if(x==="closed")return "closed";if(x==="connected"||v)return "connected";if(R)throw new L("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");v=true;let A;try{for(let D of m.splice(0))D();for(let D of u.splice(0))D();a.close(),A=await e();}finally{v=false;}if(g)return y?A.leave().catch(()=>{}):A.close(),"closed";a=A,G(a);let M=k();if(M===null)throw a.close(),new L("connection_failed","this peer rejoined the match but the host never answered with a link");return B(M),"connected"},abandon(A){I(A);},onClosed(A){g?A():p.push(A);}}}function Io(n){let e=0,t=new Map;return {resolve(){if(!n.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},s=l=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(l));};t.set(r,s),o.timer=n.clock.setTimeout(()=>s(void 0),n.timeoutMs??2e3);let a=false;try{a=n.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){t.get(r)?.(i);}}}var vf=12e4;function nt(n,e){return {outcome:n,reason:e}}function ec(n){let e=false,t=new Map,r=(i,o,s,a)=>{if(!n.bridge.parentSupports(i))return Promise.resolve(nt("unavailable","error"));if(e)return Promise.resolve(nt("declined","busy"));let l=`purchase-${we()}`;return new Promise(d=>{let m={},u=g=>{t.delete(l)&&(e=false,n.clock.clearTimeout(m.timer),d(g));};e=true,t.set(l,{finish:u,check:s,label:a}),m.timer=n.clock.setTimeout(()=>u(nt("unavailable","error")),n.timeoutMs??vf);let p=false;try{p=o(l);}catch{}p||u(nt("unavailable","error"));})};return {api:{request(i){return r("purchases",o=>n.bridge.requestPurchase(o,i.kind,i.targetId,i.currencySlug,i.quantity,i.catalogId),o=>o===void 0?null:n.confirm(o),o=>`purchase ${JSON.stringify(o)}`)}},requestAvatar3d(i){return r("avatar3dPurchases",o=>n.bridge.requestAvatar3dPurchase(o,i.itemId,i.currencySlug),()=>n.confirmAvatar3d(i.itemId),()=>`3D avatar ${JSON.stringify(i.itemId)}`)},settle(i){let o=i.outcome==="ok"||i.outcome==="declined"?i.outcome:"unavailable",s=t.get(i.requestId);if(s===void 0){n.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(i.requestId));return}let{finish:a}=s;if(o!=="ok"){a(nt(o,ks(i.reason)));return}let l=i.purchaseId,d;try{d=s.check(l);}catch{d=Promise.resolve("unknown");}if(d===null){n.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),a(nt("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"&&n.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+s.label(l)),a(nt("unavailable","error"));})();}}}async function tc(n,e){try{return (await Fa(n,e)).granted?"granted":"absent"}catch(t){return t instanceof O&&t.reason==="not_found"?"absent":"unknown"}}var _f="small_human",nc=/^[a-z][a-z0-9_]{0,31}$/,rc=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,wf=8;function Co(n){if(n===null)return [];if(n.avatars3d!==void 0)return n.avatars3d;let{avatar3dId:e,avatar3dModelUrl:t,avatar3dIconUrl:r}=n;return e===void 0||t===void 0||r===void 0?[]:[{family:_f,id:e,modelUrl:t,iconUrl:r}]}function kf(n,e){return n.length===e.length&&n.every((t,r)=>{let i=e[r];return t.family===i.family&&t.id===i.id&&t.modelUrl===i.modelUrl})}function Rf(n){let e=n??{},t=typeof e.item_id=="string"&&rc.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&nc.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=Zn(e.icon_url),l=Zn(e.model_url),d=[];for(let m of Array.isArray(e.prices)?e.prices:[]){let u=m??{};typeof u.currency_slug=="string"&&u.currency_slug!==""&&typeof u.price=="number"&&Number.isSafeInteger(u.price)&&u.price>0&&d.push({currencySlug:u.currency_slug,price:u.price});}if(!(t===void 0||r===void 0||i===void 0||o===void 0||a===void 0||l===void 0||d.length===0))return {itemId:t,slug:i,family:r,displayName:o,...s===void 0?{}:{description:s},iconUrl:a,modelUrl:l,prices:d}}function Sf(n){if(!Array.isArray(n))return [];let e=[];for(let t of n)if(typeof t=="string"&&nc.test(t)&&!e.includes(t)&&e.push(t),e.length===wf)break;return e}function ic(n){let e=new Set,t=Co(n.player()),r=i=>{n.log?.(`[gem] an avatars3d onChange listener threw: ${i instanceof Error?i.message:String(i)}`);};return n.subscribe(i=>{let o=Co(i);if(!kf(t,o)){t=o;for(let s of [...e])try{s(o);}catch(a){r(a);}}}),{async families(){return Sf(await n.configFamilies())},worn(i){let o=Co(n.player());if(i!==void 0)return o.find(l=>l.family===i);let a=n.player()?.avatar3dId;return (a===void 0?void 0:o.find(l=>l.id===a))??o[0]},async offers(){let i=await n.readOffers(),o=[];for(let s of Array.isArray(i?.offers)?i.offers:[]){let a=Rf(s);a!==void 0&&o.push(a);}return o},purchase(i){let o=i?.itemId,s=i?.currencySlug;return typeof o!="string"||!rc.test(o)?Promise.resolve({outcome:"declined",reason:"not_purchasable"}):typeof s!="string"||s===""?Promise.resolve({outcome:"declined",reason:"unknown_currency"}):n.purchase({itemId:o,currencySlug:s})},onChange(i){return e.add(i),()=>{e.delete(i);}}}}async function oc(n,e){try{return (await ba(n,e))?.owned===!0?"granted":"absent"}catch(t){return t instanceof O&&t.reason==="not_found"?"absent":"unknown"}}function ac(n){return Ma(n)}var xf=6e5;function sc(n){let e=null,t=new Map;return {api:{requestSignIn(){if(!n.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=>{t.delete(r)&&(e=null,n.clock.clearTimeout(o.timer),i(l));};t.set(r,s),o.timer=n.clock.setTimeout(()=>{s({outcome:"unavailable"});},n.timeoutMs??xf);let a=false;try{a=n.bridge.requestSignIn(r);}catch{}a||s({outcome:"unavailable"});}),e}},settle(r){let i=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",o=t.get(r.requestId);if(o===void 0){n.onDropped?.(`gem.signInResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}o({outcome:i});}}}var Af=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),Pf=["utm_"];function lc(n){return Af.has(n)||Pf.some(e=>n.startsWith(e))}var dc=16,cc=512,Tf=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Ef=/[\p{Cc}\p{Cf}]/u,If=/\p{Cs}/u,Me="[gem] gem.share.request:";function uc(n){let{frame:e,log:t}=n,r=false,i=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,o=s=>{t!==null&&(t===void 0?console.warn(s):t(s));};return {get available(){return i()!==null},request(s){let a=i();if(a===null)throw new Error(`${Me} 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(`${Me} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!Cf(l))throw new TypeError(`${Me} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>dc)throw new TypeError(`${Me} at most ${dc} params; got ${d.length}`);let m=[];for(let[u,p]of d){let g=JSON.stringify(u);if(!Tf.test(u))throw new TypeError(`${Me} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(lc(u))throw new TypeError(`${Me} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Me} param ${g}: values must be strings`);if(p.length>cc)throw new TypeError(`${Me} param ${g}: a value is at most ${cc} characters`);if(Ef.test(p))throw new TypeError(`${Me} param ${g}: control and format characters are not allowed`);if(If.test(p))throw new TypeError(`${Me} param ${g}: a value must be well-formed text`);m.push({key:u,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 Cf(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var Gf="(any-pointer: coarse)";function Df(n){let e=Array.isArray(n)?n:[n],t=[],r=1e4;for(let i of e){if(typeof i!="number"||!Number.isFinite(i)||i<0)return null;if(t.length===99||r===0)continue;let o=Math.min(Math.trunc(i),1e4,r);t.push(o),r-=o;}return t.length%2===0&&t.pop(),t.every(i=>i===0)?[]:t}function mc(n){let{frame:e,log:t}=n,r=n.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(Gf),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,u)=>{s.has(m)||(s.add(m),t!==null&&(t===void 0?console.warn(u):t(u)));};return {get available(){return a()||l()},vibrate(m){let u=a();if(!u&&!l())return false;let p=Df(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(u)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 It=Math.PI/180,Oe=Object.freeze({touch:Object.freeze({yaw:1*It,pitch:.66*It}),mouse:Object.freeze({yaw:.5*It,pitch:.5*.77*It}),stick:Object.freeze({yaw:240*It,pitch:240*.77*It}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),Mo="[gem.controls]",Oo=Object.freeze({yaw:0,pitch:0}),Lr=n=>Number.isFinite(n)?n:0,pc=(n,e)=>({yaw:n+0,pitch:e+0});function gc(n){let e=Lr(n),t=(Math.abs(e)-Oe.stickDeadzone)/(1-Oe.stickDeadzone),r=Oe.stickCurve,i=(Math.exp(r*t)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,i))+0}function $f(n){let e=Math.min(1,2*Math.abs(n)/Math.PI);return (1-Math.pow(e,.75))*(1-Oe.touchPitchMin)+Oe.touchPitchMin}function yc(n,e){if(n===void 0)return {};if(typeof n!="object"||n===null)throw new TypeError(`${Mo} ${e} takes an options object`);let t=n;for(let r of ["sensitivity","gamepadSensitivity"]){let i=t[r];if(i!==void 0&&!(typeof i=="number"&&Number.isFinite(i)&&i>0))throw new TypeError(`${Mo} ${e}: ${r} must be a finite number above 0 (1 = the base speed); got ${String(i)}`)}if(t.invertY!==void 0&&typeof t.invertY!="boolean")throw new TypeError(`${Mo} ${e}: invertY must be a boolean; got ${String(t.invertY)}`);return t}function Ff(n,e){let t=yc(e,"look()"),r=t.sensitivity,i=t.gamepadSensitivity,o=t.invertY,s=a=>o??a?.invertLookY??false;return {fromPointer(a,l,d,m){let u=Lr(a),p=Lr(l);if(u===0&&p===0)return Oo;let g=n(),y=r??(g===null?void 0:g.lookSensitivity/100)??1,v=d==="touch"||d==="pen",R=v?Oe.touch:Oe.mouse,x=u*R.yaw*y,I=-p*R.pitch*y;return s(g)&&(I=-I),v&&m!==void 0&&Number.isFinite(m)&&I*m>0&&(I*=$f(m)),pc(x,I)},fromStick(a,l,d){let m=Lr(d);if(m<=0)return Oo;let u=gc(a),p=gc(l);if(u===0&&p===0)return Oo;let g=n(),y=i??(g===null?void 0:g.gamepadLookSensitivity/100)??1,v=u*Oe.stick.yaw*m*y,R=-p*Oe.stick.pitch*m*y;return s(g)&&(R=-R),pc(v,R)},set(a){let l=yc(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(i=l.gamepadSensitivity),"invertY"in l&&(o=l.invertY);}}}function fc(n){return {look:e=>Ff(n.recommended,e),LOOK_BASE:Oe}}function hc(n,e){return n==null?e?"low":"medium":n==="low"||n==="high"?n:"medium"}var qf=/(?:Z|[+-]\d{2}:?\d{2})$/i;function bc(n){if(typeof n!="string"||!qf.test(n))return;let e=Date.parse(n);return Number.isFinite(e)&&e>0?e:void 0}function vn(){return {declared:false,grantable:false,heldLimitReached:false}}function vc(n,e){let t=typeof n=="object"&&n!==null?n:{},r=bc(t.resets_at),i=r===void 0?{}:{resetsAt:r};if(t.declared!==true)return {...vn(),...i};let o=t.remaining_today,s=typeof o=="number"&&Number.isFinite(o)&&o>=0?Math.floor(o):void 0,a=t.next_eligible_at,l=bc(a),d=t.held_limit_reached===true,m=a!=null,u=o!=null&&s===void 0;return {declared:true,grantable:t.grantable===true&&e&&s!==0&&!u&&!m&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var Nf=18e4,Lo=32,jf=/^[a-z0-9_-]+$/,Uf="rewarded_requires_user_gesture";function Bf(){let n=globalThis.navigator?.userActivation?.isActive;return typeof n=="boolean"?n:void 0}var Wf=1e3;function Vf(){let n=globalThis,e=n.navigator?.getGamepads,t=n.performance?.now;if(typeof e!="function"||typeof t!="function")return;let r=t.call(n.performance),i=e.call(n.navigator);for(let o=0;o<i.length;o+=1){let s=i[o]?.timestamp;if(typeof s=="number"&&r-s>=0&&r-s<=Wf)return true}return false}var _c=1e4;function Hf(n){return n==="interstitial"||n==="rewarded"}function wc(n){return typeof n=="string"&&n!==""&&n.length<=Lo&&jf.test(n)}function Kf(n){let e=typeof n=="object"&&n!==null?n:{};return [e.name,e.reason,e.status].join()}function Gr(n){return typeof n=="string"?JSON.stringify(n):typeof n}function kc(n){let e=false,t=new Map,r=new Map,i=new Set,o=d=>{try{n.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let m=n.log;if(m!==null)try{m===void 0?console.warn(`[gem] ${d}`):m(`[gem] ${d}`);}catch{}},l=d=>{let m=n.readAvailability;if(m===void 0)return Promise.resolve(vn());let u=r.get(d);if(u!==void 0)return u;let p=new Promise(g=>{let y={},v=h=>y.done===true?false:(y.done=true,n.clock.clearTimeout(y.timer),g(h),true),R=(h,k)=>{!v(vn())||i.has(h)||(i.add(h),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${k}. Said once.`));},x=h=>{R(Kf(h),`the read failed (${h instanceof Error?h.message:Gr(h)})`);},I;try{I=Promise.resolve(m(d,AbortSignal.timeout(_c)));}catch(h){I=Promise.reject(h);}y.timer=n.clock.setTimeout(()=>{R("timeout","no answer within 10 s");},_c),I.then(h=>{try{v(vc(h,n.bridge.parentSupports("ads")));}catch(k){x(k);}},x);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return wc(d)?l(d):(o(`gem.ads.rewardedStatus(${Gr(d)}) answered not grantable: a placement is 1..${String(Lo)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(vn()))},requestAd(d){if(!n.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let m=d?.placement,u=d?.format;if(!wc(m)||!Hf(u))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${Gr(m)}, format ${Gr(u)}. A placement is 1..${String(Lo)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});if(u==="rewarded"){let g;try{g=(n.userActivation??Bf)();}catch{g=void 0;}if(g===false)try{(n.recentGamepadInput??Vf)()===!0&&(g=!0);}catch{}if(g===false){let y=`${Uf}: 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=x=>{t.delete(p)&&(e=false,n.clock.clearTimeout(y.timer),g(x));};e=true,t.set(p,v),y.timer=n.clock.setTimeout(()=>{v({outcome:"unavailable"});},n.timeoutMs??Nf);let R=false;try{R=n.bridge.requestAd(p,m,u);}catch{}R||v({outcome:"no_ad"});})}},settle(d){let m=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",u=t.get(d.requestId);if(u===void 0){n.onDropped?.(`gem.adResult (${m}) for an unknown requestId: `+JSON.stringify(d.requestId));return}u({outcome:m});}}}var Rc=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),Sc=18e4,Jf=1e4,zf=/^[a-z0-9_-]{1,32}$/;function xc(n){return typeof n=="string"?JSON.stringify(n):typeof n}var _n=Object.freeze({shown:false});function Ac(n){let e=new Map,t,r=false,i=o=>{try{n.onDropped?.(o);}catch{}return _n};return {api:{signal(o){try{if(!n.bridge.parentSupports("moments"))return r?Promise.resolve(_n):(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(!Rc.includes(s)||a!==void 0&&(typeof a!="string"||!zf.test(a)))return Promise.resolve(i(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${xc(s)}, placement ${xc(a)}. A kind is one of ${Rc.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'. Answering shown: false.`));if(!n.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=n.clock.now();if(t!==void 0&&l-t<Jf)return Promise.resolve(i(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(l-t)} 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 u={},p=(y,v)=>{e.delete(d)&&(n.clock.clearTimeout(u.timer),v&&(t=n.clock.now()),m(y));};e.set(d,y=>p(y,!0)),u.timer=n.clock.setTimeout(()=>{e.has(d)&&(p(_n,!0),i(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((n.timeoutMs??Sc)/1e3)} s. Answering shown: false.`));},n.timeoutMs??Sc);let g=!1;try{g=n.bridge.signalMoment(d,s,a);}catch{}g||p(_n,!1);})}catch{return Promise.resolve(_n)}}},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 Go=16384;function Pc(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e;try{e=JSON.stringify(n);}catch{return null}return typeof e!="string"?null:Yf(e)}function Yf(n){let e=0;for(let t=0;t<n.length;t+=1){let r=n.charCodeAt(t);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=n.charCodeAt(t+1);i>=56320&&i<=57343?(e+=4,t+=1):e+=3;}else e+=3;}return e}var Xf=1e4,Qf=5e3;function Tc(n){let e=null,t=false,r=[],i=new Map,o=()=>{for(let s of r.splice(0))s();};return {api:{get current(){return e},wait(s=Qf){return t?Promise.resolve(e):new Promise(a=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,1);},d=()=>{n.clock.clearTimeout(m),l(),a(e);},m=n.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!n.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=Pc(s);if(a===null)return n.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 u={},p=y=>{i.delete(d)&&(n.clock.clearTimeout(u.timer),y==="stored"&&(e=l,t=true,o()),m(y));};i.set(d,p),u.timer=n.clock.setTimeout(()=>p("unavailable"),n.timeoutMs??Xf);let g=false;try{g=n.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,t=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){n.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var wn=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 Zf=/^[a-z0-9][a-z0-9_-]{0,39}$/;function eh(n){return typeof n=="string"&&Zf.test(n)}function Dr(n){if(n===null||eh(n))return n;let e=typeof n=="string"?JSON.stringify(n.length>48?`${n.slice(0,48)}\u2026`:n):`a value of type ${typeof n}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}function Ec(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Do(n,e){if(n!==true)return {visible:false};let t=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!t.includes(i)&&t.push(i);return !r&&t.length===0?{visible:true}:{visible:true,currencies:t.slice(0,8),score:r}}function $r(n){let e=[];for(let t of Array.isArray(n)?n:[]){if(e.length===4)break;if(typeof t!="object"||t===null)continue;let{id:r,label:i}=t;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 Ic(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function th(n){let e=n.untrusted,t=Ge(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,i=r?Ge(r,"gem.player.displayTag"):void 0,o=n.discriminator||n.displayTag,s=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,a=n.avatarIconUrl||n.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=n.avatarIconId,m=n.avatar3dId,u={displayName:t,displayHandle:i??t,badges:(n.badges??[]).map(v=>({itemId:v.itemId,iconUrl:v.iconUrl}))};n.playerId&&(u.playerId=n.playerId),s&&(u.discriminator=s),i&&(u.displayTag=i),a&&(u.avatarIconUrl=u.avatarUrl=a),d&&l.test(d)&&(u.avatarIconId=d),m&&l.test(m)&&(u.avatar3dId=m),n.avatar3dModelUrl&&(u.avatar3dModelUrl=n.avatar3dModelUrl),n.avatar3dIconUrl&&(u.avatar3dIconUrl=n.avatar3dIconUrl),n.avatars3d&&(u.avatars3d=n.avatars3d.filter(v=>l.test(v.id)&&/^[a-z][a-z0-9_]*$/.test(v.family)).filter((v,R,x)=>x.findIndex(I=>I.family==v.family)==R).map(({family:v,id:R,modelUrl:x,iconUrl:I})=>({family:v,id:R,modelUrl:x,iconUrl:I})));let p=n.boost,g=(p?.multipliers??[]).map(v=>({currencyId:v.currencyId,currencySlug:v.currencySlug,multiplier:v.multiplierBp/1e4})),y=g.some(v=>v.multiplier>1);return u.boost=y&&p?.expiresInDays?{active:y,multipliers:g,expiresInDays:p.expiresInDays}:{active:y,multipliers:g},u}var nh=1e4,kn=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??he,this.inbound=new Dt(this.clock),this.outbound=new Dt(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=>ni(a,e.origin))||bs(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=Ln["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!ni(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=vs(Mn,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:U,type:"gem.error",code:"version_mismatch",message:`frame supports v${Mn.min}..v${Mn.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=nh){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(t=>{let r=o=>{this.clock.clearTimeout(i),t(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),t(this.state);},e);this.settleWaiters.push(r);})}progress(e,t){this.send({gem:U,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:U,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:U,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),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 t={gem:U,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(t.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(t.origin={x:Ec(e.origin.x),y:Ec(e.origin.y)}),this.send(t),true}showPortraitBorders(e){let t=Dr(e);return t===void 0||!this.gated("portraitBorders")?false:this.send(t===null?{gem:U,type:"gem.portraitBorders"}:{gem:U,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.gated("walletDisplay")?this.send({gem:U,type:"gem.walletDisplay",...Do(e,t?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:U,type:"gem.menu",...$r(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:t,value:r})=>({key:t,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:Ic(e.fps,1e3),frameTimeP95Ms:Ic(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,t,r){this.send({gem:U,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:U,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:U,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,s){return this.send({gem:U,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s}})}requestAvatar3dPurchase(e,t,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:U,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:t,currencySlug:r}):false}putDeviceSettings(e,t){return this.send({gem:U,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:U,type:"gem.requestAd",requestId:e,placement:t,format:r})}signalMoment(e,t,r){return this.send({gem:U,type:"gem.signalMoment",requestId:e,kind:t,...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,t,r,i){return this.send({gem:U,type:"gem.requestFriendChallenge",requestId:e,playerId:t,template:r,...i===void 0?{}:{params:i}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let t of this.settleWaiters.splice(0))t(e);this.options.onStateChange?.(e);}}refuseMalformed(e,t){if(!this.inbound.allow(On)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(On)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(On)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:U,type:"gem.error",code:e,...t===void 0?{}:{message:t}});}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 t=e.type;if(!this.outbound.allow(t))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${t}`),false;let r=Ln[t]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${t}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,t=[]){let r=false;try{r=this.dispatchInbound(e,t);}finally{r||Cc(t);}}dispatchInbound(e,t){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let i=Ln[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.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=t[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 Cc(t.slice(1)),this.options.onScreenshot(d,l,(m,u)=>this.screenshotDenied(m,u)),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?.(th(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,t){this.send({gem:U,type:"gem.screenshot.denied",reason:e,retryable:t});}};function Cc(n){for(let e of n)try{e?.close?.();}catch{}}var Mc="https://api.gemarcade.com";function $o(n){let e;try{e=new URL(n);}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 rh=new Set(["localhost","127.0.0.1","[::1]"]);function Oc(n){let e=$o(n);if(e!==null)return e;let t=new URL(n);return t.protocol==="http:"&&!rh.has(t.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 Lc(n){return Object.freeze(n.map(([e,t])=>Object.freeze({node:e,parent:t})))}function ih(){let n=[["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 t=r=>`${r}_${e}`;n.push([t("shoulder"),"upper_chest"],[t("upper_arm"),t("shoulder")],[t("lower_arm"),t("upper_arm")],[t("hand"),t("lower_arm")],[t("hand_socket"),t("hand")]);for(let r of ["thumb","index","middle","ring","little"])for(let i=1;i<=3;i++)n.push([t(`${r}_${i}`),t(i===1?"hand":`${r}_${i-1}`)]);}for(let e of ["l","r"]){let t=r=>`${r}_${e}`;n.push([t("upper_leg"),"hips"],[t("lower_leg"),t("upper_leg")],[t("foot"),t("lower_leg")],[t("toes"),t("foot")]);}return n}var oh=Object.freeze({small_human:Lc([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:Lc(ih())});var sh=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),lh=Mc,dh=["top-left","top-right","bottom-left","bottom-right"],Gc=8e3,Fo=15e3,ch=9e4,uh=1/0,mh=8e3,ph=5e3,gh=5e3;async function yh(n,e,t,r){if(n.isInRoom)try{await n.leave();}catch{}r?.endSession("session_ended"),e!==null&&e.currentState==="connected"&&e.exit(t);}function Rn(n){let e=null,t=false,r=[];return {get current(){return e},set(i){e=i;for(let o of r.splice(0))o(i);},release(){t=true;for(let i of r.splice(0))i(e);},wait(i){return e!==null||t?Promise.resolve(e):new Promise(o=>{let s=()=>{let d=r.indexOf(a);d>=0&&r.splice(d,1);},a=d=>{n.clearTimeout(l),s(),o(d);},l=n.setTimeout(()=>{s(),o(e);},i);r.push(a);})}}}function $x(n={}){let e=n.clock??he,t=n.log===void 0?c=>console.info(c):n.log,r=n.baseUrl??void 0;if(r!=null){let c=$o(r);if(c!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${c}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=Js(typeof window>"u"?void 0:window.location?.search),o=go();o.mark("sdk created");let s=()=>cr(ne.gameVersion,n.clientVersion?.gameVersion),a=new Jt({client:()=>dt,clock:e,gameId:()=>ne.identity?.gameId??null,playerId:()=>ne.identity?.playerId??null,environment:()=>{let c=s();return {sdk_version:Qo(),...c===null?{}:{game_version:c}}},...n.analytics===void 0?{}:{options:n.analytics},log:t}),l=td(()=>{o.mark("engaged"),a.release(),F.reportEngaged();},typeof window>"u"?{}:window),d=c=>{if(c===false)return null;let S=c?.attempts??uh,q=c?.budgetMs??ch;return !(S>0)||!(q>0)?null:{attempts:S,budgetMs:q,maxDelayMs:c?.maxDelayMs??mh}},m=c=>{c.on("created",()=>{o.mark("room created");}),c.on("joined",()=>{o.mark("room joined");}),c.on("matchAllocationStarted",()=>{o.mark("allocation started");}),c.on("matchReady",()=>{o.mark("match ready");}),c.on("matchFailed",()=>{o.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new wn;let u=n.allowedEmbedders;if(u!=null&&!Array.isArray(u))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 p=Array.from(u??[]),g=p.filter(c=>typeof c!="string"||!ti(c));if(g.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${g.length===1?"an entry":"entries"} that ${g.length===1?"is":"are"} not an origin: ${g.map(c=>typeof c=="string"?JSON.stringify(c):String(c)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let y=Object.freeze([...new Set([...sh,...p])]),v=Rn(e),R=new Set,x=Rn(e),I=false,h=Rn(e),k=el(t),E=Rn(e),T=n.manageAudio===false?null:dd();n.selectableText!==true&&cd();let B=null,G=null,j=()=>{B===null||B===G||F.reportMuted(B)&&(G=B);},A,M,D=-1/0,N=null,W=()=>{if(A===void 0||N!==null||A===M)return;let c=D+1e3-e.now();if(c>0){N=e.setTimeout(()=>{N=null,W();},c);return}F.showPortraitBorders(A)&&(M=A,D=e.now());},V=null,te=null,pe=()=>{if(V===null)return false;let c=JSON.stringify(Do(V.visible,V.only));return c===te?F.parentSupports("walletDisplay"):F.setWalletVisible(V.visible,V)?(te=c,true):false},J=null,$e=null,_e=()=>{if(J===null)return false;let c=JSON.stringify($r(J.items));return c===$e?F.parentSupports("gameMenu"):F.setMenu(J.items)?($e=c,true):false},fe=null,Fe=null,Z=()=>fe===null?false:fe===Fe?F.parentSupports("gemCorner"):F.setGemCorner(fe)?(Fe=fe,true):false,z=ud({report:c=>F.reportFrameStats(c)}),oe=false,ge=vd(()=>Xo,()=>oe),qe=c=>{let S=oe&&!c,q=oe!==c;if(oe=c,S&&ge.close(),!!q)try{n.onDevToolsPermissionChange?.(c);}catch(re){t?.(`[gem] onDevToolsPermissionChange threw: ${re instanceof Error?re.message:String(re)}`),queueMicrotask(()=>{throw re});}},Le=r??lh,Fr=r!==void 0,rt,it=c=>(t?.(`[gem] token refused: ${c}`),n.onError?.("internal",c),false),Ct=(c,S)=>{if(c===void 0)return S!==void 0?it("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 q=Oc(c);return q!==null?it(`the embedder named an API root that cannot be used: ${q}. Its value is withheld here rather than written to logs.`):rt!==void 0&&rt!==c?it("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."):(rt=c,Fr||(Le=c),true)},Mt=window.location?.origin,ot=null,f=-1/0,C=2e3,$=new Set,Q=c=>ot!==false?Promise.resolve(true):new Promise(S=>{let q=e.setTimeout(()=>{$.delete(re),S(false);},c),re=()=>{e.clearTimeout(q),$.delete(re),S(true);};$.add(re);}),ye=()=>{},at=null,F=new kn({allowedEmbedders:y,...typeof Mt=="string"&&Mt!==""?{selfOrigin:Mt}:{},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","engagement","reservedAreas","viewport","purchases","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges",...n.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:c=>{at=c,n.onRefused?.(c);},...n.onError===void 0?{}:{onError:n.onError},onStateChange:c=>{ne.onBridgeState(c),c!=="connected"&&z.setRequested(false),G=null,te=null,$e=null,Fe=null,M=void 0,c==="refused"&&(console.error("[gem] this game refused the page that framed it"+(at===null?"":` (${at})`)+", 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."),ye()),c==="connected"&&(o.mark("bridge connected"),Dc(),j(),W(),pe(),_e(),Z(),F.unbiddenLaunch&&!l.engaged&&a.hold(),a.startSession(),l.engaged&&F.reportEngaged()),n.onStateChange?.(c);},onPlayer:c=>{v.set(c);for(let S of [...R])S(c);n.onPlayer?.(c);},onPrefs:c=>{let S={reducedMotion:c.reducedMotion,muted:c.muted,locale:c.locale,showFrameStats:c.showFrameStats===true,recommended:c.recommended===void 0?null:Object.freeze({volume:c.recommended.volume,batterySaver:c.recommended.batterySaver,keyboardLayout:c.recommended.keyboardLayout,gamepadConfirm:c.recommended.gamepadConfirm,vibration:c.recommended.vibration,lookSensitivity:c.recommended.lookSensitivity??100,gamepadLookSensitivity:c.recommended.gamepadLookSensitivity??100,invertLookY:c.recommended.invertLookY??false,touchMovement:c.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:hc(c.recommended.graphicsQuality,c.recommended.batterySaver),graphicsQualityAuto:c.recommended.graphicsQualityAuto??true})};x.set(S),G=S.muted,T?.setMuted(S.muted),z.setRequested(S.showFrameStats&&F.parentSupports("frameStats")),n.onPrefs?.(S);},onCohorts:c=>{let S=Object.freeze(c.cohorts.map(q=>Object.freeze({experimentId:q.experimentId,variantKey:q.variantKey})));h.set(S),n.onCohorts?.(S);},onEarnAllowanceChanged:()=>k.emit(),onViewport:c=>{let S=Object.freeze({insets:Object.freeze({top:c.insets.top,right:c.insets.right,bottom:c.insets.bottom,left:c.insets.left}),reserved:Object.freeze((c.reserved??[]).map(re=>Object.freeze({x:re.x,y:re.y,width:re.width,height:re.height})))});E.set(S);let q=gd();yd(q,S.insets),hd(q,S.reserved,fd()),n.onViewport?.(S);},onPause:c=>{I=c.paused,a.setPaused(c.paused),z.setPaused(c.paused),n.onPause?.(c.paused);},onMenuSelect:c=>{J===null||c.entry!=="item"||!($r(J.items).items??[]).some(q=>q.id===c.id)||J.items?.find(q=>q.id===c.id)?.onSelect?.();},onWillTerminate:c=>{a.endSession(c.reason),n.onWillTerminate?.({reason:c.reason,graceMs:c.graceMs});},onToken:c=>{let S=c.garden;if(qe(c.allowDevTools===true),!Ct(c.apiBaseUrl,S))return;let q=c;ne.onToken(q);let re=ne.identity;re&&(qr.set(re),qo||(qo=true,de.reconcileSeats().catch(()=>{}))),No.push({token:q.token,expiresAt:q.expiresAt});},onTokenDenied:c=>{qe(false),ne.onDenied(c);},onScreenshot:(c,S,q)=>{ad(c,S,q,{...n.onScreenshot===void 0?{}:{handler:n.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{sd(F,n.onFeedbackContext);},onDevtools:c=>{c==="close"?ge.close():c==="open"?ge.openFrom("platform").catch(()=>{}):ge.isOpen?ge.close():ge.openFrom("platform").catch(()=>{});},onRoomEvent:c=>de.handleRoomEvent({event:c.event,roomId:c.roomId,...c.matchId===void 0?{}:{matchId:c.matchId},...c.version===void 0?{}:{version:c.version},...c.reason===void 0?{}:{reason:c.reason},...c.platform===void 0?{}:{platform:c.platform}}),onSeatedEvent:c=>de.handleSeated(c.roomId),onAutoStartFailedEvent:c=>de.handleAutoStartFailed(c.roomId,c.code),onTicketEvent:c=>de.handleTicketEvent({event:c.event,ticketId:c.ticketId,...c.partySize===void 0?{}:{partySize:c.partySize},...c.queuedAt===void 0?{}:{queuedAt:c.queuedAt},...c.expiresAt===void 0?{}:{expiresAt:c.expiresAt},...c.reason===void 0?{}:{reason:c.reason},...c.roomId===void 0?{}:{roomId:c.roomId}}),onSocketState:c=>{let S=ot;if(ot=c.connected,c.connected)for(let re of [...$])re();if(!c.connected||S===true)return;let q=e.now();q-f<C||(f=q,de.reconcile().catch(()=>{}));},onSignalEvent:c=>{let S=typeof c.data=="object"&&c.data!==null&&!Array.isArray(c.data)?c.data:{};ct.handleSignalEvent(c.matchId,c.event,S),c.event==="matchEnded"&&de.reconcile({matchId:c.matchId,...typeof S.reason=="string"?{reason:S.reason}:{}}).catch(()=>{});},onDedicatedEvent:c=>{c.event==="matchEnded"&&(Ot.handleMatchEnded(c.matchId,c.reason),de.reconcile({matchId:c.matchId,...c.reason===void 0?{}:{reason:c.reason}}).catch(()=>{})),st.handleEvent(c);},onClusterTarget:c=>Pn.accept(c.clusterTargetId,c.clusterTargetIds),onLocalServer:c=>Tn.accept(c),onLocalServerDenied:c=>Tn.refuse(c),onPartyResult:c=>Uo.settle(c.requestId,c.partyId),onPurchaseResult:c=>jr.settle(c),onDeviceSettings:c=>{An.receive(c),n.onDeviceSettings?.(An.api.current);},onDeviceSettingsResult:c=>An.settle(c),onAdResult:c=>Wo.settle(c),onMomentResult:c=>Vo.settle(c),onSignInResult:c=>Ho.settle(c),onFriendChallengeResult:c=>Ko.settle(c)}),st=new hn({bridge:F}),qr=Rn(e);ye=()=>{qr.release(),v.release(),h.release();},F.currentState==="refused"&&ye();let qo=false,Nr=new Set,Sn,No={current:()=>Sn,subscribe:c=>(Nr.add(c),Sn!==void 0&&c(Sn),()=>Nr.delete(c)),push:c=>{Sn=c;for(let S of [...Nr])try{S(c);}catch(q){t?.(`[gem] a server-token listener threw: ${q instanceof Error?q.message:String(q)}`);}}},ne=wd({bridge:F,clock:e,onStateChange:(c,S)=>{if(c==="ready"){if(o.mark("token ready")){let q=o.marks.find(re=>re.name==="token ready")?.at;a.trackPlatform("gem_boot_ready",q===void 0?{}:{boot_ms:Math.max(0,Math.round(q))});}}else c==="lost"&&(o.mark("token lost"),a.trackPlatform("gem_auth_lost"));n.onAuthStateChange?.(c,S);}}),jo=()=>{let c=ne.identity;return !c||ne.source.currentState==="lost"?null:`${c.playerId}\0${c.gameId}\0${c.channel}`},Dc=()=>{o.mark("token requested"),ne.source.get().catch(()=>{});},Uo=Io({bridge:F,clock:e}),xn={},jr=ec({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c),confirm:async c=>xn.confirm?.(c)??"unknown",confirmAvatar3d:async c=>xn.confirmAvatar3d?.(c)??"unknown"}),An=Tc({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c)}),Bo={},Wo=kc({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c),readAvailability:(c,S)=>Bo.read?.(c,S)??Promise.reject(new Error("the gem-api client is not built yet")),log:n.log}),Vo=Ac({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c)}),Ho=sc({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c)}),Ko=Zs({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c)}),Pn=dl({bridge:F,clock:e}),Tn=bd({bridge:F,clock:e}),Ur=c=>{let S=F.handleWindowMessage({data:c.data,origin:c.origin,source:c.source,ports:c.ports});return S&&window.removeEventListener("message",Ur),S};window.addEventListener("message",Ur);let lt=nd(window,Ur),$c=lt?.capture,Br=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Br?.domInteractive!==void 0&&Br.domInteractive>0&&o.mark("document parsed",Br.domInteractive),$c?.late&&t?.("[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 Wr=n.handshakeWarningMs;Wr!==null&&t&&e.setTimeout(()=>{let c=lt===null?"no capture script ran":`capture: ${lt.delivered} offer(s) delivered, ${lt.stale} stale, ${lt.capture.dropped} evicted${lt.capture.late?", installed late":""}`;if(F.currentState==="connected"){t(`[gem] handshake connected. boot: ${o.timeline()} \xB7 ${c}`);return}t(`[gem] no completed handshake after ${Wr??Gc}ms (bridge state: ${F.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${o.timeline()} \xB7 `+c);},Wr??Gc);let Fc=Ir({get baseUrl(){return Le},tokenSource:ne.source,get defaultQuery(){let c=ne.identity;return c?{game_id:c.gameId,channel:c.channel}:{}}}),dt=new Be({transport:Fc,clock:e}),ue={client:dt,gameId:()=>ne.identity?.gameId??""};xn.confirm=c=>tc(ue,c),xn.confirmAvatar3d=c=>oc(ue,c),Bo.read=(c,S)=>as(ue,"players","me",c,{signal:S});let qc=()=>ne.identity?.channel??"release",Vr=new Xn(ue,qc),Nc=ic({player:()=>v.current,subscribe:c=>(R.add(c),()=>{R.delete(c);}),configFamilies:async()=>(await Vr.load())?.avatar_3d_families,readOffers:()=>ac(ue),purchase:c=>jr.requestAvatar3d(c),log:n.log}),Jo=async c=>(await Vr.load())?.currency(c)?.id??void 0,zo=Vn(ue,mi,{identity:jo,resolveCurrencyId:Jo}),Hr=async c=>{let S=await qr.wait(c);if(S)return S;throw F.currentState==="refused"?new ie("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new ie("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},Kr=d(n.autoReconnect),de=Qi({client:dt,clock:e,gameId:()=>ne.identity?.gameId??null,playerId:()=>ne.identity?.playerId??null,awaitGameId:async()=>(await Hr(Fo)).gameId,resolveParty:Uo.resolve,resolveClusterTargets:Pn.resolveList,refreshClusterTargets:Pn.refresh,ensureLocalServer:Tn.ensure,localHostAvailable:Tn.available,...n.clientVersion===void 0?{}:{clientVersion:n.clientVersion},platformGameVersion:()=>ne.gameVersion,...n.pollRooms===void 0?{}:{poll:n.pollRooms},...n.recoverStaleMembership===void 0?{}:{recoverStaleMembership:n.recoverStaleMembership},...n.retryAutoStart===void 0?{}:{retryAutoStart:n.retryAutoStart},...n.watchSeats===void 0?{}:{watchSeats:n.watchSeats},...n.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:n.seatPollIntervalMs},...Kr===null?{}:{autoReconnect:{...Kr,redial:(c,S)=>Jr.redialMatch(c,S),abandon:(c,S)=>Jr.abandonMatch(c,S)}}});m(de),Zl({analytics:a,rooms:de});let ct=Ql({client:dt,clock:e,rooms:de,bridge:F,gameId:()=>ne.identity?.gameId??"",baseUrl:()=>Le,resolveClusterTarget:Pn.resolve,boot:o,...n.log===void 0?{}:{log:n.log}}),Yo=po(o,t),Ot=Fd({client:dt,clock:e,rooms:de,signaling:()=>st.channel(),signalingReady:Q,log:t??(()=>{})}),Jr=Qd({rooms:de,p2p:{connect:c=>Yo(ct.connect(c)),session:c=>ct.session(c)},dedicated:{connect:(c=>Pr(o,"welcome",Ot.connect(c),t))},clock:e,identity:()=>ne.identity,apiBaseUrl:()=>Le,tokens:No,room:()=>de.currentRoom,autoReconnect:Kr!==null,...n.log===void 0?{}:{log:n.log}}),jc=async()=>(await Hr(Fo)).playerId,Xo={client:dt,boot:o,get identity(){return ne.identity},awaitIdentity:(c=Fo)=>Hr(c),awaitBridge:c=>F.settled(c),get player(){return v.current},awaitPlayer:(c=ph)=>v.wait(c),me:zo,characters:new Kn(ue,void 0,jo,Jo),transfers:new zn(ue,mi,zo.inventory),gameConfig:Vr,purchases:jr.api,deviceSettings:An.api,moments:Vo.api,ads:Wo.api,account:Ho.api,share:uc({frame:F,log:n.log}),vibration:mc({frame:F,log:n.log}),get avatarPickerAvailable(){return F.currentState==="connected"&&F.parentSupports("avatarPicker")},openAvatarPicker:c=>F.requestAvatarPicker(c?.tab),avatars3d:Nc,controls:fc({recommended:()=>x.current?.recommended??null}),analytics:a,leaderboards:new Ut(ue),challenges:new qt(ue),showcase:new Bt(ue,jc),friends:new Wt(ue,{challenge:Ko.challenge,...i===void 0?{}:{launchedChallengeId:i}}),platform:new Ht(ue,k,t),profiles:new Kt(ue),functions:new Je((c,S)=>Ha(ue,c,S)),get prefs(){return x.current},get paused(){return I},get cohorts(){return h.current},get viewport(){return E.current},awaitCohorts:(c=gh)=>h.wait(c),reportMuted:c=>{B=!!c,j();},showPortraitBorders:c=>{let S=Dr(c);S!==void 0&&(A=S,W());},cueReward:c=>F.cueReward(c),setWalletVisible:(c,S)=>{let q=Array.isArray(S?.only)?[...S.only]:void 0;return V=q===void 0?{visible:c===true}:{visible:c===true,only:q},pe()},setMenu:c=>(J=Array.isArray(c?.items)?{items:c.items.map(S=>({...S}))}:{},_e()),setGemCorner:c=>{if(!dh.includes(c)){let S=typeof c=="string"?JSON.stringify(c.slice(0,48)):`a value of type ${typeof c}`;return console.warn(`[gem] setGemCorner: ${S} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return fe=c,Z()},reportFrame:()=>z.draw(),exit:c=>yh(de,F,c,a),frame:F,devtools:ge,rooms:de,dedicatedServer:{listClusterTargets:c=>Ot.listClusterTargets(c),connect:(c=>Pr(o,"welcome",Ot.connect(c),t)),handleMatchEnded:(c,S)=>Ot.handleMatchEnded(c,S)},p2p:{handleSignalEvent:(c,S,q)=>ct.handleSignalEvent(c,S,q),session:c=>ct.session(c),connect:c=>Yo(ct.connect(c))},match:Jr};return Xo}
|
|
3
|
+
export{sh as ARCADE_EMBEDDERS,oh as AVATAR_RIGS,Jt as AnalyticsApi,ie as AuthError,qt as ChallengesApi,Go as DEVICE_SETTINGS_MAX_BYTES,w as DedicatedServerError,Ke as FriendChallengeError,Wt as FriendsApi,Je as FunctionsApi,O as GemApiError,Be as GemClient,ce as GemConfigError,kn as GemFrame,or as GemFunctionError,se as GemSaveError,wn as GemUnframedError,Ut as LeaderboardsApi,$s as MAX_PERIODS_BACK,Cm as PLATFORM_EVENTS,Ht as PlatformApi,rr as PlatformCurrenciesApi,ir as PlatformEarnAllowanceApi,be as PlayerText,Kt as ProfilesApi,Ne as PurchaseRefusal,Bt as ShowcaseApi,ae as TransportRefusal,Zt as UNRELIABLE_CHANNEL_LABEL,Ge as asPlayerText,go as createBootTimeline,$x as createGem,yh as leaveAndExit,Se as mapIdentity,Pr as markOnResolve,rm as platformIconUrl,Xt as presentJoinCredential,kt as readTemplateTransports,en as readTransportAdvert,po as reportOnResolve,ft as text,yr as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.game.js.map
|
|
3
4
|
//# sourceMappingURL=gem-web-sdk.game.js.map
|