@indiegems/gem-web-sdk 21.1.1 → 22.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/function.d.ts +1 -0
- package/dist/game.d.ts +7 -1
- package/dist/gem-web-sdk.bridge.js +2 -2
- package/dist/gem-web-sdk.conformance.js +3 -3
- package/dist/gem-web-sdk.esm.js +3 -3
- package/dist/gem-web-sdk.function.js +2 -2
- package/dist/gem-web-sdk.game.js +3 -3
- package/dist/gem-web-sdk.min.js +3 -3
- package/dist/gem-web-sdk.sdk.js +3 -3
- package/dist/gem-web-sdk.server-api.js +1 -1
- package/dist/gem-web-sdk.server.js +2 -2
- package/dist/index.d.ts +15 -3
- package/dist/sdk.d.ts +8 -1
- package/dist/server-api.d.ts +1 -0
- package/dist/server.d.ts +3 -0
- package/docs/api/api-reference-function.md +1 -1
- package/docs/api/api-reference-game.md +152 -1
- package/docs/api/api-reference-server.md +28 -1
- package/docs/api/reference.json +114 -4
- package/docs/arcade-economy.md +3 -1
- package/docs/changelog.md +14 -0
- package/docs/daily-challenges.md +3 -1
- package/docs/getting-started.md +1 -1
- package/docs/inventory-and-catalogs.md +57 -2
- package/docs/manifest.json +16 -16
- package/docs/server-bundles.md +2 -2
- package/docs/serverless-functions.md +17 -0
- package/docs/what-a-game-must-do.md +22 -1
- package/package.json +1 -1
- package/schema/bridge.v1.json +68 -1
- package/schema/capabilities.public.json +6 -0
package/dist/gem-web-sdk.min.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var GemWebSdkGame=(function(exports){'use strict';var Ap=Object.defineProperty;var xp=(t,e)=>{for(var n in e)Ap(t,n,{get:e[n],enumerable:true});};var Bi="GemWebSdkHandshake";function Pp(){return typeof document>"u"?void 0:document.readyState}var ks=()=>Date.now();function As(t={}){let e=t.win??window,n=e,r=n[Bi];if(r!==void 0)return r;let i=t.readyState??Pp,o=t.now??ks,s=[],a=[],l=u=>{let c=u.data;!c||c.type!=="gem.handshake"||(s.length>=4&&(s.shift(),a.shift(),d.dropped+=1),s.push(u),a.push(o()));};e.addEventListener("message",l);let d={events:s,times:a,dropped:0,late:i()==="complete",uninstall(){e.removeEventListener("message",l);}};return n[Bi]=d,d}function xs(t,e,n={}){let r=t[Bi];if(r===void 0)return null;let i=n.ttlMs??9500,o=n.now??ks,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,u=false,c=o()-i;for(let g=s.length-1;g>=0;g--){let p=a?.[g];if(p!==void 0&&p<c){d+=1;continue}if(l+=1,e(s[g])===true){u=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:u}}globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:21.1.1]";function Ps(){let t=globalThis.__gemWebSdkVersion;if(typeof t!="string")return "";let e=t.lastIndexOf(":"),n=t.lastIndexOf("]");return e<0||n<=e+1?"":t.slice(e+1,n)}var Ep={initialDelayMs:2e3,maxDelayMs:6e4};function Tp(t,e){return e!==void 0?!e:t==="chain_exhausted"}var kt=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;retry=null;failures=0;notBefore=0;disposed=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new re(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.pastChainCeiling())throw new re("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new re(this.failure??"unavailable","the embedder asked for no new token yet; one is asked for when that wait is over");return this.refresh(this.nextReason())}pastChainCeiling(){return this.grant===null||this.seconds()<this.grant.chainEndsAt?false:(this.enter("lost","chain_exhausted"),true)}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}dispose(){this.disposed=true,this.cancelRetry();}scheduleRetry(e){if(this.cancelRetry(),this.failures+=1,this.notBefore=e===void 0?0:this.options.clock.now()+e,this.disposed)return;let{initialDelayMs:n,maxDelayMs:r}=Ep,i=Math.min(r,n*2**(this.failures-1)),o=Math.max(i/2,e??0)+Math.random()*(i/2);this.retry={handle:this.options.clock.setTimeout(()=>this.retryNow(),o)};}retryNow(){this.retry=null,this.notBefore=0,!(this.state==="lost"||this.pastChainCeiling())&&this.refresh(this.nextReason()).catch(()=>{});}cancelRetry(){this.retry!==null&&(this.options.clock.clearTimeout(this.retry.handle),this.retry=null);}refresh(e){if(this.inFlight)return this.inFlight;this.cancelRetry();let n=this.generation;this.enter("pending");let r=this.options.request(e).then(i=>{if(n!==this.generation)throw new re("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=Ip(i),{retryable:s,retryAfterMs:a}=i??{};throw n===this.generation&&(Tp(o,typeof s=="boolean"?s:void 0)?this.enter("lost",o):(this.scheduleRetry(typeof a=="number"&&Number.isFinite(a)&&a>0?a:void 0),this.enter("degraded",o))),i instanceof re?i:new re(o,String(i))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){(e==="ready"||e==="lost")&&this.cancelRetry(),e==="ready"&&(this.failures=0,this.notBefore=0),this.failure=n??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,n));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},re=class t extends Error{constructor(n,r){super(`auth ${n}: ${r}`);this.reason=n;this.name="AuthError";}reason;static isAuthError(n){if(n instanceof t)return true;let r=n;return r?.name==="AuthError"&&typeof r.reason=="string"}};function Ip(t){if(t instanceof re)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var de=class t extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof t)return true;let n=e;return n?.name==="TransportRefusal"&&n.retryable===false}},sr=["if-match","if-none-match"],Es=4096;function Cp(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let i=n.toLowerCase();if(!sr.includes(i)||r===void 0)continue;let o=typeof r=="string"?Mp(r):r;if(typeof o!="string"||o.length>Es||!Op(o))throw new de(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${Es} 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 Mp(t){let e=i=>i===32||i===9||i===10||i===13,n=0,r=t.length;for(;n<r&&e(t.charCodeAt(n));)n++;for(;r>n&&e(t.charCodeAt(r-1));)r--;return t.slice(n,r)}function Op(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n!==9&&(n<32||n===127||n>255))return false}return true}function Gp(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new de("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new de("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function Ts(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=Cp(i.headers),s=Gp(i),a=Object.freeze({...i,headers:o,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await t(a,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let u=await e.tokenSource.get(),c=await t(a,u);if(c.status===401)throw e.tokenSource.close("unavailable"),new re("unavailable","the server refused a freshly minted token");return c}}}function lr(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Lp(e))}function dr(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function Ui(t){return new TextDecoder().decode(dr(t))}function Lp(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var O=class extends Error{constructor(n,r,i,o,s){super(`${n} (${r}): ${i}`);this.reason=n;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},Ms=new WeakMap;function Os(t){return Ms.get(t)??{}}var Dp=new Set([408,429,500,502,503,504]),$p=6e4,Gs=new WeakMap;function Ls(t,e){Gs.set(t,e);}function Is(t){return t!==null&&(t.reason==="rate_limited"||t.retryAfterSeconds!==void 0)}function Fp(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new de(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(t)}. This is a configuration fault, not a server failure.`);return t}var Je=class{constructor(e){this.options=e;}options;async get(e,n){return this.send({method:"GET",path:e,signal:n},true)}async getWithEtag(e,n={}){let r=await this.sendRaw({method:"GET",path:e,...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{headers:{"if-none-match":n.ifNoneMatch}}},true),i=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...i}:{modified:true,body:r.body,...i}}async put(e,n,r,i={}){return this.send({method:"PUT",path:e,body:n,signal:r,...Yt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async post(e,n,r,i={}){return this.send({method:"POST",path:e,body:n,signal:r,...Yt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async postBytes(e,n,r,i={}){let o=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...Yt(i)},i.replaySafe===true,i.retryRateLimited!==false);return {bytes:qp(o.body),...o.invocationId===void 0?{}:{invocationId:o.invocationId}}}async patch(e,n,r,i={}){return this.send({method:"PATCH",path:e,body:n,signal:r,...Yt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...Yt(r)},r.replaySafe===true,r.retryRateLimited!==false)}async send(e,n,r=true){return (await this.sendRaw(e,n,r)).body}async sendRaw(e,n,r=true){let i=n?Fp(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw Cs(e.signal);let s=e.signal===void 0?void 0:Gs.get(e.signal);for(let a=0;a<i;a++){if(a>0){let u=this.backoffMs(a,o);if(Is(o)&&s!==void 0&&u>=s())throw o;await this.backoff(u,e.signal);}if(e.signal?.aborted)throw Is(o)&&s!==void 0&&s()<=0?o:Cs(e.signal);let l;try{l=await this.options.transport.request(e);}catch(u){if(re.isAuthError(u)||de.isRefusal(u)||e.signal?.aborted||Np(u))throw u;o=new O("unavailable",0,String(u));continue}if(l.status>=200&&l.status<300||l.status===304)return l;let d=jp(l);if(!Dp.has(l.status)||l.status===429&&!r)throw d;o=d;}throw o??new O("unavailable",0,"no attempt was made")}backoffMs(e,n){let r=n?.retryAfterSeconds,i=r!==void 0?r*1e3:2**(e-1)*250,o=2**(e-1)*250;return Math.min(Math.max(i,o),$p)}backoff(e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=this.options.clock,o=false,s=false,a,l=()=>{o||(o=true,s&&i.clearTimeout(a),n?.removeEventListener("abort",l),r());};n?.addEventListener("abort",l,{once:true}),a=i.setTimeout(l,e),s=true,o&&i.clearTimeout(a);})}};function qp(t){if(t instanceof Uint8Array)return t;if(t==null)return new Uint8Array(0);let e=typeof t=="string"?t:JSON.stringify(t);return new TextEncoder().encode(e)}function Yt(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function Cs(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Np(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function jp(t){let e=Up(t),n=Hp(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&Ms.set(e,r),e}var Bp=new Map([["insufficient_funds","insufficient_funds"]]);function Up(t){let{status:e,body:n}=t,r=Wp(n),i=t.retryAfterSeconds??Kp(n),o=Vp(n),s=o===void 0?void 0:Bp.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 Wp(t){if(typeof t=="string")return t;let e=t?.message;if(typeof e=="string")return e;let n=t?.error;if(typeof n=="string")return n;let r=n?.message;return typeof r=="string"?r:"no detail"}function Hp(t){let n=t?.error?.details;return n===null?void 0:n}function Vp(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Kp(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function k(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function Ds(t,e,n){let r=`/v1/inventory/transfers/${k(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function $s(t,e,n,r,i,o){let s=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}/add`;return t.client.post(s,i,o?.signal)}async function Fs(t,e,n){let r=`/v1/inventory/transfers/${k(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function qs(t,e,n){let r=`/v1/games/${k(t.gameId())}/matchmaking/tickets/${k(e)}`;return t.client.delete(r,n?.signal)}async function Ns(t,e,n,r,i,o){let s=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}/claim`;return t.client.post(s,i,o?.signal)}async function js(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function Bs(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Us(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Ws(t,e,n){let r=`/v1/games/${k(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function Hs(t,e,n,r,i){let o=`/v1/settings/${k(e)}/${k(n)}/${k(r)}`;return t.client.delete(o,i?.signal)}async function Vs(t,e,n,r,i){let o=`/v1/saves/${k(e)}/${k(n)}/${k(r)}`;return t.client.delete(o,i?.signal)}async function Ks(t,e,n,r){let i=`/v1/showcase/players/${k(e)}/${k(n)}`;return t.client.delete(i,r?.signal)}async function Js(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function zs(t,e,n,r,i,o){let s=`/v1/saves/${k(e)}/${k(n)}/${k(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function Xs(t,e,n){let r=`/v1/games/${k(t.gameId())}/avatars-3d/${k(e)}/owned`;return t.client.get(r,n?.signal)}async function Ys(t,e,n){let r=`/v1/games/${k(t.gameId())}/config/channels/${k(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Qs(t,e,n){let r=`/v1/characters/${k(e)}`;return t.client.get(r,n?.signal)}async function Zs(t,e,n){let r=`/v1/inventory/loot-tables/${k(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function el(t,e,n,r,i){let o=`/v1/settings/${k(e)}/${k(n)}/${k(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function tl(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${k(e)}/${k(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function nl(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/items/${k(r)}`;return t.client.get(o,i?.signal)}async function rl(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${k(e)}/${k(n)}/${k(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function il(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/orders/${k(r)}`;return t.client.get(o,i?.signal)}async function ol(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}`;return t.client.get(o,i?.signal)}async function al(t,e,n,r,i,o){let s=`/v1/inventory/${k(e)}/${k(n)}/catalogs/${k(r)}/recipes/${k(i)}/availability`;return t.client.get(s,o?.signal)}async function sl(t,e,n,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${k(e)}/${k(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Wi(t,e,n,r,i){let o=`/v1/saves/${k(e)}/${k(n)}/${k(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function ll(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${k(e)}/friends`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function dl(t,e,n){let r=`/v1/showcase/friends/${k(e)}`;return t.client.get(r,n?.signal)}async function cl(t,e){let n=`/v1/games/${k(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function ul(t,e,n){let r=`/v1/inbox/friend-challenges/${k(e)}`;return t.client.get(r,n?.signal)}async function ml(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${k(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function pl(t,e){let n=`/v1/games/${k(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function gl(t,e){let n=`/v1/games/${k(t.gameId())}/players/me/passes`;return t.client.get(n,e?.signal)}async function cr(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function fl(t,e,n){let r=`/v1/profiles/players/${k(e)}`;return t.client.get(r,n?.signal)}async function yl(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function hl(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${k(e)}`;return t.client.get(r,n?.signal)}async function bl(t,e,n,r){let i=`/v1/showcase/players/${k(e)}/${k(n)}`;return t.client.get(i,r?.signal)}async function vl(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function _l(t,e,n){let r=`/v1/inventory/transfers/${k(e)}`;return t.client.get(r,n?.signal)}async function wl(t,e,n){let r=`/v1/games/${k(t.gameId())}/matchmaking/tickets/${k(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function Sl(t,e,n){let r=`/v1/games/${k(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{...n?.keepalive===void 0?{}:{keepalive:n.keepalive},replaySafe:true,retryRateLimited:false})}async function Rl(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function kl(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/platform-funded-game-inventory-purchases`;return t.client.post(o,r,i?.signal)}async function Al(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function xl(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Pl(t,e){return t.client.get("/v1/characters",e?.signal)}async function El(t,e,n,r){let i=`/v1/settings/${k(e)}/${k(n)}`;return t.client.get(i,r?.signal)}async function Tl(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${k(e)}/${k(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Il(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${k(e)}/${k(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Cl(t,e){let n=new URLSearchParams;e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inbox/friend-challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Ml(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),i="/v1/friends"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Ol(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Gl(t,e,n){let r=`/v1/inbox/friend-challenges/${k(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function Ll(t,e,n,r){let i=`/v1/games/${k(t.gameId())}/matches/${k(e)}/end`;return t.client.post(i,n,r?.signal)}async function Dl(t,e,n,r,i,o){let s=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}/max`;return t.client.post(s,i,o?.signal)}async function $l(t,e,n,r,i,o){let s=`/v1/settings/${k(e)}/${k(n)}/${k(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Fl(t,e,n,r,i){let o=`/v1/showcase/players/${k(e)}/${k(n)}`;return t.client.put(o,r,i?.signal)}async function ql(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/rewarded-placements/${k(r)}/availability`;return t.client.get(o,i?.signal)}async function Nl(t,e,n){let r=`/v1/inventory/transfers/${k(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function jl(t,e,n,r){let i=`/v1/characters/${k(e)}`;return t.client.patch(i,n,r?.signal)}async function Bl(t,e,n,r,i,o){let s=`/v1/saves/${k(e)}/${k(n)}/${k(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function Ul(t,e,n,r,i,o){let s=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}/reset`;return t.client.post(s,i,o?.signal)}async function Wl(t,e,n){let r=`/v1/characters/${k(e)}`;return t.client.delete(r,n?.signal)}var j="gem-web-bridge",mr={min:1,max:1},Jp=65536,Hl=8,ur=5e3,Vl=1024;var Qt=Object.create(null),pr="__malformed";var Ki=Object.create(null),zp=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"],["gem.prefs.","audioChannels"],["gem.share.","shareRemap"]]);function gr(t){let e=Ki[t];if(e!==void 0)return e;for(let[n,r]of zp)if(t.startsWith(n))return r}function At(t){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(t);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function Xp(t){let e;try{e=new URL(t);}catch{return false}return e.username!==""||e.password!==""?false:e.protocol==="https:"?true:e.protocol==="http:"&&(e.hostname==="localhost"||e.hostname==="127.0.0.1")}function Yp(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function Qp(t){return /^[a-z_]+$/.test(t)}function Zp(t){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(t)&&!t.includes("--")}function Hi(t,e,n){if(e>Hl)return `nesting deeper than ${Hl}`;if(++n.nodes>ur)return `more than ${ur} values`;if(n.bytes>n.cap)return `over the ${n.cap} byte limit`;if(t==null)return n.bytes+=4,null;let r=typeof t;if(r==="boolean")return n.bytes+=5,null;if(r==="number")return n.bytes+=8,null;if(r==="string")return n.bytes+=t.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=t;if(n.seen.has(i))return "a repeated or cyclic object reference";if(n.seen.add(i),Array.isArray(t)){if(t.length>Vl)return `an array of ${t.length} entries, over the ${Vl} limit`;n.bytes+=2;for(let a of t){let l=Hi(a,e+1,n);if(l)return l}return null}let o=Object.getPrototypeOf(t);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";n.bytes+=2;let s=t;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++n.nodes>ur)return `more than ${ur} values`;if(n.bytes+=a.length*3+4,n.bytes>n.cap)return `over the ${n.cap} byte limit`;let l=Hi(s[a],e+1,n);if(l)return l}return null}function eg(t,e=Jp){let n={nodes:0,bytes:0,seen:new Set,cap:e},r=Hi(t,0,n);return r?`message contains ${r}`:n.bytes>e?`message is over the ${e} byte limit`:null}var tg={origin:[At,"not a well-formed origin"],url:[Xp,"not a safe absolute http(s) URL"],bcp47:[Yp,"not a well-formed BCP 47 tag"],code:[Qp,"not a code of lower-case letters and underscores"],gameRef:[Zp,"not a game id or web address"]};function Kl(t,e,n){for(let r of e){let i=n===""?r[0]:`${n}.${r[0]}`,o=t[r[0]];if(o==null){if(r[1]<"a")continue;return `${i}: required`}let s=Vi(o,r,i);if(s)return s}return null}function Vi(t,e,n){let r=e[1].toLowerCase();switch(r){case "u":return typeof t=="boolean"?null:Vi(t,typeof t=="string"?[e[0],"s",e[2]]:[e[0],"n",e[3],e[4]],n);case "s":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e[2])return `${n}: exceeds ${e[2]} characters`;if(e[3]){let[i,o]=tg[e[3]];if(!i(t))return `${n}: ${o}`}return null}case "n":case "i":return typeof t!="number"||!(r=="i"?Number.isInteger:Number.isFinite)(t)?`${n}: expected ${r=="i"?"integer":"number"}`:t<e[2]||t>e[3]?`${n}: out of range ${e[2]}..${e[3]}`:null;case "b":return typeof t=="boolean"?null:`${n}: expected boolean`;case "e":{let i=e[2];return i.includes(t)?null:`${n}: not one of ${i.join("|")}`}case "o":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:Kl(t,e[2],n);case "j":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "a":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e[2])return `${n}: exceeds ${e[2]} items`;let i=e[3],o=`${n}[]`;for(let s of t){if(s==null){if(i[1]<"a")continue;return `${o}: required`}let a=Vi(s,i,o);if(a)return a}return null}default:return `${n}: unknown kind ${String(r)}`}}var Jl=Object.create(null);function P(t,e,n,r,i){return Qt[t]=n,r&&(Ki[t]=r),Jl[t]=o=>{let s=eg(o,i);if(s)return s;if(typeof o!="object"||o===null||Array.isArray(o))return "message: expected object";let a=o;return a.gem!==j?"gem: wrong protocol marker":a.type!==t?`type: expected ${t}`:Kl(a,e,"")}}var Zt=["","s",64],V=["requestId","s",64],en=["matchId","s",64],Ne=["reason","S",64,"code"],ze=["outcome","e",["ok","declined","unavailable"]];P("gem.handshake",[["versions","o",[["min","i",1,1e3],["max","i",1,1e3]]],["capabilities","A",64,Zt],["embedder","s",2048,"origin"],["unbidden","B"]],30);P("gem.handshake.accept",[["v","i",1,1e3],["capabilities","A",64,Zt]],5);P("gem.token",[["token","s",4096],["requestId","S",64],["generation","i",0,2147483647],["apiBaseUrl","S",512,"url"],["playerId","s",64],["gameId","s",64],["channel","e",["dev","test","release"]],["gameVersion","S",64],["expiresAt","i",0,4102444800],["chainEndsAt","i",0,4102444800],["allowDevTools","B"]],30);P("gem.token.denied",[V,["retryable","b"],["retryAfterMs","I",0,36e5],["reason","e",["chain_exhausted","unavailable"]],["correlationId","s",64]],30);P("gem.player",[["untrusted","o",[["displayName","s",64],["displayTag","S",80],["displayHandle","s",80]]],["playerId","S",64],["discriminator","S",8],["avatarIconUrl","S",2048,"url"],["avatarIconId","S",64],["avatar3dId","S",64],["avatar3dModelUrl","S",2048,"url"],["avatar3dIconUrl","S",2048,"url"],["avatars3d","A",8,["","o",[["family","s",32],["id","s",64],["modelUrl","s",256,"url"],["iconUrl","s",256,"url"]]]],["badges","A",2,["","o",[["itemId","s",64],["iconUrl","s",2048,"url"]]]],["displayTag","s",8],["avatarUrl","S",2048,"url"],["boost","O",[["multipliers","a",8,["","o",[["currencyId","s",64],["currencySlug","s",32],["multiplierBp","i",1e4,1e6]]]],["expiresInDays","I",1,7]]]],12);P("gem.pause",[["paused","b"]],120);P("gem.prefs",[["reducedMotion","b"],["muted","b"],["showFrameStats","B"],["music","B"],["sounds","B"],["locale","s",35,"bcp47"],["recommended","O",[["volume","i",0,100],["batterySaver","b"],["keyboardLayout","e",["wasd","arrows"]],["gamepadConfirm","e",["south","east"]],["vibration","b"],["lookSensitivity","I",20,400],["gamepadLookSensitivity","I",20,400],["invertLookY","B"],["touchMovement","S",16,"code"],["graphicsQuality","S",16,"code"],["graphicsQualityAuto","B"],["colorHelp","B"]]]],60);P("gem.cohorts",[["cohorts","a",8,["","o",[["experimentId","s",36],["variantKey","s",32]]]]],12,"cohorts");P("gem.earnAllowanceChanged",[],30,"earnAllowance");P("gem.viewport",[["insets","o",[["top","i",0,4096],["right","i",0,4096],["bottom","i",0,4096],["left","i",0,4096]]],["reserved","A",4,["","o",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384],["control","O",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384]]]]]]],60,"viewport");P("gem.deviceSettings",[["settings","J"]],12,"deviceSettings");P("gem.willTerminate",[["reason","e",["grant_expiring","session_ended","navigating","kill_switch"]],["graceMs","i",0,6e4]],10);P("gem.roomEvent",[["event","e",["updated","match_started","match_ready","match_failed","version_stale"]],["roomId","s",64],["matchId","S",64],["version","I",0,2147483647],["reason","S",64],["platform","E",["universal","mobile"]]],120,"rooms");P("gem.socketState",[["connected","b"],["reason","E",["connecting","dropped","watchdog","terminal"]]],12,"socketState");P("gem.seatedEvent",[["roomId","s",64]],60,"partySeating");P("gem.autoStartFailedEvent",[["roomId","s",64],["code","s",64]],30,"autoStartFailure");P("gem.ticketEvent",[["event","e",["queued","matched","expired","cancelled","failed"]],["ticketId","s",64],["partySize","I",1,64],["queuedAt","I",0,4102444800],["expiresAt","I",0,4102444800],["reason","S",64],["roomId","S",64]],60,"ticketEvents");P("gem.signalEvent",[["event","e",["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]],en,["data","j"]],1800,"p2p");P("gem.relayDraining",[en,["clusterTargetId","s",64],["relayIps","a",16,Zt],["drainingSince","s",40],["deadline","s",40]],60,"p2pRelayDrain");P("gem.dedicatedEvent",[["event","e",["answer","error","matchEnded"]],en,["sdp","S",10240],["sessionId","S",64],["code","S",64],["message","S",256],["reason","S",64]],120,"dedicated");P("gem.partyResult",[V,["partyId","S",64]],30,"parties");P("gem.clusterTarget",[["clusterTargetId","s",64],["clusterTargetIds","A",3,Zt]],12,"clusterTarget");P("gem.graphicsRoutes",[["entries","a",32,["","o",[["gpu","s",32],["route","S",32],["host","S",32]]]]],12,"graphicsRoutes");P("gem.devtools",[["action","e",["open","close","toggle"]]],30,"devtools");P("gem.screenshot",[["maxWidth","i",1,7680],["maxHeight","i",1,4320]],6,"screenshot");P("gem.screenshot.denied",[["reason","e",["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]],["retryable","b"]],12,"screenshot");P("gem.requestContext",[],12,"feedbackContext");P("gem.gameContext",[["context","j"]],12,"feedbackContext");P("gem.signal",[["signal","e",["join","offer","answer","ice","migrationAck","hostUnreachable"]],en,["data","j"]],1200,"p2p");P("gem.dedicatedOffer",[en,["sdp","s",10240],["intent","e",["initial","ice_restart","full_reconnect"]]],60,"dedicated");P("gem.partyRequest",[V],12,"parties");P("gem.ready",[],5);P("gem.engaged",[],5,"engagement");P("gem.progress",[["loaded","i",0,1099511627776],["total","i",0,1099511627776]],600);P("gem.requestToken",[V,["reason","e",["initial","expiring","rejected"]]],12);P("gem.requestLocalServer",[V,["gameRoomId","s",64]],6,"localHost");P("gem.localServer",[V,["serverId","S",128]],30,"localHost");P("gem.localServer.denied",[V,["retryable","b"],["reason","e",["refused","unavailable"]]],30,"localHost");P("gem.exit",[["reason","S",64]],5);P("gem.openExternal",[["url","s",2048,"url"]],6);P("gem.requestFullscreen",[["enabled","b"]],30);P("gem.audioState",[["muted","b"]],120,"audioState");P("gem.rewardCue",[["currencySlug","s",32],["expected","I",1,1e9],["origin","O",[["x","i",0,16384],["y","i",0,16384]]]],60,"rewardCue");P("gem.walletDisplay",[["visible","b"],["currencies","A",8,Zt],["score","B"]],60,"walletDisplay");P("gem.controlsDeclare",[["uses","o",[["lookSensitivity","S",16,"code"],["gamepadLookSensitivity","S",16,"code"],["invertLookY","S",16,"code"],["touchMovement","S",16,"code"]]]],60,"controls");P("gem.menu",[["settings","b"],["items","A",4,["","o",[["id","s",32],["label","s",40]]]]],60,"gameMenu");P("gem.menuSelect",[["entry","e",["settings","item"]],["id","S",32]],60,"gameMenu");P("gem.gemCorner",[["corner","e",["top-left","top-right","bottom-left","bottom-right"]]],12,"gemCorner");P("gem.menuStyle",[["ground","S",7],["accent","S",7]],12,"menuStyle");P("gem.settingsDeclare",[["settings","a",8,["","o",[["id","s",40],["label","s",40],["kind","e",["toggle","slider","choice"]],["value","u",40,-1e6,1e6],["quick","B"],["icon","S",16,"code"],["min","N",-1e6,1e6],["max","N",-1e6,1e6],["step","N",0,1e6],["options","A",4,["","o",[["id","s",40],["label","s",40]]]]]]]],120,"gameSettings");P("gem.settingChange",[["id","s",40],["value","u",40,-1e6,1e6]],120,"gameSettings");P("gem.requestShare",[["requestId","S",64],["params","a",16,["","o",[["key","s",64],["value","s",512]]]]],6,"share");P("gem.shareResult",[V,["outcome","e",["accepted","refused"]],Ne,["key","S",64]],30,"shareResult");P("gem.requestAvatarPicker",[["tab","E",["2d","3d"]]],6,"avatarPicker");P("gem.vibrate",[["pattern","a",99,["","i",0,1e4]]],600,"vibration");P("gem.frameStats",[["fps","i",0,1e3],["frameTimeP95Ms","i",0,1e5],["counts","E",["pageFrames","gameDraws"]]],120,"frameStats");P("gem.portraitBorders",[["name","S",40]],60,"portraitBorders");P("gem.error",[["code","e",["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]],["message","S",256]],60);P("gem.requestPurchase",[V,["purchaseKind","e",["item","recipe"]],["targetId","s",64],["currencySlug","s",32],["quantity","I",1,10],["catalogId","S",64],["origin","E",["sheet","direct_refused"]]],12,"purchases");P("gem.requestAvatar3dPurchase",[V,["itemId","s",64],["currencySlug","s",32]],12,"avatar3dPurchases");P("gem.purchaseResult",[V,ze,Ne,["purchaseId","S",64]],30,"purchases");P("gem.purchaseSettled",[["purchaseKind","e",["item","recipe"]],["targetId","s",64],["catalogId","S",64],["quantity","i",1,10],["purchaseId","S",64]],30,"purchaseSettled");P("gem.deviceSettings.put",[V,["settings","j"]],30,"deviceSettings");P("gem.deviceSettings.result",[V,["outcome","e",["stored","too_large","unavailable"]]],30,"deviceSettings");P("gem.requestAd",[V,["placement","s",32],["format","e",["interstitial","rewarded"]]],6,"ads");P("gem.adResult",[V,["outcome","e",["shown","no_ad","unavailable"]]],12,"ads");P("gem.signalMoment",[V,["kind","e",["level_end","run_end","match_end","menu_return","other_break"]],["placement","S",32],["wall","B"]],6,"moments");P("gem.momentResult",[V,["shown","b"]],12,"moments");P("gem.requestSignIn",[V],6,"signIn");P("gem.signInResult",[V,["outcome","e",["signed_in","declined","unavailable"]]],12,"signIn");P("gem.requestFriendChallenge",[V,["playerId","s",64],["template","s",64],["params","J"]],12,"friendChallenges");P("gem.friendChallengeResult",[V,["outcome","e",["accepted","cancelled","refused","unavailable","rate_limited","invalid"]],["code","S",64],["param","S",64],["channel","S",16],["configVersion","I",0,9007199254740991],["retryAfterMs","I",0,864e5],["detail","S",300]],30,"friendChallenges");P("gem.requestAppLinks",[V],12,"appLinks");P("gem.appLinksResult",[V,ze,Ne,["arcade","O",[["store","e",["app_store","google_play"]]]],["game","O",[["store","e",["app_store","google_play"]]]]],30,"appLinks");P("gem.requestOpenApp",[V,["target","e",["arcade","game"]]],6,"appLinks");P("gem.openAppResult",[V,ze,Ne],30,"appLinks");var zl=P("gem.requestOpenGame",[V,["ref","s",40,"gameRef"]],6,"openGame");P("gem.openGameResult",[V,ze,Ne],30,"openGame");P("gem.requestSimilarGames",[V,["limit","I",1,24]],12,"openGame");P("gem.similarGamesResult",[V,ze,Ne,["games","a",24,["","o",[["gameId","s",36,"gameRef"],["slug","S",40,"gameRef"],["iconUrl","s",1024,"url"],["capsuleLandscapeUrl","s",1024,"url"],["capsulePortraitUrl","s",1024,"url"],["previewVideoUrl","S",1024,"url"],["previewPosterUrl","S",1024,"url"],["untrusted","o",[["name","s",64],["tagline","s",64],["shortDescription","s",320],["tags","a",10,["","s",32]]]]]]]],30,"openGame",524288);P("gem.requestStoreOffers",[V],12,"store");P("gem.storeOffersResult",[V,ze,Ne,["offers","a",32,["","o",[["skuId","s",64],["kind","e",["gem_pack","boost","pass","bundle"]],["name","s",80],["description","s",400],["imageUrl","S",1024,"url"],["priceDisplay","s",32],["grant","O",[["currency","s",32],["amount","i",1,1e9]]]]]]],30,"store",262144);P("gem.requestStorePurchase",[V,["skuId","s",64]],12,"store");P("gem.storePurchaseResult",[V,ze,Ne],30,"store");P("gem.storePurchaseSettled",[["skuId","s",64]],30,"store");P("gem.requestStoreOfferSheet",[V,["skuId","s",64]],12,"storeOfferSheet");P("gem.storeOfferSheetResult",[V,ze,Ne],30,"storeOfferSheet");var fr=Object.freeze(Jl);Qt.__malformed=60;Object.freeze(Qt);Object.freeze(Ki);var ce={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},tn=class{constructor(e=ce){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Qt[e];if(n===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??n,s=Math.max(0,r-i),a=Math.min(n,o+s*n/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function xt(t,e){return t.toLowerCase()===e.toLowerCase()}function Xe(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function yr(t,e){if(typeof e!="string"||e==="")return false;let n,r;try{n=new URL(t),r=new URL(e);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||n.username!==""||n.password!==""||n.pathname!=="/"||n.search!==""||n.hash!==""||n.port===""?false:Xe(n.hostname)&&Xe(r.hostname)}function Xl(t,e){if(e.min>e.max)return null;let n=Math.min(t.max,e.max),r=Math.max(t.min,e.min);return n>=r?n:null}var hr=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,n={}){let i=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,o=i.find(a=>a.currencyId===e),s;return !o&&this.resolveCurrencyId&&(s=await this.resolveCurrencyId(e).catch(()=>{}),s!==void 0&&(o=i.find(a=>a.currencyId===s))),{currencyId:o?o.currencyId:s??e,total:o?o.total:null,...o?.buckets===void 0?{}:{buckets:o.buckets}}}};function zi(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let i=r??{};typeof i.id!="string"||i.id===""||typeof i.threshold!="number"||!Number.isFinite(i.threshold)||n.push({id:i.id,threshold:i.threshold,points:typeof i.points=="number"?i.points:0,hidden:i.hidden===true,...typeof i.unlocked_at=="number"&&Number.isFinite(i.unlocked_at)?{unlockedAt:i.unlocked_at}:{},...i.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var Yl="inventory",Pt=t=>typeof t=="number"?t:0,nn=t=>typeof t=="string"?t:"";function Ji(t,e){let n=t??{},r=typeof n.next_cursor=="string"?n.next_cursor:void 0;return {data:Array.isArray(n.data)?n.data.map(e):[],...r===void 0?{}:{nextCursor:r}}}function Ql(t){let e=t??{};return {itemDefinitionId:nn(e.item_definition_id),instanceId:nn(e.instance_id),quantity:Pt(e.quantity),acquiredAt:Pt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function ng(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Ji(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(s=>{let a=s??{};return {bucket:nn(a.bucket),balance:Pt(a.balance)}}):void 0;return {currencyId:nn(i.currency_id),total:Pt(i.total),...o===void 0?{}:{buckets:o}}}),items:Ji(e.items,Ql),progressions:Ji(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:nn(i.progression_definition_id),currentValue:Pt(i.current_value),completionCount:Pt(i.completion_count),isCompleted:i.is_completed===true,...zi(i)}}),...n===void 0?{}:{etag:n}}}var br=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Yl}#buckets`:Yl;return this.cache.read(n,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,n){let r=await this.snapshot();if(r.items.nextCursor===void 0){let o=r.items.data.filter(s=>s.itemDefinitionId===e);if(o.length>0)return o}let i=await nl(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(i)?i.map(Ql):[]}page(e){return this.fetch(e)}refresh(){this.invalidate();}onChanged(e){return this.cache.onInvalidate(e)}invalidate(){this.cache.invalidate();}async fetch(e){let n=await tl(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 ng(n)}};var rg={unknown_currency:1,currency_not_in_game_payable:1,not_purchasable:1,no_price_in_currency:1,busy:1,cancelled:1,insufficient_funds:1,price_mismatch:1,config_version_stale:1,platform_currency_unavailable:1,not_available:1,recipe_locked:1,already_owned:1,guest_upgrade_required:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},ig=new Set(Object.keys(rg));function Zl(t){return typeof t=="string"&&ig.has(t)?t:"error"}var Ye=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var ie=t=>typeof t=="string"?t:"",og=t=>typeof t=="string"?t:ie(t&&typeof t=="object"?t.type:void 0),Le=t=>typeof t=="number"?t:0;function ag(t){let e=t??{};return {prerequisiteType:ie(e.prerequisite_type),referenceId:ie(e.reference_id),required:Le(e.required),current:Le(e.current)}}function rn(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:ie(e.order_id),status:ie(e.status),...n===void 0?{}:{etag:n}}}function vr(){return crypto.randomUUID()}var sg="recipe-usage",ed=100;function _r(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:ie(e.currency_id),bucket:ie(e.bucket),delta:Le(e.delta),balanceAfter:Le(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:ie(e.item_definition_id),instanceId:ie(e.instance_id),delta:Le(e.delta),quantityAfter:Le(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:ie(e.progression_definition_id),delta:Le(e.delta),valueAfter:Le(e.value_after),completed:e.completed===true};default:return {kind:"other",type:ie(e.type)}}}function lg(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:ie(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Le(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(_r):[]}}function dg(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(lg):void 0;return {orderId:ie(e.order_id),status:ie(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(_r):[],consumed:Array.isArray(e.consumed)?e.consumed.map(_r):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(_r):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function cg(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:ie(e.target_order_id)||ie(e.source_order_id),status:ie(e.status),purchaseId:ie(e.purchase_id),sourceOrderId:ie(e.source_order_id),price:{currencyId:ie(n.platform_currency_id),amount:Le(n.price)}}}function ug(t){let e=t??{},n=typeof e.last_used_at=="string"?e.last_used_at:void 0,r=typeof e.cooldown_expires_at=="string"?e.cooldown_expires_at:void 0;return {recipeId:ie(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...n===void 0?{}:{lastUsedAt:n},...r===void 0?{}:{cooldownExpiresAt:r}}}function td(t){switch(t.type){case "currency_grant":case "currency_consume":return {type:t.type,currency_id:t.currencyId,amount:t.amount};default:return {type:t.type,item_definition_id:t.itemDefinitionId,quantity:t.quantity}}}var wr=class{constructor(e,n,r,i){this.api=e;this.entity=n;this.cache=r;this.handOffRefused=i;}api;entity;cache;handOffRefused;async create(e,n={}){let r=await this.write(()=>Us(this.api,this.entity.type,this.entity.id,{operations:e.map(td),source:n.source??"play",nonce:vr()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return rn(r)}async createMany(e,n={}){return this.write(()=>Bs(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(td),nonce:vr()})),source:n.source??"play"},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}))}async recipeAvailability(e,n,r){let o=await al(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},s=typeof o.uses_remaining=="number"?o.uses_remaining:void 0,a=typeof o.cooldown_expires_at=="string"?o.cooldown_expires_at:void 0,l=Array.isArray(o.lock_reasons)?o.lock_reasons.map(ag):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>og(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(sg,[],async()=>{let n=await sl(this.api,this.entity.type,this.entity.id,{limit:ed})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(ug),truncated:r.length>=ed}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let c=e,g=await this.write(()=>Js(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:vr()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...dg(g)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,i]=await Promise.all([yl(this.api,n.signal===void 0?{}:{signal:n.signal}),cr(this.api,n.signal===void 0?{}:{signal:n.signal})]),o=e.payment.currencySlug.toLowerCase(),s=i.currencies.find(c=>c.currency_id.toLowerCase()===o||c.slug.toLowerCase()===o);if(s===void 0){let c=i.currencies.map(g=>g.slug);throw new Ye("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${c.length===0?"none":c.join(", ")}`)}let a=e.kind==="item"?r.items.find(c=>c.item_id===e.targetId):r.recipes.find(c=>c.recipe_id===e.targetId&&c.catalog_id===e.catalogId);if(a===void 0)throw new Ye("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=a.platform_prices.find(c=>c.platform_currency_id===s.currency_id);if(l===void 0){let c=p=>i.currencies.find(f=>f.currency_id===p)?.slug??p,g=a.platform_prices.map(p=>`${c(p.platform_currency_id)} ${p.price}`);throw new Ye("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.slug} price. It is priced in: ${g.length===0?"nothing":g.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Ye("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let u;try{u=await this.write(()=>kl(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:vr(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));}catch(c){if(this.handOffRefused!==void 0&&c instanceof O&&c.status===403&&c.code==="guest_upgrade_required")try{this.handOffRefused({kind:e.kind,targetId:e.targetId,...e.kind==="recipe"?{catalogId:e.catalogId}:{},currencySlug:s.slug,quantity:d});}catch{}throw c}return cg(u)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let i=await this.write(()=>$s(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return rn(i)}async maxProgression(e,n,r){let i=await this.write(()=>Dl(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return rn(i)}async claimProgression(e,n){let r=await this.write(()=>Ns(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return rn(r)}async resetProgression(e,n){let r=await this.write(()=>Ul(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return rn(r)}async write(e){return this.cache.invalidate(),e()}};var Xi=t=>typeof t=="string"?t:"",mg=t=>typeof t=="number"?t:0;function nd(t){let e=t??{};return {orderId:Xi(e.order_id),status:Xi(e.status),source:Xi(e.source),createdAt:mg(e.created_at)}}var Sr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await Tl(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(nd):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await il(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return nd(r)}};var pg=["live"],Yi=6e4,rd=864e5;function gg(t){let e=t?.passes;if(!Array.isArray(e))return Object.freeze([]);let n=e.flatMap(r=>{let i=r??{};if(typeof i.pass!="string"||i.pass==="")return [];let o=i.held===true,s=o&&typeof i.ends_at=="string"?i.ends_at:null;return [Object.freeze({pass:i.pass,held:o,endsAt:s})]});return Object.freeze(n)}function fg(t){let n=t.flatMap(r=>r.endsAt===null?[]:[Date.parse(r.endsAt)]).filter(r=>Number.isFinite(r));return n.length===0?null:Math.min(...n)}function id(t,e,n={}){let{watch:r}=n,i=new Set,o=null,s=0,a=null,l=Yi,d=()=>{a!==null&&r?.clock.clearTimeout(a.handle),a=null;},u=b=>{d(),!(r===void 0||i.size===0)&&(a={handle:r.clock.setTimeout(S,b)});},c=b=>{let R=fg(b);if(R===null||r===void 0){d();return}let h=R-r.clock.now();u(h>0?Math.min(h,rd):Yi);},g=b=>{r?.log?.(`[gem] a passes 'changed' listener threw: ${b instanceof Error?b.message:String(b)}`);},p=b=>{let R=o!==null&&JSON.stringify(o)!==JSON.stringify(b);if(o=b,l=Yi,c(b),!!R)for(let h of [...i])try{let _=h(b);typeof _?.then=="function"&&_.then(void 0,g);}catch(_){g(_);}},f=()=>{let b=s;return e.read("passes",pg,()=>gl(t)).then(R=>{if(b!==s)return f();let h=gg(R);return p(h),h})},y=()=>{f().catch(()=>{u(l),l=Math.min(l*2,rd);});};function S(){s+=1,e.invalidate(),d(),r!==void 0&&i.size>0&&y();}return {api:{list:f,async get(b){return (await f()).find(h=>h.pass===b)??Object.freeze({pass:b,held:false,endsAt:null})},on(b,R){let h=i.size===0;return i.add(R),h&&r!==void 0&&(o===null?y():c(o)),()=>{i.delete(R),i.size===0&&d();}}},recheck:S}}var od=t=>typeof t=="number"?t:0,yg=t=>typeof t=="string"?t:"";function hg(t){let e=t??{};return {progressionDefinitionId:yg(e.progression_definition_id),currentValue:od(e.current_value),completionCount:od(e.completion_count),isCompleted:e.is_completed===true,...zi(e)}}var Rr=class{constructor(e,n,r){this.api=e;this.entity=n;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,n){let i=(await this.inventory.snapshot()).progressions.data.find(o=>o.progressionDefinitionId===e);if(i&&i.achievementsUnavailable!==true)return i;try{let o=await ol(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return hg(o)}catch{return i??null}}};var on=class{constructor(e,n){this.clock=e;this.identity=n;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,n,r,i){this.rebind();let o=n.length===0,s=o?e:e+"\0"+n.join("\0"),a=this.slots.get(s);if(a){let c=a.filledAt;if(c!==void 0&&(i===void 0||this.clock.now()-c<=i))return Promise.resolve(a.value);if(a.inFlight)return a.inFlight}let l=a??{};this.slots.set(s,l);let d=this.generation,u=r().then(c=>(o&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===u&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=u,u}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function bg(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var vg=new Set(sr);function _g(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))vg.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function kr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return Ts(async(n,r)=>{let i;try{i=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new de("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let o;try{o=new URL(i.href.replace(/\/+$/,"")+n.path);}catch{throw new de(`${JSON.stringify(typeof n.path=="string"?bg(n.path):"(a non-string path)")} does not form a valid URL against ${i.protocol}//${i.host}. This is a malformed request, not a server failure.`)}if(o.protocol!==i.protocol||o.host!==i.host)throw new de(`${JSON.stringify(o.pathname)} resolves to ${o.protocol}//${o.host}, not ${i.protocol}//${i.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(o.username!==""||o.password!==""){let p=i.username!==""||i.password!=="",f=o.username!==i.username||o.password!==i.password,y=p?f?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new de(`the ${y} puts credentials in the URL, which cannot be fetched (${n.method} ${o.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[p,f]of Object.entries(t.defaultQuery??{}))o.searchParams.has(p)||o.searchParams.set(p,f);let s=n.bytes,a=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(s=JSON.stringify(n.body),a="application/json");}catch(p){throw new de(`the body of ${n.method} ${JSON.stringify(o.pathname)} could not be serialised to JSON: ${String(p)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(o.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},..._g(n.headers)},body:s,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let p=await l.text();if(p.length>0)try{d=JSON.parse(p);}catch{d=p;}}let u=l.headers.get("etag"),c=Qi(l.headers.get("retry-after")),g=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...u===null?{}:{etag:u},...c===void 0?{}:{retryAfterSeconds:c},...g===null||g===""?{}:{invocationId:g}}},t)}function Qi(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}function Zi(t){let e=i=>new RegExp(`<${i}>([^<]{0,300})</${i}>`).exec(t)?.[1]?.trim()||void 0,n=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(n.length>0)return n.join(" \u2014 ");let r=t.trim();return r?r.slice(0,300):""}async function Ar(t){try{let e=Zi(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var oe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},wg=3e4,Sg=5e3,ad=6e4,Rg=2**31-1,sd="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",kg=/^[A-Za-z0-9_]{1,64}$/;function je(t){let e=t.length===0?"a save key cannot be empty":t.length>64?`it is ${t.length} characters; a save key is at most 64`:t.startsWith("_")||t.startsWith("$")?`it begins with ${JSON.stringify(t[0])}, and \`_\` and \`$\` are reserved prefixes`:"a save key is ASCII letters, digits and underscores only \u2014 no hyphens, spaces or other punctuation, unlike a template slug";if(!kg.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function ld(t,e){let n=new AbortController,r=Date.now()+e;Ls(n.signal,()=>r-Date.now());let i=AbortSignal.timeout(e),o=()=>n.abort(i.reason),s=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(i.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",s,{once:true})),{signal:n.signal,release:()=>{i.removeEventListener("abort",o),t?.removeEventListener("abort",s);}}}function eo(t,e){return t.aborted&&e?.aborted!==true}var Ag=new Set(["x-ms-blob-type"]),xg=/^[ -~]+$/;function Pg(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(t)?"a list":typeof t}, which is not a set of headers.`);let n={};for(let[r,i]of Object.entries(t)){let o=r.toLowerCase();if(!Ag.has(o))throw new oe("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"||!xg.test(i))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(o in n)throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);n[o]=i;}return n}function to(t){let e=typeof t.metadata=="object"&&t.metadata!==null&&!Array.isArray(t.metadata)?t.metadata:void 0;return {key:t.key,sizeBytes:t.size_bytes,etag:t.etag,...e===void 0?{}:{metadata:e},createdAt:t.created_at,updatedAt:t.updated_at}}function no(t){return t?.reason==="not_found"}function Eg(t){return t?.code==="save_conflict"}function dd(t){return t instanceof O&&t.reason==="rate_limited"}async function cd(t,e){let n=await Ar(e);return new O("rate_limited",429,`the save ${t} answered 429: too many save calls. ${n}`.trim(),Qi(e.headers.get("retry-after")))}function xr(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Tg(t,e,n,r,i){let o=false,s=()=>o?false:(o=true,a.detach?.(),true),a={signal:n.signal,budget:r,deadlineAt:Date.now()+r,teardown:n.teardown===true,overwrite:n.overwrite===true,identity:i,resolve:l=>{s()&&t(l);},reject:l=>{s()&&e(l);},detach:void 0};return a}function ud(t,e){return t!==null&&e!==null&&e!==t}function md(t){return new oe("save_conflict",`save ${JSON.stringify(t)} was not written: the signed-in player changed while it waited for the write before it, and it holds the last player's progress.`)}var Pr=class{constructor(e,n,r={},i){this.api=e;this.entity=n;this.options=r;this.identity=i;}api;entity;options;identity;versions=new Map;seq=0;versionsOf=null;writes=new Map;holdUntil=0;async put(e,n,r={}){let i;try{i=JSON.stringify(n);}catch(o){throw new oe("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 oe("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(i),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){if(je(e),r.signal?.aborted)throw xr(r.signal);let i=this.budget(r.timeoutMs),o=this.slotWrites(e);return new Promise((s,a)=>{let l=o.queued;l?.release();let d=l?.waiters[l.waiters.length-1];d!==void 0&&this.holdOwn(o,d);let u=this.identity?.()??null;for(let c of l?.waiters.slice()??[])ud(c.identity,u)&&this.drop(o,c,md(e));o.queued=this.queue(o,n,r,Tg(s,a,r,i,u),l?.waiters??[]),o.wake?.(),this.pump(e,o);})}holdOwn(e,n){let{signal:r}=n,i=n.deadlineAt-Date.now();if(r?.aborted)return this.drop(e,n,xr(r));if(i<=0)return this.drop(e,n,this.timeout("save",n.budget));let o=AbortSignal.timeout(i),s=()=>this.drop(e,n,this.timeout("save",n.budget)),a=()=>{r&&this.drop(e,n,xr(r));};o.addEventListener("abort",s,{once:true}),r?.addEventListener("abort",a,{once:true}),n.detach=()=>{o.removeEventListener("abort",s),r?.removeEventListener("abort",a);};}drop(e,n,r){let i=e.queued?.waiters,o=i?.indexOf(n)??-1;o>=0&&i?.splice(o,1),n.reject(r),e.wake?.();}queue(e,n,r,i,o){let{budget:s}=i,a=[...o,i],l=AbortSignal.timeout(s),d=p=>{if(e.queued===g){this.take(e,g);for(let f of a)f.reject(p);e.wake?.();}},u=()=>d(this.timeout("save",s)),c=()=>{r.signal&&d(xr(r.signal));};l.addEventListener("abort",u,{once:true}),r.signal?.addEventListener("abort",c,{once:true});let g={bytes:n,options:r,budget:s,deadlineAt:i.deadlineAt,identity:i.identity,waiters:a,release:()=>{l.removeEventListener("abort",u),r.signal?.removeEventListener("abort",c);}};return g}async pump(e,n){if(!n.running){n.running=true;try{for(let r=n.queued;r!==void 0;r=n.queued){let i=Date.now(),o=this.holdUntil-i;if(o>0){if(o>=r.deadlineAt-i){this.take(n,r);for(let l of r.waiters)l.reject(this.held(e,o));continue}for(let l of r.waiters.slice(0,-1))o>=l.deadlineAt-i&&this.drop(n,l,this.held(e,o));}let s=Math.max(o,this.spacing(n,r,i));if(s>0){await this.pause(n,s);continue}this.take(n,r);let a;try{a=this.precondition(e,r);}catch(l){for(let d of r.waiters)d.reject(l);continue}n.lastSentAt=i;try{let l=await this.send(e,r,a);for(let d of r.waiters)d.resolve(l);}catch(l){for(let d of r.waiters)d.reject(l);}}}finally{n.running=false;}}}spacing(e,n,r){if(e.lastSentAt===void 0||n.waiters.some(s=>s.teardown))return 0;let i=this.options.minWriteIntervalMs??Sg,o=Math.min(...n.waiters.map(s=>s.deadlineAt-s.budget/2));return Math.min(e.lastSentAt+i,o)-r}pause(e,n){return new Promise(r=>{let i=()=>{clearTimeout(o),e.wake===i&&(e.wake=void 0),r();},o=setTimeout(i,Math.min(n,Rg));e.wake=i;})}take(e,n){e.queued===n&&(e.queued=void 0),n.release();}slotWrites(e){let n=this.writes.get(e);return n===void 0&&(n={running:false,queued:void 0,lastSentAt:void 0,wake:void 0},this.writes.set(e,n)),n}noteRateLimit(e){if(!dd(e))return;let n=e.retryAfterSeconds,r=n===void 0?ad:Math.min(n*1e3,ad);this.holdUntil=Math.max(this.holdUntil,Date.now()+r);}held(e,n){let r=Math.ceil(n/1e3);return new O("rate_limited",429,`save ${JSON.stringify(e)} was not sent: the platform refused a save call for the rate, and the wait it asked for ends in ${r}s, after this call's timeoutMs. Keep the state and write once the wait is over.`,r)}async send(e,n,r){let{bytes:i,options:o,budget:s}=n,a=o.contentType??"application/octet-stream",l=ld(o.signal,Math.max(0,n.deadlineAt-Date.now()));try{let d=await Bl(this.api,this.entity.type,this.entity.id,e,{size_bytes:i.byteLength,content_type:a,...r,...o.metadata===void 0?{}:{metadata:o.metadata}},{signal:l.signal});if(typeof d.upload_url!="string"||typeof d.session_id!="string")throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let u=Pg(d.upload_headers,e),c,g=this.options.fetch??globalThis.fetch.bind(globalThis);try{c=await g(d.upload_url,{method:"PUT",headers:{"content-type":a,...u},body:i,credentials:"omit",signal:l.signal});}catch(f){throw eo(l.signal,o.signal)?this.timeout("upload",s):new oe("upload_failed",`${sd} for PUT. Underlying error: ${f}`)}if(c.status===429)throw await cd("upload",c);if(!c.ok){let f=await Ar(c);throw new oe("upload_failed",c.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+f:`the save upload answered ${c.status}. `+(c.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+f)}let p=to(await zs(this.api,this.entity.type,this.entity.id,e,{session_id:d.session_id},{signal:l.signal}));return this.remember(e,p.etag?{kind:"etag",etag:p.etag}:void 0),p}catch(d){throw Eg(d)?new oe("save_conflict",`save ${JSON.stringify(e)} was not written: the stored save changed since this game last loaded or wrote it, so another device or tab saved in between. Load it again and decide what to write from what is stored, rather than resending this write.`):(this.noteRateLimit(d),this.rethrow(d,o.signal,l.signal,"save",s))}finally{l.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(i){throw new oe("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${i}`)}}async getBytes(e,n={}){je(e);let r=this.budget(n.timeoutMs),i=ld(n.signal,r),o=this.seq;try{let s;try{let u=await Wi(this.api,this.entity.type,this.entity.id,e,{signal:i.signal});if(!u.modified)return this.remember(e,{kind:"empty"},o),null;s=u.body;}catch(u){if(no(u))return this.remember(e,{kind:"empty"},o),null;throw u}if(typeof s.download_url!="string")throw new oe("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),l;try{l=await a(s.download_url,{credentials:"omit",signal:i.signal});}catch(u){throw eo(i.signal,n.signal)?this.timeout("download",r):new oe("download_failed",`${sd} for GET. Underlying error: ${u}`)}if(l.status===429)throw await cd("download",l);if(!l.ok){let u=await Ar(l);throw new oe("download_failed",`the save download answered ${l.status}. `+(l.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+u)}let d=new Uint8Array(await l.arrayBuffer());return this.remember(e,s.etag?{kind:"etag",etag:s.etag}:void 0,o),d}catch(s){throw this.slots().get(e)===void 0&&this.remember(e,{kind:"failed"}),this.noteRateLimit(s),this.rethrow(s,n.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,n={}){try{let r=await Wi(this.api,this.entity.type,this.entity.id,je(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?to(r.body):null}catch(r){if(no(r))return null;throw r}}async list(e={}){let n=await Il(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}}),r=n.next_cursor;return {saves:(n.data??[]).map(to),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await Vs(this.api,this.entity.type,this.entity.id,je(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!no(r))throw r}this.remember(e,{kind:"empty"});}precondition(e,n){if(ud(n.identity,this.identity?.()??null))throw md(e);if(n.waiters.some(i=>i.overwrite))return {};let r=this.slots().get(e);if(r===void 0)return {};if(r.kind==="etag")return {if_match:r.etag};if(r.kind==="empty")return {if_none_match:"*"};throw new oe("load_failed",`save ${JSON.stringify(e)} was not written: the last load of this slot failed, so what this write would replace is unknown, and it could be the player's real progress. Load it again before saving, or pass overwrite: true if replacing whatever is stored is what you mean.`)}remember(e,n,r){let i=this.slots(),o=i.get(e);r!==void 0&&o!==void 0&&o.kind!=="failed"&&o.seq>r||(this.seq+=1,n===void 0?i.delete(e):i.set(e,{...n,seq:this.seq}));}slots(){let e=this.identity?.()??null;return e!==null&&e!==this.versionsOf&&(this.versionsOf!==null&&this.versions.clear(),this.versionsOf=e),this.versions}budget(e){return e??this.options.timeoutMs??wg}timeout(e,n){return new oe("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,i,o){return e instanceof oe||dd(e)?e:eo(r,n)?this.timeout(i,o):e}};function Ig(t){try{return Ui(t)}catch{return t}}function ro(t,e){let n=t??{},r=typeof n.etag=="string"?n.etag:e;return {key:typeof n.key=="string"?n.key:"",value:typeof n.value=="string"?Ig(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var Er=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await El(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>ro(i)):[]}async get(e,n={}){try{let r=await el(this.api,this.entity.type,this.entity.id,e,{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?ro(r.body,r.etag):null}catch(r){if(pd(r))return null;throw r}}async put(e,n,r={}){let i=await $l(this.api,this.entity.type,this.entity.id,e,{value:lr(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return ro(i)}async delete(e,n){try{await Hs(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!pd(r))throw r}}};function pd(t){return t?.reason==="not_found"}function io(t,e,n={}){let r=new on(ce,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let i=new br(t,e,r);return {settings:new Er(t,e),inventory:i,saves:new Pr(t,e,n.saves??{},n.identity),currencies:new hr(i,n.resolveCurrencyId),mutations:new wr(t,e,r,n.handOffRefusedPurchase),orders:new Sr(t,e),progressions:new Rr(t,e,i)}}function gd(t,e,n={}){let r=new on(ce,n.identity),i=id(t,r,n);return {scope:{...io(t,e,n),passes:i.api},recheckPasses:i.recheck}}var oo={type:"players",id:"me"};var at=t=>typeof t=="string"?t:"",Et=t=>typeof t=="number"?t:0;function Tr(t,e){let n=e??{},r=at(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:at(n.player_id),gameId:at(n.game_id),channel:at(n.channel)||"release",name:at(n.name),slotIndex:Et(n.slot_index),isActive:n.is_active!==false,createdAt:at(n.created_at),updatedAt:at(n.updated_at)}}var Ir=class{constructor(e,n,r,i){this.api=e;this.saves=n;this.identity=r;this.resolveCurrencyId=i;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let n=this.scopes.get(e);return n||(n=io(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,n)),n};async list(e){let r=(await Pl(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>Tr(this.scope,i)):[]}async get(e,n){let r=await Qs(this.api,e,n===void 0?{}:{signal:n});return Tr(this.scope,r)}async create(e){let n=await js(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Tr(this.scope,n)}async update(e,n,r){let i=await jl(this.api,e,{name:n},r===void 0?{}:{signal:r});return Tr(this.scope,i)}async delete(e,n){await Wl(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await vl(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:Et(r?.total_slots),availableSlots:Et(r?.available_slots),activeCharacterCount:Et(r?.active_character_count),defaultMaxSlots:Et(r?.default_max_slots),purchasedExtraSlots:Et(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var hd="[gem: use gem.text.toPlain()]",fd=new Set,yd;function Cg(t){try{if(fd.has(t))return;let e=globalThis.location;if(yd??=!!e?.port&&Xe(e.hostname??""),!yd)return;fd.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${hd}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
|
|
2
|
-
${new Error().stack}`);}catch{}}var ve=class{#e;#n;constructor(e,n="player text"){this.#e=e,this.#n=n,Object.freeze(this);}toString(){return Cg(this.#n),hd}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function he(t,e){return new ve(t,e)}var st={toPlain(t){return ve.unwrap(t)},compare(t,e,n){let r=t instanceof ve?ve.unwrap(t):t,i=e instanceof ve?ve.unwrap(e):e;if(typeof Intl>"u"||typeof Intl.Collator!="function")return r<i?-1:r>i?1:0;let o;try{o=new Intl.Collator(n);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(t,e){let n=t instanceof ve?ve.unwrap(t):t,r=e instanceof ve?ve.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var Tt=t=>typeof t=="string"?t:"";function Cr(t){let e=t??{},n=typeof e.message=="string"&&e.message.length>0?e.message:void 0,r=typeof e.resolved_at=="string"?e.resolved_at:void 0;return {id:Tt(e.transfer_id),status:Tt(e.status),sourceEntityId:Tt(e.source_entity_id),targetEntityId:Tt(e.target_entity_id),...n===void 0?{}:{message:he(n,"transfer.message")},createdAt:Tt(e.created_at),expiresAt:Tt(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Mg(){return crypto.randomUUID()}var Mr=class{constructor(e,n,r){this.api=e;this.self=n;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let n=await Rl(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:Mg()},e.signal===void 0?{}:{signal:e.signal});return Cr(n)}async list(e={}){let r=await Ol(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(Cr):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await _l(this.api,e,n===void 0?{}:{signal:n});return Cr(r)}async accept(e,n){return this.resolve(()=>Ds(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>Nl(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>Fs(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Cr(await e())}};var Og=t=>typeof t=="string"?t:"",Gg=t=>typeof t=="string"&&t?t:void 0,Lg=t=>typeof t=="number"?t:void 0;function bd(t){let e=new Map(t.map(r=>[r.id,r])),n=new Map(t.filter(r=>r.slug).map(r=>[r.slug,r]));return r=>e.get(r)??n.get(r)??null}function Dg(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new pe("config_malformed",`the config document is ${t===null?"null":typeof t}, expected a JSON object`);let e=t,n=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new pe("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Lg(e.version);if(r===void 0)throw new pe("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let i=(l,d,u)=>{let c=Og(l.id);if(!c)throw new pe("config_malformed",`${d}[${u}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return c},o=n("items");o.forEach((l,d)=>i(l??{},"items",d));let s=n("currencies");s.forEach((l,d)=>i(l??{},"currencies",d));let a=t;return {...a,version:r,hash:typeof a.hash=="string"?a.hash:"",items:o,currencies:s,catalogs:n("catalogs"),loot_tables:n("loot_tables"),affix_pools:n("affix_pools"),progressions:n("progressions"),game_room_templates:n("game_room_templates"),kv:typeof a.kv=="object"&&a.kv!==null&&!Array.isArray(a.kv)?a.kv:{},item:bd(o),currency:bd(s)}}var pe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},vd=10*1024*1024,_d=15e3,wd=new Set(["dev","test","release"]);function $g(t){if(!wd.has(t))throw new pe("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...wd].join(", ")}. gem-api would reject the assignment read.`);return t}var Or=t=>typeof t=="number"?t:0,ao=t=>typeof t=="string"?t:"";function Fg(t){let e=t??{},n=Array.isArray(e.entries)?e.entries.map(r=>{let i=r??{},o=typeof i.rarity_tier=="string"?i.rarity_tier:void 0;return {entryId:ao(i.entry_id),weight:Or(i.weight),dropRate:Or(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:ao(e.loot_table_id),name:ao(e.name),rollCount:Or(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Or(e.total_weight),entries:n}}var Gr=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=void 0;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded!==void 0)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,n=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===n&&(this.inFlight=null);});return this.inFlight=n,n}refresh(){this.loaded=void 0,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new pe("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 Zs(this.api,e,n===void 0?{}:{signal:n});return Fg(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??_d),n;try{let l=await Ys(this.api,$g(this.channel()),{signal:e});if(!l.modified)throw new pe("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof pe)throw l;if(l?.reason==="not_found")return null;throw l}let r=Gg(n.config_url);if(r===void 0)return null;let i=this.options.fetch??globalThis.fetch.bind(globalThis),o;try{o=await i(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new pe("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??_d}ms`):new pe("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=>Zi(d)).catch(()=>"");throw new pe("config_unreachable",`the config document answered ${o.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await o.text();if(s.length>vd)throw new pe("config_too_large",`the config document is ${s.length} bytes, over the ${vd} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new pe("config_malformed",`config document is not JSON: ${String(l)}`)}return Dg(a)}};var Sd=400,De=t=>typeof t=="string"?t:"",qg=/(?:Z|[+-]\d{2}:?\d{2})$/i;function lt(t){let e=De(t);if(!qg.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Ng=/^[0-9a-f]{1,64}$/,jg=/^[0-9a-f]{16}$/,Bg=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Ug=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function so(t){let e=De(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,i,o]=[Number(n[1]),Number(n[2]),Number(n[3])],s=new Date(Date.UTC(r,i-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===i-1&&s.getUTCDate()===o?e:void 0}var Wg=4096,Hg=new TextEncoder;function Vg(t){let e=De(t.challenge_data),n=De(t.challenge_data_hash);return e===""||!jg.test(n)?{}:Hg.encode(e).length>Wg?{}:{data:e,dataHash:n}}function Kg(t){let e=t??{},n=lt(e.period_start_at),r=lt(e.period_ends_at);if(n===0||r===0)return;let i=De(e.slug),o=De(e.seed),s=so(e.period_local_date),a=De(e.boundary),l=De(e.reset_time);return {id:De(e.progression_definition_id),...i===""?{}:{slug:i},window:De(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:Bg.test(a)?a:"",resetTime:Ug.test(l)?l:"",seed:Ng.test(o)?o:"",...Vg(e)}}function It(t){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(t)}`)}function Lr(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Kg).filter(n=>n!==void 0):[]}var an=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;It(n);let r=await xl(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return Lr(r)}};function $e(t){return typeof t=="string"&&t!==""?t:void 0}var Rd=new Set(["localhost","127.0.0.1","[::1]"]);function dt(t){return Ct(t)}function Ct(t){let e=$e(t);if(e===void 0)return;let n;try{n=new URL(e);}catch{return}if(!(n.username!==""||n.password!=="")&&(n.protocol==="https:"||n.protocol==="http:"&&Rd.has(n.hostname)))return e}var Jg=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,zg=/^[a-z][a-z0-9_]{0,31}$/;function Xg(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let i=r??{},o=$e(i.family),s=$e(i.avatar_3d_id),a=dt(i.model_url),l=dt(i.icon_url);o===void 0||!zg.test(o)||n.has(o)||s===void 0||!Jg.test(s)||a===void 0||l===void 0||(n.add(o),e.push({family:o,id:s,modelUrl:a,iconUrl:l}));}return e}function Yg(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},i=$e(r.item_id),o=dt(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function Ee(t){let e=t??{},n=$e(e.player_id),r=$e(e.display_name),i=$e(e.discriminator),o=$e(e.display_tag),s=$e(e.avatar_icon_id),a=dt(e.avatar_icon_url),l=$e(e.avatar_3d_id),d=dt(e.avatar_3d_model_url),u=dt(e.avatar_3d_icon_url),c=Xg(e.avatars_3d);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:he(r,"displayName")},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:he(o,"displayTag")},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...u===void 0?{}:{avatar3dIconUrl:u},...c===void 0?{}:{avatars3d:c},badges:Yg(e.badges)}}var Qg=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function lo(t){if(t===void 0)return;let e=dt(t);if(e===void 0)return;let n=new URL(e);return Rd.has(n.hostname)||Qg.has(n.origin)?e:void 0}var kd=100,Pd=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function co(t){let{periodsBack:e,period:n,playerId:r}=t;if(It(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!Pd.test(n)))throw new TypeError(`period must be a period id such as 2026-10-02 (a result's period.id), got ${String(n)}`);if(r!==void 0&&(typeof r!="string"||r===""))throw new TypeError("playerId must be a player id");return {...e===void 0?{}:{periods_back:e},...n===void 0?{}:{period:n},...r===void 0?{}:{player_id:r}}}function Ed(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!Pd.test(e))return;let n=so(t.period_local_date),r=lt(t.period_start_at),i=lt(t.period_ends_at),o=r>0&&i>0;return {id:e,...n===void 0?{}:{localDate:n},...o?{startAt:r,endsAt:i}:{},opensAt:lt(t.opens_at),closesAt:lt(t.closes_at),final:t.final===true}}var sn=t=>typeof t=="string"?t:"",Mt=t=>typeof t=="number"?t:0,ln=t=>typeof t=="string"?t:void 0,Zg=t=>typeof t=="number"?t:void 0,Td={player:"players",character:"characters"};function ef(t,e){let n=t??{},r=ln(n.entity_id),i=typeof n.entity_type=="string"&&Object.hasOwn(Td,n.entity_type)?n.entity_type:void 0,o=Id(n.stats),s=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,a=e?n.is_viewer===true:void 0;return {...Ee(n),rank:Mt(n.rank),occurredAt:Mt(n.occurred_at),...a===void 0?{}:{isViewer:a},...r===void 0?{}:{entityId:r},...i===void 0?{}:{entityType:i},...o===void 0?{}:{stats:o},...s===void 0?{}:{properties:s}}}function Ad(t,e){let n=t??{},r=ln(n.bucket_1),i=ln(n.bucket_2),o=Zg(n.update_frequency_seconds),s=Ed(n);return {leaderboardType:sn(n.leaderboard_type),runType:sn(n.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(n.entries)?n.entries.map(a=>ef(a,e)):[],generatedAt:Mt(n.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...s===void 0?{}:{period:s}}}function xd(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=Id(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:Mt(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function Id(t){if(t===null||typeof t!="object")return;let e={};for(let[n,r]of Object.entries(t))typeof r=="number"&&(e[n]=r);return e}function tf(t,e,n){let r=t??{},i=ln(r.bucket_1),o=ln(r.bucket_2),s=Ed(r);return {leaderboardType:sn(r.leaderboard_type),runType:sn(r.run_type),entityType:e,entityId:n,...i===void 0?{}:{bucket1:i},...o===void 0?{}:{bucket2:o},entries:Array.isArray(r.entries)?r.entries.map(xd).filter(a=>a!==void 0):[],personalBest:xd(r.personal_best)??null,totalRuns:Mt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:Mt(r.generated_at),...s===void 0?{}:{period:s}}}var dn=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=co(n),i=await ml(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Ad(i,false)}async friends(e,n={}){let r=co(n),i=await ll(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Ad(i,true)}async mine(e,n={}){return this.#n(e,"player","me",n)}async character(e,n,r={}){return this.#n(e,"character",n,r)}async#n(e,n,r,i){if(i.limit!==void 0){let{limit:l}=i;if(!Number.isInteger(l)||l<1||l>kd)throw new TypeError(`limit must be an integer between 1 and ${kd}, got ${String(l)}`)}let o=co(i),s=await rl(this.#e,e,Td[n],r,{...o,...i.bucket1===void 0?{}:{bucket_1:i.bucket1},...i.bucket2===void 0?{}:{bucket_2:i.bucket2},...i.limit===void 0?{}:{limit:i.limit},...i.signal===void 0?{}:{signal:i.signal}}),a=n==="player"&&r==="me"&&sn((s??{}).entity_id)||r;return tf(s,n,a)}};var Dr=t=>typeof t=="string"?t:"",uo=t=>typeof t=="number"?t:0;function Cd(t){let e=t??{};return {playerId:Dr(e.player_id),key:Dr(e.key),value:e.value,updatedAt:uo(e.updated_at)}}function nf(t){let e=t??{};return {...Ee(e),playerId:Dr(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:uo(e.updated_at)}}function rf(t){return t?.reason==="not_found"}var cn=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let i=await dl(this.api,je(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:Dr(i.key),entries:Array.isArray(i.entries)?i.entries.map(nf):[],generatedAt:uo(i.generated_at)}}async of(e,n,r={}){try{return Cd(await bl(this.api,e,je(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(rf(i))return null;throw i}}async set(e,n,r={}){if(je(e),n===void 0)throw new TypeError(`showcase value for ${JSON.stringify(e)} is undefined, which is not JSON. Use clear() to remove one.`);try{JSON.stringify(n);}catch(o){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}.`,{cause:o})}let i=await this.selfPlayerId();return Cd(await Fl(this.api,i,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await Ks(this.api,r,je(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var of="gemChallenge",Md=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Od(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(of)??void 0}catch{return}}var ct=class extends O{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,i]of Object.entries(n))i!==void 0&&Object.assign(this,{[r]:i});}},$r=t=>typeof t=="string"?t:void 0;function Gd(t){let e=t??{};return {...Ee(e),playerId:$r(e.player_id)??""}}function Ld(t){let e=t.has_more===true?$r(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function af(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(Gd):[],...Ld(e)}}var mo=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function sf(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"||typeof e[1]=="number"&&Number.isFinite(e[1])))}function Dd(t){let e=t??{},n=mo(e.opened_at),r=mo(e.answered_at);return {id:$r(e.item_id)??"",from:Gd(e.sender),template:$r(e.template)??"",params:sf(e.params),createdAt:mo(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function lf(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(Dd):[],...Ld(e)}}function df(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var un=class{#e;#n;#o;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#o=n.launchedChallengeId;}async list(e={}){let n=await Ml(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return af(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let n=await Cl(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return lf(n)}async launchedChallenge(e={}){let n=this.#o;if(n===void 0||!Md.test(n))return null;try{return Dd(await ul(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(df(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!Md.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 Gl(this.#e,e);}};var cf=0;function ge(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++cf)}-${String(Date.now())}-${t}`}}var uf=12e4,$d=8,mf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,pf=/^[a-z0-9][a-z0-9_-]{0,63}$/;function mn(t,e,n={}){return new ct(new O("invalid",400,e,void 0,t),n)}function gf(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function ff(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!mf.test(e))return {error:mn("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!pf.test(n))return {error:mn("unknown_template","template must be a friend_challenge_templates key from this game's config")};if(r===void 0)return {playerId:e,template:n,params:void 0};if(!gf(r))return {error:mn("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:mn("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return o.length>$d?{error:mn("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String($d)}`)}:{playerId:e,template:n,params:i}}function yf(t){switch(t.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:t.outcome}};case "rate_limited":{let e=t.retryAfterMs,n=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new ct(new O("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new ct(new O("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function hf(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function Fd(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=ff(n);if("error"in r)return Promise.reject(r.error);let i=`challenge-${ge()}`;return new Promise((o,s)=>{let a={},l=u=>{e.delete(i)&&(t.clock.clearTimeout(a.timer),"error"in u?s(u.error):o(u.outcome));};e.set(i,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??uf);let d=false;try{d=t.bridge.requestFriendChallenge(i,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(n){let r=e.get(n.requestId);if(r===void 0){t.onDropped?.(`gem.friendChallengeResult (${hf(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(yf(n));}}}var Fr=t=>typeof t=="string"?t:void 0;function bf(t){let e=t??{},n=Fr(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Fr(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var qr=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await cr(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=bf(o);s!==void 0&&i.push(s);}return i}},po=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function vf(t){let e=t??{},n=Fr(e.currency_id);if(n===void 0||n==="")return;let r=po(e.limit),i=Math.min(po(e.earned),r),o=Math.min(po(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:Fr(e.currency_slug)??"",currencyId:n,limit:r,earned:i,remaining:o,period:e.period==="day"?"day":"window",periodDays:a,...d===void 0?{}:{resetsAt:d}}}function qd(t){let e=new Set,n=r=>{t?.(`[gem] an earnAllowance 'changed' listener threw: ${r instanceof Error?r.message:String(r)}`);};return {on(r){return e.add(r),()=>{e.delete(r);}},emit(){for(let r of [...e])try{let i=r();typeof i?.then=="function"&&i.then(void 0,n);}catch(i){n(i);}}}}var Nr=class{#e;#n;#o;constructor(e,n,r){this.#e=e,this.#n=n,this.#o=r;}async get(e={}){let r=(await pl(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=vf(o);s!==void 0&&i.push(s);}return i}on(e,n){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(n)??(()=>{})}},pn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new qr(e),this.earnAllowance=new Nr(e,n,r);}};var go=t=>typeof t=="string"?t:"",Nd=t=>typeof t=="number"?t:0;function _f(t){let e=t??{};return {key:go(e.key),visibility:go(e.visibility),value:e.value,updatedAt:Nd(e.updated_at)}}function wf(t){let e=t??{};return {...Ee(e),playerId:go(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(_f):[],generatedAt:Nd(e.generated_at)}}function Sf(t){return t?.reason==="not_found"}var gn=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return wf(await fl(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(Sf(r))return null;throw r}}};var Rf=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]]),fn=class extends O{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:Rf.get(this.code))??super.retryable}},Qe=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=kf(e),i;try{i=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(o){throw o instanceof O?xf(o):o}return Af(i)}};function kf(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let e;try{e=JSON.stringify(t);}catch(n){throw new de(`the function input could not be serialised to JSON: ${String(n)}. Pass bytes, or a value JSON can carry. This is a bug in the call, not a server failure.`)}if(e===void 0)throw new de(`the function input is ${typeof t}, which JSON cannot carry. Pass bytes \u2014 an empty Uint8Array for no input \u2014 or a JSON value. This is a bug in the call, not a server failure.`);return new TextEncoder().encode(e)}function Af(t){let{bytes:e}=t,n=()=>new TextDecoder("utf-8",{fatal:true}).decode(e);return {bytes:e,...t.invocationId===void 0?{}:{invocationId:t.invocationId},text:n,json:()=>JSON.parse(n())}}function xf(t){let{details:e,invocationId:n}=Os(t),i=e?.untrusted?.message,o=e?.reason;return new fn(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof i=="string"?{functionMessage:i}:{},...t.code==="function_failed"&&typeof o=="string"?{failure:o}:{}})}function jr(t,e){let n=e?.retryAfterSeconds,r=typeof n=="number"&&Number.isFinite(n)&&n>0?n*1e3:0,i=1e4*2**Math.min(Math.max(0,t-1),16);return Math.min(Math.max(r,i),3e5)}var Pf=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost","gem_graphics_context_lost"],fo="gem_";function yo(t){return t.startsWith(fo)}function Ef(t){let e=2166136261;for(let n of new TextEncoder().encode(t))e^=n,e=Math.imul(e,16777619);return e>>>0}function Tf(t){let e=t;return e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^=e>>>16,e>>>0}function Br(t,e,n){if(ho(t,n),typeof e!="string"||e==="")throw new TypeError("[gem] experiment: playerId must be a non-empty string");let r=typeof n=="number"?n:n.length,i=Tf(Ef(`${t}:${e}`))%r;return typeof n=="number"?i:n[i]}function ho(t,e){if(typeof t!="string"||t==="")throw new TypeError("[gem] experiment: key must be a non-empty string");if(typeof e=="number"){if(!Number.isInteger(e)||e<1||e>2048)throw new RangeError(`[gem] experiment '${t}': the count must be an integer from 1 to 2048; got ${String(e)}`);return}if(!Array.isArray(e))throw new TypeError(`[gem] experiment '${t}': pass a count or a list of strings; got ${typeof e}`);let n=e;if(n.length<1||n.length>2048)throw new RangeError(`[gem] experiment '${t}': the list must hold 1 to 2048 strings; got ${n.length}`);if(!n.every(r=>typeof r=="string"))throw new TypeError(`[gem] experiment '${t}': every option must be a string`)}var jd=1e4,Bd=50,If=500,Cf=65536-4*1024,Mf=24*1024;function Ud(t){let e={},n={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=i:typeof i=="number"&&Number.isFinite(i)&&(n[r]=i);return {dimensions:e,measures:n}}var Of=6e4;function Gf(t){let e=new Map;for(let n of t??[]){let r=new Set;for(let[i,o]of Object.entries(n.dimensions??{})){let s=o?.range;typeof s=="object"&&s!==null&&r.add(i);}r.size>0&&e.set(n.id,r);}return e}function Lf(t,e){if(e===void 0)return t;let n=null,r={};for(let[i,o]of Object.entries(t.measures))e.has(i)?(n??={...t.dimensions})[i]=String(o):r[i]=o;return n===null?t:{dimensions:n,measures:r}}var Wd=t=>typeof t=="number"?t:0,Df=t=>typeof t=="string"?t:"";function Ur(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function $f(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:Wd(o.index),code:Df(o.code)}}):[];return {accepted:Wd(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function bo(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.floor(Math.random()*16);return (e==="x"?n:n&3|8).toString(16)})}function Ff(t){return t?.retryable===true}var yn=class{#e;#n;#o;#h;#t=[];#b={};#a=0;#s=null;#v=false;#_=false;#m=0;#w=0;#S=0;#r=false;#R=null;#l=null;#c=false;#i=false;#p=false;#k=false;#A=false;#g=void 0;#x=false;#P=0;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#o=Math.max(jd,e.options?.flushIntervalMs??jd),this.#h=Math.max(1,Math.floor(e.options?.maxQueue??If));}track(e,n={}){if(!this.#n||this.#r)return;if(yo(e)){this.#A||(this.#A=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.#E(e,Ud({...this.#b,...n}));let r=this.#C();this.#g===void 0&&!this.#x&&r!==null&&r!==""&&(this.#x=true,this.#M());}setContext(e){this.#b={...this.#b,...e};}async experiment(e,n){ho(e,n);let r=this.#e.awaitPlayerId===void 0?this.#e.playerId():await this.#e.awaitPlayerId();if(r===null)throw new Error(`[gem] experiment '${e}': no player to select for \u2014 this call was not made by a player.`);return typeof n=="number"?Br(e,r,n):Br(e,r,n)}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#i)return Ur();let n=this.#C();if(n===null||n==="")return this.#t.length>0&&!this.#k&&(this.#k=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.")),Ur();let r=e.keepalive===true;if(!r&&this.#e.declarations!==void 0&&this.#t.some(d=>!yo(d.name))&&await this.#M(),this.#I(),this.#t.length===0||this.#m>0&&!r)return Ur();this.#u();let i=this.#t.splice(0,this.#G(r)),o=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:bo(),sent_at_ms:s,events:i.map(d=>Hd(d,s,this.#g?.get(d.name)))},l={client:this.#e.client(),gameId:()=>n};this.#m+=1;try{let d=await Sl(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),u=$f(d,o);return this.#w=0,this.#S=0,this.#L(u),u}catch(d){throw Ff(d)?(this.#O(i,o),this.#w+=1,this.#S=this.#e.clock.now()+jr(this.#w,d)):this.#y(`[gem] analytics: ${i.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#m-=1,this.#t.length>0&&this.#d();}}trackPlatform(e,n={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#E(e,Ud(n));}hold(){this.#r||this.#l!==null||(this.#i=true,this.#u());}release(){if(!this.#i||this.#r)return;this.#i=false;let e=this.#e.clock.now(),n=this.#t.map(r=>({...r,atMs:e}));this.#t=n,this.#p&&(this.#p=false,this.#l=e,this.#c=false,this.#t.unshift({uid:bo(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=Bd?this.#f():this.#t.length>0&&this.#d();}get held(){return this.#i}startSession(){if(!(this.#r||this.#l!==null)){if(this.#i){this.#p=true;return}this.#l=this.#e.clock.now(),this.#c=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#c)return;if(this.#c=true,this.#i){this.#p=false,this.#t=[],this.#a=0;return}let n=this.#l;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#f({keepalive:true});}setPaused(e){this.#r||e===this.#v||(this.#v=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#d());}setHidden(e){this.#r||e===this.#_||(this.#_=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}#E(e,n){let{dimensions:r,measures:i}=n;for(this.#I();this.#t.length>=this.#h;)this.#t.shift(),this.#a+=1;this.#t.push({uid:bo(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#t.length>=Bd?this.#f():this.#d();}#f(e={}){if(e.keepalive!==true&&this.#T()>0){this.#d();return}this.flush(e).catch(()=>{});}#T(){return Math.max(0,this.#S-this.#e.clock.now())}#O(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#h;)this.#t.shift(),this.#a+=1;}#G(e){let n=e?Mf:Cf,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(Hd(s,0,this.#g?.get(s.name))).length+1,i>n)return Math.max(1,o)}return r}#d(){this.#s!==null||this.#v||this.#_||this.#i||this.#r||this.#m>0||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#f();},Math.max(this.#o,this.#T())));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#I(){let e=this.#D();e===null||e===""||(this.#R!==null&&this.#R!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#c=false),this.#R=e);}#L(e){for(let n of e.rejected)this.#y(`[gem] analytics: an event was refused (${n.code}). `+qf(n.code));}#y(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#C(){try{return this.#e.gameId()}catch{return null}}#D(){try{return this.#e.playerId()}catch{return null}}async#M(){let e=this.#e.declarations;if(e!==void 0&&!(this.#e.clock.now()<this.#P))try{this.#g=Gf(await e());}catch{this.#P=this.#e.clock.now()+Of;}}};function Hd(t,e,n){let{dimensions:r,measures:i}=Lf(t,n);return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:r,measures:i}}function qf(t){switch(t){case "analytics_not_declared":return "This channel has no analytics_events section at all \u2014 promote a game config that declares one. The gem_* events in the same batch were still recorded.";case "unknown_event":return "This channel declares a set of events and this name is not in it \u2014 check the spelling, or declare it in analytics_events.";case "unknown_dimension":return "A string property on this event is not declared as one of its dimensions.";case "missing_dimension":return "A dimension this event declares was not supplied.";case "dimension_value_not_declared":return "A dimension value is outside the closed set the config declares for it.";case "unknown_measure":return "A numeric property on this event is not declared as one of its measures.";case "measure_wrong_type":return "A measure was the wrong shape \u2014 an int measure refuses a fractional value.";case "source_not_permitted":return "This event is declared for the server only, so a client may not emit it.";default:return "See the analytics_events section of your game config."}}function Se(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function Te(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=Se(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Nf=2e3,jf=5e3;function Kd(t){let e=[],n=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let s,a=new Promise(l=>{let d=false,u=null;s=c=>{d||(d=true,r=null,t.clock.clearTimeout(u),l(c));},u=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??Nf);});return r={promise:a,settle:s},a};return {resolveList:o,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(s=>s[0])},refresh(s){return !Vd(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=u=>{i.delete(d)&&(t.clock.clearTimeout(l),a(u));};i.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??jf);})},accept(s,a){let l=Te(a),d=Se(s),u=l.length>0?l:d===void 0?[]:[d];if(u.length!==0){e=u,r?.settle(u);for(let[c,g]of [...i])Vd(u,g)||c(u);}}}}function Vd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Bf=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),A=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="DedicatedServerError",this.retryable=Bf.has(n),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var Jd=["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"],Uf=new Set(Jd);function Ze(t){return typeof t=="string"&&Uf.has(t)?t:"unknown"}var Wr="webrtc_dedicated",So=["universal","mobile","web"];var Wf="p2p_unavailable",Hf="capacity_unavailable",Vf=2,zd=3e4,Xd=1e3,Yd=2e4;async function Ro(t){let e=Se(t.clusterTargetId),n=t.nextClusterTarget,r=0,i=t.clock??ce,o=t.retry??{},s=o.budgetMs??zd,a=o.maxDelayMs??Yd,l=o.initialDelayMs??Xd,d=i.now(),u=d+s,c=0;for(;;){c++;try{let g=await Po(t.signal,"while allocating",()=>t.client.post(`${ec(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:g.match_id,status:g.status}}catch(g){if(!Kf(g)||s<=0)throw g;if(g.status===503&&g.code===Wf)throw new A("p2p_unavailable",`room ${t.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${g.message}`,{cause:g});if(r=g.code===Hf?r+1:0,n!==void 0&&r>=Vf){let b=n;n=void 0;let R=Se(await b());R!==void 0&&(e=R,r=0);}let p=Math.min(a,l*2**(c-1)),f=Math.min(a,(g.retryAfterSeconds??0)*1e3),S=Math.max(p/2,f)+Math.random()*(p/2);if(i.now()+S>u)throw Jf(t,g,c,i.now()-d,s);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-d,budgetMs:s,nextAttemptInMs:S,status:g.status,message:g.message}),await Hr(i,S,t.signal),t.signal?.aborted)throw wo("while waiting to allocate")}}}function Kf(t){return t instanceof O?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function Jf(t,e,n,r,i){let o=`${n} attempt${n===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new A("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${o}: ${e.message}`,{cause:e}):new A("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${o}: ${e.message}`,{cause:e})}var zf=12e4,Xf=1e3;async function ko(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??Xf,i=t.timeoutMs??zf,o=e.now()+i,s=Qd(t),a={seen:t.knownToExist===true};for(;;){let l=await Zd(t,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new A("timeout",`match ${n} was still ${l.status} after ${i}ms`);await Hr(e,r,t.signal);}}async function Ao(t){return (await Zd(t,Qd(t),{seen:t.knownToExist===true})).outcome}function Qd(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${ec(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function Zd(t,e,n){let{matchId:r}=t,i=t.clock.now(),o;try{o=await Po(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(s){if(s instanceof O&&s.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(n.seen=true,o.status==="ready")return {status:"ready",outcome:Yf(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Ze(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function xo(t){let e=await Po(t.signal,"while listing cluster targets",()=>t.client.get("/v1/ping/targets",t.signal)),n=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||n.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return n}async function Po(t,e,n){if(t?.aborted)throw wo(e);try{return await n()}catch(r){throw t?.aborted?wo(e,r):r}}function wo(t,e){return new A("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function Yf(t,e,n){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:t,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:n+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function ec(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Hr(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{t.clearTimeout(o),n?.removeEventListener("abort",i),r();},o=t.setTimeout(i,e);n?.addEventListener("abort",i);})}function tc(t){return typeof t=="string"&&t.trim()!==""}function Vr(t,e){return tc(t)?t.trim():tc(e)?e:null}var Kr="0.1.0-beta",nc="0-beta",Ot="web",Qf=/^(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 Zf(t){let e=Qf.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function rc(t,e){let n=ey(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:Kr};let i=Zf(r);if(i===null)throw new A("misconfigured",`${e} refused: engineVersion '${r}' is not semver, so no engine line can be derived from it and gem-api answers 400. Omit it \u2014 a browser game has no engine version of its own, and the SDK reports '${Kr}' for it.`);if(i!==nc)throw new A("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${nc}' 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 '${Kr}' for it.`);return {...t,platform:n,engineVersion:r}}function ey(t,e){if(t===void 0||t===Ot)return Ot;if(!So.includes(t))throw new A("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${So.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${Ot}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${Ot}' 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.`),Ot}function hn(t){let e=t??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let n=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:ic(e.queued_at),expiresAt:ic(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function ic(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var ty=3,oc=1e3,Jr=class{constructor(e){this.options=e;this.snapshot=e.first;let n=new Promise((o,s)=>{this.resolve=o,this.reject=s;});n.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:n,cancel:()=>(this.requestCancel(),n)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let n=e?oc:Math.max(oc,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},n);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,n=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){n=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(n);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof O&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<ty){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let n=e instanceof O&&e.code==="matchmaking_unavailable";this.settle({status:n?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let n=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:n});}catch(n){this.busy=false,this.fail(n);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};var ny="gemPlayWith",ry=/^[A-Za-z0-9_-]{16,128}$/;function ac(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(ny);}catch{return}return e!==null&&ry.test(e)?e:void 0}function sc(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var iy="join",oy="welcome",ay="rejected",lc=25e3,sy=1e3,Eo=1;function To(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var ly={credential_expired:"credential_expired",credential_reused:"credential_reused",credential_timeout:"timeout",join_rate_limited:"join_rate_limited",expected_join:"join_refused",invalid_credential:"join_refused",credential_not_for_this_channel:"join_refused"};function Io(t){let e=typeof t=="string"?t:"unknown";return new A(ly[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function bn(t){let{channel:e,clock:n}=t;return new Promise((r,i)=>{let o=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??lc),a=n.setTimeout(()=>y(new A("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(s,sy)),l=S=>{let b=S.data;if(typeof b!="string"){c(b);return}let R;try{R=JSON.parse(b);}catch{c(b);return}if(o){c(b);return}if(R.t===oy){let h=To(R.heartbeat_interval);f({...typeof R.player_id=="string"?{playerId:R.player_id}:{},...typeof R.match_id=="string"?{matchId:R.match_id}:{},...h===void 0?{}:{heartbeatIntervalMs:h}});return}if(R.t===ay){y(Io(R.reason));return}c(b);},d=()=>{y(new A("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},u=()=>{y(new A("aborted","the caller aborted during the join exchange"));},c=S=>{o&&t.onMessage?.(S);},g=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",u);},p=()=>{e.removeEventListener("message",l);},f=S=>{o=true,g(),t.onMessage===void 0&&p(),r({welcome:S,detach:p});},y=S=>{o||(o=true,g(),p(),i(S));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){u();return}t.signal?.addEventListener("abort",u);try{e.send(JSON.stringify({t:iy,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:Eo}:{}}));}catch(S){y(new A("connection_failed",`the join frame could not be sent on the open channel: ${String(S)}`,{cause:S}));}})}var ut=1,vn=2,Co=4,Go=8,dy=2,cy=1e3,Lo="heartbeat timeout",_n="gem-uu",zr=2,cc="gem_transports";function Gt(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!uy(r)||e.includes(r)||e.push(r);}return e}function uy(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function wn(t,e){if(typeof t!="object"||t===null)return null;let n=t[cc];if(typeof n!="object"||n===null)return null;let r=n;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function Xr(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var uc=new TextEncoder,mc=new TextDecoder;function Do(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function $o(t){let e=0;return t?.reliable===false&&(e|=ut),t?.ordered===false&&(e|=vn),e}function Fo(t){return {reliable:(t&ut)===0,ordered:(t&vn)===0}}var qo={reliable:true,ordered:true};function pc(t){return JSON.stringify({t:"join",credential:t,wire:zr,heartbeat:Eo})}function gc(t){let e;try{e=JSON.parse(t);}catch{throw new A("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=To(e.heartbeat_interval);return {...e.player_id===void 0?{}:{playerId:e.player_id},...e.match_id===void 0?{}:{matchId:e.match_id},...n===void 0?{}:{heartbeatIntervalMs:n}}}throw e.t==="rejected"?Io(e.reason):new A("join_refused","the server answered the join out of protocol")}function Yr(){return typeof globalThis.WebTransport=="function"&&No===null}function Qr(){return No}var No=null;var dc="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function my(t){let e=dr(t);if(e.byteLength!==32)throw new A("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var Mo=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new A("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let s=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function Oo(t,e){let n=new Uint8Array(5+e.byteLength);return new DataView(n.buffer).setUint32(0,e.byteLength+1,true),n[4]=t,n.set(e,5),n}async function Sn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new A("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new a(t.url):new a(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:my(t.certHashBase64)}]});}let r=n,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(No=dc,i(new A("connection_failed",`${dc}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new A("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([a.read(),s]);if(a.releaseLock(),l.done||l.value===void 0)return i(new A("connection_failed","the session ended before the control stream arrived"));let d=l.value,u=d.writable.getWriter();await u.write(Oo(Co,uc.encode(pc(t.credential))));let c=new Mo,g=d.readable.getReader(),p;for(;p===void 0;){let f=await Promise.race([g.read(),s]);if(f.done||f.value===void 0)return i(new A("connection_failed","the control stream closed before the join was answered"));for(let y of c.push(f.value)){p=gc(mc.decode(y.payload));break}}return {link:py(r,u,g,c,t.log??(f=>console.warn(f)),yc(p,t.clock)),welcome:p}}catch(a){return i(a)}}function py(t,e,n,r,i,o){let s,a,l=false,d=f=>{if(!l){l=true,u.stop();try{t.close();}catch{}a?.(f);}},u=Bo(o,()=>d(Lo)),c=(f,y)=>{u.heard(),(f&Go)===0&&s!==void 0&&((f&Co)!==0?s(mc.decode(y),qo):s(y,Fo(f)));};(async()=>{try{for(;;){let f=await n.read();if(f.done||f.value===void 0)break;for(let y of r.push(f.value))c(y.flags,y.payload);}}catch{}d("stream closed");})();let g,p;try{let f=t.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let y=f.readable.getReader();p=f.writable.getWriter(),g=f,(async()=>{try{for(;;){let S=await y.read();if(S.done||S.value===void 0)break;let b=S.value;b.byteLength!==0&&c((b[0]??0)|ut|vn,b.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(f){g=void 0,p=void 0,i(`[gem] webtransport datagram lane unusable (${Xr(f)}); unreliable sends ride the stream`);}return t.closed.then(f=>d(fc(f?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(f,y){if(l)return;if(typeof f=="string"){e.write(Oo(Co,uc.encode(f))).catch(()=>d("write failed"));return}let S=$o(y);if((S&ut)!==0&&p!==void 0){let b=Do(S,f),R=g?.maxDatagramSize;if(R===void 0||b.byteLength<=R){p.write(b).catch(()=>{});return}}e.write(Oo(S,f)).catch(()=>d("write failed"));},onMessage(f){s=f;},onClose(f){a=f;},close(){d("closed");}}}function jo(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new A("connection_failed","this environment has no WebSocket"));n=new i(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new A("timeout","websocket did not come up in time")));},e),l=p=>{s||(s=true,clearTimeout(a),r.close(),o(p));},d=()=>{r.send(pc(t.credential));},u=p=>{if(s)return;if(typeof p.data!="string"){l(new A("join_refused","the server sent binary before answering the join"));return}let f;try{f=gc(p.data);}catch(y){l(y);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",u),r.removeEventListener("close",c),r.removeEventListener("error",g),i({link:gy(r,yc(f,t.clock)),welcome:f});},c=()=>{l(new A("connection_failed","the websocket closed before the join was answered"));},g=()=>{l(new A("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",u),r.addEventListener("close",c),r.addEventListener("error",g),r.readyState===1&&d();})}function fc(t){return typeof t=="string"&&t.length>0?t:void 0}function yc(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function Bo(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,cy)*dy,i=n.now(),o=null,s=()=>{o=null;let a=n.now()-i;if(a>=r){e();return}o=n.setTimeout(s,r-a);};return o=n.setTimeout(s,r),{heard:()=>{i=n.now();},stop:()=>{o!==null&&(n.clearTimeout(o),o=null);}}}function gy(t,e){let n,r,i=false,o=a=>{if(!i){i=true,s.stop();try{t.close();}catch{}r?.(a);}},s=Bo(e,()=>o(Lo));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,qo);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Go)===0&&n?.(l.slice(1),Fo(d));})),t.addEventListener("close",(a=>o(fc(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!i){if(typeof a=="string"){t.send(a);return}t.send(Do($o(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){o("closed");}}}function Uo(t,e,n,r){let i,o,s=false,a=n,l=c=>{if(!s){s=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}o?.(c);}},d=Bo(r,()=>l(Lo)),u=(c,g)=>{if(d.heard(),typeof c=="string"){i?.(c,qo);return}let p=new Uint8Array(c);if(p.byteLength===0)return;let f=p[0]??0;(f&Go)===0&&i?.(p.slice(1),Fo(f|g));};if(t.addEventListener("message",(c=>u(c.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),a!==void 0){let c=a;c.addEventListener("message",(g=>u(g.data,ut|vn))),c.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(c,g){if(s)return;if(typeof c=="string"){t.send(c);return}let p=$o(g),f=Do(p,c);if((p&ut)!==0&&a!==void 0&&a.readyState==="open"){a.send(f);return}t.send(f);},onMessage(c){i=c;},onClose(c){o=c;},close(){l("closed");}}}function hc(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let i=Wo(r);i!==void 0&&(e[n]=i);}return e}function bc(t){if(Array.isArray(t))return t.map(fy).filter(e=>!!e)}function Wo(t){if(Ho(t)||Array.isArray(t)&&t.every(Ho))return t}function Ho(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function fy(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Wo(e.fixed),r=Wo(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...n===void 0?{}:{fixed:n},...r===void 0?{}:{default:r},...Lt("description",yy(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Ho)?{allowed:e.allowed}:{},...Lt("min",Rn(e.min)),...Lt("max",Rn(e.max)),...Lt("minItems",Rn(e.min_items)),...Lt("maxItems",Rn(e.max_items)),...Lt("maxLength",Rn(e.max_length))}}function yy(t){return typeof t=="string"&&t.length>0?t:void 0}function Rn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Lt(t,e){return e===void 0?{}:{[t]:e}}function Be(t){let e=t??{},n=Y(e.id)??Y(e.game_room_id);if(n===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(hy):[];return {id:n,gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Fe(e.max_players)??0,memberCount:Fe(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...Ae("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...Ae("roomArgs",hc(e.room_args)),...Ae("roomArgsTemplate",bc(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",...Ae("region",Y(e.region)),...Ae("clusterTargetId",Y(e.cluster_target_id)),selfHosted:e.self_hosted===true,...Ae("matchId",Y(e.match_id)),version:Fe(e.version)??0,...Ae("templateId",Y(e.template_id)),...Ae("templateSlug",Y(e.template_slug)),roomType:Y(e.game_room_type)??"Standard",...Ae("transports",Gt(e.transports)??void 0),createdAt:Fe(e.created_at)??0,updatedAt:Fe(e.updated_at)??0,...Ae("startedAt",Fe(e.started_at))}}function hy(t){let e=t??{};return {...Ee(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:Fe(e.joined_at)??0,...Ae("groupId",Y(e.group_id)),...Ae("platform",Y(e.platform))}}function Vo(t){let e=t??{};return {id:Y(e.id)??Y(e.game_room_id)??"",gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Fe(e.max_players)??0,memberCount:Fe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Y(e.game_channel)??"release",roomType:Y(e.game_room_type)??"Standard",createdAt:Fe(e.created_at)??0}}function Y(t){return typeof t=="string"&&t.length>0?t:void 0}function Fe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ae(t,e){return e===void 0?{}:{[t]:e}}var Zr=class{constructor(e){this.options=e;}options;list(e){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.templateSlug&&n.set("template_slug",e.templateSlug),e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor&&n.set("cursor",e.cursor);let r=n.size>0?`?${n.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(Vo),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(n=>({rooms:(n.game_rooms??[]).map(Vo)}))}create(e,n,r){return vy(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},...kn(n)},e.signal).then(Be)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Be)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...kn(r)},n.signal).then(Be)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...kn(r)},n.signal).then(Be)}quickJoin(e,n,r=[]){return Ko(this.options,e,n,r).then(i=>i.room)}createTicket(e,n,r=[]){return Ws(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},...kn(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(hn)}heartbeatTicket(e){return wl(this.generated(),e).then(hn)}cancelTicket(e,n=false){return n?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(hn):qs(this.generated(),e).then(hn)}leave(e,n,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:n},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return _c(this.options,e)}close(e,n){return this.options.client.delete(this.roomV1(e),n).then(()=>{})}update(e,n){return this.options.client.patch(this.roomV2(e),{...n.name===void 0?{}:{name:n.name},...n.maxPlayers===void 0?{}:{max_players:n.maxPlayers},...n.isPublic===void 0?{}:{is_public:n.isPublic},...n.settings===void 0?{}:{settings:n.settings},...n.roomArgs===void 0?{}:{room_args:n.roomArgs}},n.signal).then(Be)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Be)}kick(e,n,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(n)}`,{},r).then(()=>this.get(e,r))}transferHost(e,n,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(n)}`,{},r).then(Be)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return vc(this.options)}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function vc(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function _c(t,e){return e===void 0&&t.selfHosted?.()===true}function Ko(t,e,n,r=[],i){let o=_c(t,e.partyId);return t.client.post(`${vc(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...by(e.templateSlugs,o),...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...o?{self_hosted:true}:{},...i===void 0?{}:{play_with_ticket:i},...kn(n)},e.signal).then(s=>({room:Be(s),playWith:i===void 0?null:sc(s)}))}function by(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function kn(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function vy(t){t!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${t}) is deprecated and was not sent. A room's seats come from the room template published in your game config \u2014 name one with templateSlug \u2014 and a room created without a template seats 8. To change a room that already exists, call update({ maxPlayers }) as its host.`);}var ei=class{listeners=new Map;retainedMatch=null;on(e,n){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(n),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===i&&n(i);});}return ()=>this.off(e,n)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...i)=>{r(),n(...i);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};var ti=class{constructor(e){this.options=e;let n=e.first,r=new Promise(a=>{this.resolve=a;}),i=()=>this.status;this.ticket={id:n.ticketId,get status(){return i()},partySize:n.partySize??0,queuedAt:n.queuedAt??0,expiresAt:n.expiresAt??0,outcome:r};let o=n.queuedAt!==void 0&&n.expiresAt!==void 0?(n.expiresAt-n.queuedAt)*1e3:9e5,s=Math.min(Math.max(o,0),9e5)+5e3;this.timer=e.clock.setTimeout(()=>{this.timer=null,this.end({status:"lost"});},s);}options;ticket;status="queued";timer=null;resolve;get id(){return this.ticket.id}end(e){this.status==="queued"&&(this.status=e.status,this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null),this.options.onSettled(),this.resolve(e));}};function _y(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var wy=1e3,Sy=3e3,Ry=6e4,ky=2,wc=new Set(["game_room_closed","game_room_gone"]),Ay=12e4,xy=5e3,Py=new Set(["invalid_cluster_target","capacity_unavailable"]),Ey=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function kc(t,e){return new zo(e,t)}var zo=class{constructor(e,n={}){this.options=e;this.internals=n;this.autoFollow=e.followMatch!==false,this.apiOptions={client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true},this.api=new Zr(this.apiOptions),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;internals;emitter=new ei;api;apiOptions;playWithAnswer=null;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await n,s=a=>this.api.create(r,this.version("create"),a);for(let a=0;;a++)try{return await s(o[a])}catch(l){if(!Jo(l))throw l;if(a+1<o.length)continue;let d=(await this.afterRefusedClusters(l,o)).find(u=>!o.includes(u));if(d===void 0)throw l;return s(d)}});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,n={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(n),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,n={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(n),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin"),Cy(e);let n=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.postQuickJoin(r,a).catch(l=>this.retryPastStaleMembership(l,r,a)),o=await this.run("quickJoin",async()=>{let a=await n;return i(a).catch(async l=>{let d=await this.afterRefusedClusters(l,a);if(d.length===0||Rc(d,a))throw l;return i(d)})}),{room:s}=o;return this.playWithAnswer=o.playWith,this.enter(s,"joined"),this.askForLocalServer(s),s}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Iy(e?.templateSlugs),this.queueing=true;try{let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let s=await n;return this.api.createTicket(r,this.version("queueForMatch"),s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||Rc(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 Jr({clock:this.options.clock,first:i,heartbeat:s=>this.track(this.api.heartbeatTicket(s)),cancel:(s,a)=>this.track(this.api.cancelTicket(s,a)),seat:s=>this.enterMatchedRoom(s),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;let n=this.heldQueued;this.heldQueued=null,n!==null&&this.showPartyTicket(n);}}async enterMatchedRoom(e){let n=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?n:(this.room!==null&&this.room.id!==n.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(n,"joined"),this.room?.id===n.id?this.room:n)}async list(e={}){let n=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",n),n}async myRooms(e){let n=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",n.rooms),n.rooms}async leave(e={}){let n=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(n.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let n=await this.myRooms(e),r=[];for(let i of n)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let n=this.requireRoom("close");await this.run("close",()=>this.api.close(n.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let n=this.room;if(!n)return null;let r;try{r=await this.track(this.api.get(n.id,e));}catch(i){if(i instanceof O&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let s=await this.askWhyEnded(o,e);this.endMatch(o,s??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let n=this.room,r=this.heldMatchId;if(!(n===null||r===null)&&!(n.status==="in_game"&&n.matchId===r)&&!(n.matchId!==void 0&&n.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>Ao({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...n===void 0?{}:{signal:n}})));}catch(s){return s instanceof O&&s.reason==="not_found"?i??null:(this.reportError("reconcile",s),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=Ze(n.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(i),i}async kick(e,n){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(i),i}async transferHost(e,n){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(i),i}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){let r=this.requireRoom("startMatch");if(!this.isHost)throw new A("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let i=Se(n.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(u,c)=>Ro({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...u===void 0?{}:{clusterTargetId:u},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:g=>{this.emitter.emit("matchStartWaiting",g),n.retry?.onWaiting?.(g);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(o,[s]).catch(async u=>{if(i!==void 0||!Jo(u))throw u;let c=await this.nextCluster([s],true);if(c===void 0)throw u;return a(c,[s,c])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new A("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let n=this.emitter.retained;return n!==null&&this.session.phase==="ready"?n:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let n=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(i)}chase(e,n,r){return ko({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:n,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(n),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new A("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!wc.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new A("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,n){this.heldMatchId===e&&(this.abandonReconnect(e,n),this.emitter.emit("matchFailed",e,n),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,n,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:n,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:n,roomReopened:r}),this.abandonReconnect(e,n));}armReconnect(e,n){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),n==="kicked"){r.abandon(e,n);return}let i={matchId:e,cause:n,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,n){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),n());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,n){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,n));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!mt()){this.park(e,()=>this.reconnectStep(e));return}let n=this.options.autoReconnect;if(n===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=n.attempts||r<wy){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:n.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(_y(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!mt()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>Ao({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,!wc.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await n.redial(e.matchId,e.deadlineAt);}catch(s){this.reportError("reconcile",s),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let n=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):n&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new A("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let n=this.session.matchId;this.session={phase:"suspended",matchId:n,reason:e},this.emitter.emit("matchSuspended",{matchId:n,cause:e}),this.armReconnect(n,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new A("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let n=this.heldMatchId;if(n===null)throw new A("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:n},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let n=this.heldMatchId;if(n!==null)try{await this.api.leaveMatch(n,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}get playWith(){return this.playWithAnswer}on(e,n){let r=this.emitter.on(e,n);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}handleRoomEvent(e){if(this.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let n=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(n).catch(()=>{}));}handleAutoStartFailed(e,n){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(n);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:n,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Py.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let n=new ti({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===n&&(this.partyWatch=null);}});this.partyWatch=n,this.emitter.emit("partyQueued",n.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let n=new Set;for(let r of e)r.status!=="closed"&&(n.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])n.has(r)||this.reported.delete(r);}async reportSeat(e){let n=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||n===null||!r.members.some(i=>i.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&mt())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let n=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(n,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!mt())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of ni)e.addEventListener(r,this.visibilityListener);let n=globalThis.document;typeof n?.addEventListener=="function"&&n.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let n=this.inFlight;this.inFlight=[],await Promise.allSettled(n);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of ni)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??xy}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new A("misconfigured","the game id is not known yet. It comes from the play token, and this manager was given no way to wait for one \u2014 pass gameId, or awaitGameId so a call made before the first token waits for it the way createGem wires it.")}playerId(){return typeof this.options.playerId=="function"?this.options.playerId():this.options.playerId}version(e){let n=this.options.clientVersion,r=Vr(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new A("misconfigured",`${e} has no game version to report \u2014 gem-api requires platform, game_version and engine_version together on every room route, and refuses a request carrying two of the three. The arcade normally supplies it with the play token; an embedder that does not, or a build running outside the arcade, leaves nobody to ask. Pass \`clientVersion: { gameVersion }\` to createGem (or to createRoomManager) as the fallback. It has to name a build you actually published, and a wrong one pins the room to the wrong build \u2014 which is why the platform answers it wherever it can.`);return rc({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return Te(await this.options.resolveClusterTargets());let e=Se(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Jo(e)||n.length===0?[]:Te(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=s=>s.find(a=>!e.includes(a)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!n?o:r(Te(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let n=this.options.resolveParty;if(n===void 0)return e;let r=await n();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,n,r){if(!(e instanceof O)||e.reason!=="conflict"||!Ey.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new O(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(n.signal);}catch{throw new O(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new O(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.postQuickJoin(n,r)}postQuickJoin(e,n){return Ko(this.apiOptions,e,this.version("quickJoin"),n,this.internals.playWithTicket)}assertNotInRoom(e){if(this.room!==null)throw new A("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new A("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new A("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,n){try{return await this.track(this.onceGameIdKnown(n))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,n){let r=n instanceof O?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof A?n.reason:"unavailable",message:n instanceof Error?n.message:String(n),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let n=this.options.ensureLocalServer;n===void 0||!e.selfHosted||e.status!=="open"||n(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,n){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(n,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let n=this.room;if(n===null||n.id!==e.id)return;let r=new Map(n.members.map(a=>[a.playerId,a])),i=new Map(e.members.map(a=>[a.playerId,a])),o=this.playerId();for(let a of i.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!i.has(a)){if(a===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,l]of i){let d=r.get(a);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",a,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=Ty(n,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let n=this.heldMatchId;n!==null&&n!==e&&this.endMatch(n,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,n=this.heldMatchId;if(e===null||n===null||this.followAbort!==null&&this.followingMatchId===n)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=n,this.track(this.onceGameIdKnown(()=>this.chase(e.id,n,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??Ay;return new Promise((i,o)=>{let s=c=>{a(),l(),this.options.clock.clearTimeout(u),e.signal?.removeEventListener("abort",d),c();},a=this.emitter.on("matchAllocationStarted",c=>s(()=>i(c))),l=this.emitter.on("matchFailed",(c,g)=>s(()=>o(new A("allocation_failed",`match ${c} did not come up: ${g}`)))),d=()=>s(()=>o(new A("aborted","the caller aborted while awaiting a match"))),u=this.options.clock.setTimeout(()=>s(()=>o(new A("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??Sy}pushedInterval(){return this.options.pushedPollIntervalMs??Ry}pushed(){return this.options.clock.now()-this.lastPushAt<ky*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=n=>{if(this.ticketWatch?.abandon(true),n?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function mt(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var ni=["visibilitychange","focus","pageshow","online"];function Ty(t,e){return t.version!==e.version||t.status!==e.status||t.matchId!==e.matchId||t.hostPlayerId!==e.hostPlayerId||t.name!==e.name||t.maxPlayers!==e.maxPlayers||t.isPublic!==e.isPublic||Sc(t)!==Sc(e)}function Sc(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Jo(t){return t instanceof O&&t.code==="invalid_cluster_target"}var ri=8;function Iy(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=ri&&t.every(n=>typeof n=="string"&&n.length>0)))throw new A("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${ri} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function Cy(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=ri&&e.every(r=>typeof r=="string"&&r.length>0)))throw new A("misconfigured",`quickJoin's templateSlugs is an array naming one to ${ri} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(t?.templateSlug!==void 0||t?.templateId!==void 0)throw new A("misconfigured","quickJoin takes templateSlugs or a single templateSlug / templateId, not both. Put every template this player accepts in templateSlugs, with the one to create from first.")}function Rc(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var My=["p2p","dedicated","unknown"],Xo=["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 Dt=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let i=Oy(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},n);}report(e){this.post(e).catch(()=>{});}};function Oy(t,e,n){let r=Math.floor(n/1e3);return t.filter(i=>Xo.includes(i.type)).slice(0,100).map(i=>{let o=Ly(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:{...Gy(i.labels),...i.value===void 0?{}:{value:i.value}}}})}function Gy(t){let e={};if(typeof t!="object"||t===null)return e;let n=0;for(let[r,i]of Object.entries(t)){if(n>=4)break;r==="value"||!Ac(r)||!Ac(i)||(e[r]=i,n+=1);}return e}function Ac(t){return typeof t=="string"&&t.length>0&&t.length<=32}function Ly(t){if(t!==void 0)return My.includes(t)?t:"unknown"}var An=class{constructor(e){this.options=e;this.reporter=new Dt({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:ii(i.credential)??"",hostFingerprint:ii(i.host_fingerprint)??"",hostEpoch:oi(i.host_epoch)??0,expiresAt:(oi(i.expires_at)??0)*1e3}}async turnLease(e,n,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,u=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);u.length!==0&&o.push({urls:u,username:ii(d.username)??"",credential:ii(d.credential)??""});}let s=oi(i.expires_at),a=oi(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??0)*1e3}}async kick(e,n,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:n},r);}async leave(e,n=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:n});}async telemetry(e,n){await this.reporter.post(e,n);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}},Dy=new Set(["cluster_hidden","invalid_cluster_target"]);async function xc(t,e,n,r){let i=Te(n);if(i.length===0)throw new Error("no cluster to lease TURN from");let o;for(let s of i)try{return {...await t.turnLease(e,s,r),clusterTargetId:s}}catch(a){if(!$y(a))throw a;o=a;}throw o}function $y(t){return t instanceof O&&Dy.has(t.code??"")}function ii(t){return typeof t=="string"&&t.length>0?t:void 0}function oi(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var Fy=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),q=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="P2pError",this.retryable=Fy.has(n);}reason;retryable};var Pc=10240,Ec=2048,qy=new TextEncoder;function Tc(t){return qy.encode(t).length}function Ue(t,e){let n=i=>{throw new A("invalid_sdp",`the ${e} ${i}`)},r=Tc(t);r>=Pc&&n(`is ${r} bytes, over the ${Pc} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),t.startsWith("v=")||n("does not start with 'v=', so it is not SDP"),t.includes("\0")&&n("contains a null byte"),/\r(?!\n)/.test(t)&&n("contains a bare carriage return");for(let i of t.split(/\r\n|\n/)){let o=Tc(i);o>Ec&&n(`has a ${o}-byte line, over the ${Ec} limit`);}}function ai(t){for(let e of t.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[n,r="0"]=e.slice(2).trim().split(/\s+/);if(!(n!=="audio"&&n!=="video")&&r.split("/")[0]!=="0")return true}return false}var si=class{listeners=new Map;on(e,n){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(n),()=>this.off(e,n)}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...i)=>{r(),n(...i);}));return r}emit(e,...n){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}clear(){this.listeners.clear();}};var Ny=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function Ft(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=li(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function li(t){let[e,...n]=t.trim().split(/\s+/);if(e===void 0||n.length===0)return null;let r=`${e.toLowerCase()} ${n.join("").toUpperCase()}`;return Ny.test(r)?r:null}function $t(t,e){if(t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}var Yo=5e3,jy=12e4+Yo,By=1024,Uy=6e4,Wy=1e4,Ic=64*1024,Cc=5;function Qo(t){let e=new Map,n=-1/0,r=null,i=(()=>{let a;try{a=new URL(`${t.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=t.subtle??globalThis.crypto?.subtle;if(!a)throw new q("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 q("keys_unavailable",i.reason);let a=t.fetch??((g,p)=>globalThis.fetch(g,p)),l;try{l=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(Wy)});}catch{throw new q("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 q("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let g=await l.text();if(g.length>Ic)throw new q("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Ic} characters, which is not a key set this platform publishes.`);d=JSON.parse(g);}catch(g){throw g instanceof q?g:new q("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let u=Array.isArray(d.keys)?d.keys:[];if(u.length>Cc)throw new q("keys_unavailable",`the JWKS endpoint published ${u.length} keys, over the ${Cc} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let g of u){let p=g;if(p.kty==="RSA"&&!(p.alg!==void 0&&p.alg!=="RS256")&&!(p.use!==void 0&&p.use!=="sig")&&!(typeof p.kid!="string"||p.kid.length===0))try{let f=await c.importKey("jwk",{...g,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(p.kid,f);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!i.ok)throw new q("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new q("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<n&&(n=-1/0),d-n<Uy?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var xn=class{seen=new Map;admit(e,n){for(let[r,i]of this.seen)i<=n&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=By){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+jy),true}};function Oc(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}function Mc(t){try{let e=new TextDecoder().decode(Oc(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Zo(t,e,n,r,i){let o=H=>{throw new q("peer_unauthenticated",`the peer's join credential is not usable: ${H}`)},s=t.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,l,d]=s,u=Mc(a);u===null&&o("its header does not decode"),u.alg!=="RS256"&&o(`its alg is ${JSON.stringify(u.alg)}, not RS256`),u.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(u.typ)}, not p2p+jwt`);let c=u.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let g=await n.key(c);g===null&&o("it was signed by a key this build cannot resolve");let p=i.subtle??globalThis.crypto?.subtle;p||o("this environment has no WebCrypto");let f=new TextEncoder().encode(`${a}.${l}`),y;try{y=Oc(d);}catch{o("its signature does not decode");}await p.verify({name:"RSASSA-PKCS1-v1_5"},g,y,f)||o("its signature does not verify");let b=Mc(l);b===null&&o("its payload does not decode");let R=b,h=H=>typeof R[H]=="string"?R[H]:"",_=H=>typeof R[H]=="number"&&Number.isFinite(R[H])?R[H]: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 I=_("exp")*1e3,T=_("nbf")*1e3;(!Number.isFinite(I)||e.now>I+Yo)&&o("it has expired"),Number.isFinite(T)&&e.now<T-Yo&&o("it is not valid yet");let W=h("role");W!=="host"&&W!=="client"&&o("it names no usable role");let N=_("host_epoch");N!==e.hostEpoch&&o("it names a different host epoch");let U=li(h("fingerprint"));U===null&&o("its fingerprint claim is malformed"),$t(U,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let C=li(h("host_fingerprint"));C===null&&o("its host fingerprint claim is malformed"),$t(C,e.hostFingerprint)||o("it was issued against a different host certificate");let L=h("jti");L.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(L,e.now)||o("it has already been used");let D=h("sub");return D.length===0&&o("it names no player"),{playerId:D.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:N,role:W,fingerprint:U,hostFingerprint:C,jti:L,expiresAt:I}}function ea(t){let e=new TextEncoder().encode(t.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let n=new ArrayBuffer(3+e.length+4+4),r=new DataView(n);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(n,3,e.length).set(e),r.setUint32(3+e.length,t.protocolVersion,true),r.setUint32(7+e.length,t.assignedPeerId,true),n}function ta(t){let e=new ArrayBuffer(9),n=new DataView(e);return n.setUint8(0,2),n.setUint32(1,t.protocolVersion,true),n.setUint32(5,t.assignedPeerId,true),e}function na(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function ra(t){if(t.byteLength<1)return null;let e=new DataView(t);switch(e.getUint8(0)){case 1:{if(t.byteLength<3)return null;let n=e.getUint16(1,true);return n>8192||t.byteLength<3+n+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(t,3,n)),protocolVersion:e.getUint32(3+n,true),assignedPeerId:e.getUint32(7+n,true)}}case 2:return t.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return t.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function Gc(t){switch(t){case 1:return "the host did not accept this credential";case 2:return "the host speaks a different protocol version \u2014 an engine peer refuses a browser peer here, deliberately";case 3:return "the match is full";case 4:return "the host is rate-limiting joins";case 129:return "the host verified this credential but it names a different player than the one who signalled \u2014 the host has its own line saying which";case 130:return "the host has this player on the kicked list for the current host epoch";case 131:return "the host could not fetch the platform's signing keys, so it cannot verify anyone yet \u2014 the host's console says why";default:return `the host refused with an unrecognised code (${t})`}}function Lc(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Pn=class{constructor(e,n,r){this.localPlayerId=e;this.hostPlayerId=n,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,n){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=n,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var ia={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}},We=["reliable","ordered","unreliable"];function oa(t){let e=globalThis.RTCPeerConnection;if(!e)throw new Error("[gem] this environment has no RTCPeerConnection. Pass `peerConnectionFactory` to connect against a stand-in, which is how this flow is tested outside a browser.");return new e({iceServers:t.iceServers,...t.certificates===void 0?{}:{certificates:t.certificates}})}async function En(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var $c=1,zy=3e4,Fc=2e3,Xy=5e3,qc=6e4,Yy=8,Qy=12e4,Zy=5e3,eh=8e3,Uc=18e5,th=Uc+6e4,sa=class{constructor(e=Yy){this.perMinute=e;}perMinute;sent=[];delayUntilAllowed(e){return this.prune(e),this.sent.length<this.perMinute?0:Math.max(0,(this.sent[0]??e)+6e4-e)}record(e){this.prune(e),this.sent.push(e);}prune(e){let n=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[n++]=r);this.sent.length=n;}},nh=new sa,rh=8,ih=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Mn=class{constructor(e){this.options=e;this.keys=e.keys??Qo({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new si;links=new Map;replays=new xn;keys;localPlayerId="";migration=null;lease=null;clusterTargetIds=[];leaseRenewal=null;leaseAskedAt=null;leaseRenewalWarned=false;credential=null;nextPeerId=$c+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;drainTimers=new Set;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let n of this.links.values())n.admitted&&e.push(this.expose(n));return e}peer(e){let n=this.links.get(e);return n&&n.admitted?this.expose(n):null}on(e,n){return this.emitter.on(e,n)}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}async start(e){let n=this.options.connectTimeoutMs??zy;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((s,a)=>{this.ready={resolve:s,reject:a};});if(this.clusterTargetIds=Te([this.options.clusterTargetId,...this.options.clusterTargetIds??[]]),this.clusterTargetIds.length>0)try{await this.takeLease(e),this.mark("turn leased");}catch(s){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${In(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let i=this.options.clock.setTimeout(()=>{this.fail(new q("timeout",`no usable P2P connection after ${n}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},n),o=()=>this.fail(new q("aborted","the caller aborted while connecting"));e?.aborted?o():e?.addEventListener("abort",o);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",o),this.ready=null;}}async kick(e){if(!this.isHost)throw new q("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of this.drainTimers)this.options.clock.clearTimeout(e);this.drainTimers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,n){this.closed||this.route(e,n).catch(r=>this.report_(r));}async route(e,n){switch(e){case "hello":return this.onHello(n);case "offer":return this.onOffer(n);case "answer":return this.onAnswer(n);case "ice":return this.onIce(n);case "peerLeft":return this.onPeerLeft(n);case "migration":return this.onMigration(n);case "matchEnded":return this.onMatchEnded(n);case "error":return this.onSignalingError(n);case "relayDraining":return this.onRelayDraining(n);default:return}}async onHello(e){let n=le(e.playerId),r=le(e.hostPlayerId),i=Tn(e.hostEpoch);if(!(n===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new Pn(n,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let n of e)try{await this.onOffer(n);}catch(r){this.report_(r);}}async offerToHost(e){let n=this.hostPlayerId,r=this.openLink(n,$c),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new q("invalid_sdp","the browser produced an offer with no SDP");Ue(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:Ft(r);if(i===null)throw new q("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??nh,s=()=>this.closed||e!==this.credentialGeneration,a=Xy;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,s))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(s())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(s())return;let u=d.status,c;if(u===409)c=Fc;else if(u===429){let g=d.retryAfterSeconds;typeof g=="number"&&Number.isFinite(g)&&g>=0?c=g*1e3:(c=a,a=Math.min(a*2,qc)),c=Math.min(Math.max(c,Fc),qc);}else throw d;if(!await this.waitForCredential(c,s))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=le(e.fromPlayerId),r=le(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=rh){let l=this.pendingOffers.keys().next().value;l!==void 0&&this.pendingOffers.delete(l);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let i=le(e.sessionId);if(i!==null&&this.answeredSessions.get(n)===i)return;Ue(r,"offer"),this.refuseMedia(r,"offer");let o=Ft(r);if(o===null)throw new q("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);if(this.mark("offer received"),i!==null&&this.answeredSessions.set(n,i),await this.refreshLease(false),this.closed||!this.isHost)return;let s=this.links.get(n);if(le(e.intent)==="ice_restart"&&s?.admitted===true&&s.remoteFingerprint!==null&&$t(s.remoteFingerprint,o)){await this.answer(s,r),this.mark("ice restart answered");return}s&&this.dropLink(s,"resignalled",false);let a=this.openLink(n,this.nextPeerId++);a.remoteFingerprint=o,await this.answer(a,r),this.mark("answer sent");}async answer(e,n){await e.connection.setRemoteDescription({type:"offer",sdp:n}),this.flushCandidates(e);let r=await e.connection.createAnswer();await e.connection.setLocalDescription(r);let i=e.connection.localDescription?.sdp??r.sdp;if(!i)throw new q("invalid_sdp","the browser produced an answer with no SDP");Ue(i,"answer"),this.refuseMedia(i,"answer"),this.options.signaling.answer(e.playerId,i,e.assignedPeerId);}async onAnswer(e){if(this.isHost)return;let n=le(e.fromPlayerId),r=le(e.sdp);if(n===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||n!==this.hostPlayerId)return;Ue(r,"answer"),this.refuseMedia(r,"answer");let o=Ft(r);if(o===null)throw new q("invalid_sdp","the host's answer carries no usable fingerprint");let s=Tn(e.assignedPeerId);if(i.restart!==void 0&&s!==null&&s!==i.assignedPeerId){this.warn(`the host answered the ICE restart from a new connection (peer id ${s}, this link is ${i.assignedPeerId}); dropping the link to re-dial`),this.dropLink(i,"restart_mismatch",true);return}this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:$t(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new q("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let n=e.pendingAnswer;n!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,n).catch(r=>this.report_(r));}async applyAnswer(e,n){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:n}),this.flushCandidates(e),e.restart!==void 0&&(e.restart.answered=true,this.progressRestart(e));}async onIce(e){let n=le(e.fromPlayerId),r=le(e.candidate);if(n===null||r===null)return;let i=this.links.get(n);if(!i)return;let o=le(e.sdpMid),s=Tn(e.sdpMLineIndex)??Tn(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a).catch(()=>{});}onPeerLeft(e){let n=le(e.playerId);if(n===null)return;let r=le(e.reason)??"left";if(n===this.localPlayerId){this.fail(new q("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(n);i&&this.dropLink(i,r,true);}async onMigration(e){let n=le(e.hostPlayerId),r=Tn(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:n,hostEpoch:r,...le(e.reason)===null?{}:{reason:le(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(s=>typeof s=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind==="duplicate")return;if(i.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(i.kind==="refused"){this.report_(new q("migration_failed",i.why));return}for(let s of [...this.links.values()])this.dropLink(s,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration();let o=this.hostEpoch;await this.refreshLease(false),!(this.closed||this.hostEpoch!==o)&&await this.offerToHost("full_reconnect");}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new q("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let n=le(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new q("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=le(e.code)??"unknown",r=le(e.message)??"the platform refused a signaling message",i=this.isHost?void 0:this.links.get(this.hostPlayerId)?.restart;if(i!==void 0){this.warn(`the platform refused an ICE restart (${n}: ${r})`),i.settle(false);return}this.report_(new q("signaling_failed",`${n}: ${r}`));}async onRelayDraining(e){if(this.migration===null)return;let n=new Set((Array.isArray(e.relayIps)?e.relayIps:[]).filter(c=>typeof c=="string").map(c=>c.toLowerCase())),r=this.isHost?void 0:this.links.get(this.hostPlayerId),i,o=this.options.clock.now(),s=Date.parse(le(e.deadline)??""),a=(Number.isFinite(s)?s:o+Uc)-o,l=this.options.clock.setTimeout(()=>{this.drainTimers.delete(l),this.onDrainDeadline(n,r,i).catch(c=>this.report_(c));},Math.max(0,Math.min(a,th)));if(this.drainTimers.add(l),await this.refreshLease(true),this.closed||(this.withoutDrainingRelays(n),this.isHost))return;let d=this.links.get(this.hostPlayerId);if(d===void 0||!d.admitted)return this.reportRestart("skipped","announced");let u=await Nc(d.connection,n);if(!(this.closed||this.links.get(d.playerId)!==d)){if(u===false)return this.reportRestart("skipped","announced");await this.restartIceToHost(d,"announced")&&(i=d);}}async onDrainDeadline(e,n,r){if(this.closed||this.isHost)return;let i=this.links.get(this.hostPlayerId);if(i===void 0)return;let o=await Nc(i.connection,e);if(this.closed||this.links.get(i.playerId)!==i)return;(o===true||o===null&&i===n&&i!==r)&&this.dropLink(i,"relay_deadline",true);}withoutDrainingRelays(e){let n=this.lease;if(n===null||e.size===0)return;let r=false,i=[];for(let o of n.iceServers){let s=o.urls.filter(a=>{let l=oh(a),d=l===null||!e.has(l);return r||=!d,d});s.length>0&&i.push({...o,urls:s});}r&&(this.lease={iceServers:i,expiresAt:n.expiresAt},this.reconfigureLinks());}restartIceToHost(e,n){if(e.restart!==void 0)return e.restart.done;if(e.connection.restartIce===void 0)return this.reportRestart("skipped",n),Promise.resolve(false);let r=()=>{},i=new Promise(a=>{r=a;}),o=this.options.clock.setTimeout(()=>s.settle(false),eh),s={done:i,answered:false,settle:a=>{e.restart===s&&(e.restart=void 0,this.options.clock.clearTimeout(o),this.closed||this.reportRestart(a?"success":"failed",n),r(a));}};return e.restart=s,this.offerIceRestart(e).catch(a=>{this.warn(`could not restart ICE on the connection to the host: ${In(a)}`),s.settle(false);}),i}async offerIceRestart(e){let n=e.connection;n.restartIce?.();let r=await n.createOffer();await n.setLocalDescription(r);let i=n.localDescription?.sdp??r.sdp;if(!i)throw new q("invalid_sdp","the browser produced an offer with no SDP");Ue(i,"offer"),this.refuseMedia(i,"offer"),!(e.restart===void 0||this.links.get(e.playerId)!==e)&&(this.options.signaling.offer(i,"ice_restart"),this.mark("ice restart offered"));}progressRestart(e){let n=e.restart;if(n===void 0)return;let r=e.connection.iceConnectionState;r==="failed"||r==="closed"?n.settle(false):n.answered&&aa(r)&&n.settle(true);}reportRestart(e,n){this.report([{type:"ice_restart_outcome_total",value:1,labels:{outcome:e,reason:n}}]);}async takeLease(e){this.leaseAskedAt=this.options.clock.now();let n=this.clusterTargetIds,r=await xc(this.options.api,this.options.matchId,n,e);this.lease={iceServers:r.iceServers,expiresAt:r.expiresAt},this.clusterTargetIds=n.slice(Math.max(0,n.indexOf(r.clusterTargetId)));}refreshLease(e){if(this.clusterTargetIds.length===0||this.closed)return Promise.resolve();if(this.leaseRenewal!==null)return this.leaseRenewal;let n=this.options.clock.now();if(this.leaseAskedAt!==null&&n-this.leaseAskedAt<Zy)return Promise.resolve();let r=this.lease;if(!e&&r!==null&&r.expiresAt-n>=Qy)return Promise.resolve();let i=this.takeLease().then(()=>{this.closed||(this.mark("turn re-leased"),this.reconfigureLinks());},o=>{this.leaseRenewalWarned||(this.leaseRenewalWarned=true,this.warn(`could not renew the TURN lease for this match, so connections keep the relays they were given: ${In(o)}`));}).finally(()=>{this.leaseRenewal=null;});return this.leaseRenewal=i,i}reconfigureLinks(){for(let e of this.links.values()){let n=e.connection;if(n.setConfiguration!==void 0)try{n.setConfiguration({...n.getConfiguration?.(),iceServers:this.iceServers()});}catch{}}}iceServers(){return (this.lease?.iceServers??[]).map(e=>({urls:[...e.urls],username:e.username,credential:e.credential}))}openLink(e,n){let i=(this.options.peerConnectionFactory??oa)({iceServers:this.iceServers(),...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let g of We){let p=i.createDataChannel(g,ia[g]);p.binaryType="arraybuffer",o[g]=p;}let s={playerId:e,assignedPeerId:n,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=g=>{let p=g.candidate;p?.candidate&&this.options.signaling.candidate(e,p.candidate,p.sdpMid??void 0,p.sdpMLineIndex??void 0);},l=()=>this.onIceState(s),d=()=>this.onConnectionState(s),u=g=>{this.onHandshakeMessage(s,g.data).catch(p=>this.report_(p));},c=()=>{this.onReliableOpen(s).catch(g=>this.report_(g));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",u),s.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",u);},s.detachAll=()=>{s.detachHandshake(),i.removeEventListener("icecandidate",a),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,s),s}flushCandidates(e){let n=e.pendingCandidates;e.pendingCandidates=[];for(let r of n)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let n=this.credential;if(n===null)throw new q("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=n.expiresAt)throw new q("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(ea({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=ra(n);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new q(Lc(r.reason),Gc(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,n,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=Ft(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 Zo(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(s){let a=s instanceof q&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",In(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(ta({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send(na(n));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){this.progressRestart(e);let n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(n==="disconnected"){if(e.recovering===true)return;if(e.admitted&&e.connection.restartIce!==void 0&&this.reportedUnreachableEpoch!==this.hostEpoch){this.recoverHostLink(e).catch(r=>this.report_(r));return}}this.voteHostUnreachable(n);}}async recoverHostLink(e){let n=this.hostEpoch,r=()=>!this.closed&&this.hostEpoch===n&&this.links.get(e.playerId)===e;e.recovering=true;try{if(await this.refreshLease(!0),!r())return;if(aa(e.connection.iceConnectionState))return this.reportRestart("skipped","disconnected");if(await this.restartIceToHost(e,"disconnected")||!r()||aa(e.connection.iceConnectionState))return;this.voteHostUnreachable(jc(e.connection.iceConnectionState));}finally{e.recovering=false;}}voteHostUnreachable(e){if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,e);}catch(n){this.report_(n);}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||(e.recovering===true&&this.voteHostUnreachable(jc(e.connection.iceConnectionState)),this.dropLink(e,n,true));}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.restart?.settle(false),e.detachAll();for(let i of We)Bc(e.channels[i]);Bc(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,n);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let n=this.ready;this.ready=null,n.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof q?e:new q("connection_failed",In(e),{cause:e}));}count(e){this.counted||!ih.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(ai(e))throw new q("media_refused",`the ${n} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(n=>this.options.clock.setTimeout(n,e))}warn(e){let n=this.options.log;n!==null&&(n??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function le(t){return typeof t=="string"&&t.length>0?t:null}function Tn(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function In(t){return t instanceof Error?t.message:String(t)}async function Nc(t,e){if(t.getStats===void 0)return null;let n=new Map;try{(await t.getStats()).forEach((a,l)=>{typeof a=="object"&&a!==null&&n.set(l,a);});}catch{return null}let r=[...n.values()],i=r.find(a=>a.type==="transport")?.selectedCandidatePairId,o=(typeof i=="string"?n.get(i):void 0)??r.find(a=>a.type==="candidate-pair"&&a.selected===true)??r.find(a=>a.type==="candidate-pair"&&a.nominated===true&&a.state==="succeeded");if(o===void 0)return null;let s=[o.localCandidateId,o.remoteCandidateId].map(a=>typeof a=="string"?n.get(a):void 0);return s.every(a=>a===void 0)?null:s.some(a=>{let l=a?.address??a?.ip;return typeof l=="string"&&e.has(l.toLowerCase())})}function oh(t){let e=/^(?:turns?|stuns?):(?:\[([^\]]+)\]|([^:?/]+))/i.exec(t),n=e?.[1]??e?.[2];return n===void 0?null:n.toLowerCase()}function aa(t){return t==="connected"||t==="completed"}function jc(t){return t==="failed"||t==="closed"?t:"disconnected"}function Bc(t){try{t.close();}catch{}}var ah=100,sh=50,On=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,n){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:n});}answer(e,n,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:n,assignedPeerId:r});}candidate(e,n,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??ah)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,n){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:n,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new q("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new q("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:n,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let n=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(n),this.dropListener?.(n);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??sh));}};function K(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function et(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function qt(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function Wc(t){return typeof t=="boolean"?t:void 0}var _e=K(64),Gn=et(0,2147483647);function di(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=_e(n);typeof r=="string"&&e.push(r);}return e}function J(t,e,n){return {to:t,from:e,read:n,required:true}}function z(t,e,n){return {to:t,from:e,read:n,required:false}}var ch=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=qt("disconnected","failed","closed")(e.iceState),r=et(0,4102444800)(e.lastSeenAt);if(!(n===void 0&&r===void 0))return {...n===void 0?{}:{ice_state:n},...r===void 0?{}:{last_seen_timestamp:r}}};Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[J("sdp","sdp",K(10240)),J("signaling_intent","intent",qt("initial","ice_restart","full_reconnect")),z("sdp_hash","sdpHash",K(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[J("peer_id","peerId",_e),J("sdp","sdp",K(10240)),J("assigned_peer_id","assignedPeerId",et(0,4294967295)),z("sdp_hash","sdpHash",K(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[J("peer_id","peerId",_e),J("candidate","candidate",K(512)),z("sdp_mid","sdpMid",K(64)),z("sdp_mline_index","sdpMLineIndex",et(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[J("host_epoch","hostEpoch",Gn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[J("host_epoch","hostEpoch",Gn),z("evidence","evidence",ch)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error",p2p_relay_draining:"relayDraining"}));var uh=16,mh=t=>di(t)?.slice(0,uh);Object.freeze(Object.assign(Object.create(null),{hello:[J("playerId","player_id",_e),J("hostPlayerId","host_player_id",_e),J("hostEpoch","host_epoch",Gn),z("members","members",di)],offer:[J("fromPlayerId","from_player_id",_e),J("sdp","sdp",K(10240)),z("sessionId","signaling_session_id",K(128)),z("sdpHash","sdp_hash",K(128)),z("iceUfrag","ice_ufrag",K(64)),z("intent","signaling_intent",qt("initial","ice_restart","full_reconnect"))],answer:[J("fromPlayerId","from_player_id",_e),J("sdp","sdp",K(10240)),z("sessionId","signaling_session_id",K(128)),z("sdpHash","sdp_hash",K(128)),z("iceUfrag","ice_ufrag",K(64)),z("assignedPeerId","assigned_peer_id",et(0,4294967295))],ice:[J("fromPlayerId","from_player_id",_e),J("candidate","candidate",K(512)),z("sdpMid","sdp_mid",K(64)),z("sdpMLineIndex","sdp_m_line_index",et(0,255)),z("sdpMLineIndexAlt","sdp_mline_index",et(0,255))],peerJoined:[J("playerId","player_id",_e)],peerLeft:[J("playerId","player_id",_e),z("reason","reason",K(64))],migration:[J("hostPlayerId","new_host_player_id",_e),J("hostEpoch","host_epoch",Gn),z("reason","reason",K(64)),z("kickedPlayerIds","kicked_player_ids",di),z("migrationComplete","migration_complete",Wc)],matchEnded:[z("reason","reason",K(64))],error:[z("code","code",K(64)),z("message","message",K(256))],relayDraining:[J("clusterTargetId","cluster_target_id",_e),J("relayIps","relay_ips",mh),J("drainingSince","draining_since",K(40)),J("deadline","deadline",K(40))]}));Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));var gt="webrtc_p2p";function Vc(t){let e=new An({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,i,o){n.get(r)?.handleSignal(i,o);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new q("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let i=Se(r.clusterTargetId),o=i===void 0?await ph(t):[i];t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let s=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==gt)throw new q("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${gt}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new On({bridge:t.bridge,matchId:s.matchId,clock:t.clock}),l=new Mn({api:e,clock:t.clock,matchId:s.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:a,...o.length===0?{}:{clusterTargetIds:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await En(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});a.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(s.matchId,l),l.on("matchEnded",()=>n.delete(s.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(s.matchId),l.close(),d}return l}}}async function ph(t){if(t.resolveClusterTargets!==void 0)return Te(await t.resolveClusterTargets());let e=Se(await t.resolveClusterTarget?.());return e===void 0?[]:[e]}function Kc(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,i=t.document??globalThis.document,o=[];if(typeof r.addEventListener=="function"){let a=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",a),o.push(()=>r.removeEventListener?.("pagehide",a));let l=()=>e.setHidden(!mt());for(let d of ni)r.addEventListener(d,l),o.push(()=>r.removeEventListener?.(d,l));typeof i?.addEventListener=="function"&&(i.addEventListener("resume",l),o.push(()=>i.removeEventListener?.("resume",l))),e.setHidden(!mt());}let s=new Map;return o.push(n.on("matchReady",a=>{let l=a.protocol===gt?"p2p":"dedicated";s.set(a.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),o.push(n.on("matchEnded",a=>{let l=s.get(a.matchId);l!==void 0&&(s.delete(a.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let a of o.splice(0))try{a();}catch{}s.clear();}}var gh=[[/swiftshader|llvmpipe|softpipe|software|basic render driver/i,"software"],[/powervr d-series/i,"powervr_d_series"],[/powervr|imagination/i,"powervr_other"],[/adreno/i,"adreno"],[/mali|immortalis/i,"mali"],[/xclipse/i,"xclipse"],[/apple/i,"apple"],[/nvidia|geforce|quadro|tegra/i,"nvidia"],[/\bamd\b|radeon|\bati\b/i,"amd"],[/intel/i,"intel"]];function Ln(t){if(t===null||t==="")return "unknown";for(let[e,n]of gh)if(e.test(t))return n;return "other"}function la(t){return t===null||t===""?"unknown":/^ANGLE \(/.test(t)?/vulkan/i.test(t)?"angle_vulkan":/opengl es/i.test(t)?"angle_gles":/direct3d11|d3d11/i.test(t)?"angle_d3d11":/direct3d9|d3d9/i.test(t)?"angle_d3d9":/metal/i.test(t)?"angle_metal":/opengl/i.test(t)?"angle_opengl":"angle_other":"native_gl"}function da(t){return /Android/.test(t)&&/; wv\)/.test(t)?"android_webview":"other"}function ca(t){try{let e=t.getParameter(t.RENDERER);if(typeof e=="string"&&e!==""&&!/^WebKit WebGL$/i.test(e))return e;let n=t.getExtension("WEBGL_debug_renderer_info");if(n){let r=t.getParameter(n.UNMASKED_RENDERER_WEBGL);if(typeof r=="string"&&r!=="")return r}return typeof e=="string"&&e!==""?e:null}catch{return null}}function fh(t){try{let{vendor:e,architecture:n,description:r}=t??{},i=[e,n,r].filter(o=>typeof o=="string"&&o!=="").join(" ").replace(/img-tec/gi,"PowerVR").replace(/qualcomm/gi,"Adreno").replace(/\barm\b/gi,"Mali").replace(/samsung/gi,"Xclipse");return Ln(i)}catch{return "unknown"}}var yh=new Set(["webgl","webgl2","experimental-webgl"]),Jc=false;function zc(t){let e=t.win??globalThis.window,n=e?.HTMLCanvasElement?.prototype;if(Jc||!e||!n)return;Jc=true;let r=t.now??(()=>performance.now()),i=da(e.navigator?.userAgent??""),o=new WeakMap,s=null,a=0,l=(g,p,f)=>{try{if(a+=1,a>5)return;t.analytics.trackPlatform("gem_graphics_context_lost",{gpu:g,host:i,route:p,...f===void 0?{}:{context_ms:Math.max(0,Math.round(r()-f))},hidden:e.document?.visibilityState==="hidden"?1:0,nth_loss:a});}catch{}},d=g=>{let p=o.get(g),f=p?.renderer??s;l(Ln(f),la(f),p?.createdAt);},u=n.getContext;n.getContext=function(g,...p){let f=u.call(this,g,...p);try{if(f&&typeof g=="string"&&yh.has(g)&&!o.has(this)){let y=ca(f);y!==null&&(s=y),o.set(this,{createdAt:r(),renderer:y}),this.addEventListener?.("webglcontextlost",()=>d(this));}}catch{}return f};let c=e.GPUAdapter?.prototype;if(c&&typeof c.requestDevice=="function"){let g=c.requestDevice;c.requestDevice=function(...p){let f=g.apply(this,p);try{let y=r(),S=fh(this.info),b=S==="unknown"?Ln(s):S;Promise.resolve(f).then(R=>R?.lost).then(R=>{R&&R.reason!=="destroyed"&&l(b,"webgpu",y);},()=>{});}catch{}return f};}e.addEventListener?.("webglcontextlost",g=>{let p=g.target;p&&!o.has(p)&&d(p);},true);}var Xc=["pointerdown","keydown"];function Yc(t,e=globalThis){let n=false,r=false,i=null,o=()=>{if(i!==null){try{e.cancelAnimationFrame?.(i);}catch{}i=null;}},s=()=>{if(!r){r=true,o();for(let p of Xc)e.removeEventListener?.(p,l,{capture:true});e.removeEventListener?.("gamepadconnected",g,{capture:true});}},a=()=>{if(!(n||r)){n=true,s();try{t();}catch{}}};function l(p){p?.isTrusted===true&&a();}let d=()=>{let p;try{p=e.navigator?.getGamepads?.()??[];}catch{return false}return p.some(f=>f?.buttons.some(y=>y.pressed)===true)},u=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(p=>p!==null)}catch{return false}},c=()=>{if(i=null,!(n||r)){if(d()){a();return}u()&&(i=e.requestAnimationFrame?.(c)??null);}};function g(){i===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let p of Xc)e.addEventListener(p,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",g,{capture:true,passive:true}),u()&&(i=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:s}}async function ci(t,e,n,r){let i=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),i}function ua(t,e){let n=false;return async r=>{let i=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),i}}function ma(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(i,o){return r.has(i)?false:(r.add(i),n.push({name:i,at:o??e()}),true)},timeline(){let i=[...n].sort((o,s)=>o.at-s.at);return i.map((o,s)=>{let a=i[s-1],l=a===void 0?"":` (+${Math.round(o.at-a.at)}ms)`;return `${o.name}@${Math.round(o.at)}ms${l}`}).join(" \u2192 ")}}}var hh=["angle_gles","native_gl","angle_opengl","angle_other","angle_d3d11","angle_d3d9","angle_metal"],bh=Object.freeze(hh.map(t=>Object.freeze({gpu:"powervr_d_series",route:t}))),Zc="gemGraphics",Qc=1e3,vh=5e3,_h=32,wh=32,Sh=300;function eu(t){if(typeof t!="string"||t==="")return null;try{let n=new URLSearchParams(t).get(Zc)?.trim().toLowerCase();return n==="webgpu"||n==="webgl"||n==="safe"?n:null}catch{return null}}function Rh(t){if(!Array.isArray(t)||t.length>_h)return null;let e=[];for(let n of t){if(n===null||typeof n!="object"||Array.isArray(n))return null;let{gpu:r,route:i,host:o}=n;if(!pa(r)||i!==void 0&&!pa(i)||o!==void 0&&!pa(o))return null;e.push(Object.freeze({gpu:r,...i===void 0?{}:{route:i},...o===void 0?{}:{host:o}}));}return Object.freeze(e)}function pa(t){return typeof t=="string"&&t!==""&&t.length<=wh}function kh(t,e){return e.some(n=>n.gpu===t.gpu&&(n.route===void 0||n.route===t.route)&&(n.host===void 0||n.host===t.host))}function Ah(t){let e=t?.navigator?.gpu;return e&&typeof e.requestAdapter=="function"?e:null}function xh(t){try{let e=t?.OffscreenCanvas;if(typeof e!="function")return null;let n=new e(1,1).getContext("webgl");if(!n)return null;let r=ca(n);try{n.getExtension("WEBGL_lose_context")?.loseContext();}catch{}return r===null?null:{gpu:Ln(r),route:la(r),host:da(t?.navigator?.userAgent??"")}}catch{return null}}function ga(t,e){return Object.freeze({route:t,listed:e})}var ui=ga("webgl",false);function tu(t){let{bridge:e,clock:n,forced:r}=t,i=()=>t.win??globalThis.window,o=t.log??null,s=null,a=false,l=new Set,d,u=null,c=false,g=(b,R,h)=>new Promise(_=>{let I=n.setTimeout(()=>_(h),Math.max(0,R));b.then(T=>{n.clearTimeout(I),_(T);},()=>{n.clearTimeout(I),_(h);});}),p=(b,R)=>(u??=Promise.resolve().then(()=>b.requestAdapter()).then(h=>h!=null,()=>false),g(u,R,false)),f=async b=>{if(a||b<=0)return;let R=n.now(),h=await e.settled(b);if(a||h!=="connected"||!e.parentSupports("graphicsRoutes"))return;let _=b-(n.now()-R);_<=0||await new Promise(I=>{let T=()=>{l.delete(T),n.clearTimeout(W),I();},W=n.setTimeout(T,_);l.add(T);});},y=async(b,R)=>ga(b!==null&&await p(b,R)?"webgpu":"webgl",true),S=async b=>{let R=n.now()+b,h=()=>Math.max(0,R-n.now()),_=Ah(i());if(r!==null&&!c&&(c=true,o?.(`[gem] graphics route forced to ${r} by the ${Zc} launch key`+(r==="webgpu"&&_===null?", but this browser has no WebGPU: webgl, listed":""))),r==="webgl")return ui;if(r==="safe")return ga("webgl",true);if(r==="webgpu")return y(_,h());await f(h()-(_===null?0:Math.min(Sh,b/2)));let I=s??bh;return I.length===0||(d===void 0&&(d=xh(i())),d===null||!kh(d,I))?ui:y(_,h())};return {api:{preferredRoute(b){let R=Number(b?.timeoutMs??Qc),h=Number.isFinite(R)?Math.min(Math.max(0,R),vh):Qc;return S(h).catch(()=>ui)}},accept(b){let R=Rh(b);a=true,R!==null&&(s=R);for(let h of [...l])h();}}}var fa=new WeakMap,nu=new WeakSet,ya=new Set,mi=new Set,pi=[],jt=null,ha=false,Ph=1920;function ba(t){return fa.get(t)}function va(t){return !ha||nu.has(t)}function _a(t){return t.kind==="webgpu"?true:t.kind!=="webgl"&&t.kind!=="webgl2"&&t.kind!=="experimental-webgl"?false:t.context.getContextAttributes()?.preserveDrawingBuffer!==true}function ru(t=globalThis.window){if(ha||!t?.HTMLCanvasElement||typeof t.requestAnimationFrame!="function")return;ha=true;for(let o of Array.from(t.document?.querySelectorAll("canvas")??[]))nu.add(o);let e=t.HTMLCanvasElement.prototype,n=e.getContext;e.getContext=function(o,...s){let a=n.call(this,o,...s);if(a&&!fa.has(this)){let l={kind:o,context:a};fa.set(this,l),_a(l)&&ya.add(this);}return a};let r=t.requestAnimationFrame,i=t.cancelAnimationFrame;t.requestAnimationFrame=o=>{let s=r.call(t,a=>{mi.delete(s);try{o(a);}finally{Eh();}});return mi.add(s),au(),s},t.cancelAnimationFrame=o=>{mi.delete(o),i.call(t,o);};}function iu(t,e){return new Promise(n=>{let r={canvas:t,done:o=>{clearTimeout(i),pi=pi.filter(s=>s!==r),n(o);}},i=setTimeout(()=>r.done(null),e);pi.push(r);})}function ou(t){return jt?.canvas===t?jt.bitmap:null}function Eh(){for(let t of pi){let e;try{e=wa(t.canvas);}catch(n){t.done(Promise.reject(n));continue}e&&t.done(createImageBitmap(t.canvas));}mi.size===0&&Th();}function Th(){let t=null;for(let r of ya)r.isConnected?(!t||r.width*r.height>t.width*t.height)&&(t=r):ya.delete(r);if(!t||t.width===0||t.height===0)return;let e=Math.min(1,Ph/Math.max(t.width,t.height)),n=e<1?{resizeWidth:Math.max(1,Math.floor(t.width*e)),resizeHeight:Math.max(1,Math.floor(t.height*e)),resizeQuality:"medium"}:{};au(),jt={canvas:t,bitmap:createImageBitmap(t,n).catch(()=>null)};}function au(){jt&&(jt.bitmap.then(t=>t?.close()),jt=null);}function wa(t){let e=Ih();if(!e)return true;e.clearRect(0,0,8,8),e.drawImage(t,0,0,8,8);let n=e.getImageData(0,0,8,8).data;for(let r=0;r<n.length;r+=4){if(n[r]|n[r+1]|n[r+2])return true;let i=n[r+3];if(i!==0&&i!==255)return true}return false}var Dn;function Ih(){if(Dn!==void 0)return Dn;if(typeof OffscreenCanvas=="function")Dn=new OffscreenCanvas(8,8).getContext("2d",{willReadFrequently:true});else {let t=globalThis.document?.createElement("canvas");t&&(t.width=t.height=8),Dn=t?.getContext("2d",{willReadFrequently:true})??null;}return Dn??null}var Sa=false;async function cu(t,e,n,r){if(Sa){e.close(),n("busy",true);return}Sa=true;let i=null;try{let o=await Oh(t,r);if(typeof o=="string"){e.close(),n(o,Ch(o));return}i=o;let a=await(r.encodeRef??(l=>Fh(l,r)))(i);if(i.close(),i=null,a===null){e.close(),n("failed",!0);return}if(a.size>$h){e.close(),n("too_large",!1);return}e.postMessage(a);}catch(o){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",o);}finally{Sa=false,i?.close();}}function Ch(t){switch(t){case "no_source":case "busy":case "failed":return true;case "not_wired":case "unsupported":case "unreadable":case "tainted":case "too_large":case "declined":return false}}var Mh=600;async function Oh(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":su(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=Dh(n);if(!r)return "no_source";try{let i=await Gh(r);return typeof i=="string"?i:su(i,t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}async function Gh(t){let e=Lh(t);if(typeof e=="string")return e;if(e.kind.includes("webgl")&&!e.context.getContextAttributes())return "unsupported";if(!_a(e))return createImageBitmap(t);let n=await iu(t,Mh);if(n)return n;let r=await ou(t);return r&&wa(r)?createImageBitmap(r):e.kind==="webgpu"?"unreadable":"unsupported"}function Lh(t){let e=ba(t);if(e)return e;if(!va(t))return "no_source";try{for(let n of ["webgl2","webgl","2d","webgpu"]){let r=t.getContext(n);if(r)return {kind:n,context:r}}}catch{return "unreadable"}return "unreadable"}function Dh(t){let e=null,n=0;for(let r of Array.from(t.querySelectorAll("canvas"))){let i=r.width*r.height;i<=0||r.clientWidth<=0||r.clientHeight<=0||!ba(r)&&!va(r)||i>n&&(e=r,n=i);}return e}async function su(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let i=Math.min(n/t.width,r/t.height),o=Math.max(1,Math.floor(t.width*i)),s=Math.max(1,Math.floor(t.height*i));try{let a=await createImageBitmap(t,{resizeWidth:o,resizeHeight:s,resizeQuality:"high"});return t.close(),a}catch{return t.close(),"too_large"}}var $h=8*1024*1024,lu="image/webp",du=.92;async function Fh(t,e){try{if(typeof OffscreenCanvas=="function"){let o=new OffscreenCanvas(t.width,t.height),s=o.getContext("2d");if(s){s.drawImage(t,0,0);let a=await o.convertToBlob({type:lu,quality:du});if(a&&a.size>0)return a}}}catch{}let n=e.documentRef??globalThis.document;if(!n)return null;let r=n.createElement("canvas");r.width=t.width,r.height=t.height;let i=r.getContext("2d");return !i||(i.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(o=>{r.toBlob(s=>o(s),lu,du);})}async function uu(t,e){if(!e)return;let n;try{n=await qh(e);}catch(r){console.error("[gem] onFeedbackContext threw; sending the report without context",r);return}if(n!=null){if(typeof n!="object"||Array.isArray(n)){console.error("[gem] onFeedbackContext must return a plain object or null; got",n);return}t.sendGameContext(n);}}function qh(t){return new Promise((e,n)=>{let r=false,i=setTimeout(()=>{r||(r=true,console.warn("[gem] onFeedbackContext did not answer within 1000ms; sending the report without context. Gather cheaply, or keep a snapshot."),e(null));},1e3);(async()=>t())().then(o=>{r||(r=true,clearTimeout(i),e(o??null));},o=>{r||(r=true,clearTimeout(i),n(o instanceof Error?o:new Error(String(o))));});})}var mu=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function gu(t=globalThis){let n=t[mu];if(n!==void 0)return n;let r=false,i=()=>r,o=Bh(t),s=[],a=Nh(t,i,o.watch);a!==null&&s.push(a);let l=jh(t,i,o.watch);l!==null&&s.push(l);let d={get muted(){return r},setMuted(u){let c=!!u;if(c!==r){r=c;for(let g of s)g();}},setPaused(u){o.setPaused(!!u);}};return Object.defineProperty(t,mu,{value:d,configurable:true}),d}function Nh(t,e,n){let r=t.AudioNode?.prototype,i=t.AudioDestinationNode;if(r===void 0||i===void 0)return null;let o=t.OfflineAudioContext,s=r.connect,a=r.disconnect,l=new Map,d=c=>{let g=c.gain,p=c.context.currentTime;g.cancelScheduledValues(p),e()?g.setValueAtTime(0,p):g.setTargetAtTime(1,p,.01);},u=c=>{let g=c.context;if(o!==void 0&&g instanceof o)return null;let p=l.get(g);return p===void 0&&(p=g.createGain(),p.gain.value=e()?0:1,s.call(p,c),l.set(g,p),n.context(g)),p};return r.connect=function(...g){let[p,...f]=g;if(p instanceof i){let y;try{y=u(p);}catch{y=null;}if(y!==null)return s.call(this,y,...f),p}return s.apply(this,g)},r.disconnect=function(...g){let[p,...f]=g;if(p instanceof i){let y=l.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...f)}catch{}}return a.apply(this,g)},()=>{for(let[c,g]of l){if(c.state==="closed"){l.delete(c);continue}try{d(g);}catch{}}}}function jh(t,e,n){let r=t.HTMLMediaElement;if(r===void 0)return null;let i=r.prototype,o=Object.getOwnPropertyDescriptor(i,"muted"),s=o?.get,a=o?.set;if(s===void 0||a===void 0)return null;let l=i.play,d=new WeakMap,u=new WeakSet,c=new Set,g=p=>{d.has(p)||d.set(p,!!s.call(p)),u.has(p)||(u.add(p),c.add(new WeakRef(p)),n.element(p)),a.call(p,(d.get(p)??false)||e());};return Object.defineProperty(i,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=d.get(this);return p===void 0?!!s.call(this):p},set(p){d.set(this,!!p),g(this);}}),i.play=function(){try{g(this);}catch{}return l.call(this)},t.document?.addEventListener("play",p=>{let f=p.target;if(f instanceof r)try{g(f);}catch{}},true),()=>{for(let p of c){let f=p.deref();if(f===void 0){c.delete(p);continue}try{a.call(f,(d.get(f)??!1)||e());}catch{}}}}var pu=["pointerup","touchend","click","keydown"];function Bh(t){let e=t.document,n=new Set,r=new WeakSet,i=new WeakSet,o=new Set,s=new WeakSet,a=new Set,l=new Set,d=false,u=false,c=t.AudioContext?.prototype,g=c?.suspend,p=c?.resume,f=c!==void 0&&typeof g=="function"&&typeof p=="function";f&&(c.suspend=function(...G){try{i.add(this);}catch{}return g.apply(this,G)},c.resume=function(...G){try{i.delete(this);}catch{}return p.apply(this,G)});let y=t.HTMLMediaElement?.prototype,S=y?.pause;y!==void 0&&typeof S=="function"&&(y.pause=function(){l.delete(this),S.call(this);});let b=x=>x.state!=="running"&&x.state!=="closed"&&r.has(x)&&!i.has(x),R=x=>x.state==="running"&&o.has(x)&&!i.has(x),h=x=>x.paused&&!x.ended,_=()=>{for(let x of n)if(x.state==="closed")n.delete(x),o.delete(x);else if(b(x)||R(x))return true;for(let x of l){if(h(x))return true;l.delete(x);}return false},I=()=>{for(let x of a){let G=x.deref();if(G===void 0){a.delete(x);continue}try{!G.paused&&!G.ended&&l.add(G);}catch{}}},T=()=>{if(u){u=false,l.clear();for(let x of pu)e?.removeEventListener?.(x,N,true);}},W=()=>{try{u&&!_()&&T();}catch{}};function N(){if(!u||d)return;let x=[];try{for(let G of n){if(G.state==="closed"){n.delete(G),o.delete(G);continue}if(b(G)){o.delete(G);try{x.push(Promise.resolve(p?.call(G)));}catch{}}else if(R(G)){o.delete(G);try{x.push(Promise.resolve(g?.call(G))),s.add(G),x.push(Promise.resolve(p?.call(G)));}catch{}}}for(let G of l){if(!h(G)){l.delete(G);continue}try{x.push(Promise.resolve(G.play()).then(()=>l.delete(G),ne=>{ne?.name!=="NotAllowedError"&&l.delete(G);}));}catch{l.delete(G);}}}catch{}if(x.length===0){W();return}Promise.allSettled(x).then(W);}let U=()=>{if(!(u||e===void 0)){u=true;for(let x of pu)e.addEventListener(x,N,true);}},C=()=>{I(),e?.visibilityState!=="hidden"&&U();},L=()=>{for(let x of n)x.state!=="closed"&&r.has(x)&&o.add(x);U();},D=()=>{o.clear(),I();};try{e?.addEventListener("visibilitychange",()=>{try{e.visibilityState==="hidden"?D():L();}catch{}},!0),t.addEventListener?.("pagehide",()=>{try{D();}catch{}}),t.addEventListener?.("pageshow",x=>{try{x.persisted&&L();}catch{}});}catch{}return {watch:{context(x){if(f)try{n.add(x),(x.state==="running"||x.currentTime>0)&&r.add(x),x.addEventListener("statechange",()=>{try{let G=x.state;G==="running"?(r.add(x),s.delete(x),o.has(x)&&U(),W()):G!=="closed"&&r.has(x)&&!i.has(x)&&!s.has(x)&&C();}catch{}});}catch{}},element(x){try{a.add(new WeakRef(x));}catch{}}},setPaused(x){d=x;}}}var Uh=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Wh=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Hh=`${Uh}${Wh}`,Ra=new WeakSet;function fu(t=globalThis.document){if(t==null||Ra.has(t))return null;try{let e=t.defaultView?.CSSStyleSheet??globalThis.CSSStyleSheet;if(Array.isArray(t.adoptedStyleSheets)&&typeof e=="function"){let r=new e;if(typeof r.replaceSync=="function")return r.replaceSync(Hh),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],Ra.add(t),"sheet"}let n=t.documentElement?.style;return n===void 0||typeof n.setProperty!="function"?null:(n.setProperty("-webkit-user-select","none"),n.setProperty("user-select","none"),n.setProperty("-webkit-tap-highlight-color","transparent"),Ra.add(t),"inline")}catch{return null}}function yu(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=t.now??(()=>globalThis.performance?.now()??Date.now()),i=false,o=false,s=false,a=null,l=null,d=null,u=[],c=false,g=0,p=null,f=[],y=()=>i&&!o&&!s,S=()=>{l=null,d=null,u=[],g=0,p=null,f=[];},b=_=>{if(a=null,!y()){S();return}if(d!==null&&u.push(_-d),d=_,l===null)l=_;else {let I=_-l;if(I>=e&&u.length>0){if(c){let T=p===null?I:r()-p;t.report(Kh(g,f,I,T));}else t.report(Vh(u,I));l=_,u=[],g=0,f=[];}}R();},R=()=>{let _=n.requestAnimationFrame;typeof _=="function"&&(a=_.call(n,b));},h=()=>{if(y()){a===null&&(S(),R());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),S();};return {setRequested(_){i=_,h();},setPaused(_){o=_,h();},draw(){if(!c){c=true,a!==null&&S();return}if(a===null||l===null)return;let _=r();p!==null&&f.length<1e3&&f.push(_-p),p=_,g+=1;},get running(){return a!==null},dispose(){s=true,h();}}}function Vh(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:hu(t),counts:"pageFrames"}}function Kh(t,e,n,r){let i=r;return e.length>0&&(i=hu(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:i,counts:"gameDraws"}}function hu(t){let e=[...t].sort((r,i)=>r-i),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var gi=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function bu(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function vu(t,e){t!==null&&(t.style.setProperty(gi.top,`${e.top}px`),t.style.setProperty(gi.right,`${e.right}px`),t.style.setProperty(gi.bottom,`${e.bottom}px`),t.style.setProperty(gi.left,`${e.left}px`));}var fi=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height",centerY:"--gem-reserved-tl-center-y",controlHeight:"--gem-reserved-tl-control-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height",centerY:"--gem-reserved-tr-center-y",controlHeight:"--gem-reserved-tr-control-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height",centerY:"--gem-reserved-bl-center-y",controlHeight:"--gem-reserved-bl-control-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height",centerY:"--gem-reserved-br-center-y",controlHeight:"--gem-reserved-br-control-height"}});function _u(){let t=globalThis,e=t.innerWidth,n=t.innerHeight;return typeof e=="number"&&e>0&&typeof n=="number"&&n>0?{width:e,height:n}:null}function Jh(t,e){let n={tl:{width:0,height:0,control:null},tr:{width:0,height:0,control:null},bl:{width:0,height:0,control:null},br:{width:0,height:0,control:null}};for(let r of t){let i=e?r.x+r.width/2<=e.width/2:r.x===0,o=e?r.y+r.height/2<=e.height/2:r.y===0,s=i?r.x+r.width:e?e.width-r.x:r.width,a=o?r.y+r.height:e?e.height-r.y:r.height,l=n[`${o?"t":"b"}${i?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));let d=r.control;if(d){let u=l.control;l.control=u?{top:Math.min(u.top,d.y),bottom:Math.max(u.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function wu(t,e,n){if(t===null)return;let r=Jh(e,n);for(let i of ["tl","tr","bl","br"]){t.style.setProperty(fi[i].width,`${r[i].width}px`),t.style.setProperty(fi[i].height,`${r[i].height}px`);let o=r[i].control;t.style.setProperty(fi[i].centerY,o?`${(o.top+o.bottom)/2}px`:""),t.style.setProperty(fi[i].controlHeight,o?`${o.bottom-o.top}px`:"");}}var zh=3e4,yi=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function Su(t){let e=t.clock??ce,n=t.timeoutMs??zh,r=new Map,i=new Map,o=0,s=a=>{let l=r.get(a);return l?(r.delete(a),i.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(a){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=i.get(a);if(l)return l;let d=new Promise((u,c)=>{let g=`ls${++o}`,p=e.setTimeout(()=>{r.delete(g),i.delete(a),c(new yi("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(n)}ms`));},n);r.set(g,{room:a,resolve:u,reject:c,timer:p}),t.bridge.requestLocalServer(g,a)||(s(g),u());});return i.set(a,d),d.catch(()=>{}),d},accept(a){s(a.requestId)?.resolve();},refuse(a){let l=s(a.requestId);l&&l.reject(new yi(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 $n={url:"https://downloads.indiegems.games/sdk/v21.1.1/gem-web-sdk.devtools.min.js",integrity:"sha384-W8zfIPY1bG8lSS3+/gSJ5SWOO8HBiojkxCPsVo4oKdGjzi8A7SsWnR9S7wer3vPe"};var Bt=null;function Xh(){return Bt!==null||(Bt=new Promise((t,e)=>{let n=document.createElement("script");n.src=$n.url,n.integrity=$n.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Bt=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${$n.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{Bt=null,e(new Error(`gem devtools: could not load ${$n.url}. Either the network refused it or its Subresource Integrity check failed, or the CDN did not answer the CORS preflight this request needs \u2014 SRI is only checkable on bytes the page may read. A locally rebuilt SDK is the commonest cause: it produces panel bytes that do not match the hash compiled into this build.`));},document.head.append(n);})),Bt}function Ru(t,e){let n=null,r=0;async function i(o){if(n!==null)return true;let s=++r;if(!e())return false;let a=await Xh();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:o,text:st,onDismiss:()=>{n?.unmount(),n=null;}})),true)}return {get isOpen(){return n!==null},close(){r+=1,n?.unmount(),n=null;},open:()=>i("game"),openFrom:i}}var Yh=1e4,ku={reason:"unavailable",retryable:false};function Au(t){let e=new Map,n=null,r=null,i=0,o=(d,u)=>{u.timer=t.clock.setTimeout(()=>{e.delete(d),u.reject({reason:"timeout",retryable:true});},t.timeoutMs??Yh);},s=(d,u)=>{let c=a(d);c&&u(c);},a=d=>{let u=e.get(d);return u?(e.delete(d),t.clock.clearTimeout(u.timer),u):null},l=new kt({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((u,c)=>{let g=t.bridge.currentState;if(g==="refused"||g==="closed"){c(ku);return}let p=`t${++i}`,f={resolve:u,reject:c,reason:d,timer:null,held:g!=="connected"};e.set(p,f),o(p,f),f.held||t.bridge.requestToken(p,d);})});return {source:l,onToken(d){let u={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){s(d.requestId,c=>c.resolve(u));return}l.accept(u);},onDenied(d){s(d.requestId,u=>u.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[u,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),o(u,c),t.bridge.requestToken(u,c.reason));else if(d==="refused"||d==="closed")for(let u of [...e.keys()])s(u,c=>c.reject(ku));},get identity(){return n},get gameVersion(){return r}}}var Qh=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Aa="embedder_relay_unavailable",Zh="embedder_no_relay",eb=new Set([Aa]),xa=new Set([Zh]),Fn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new ka(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new A("match_ended",`the match ended while the offer was in flight (${e.reason??"no reason given"}), so no server is left to answer it`));return}if(e.event==="answer"){if(typeof e.sdp!="string"||e.sdp.length===0){n.refuse(new A("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(tb(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new A("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,n);}release(e,n){this.pending.get(e)===n&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new A("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new A("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function tb(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new A(nb(t),r,{platformCode:t})}function nb(t){return t===void 0||eb.has(t)?"signaling_failed":xa.has(t)?"offer_refused":Qh.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var ka=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new A("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return n?.aborted?Promise.reject(new A("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new A("aborted","the caller aborted the signaling exchange"));},a=()=>{n?.removeEventListener("abort",s),this.hub.release(e.matchId,l),this.teardown===a&&(this.teardown=null);},l={settle:d=>{a(),i(d);},refuse:d=>{a(),o(d);}};this.teardown=a,n?.addEventListener("abort",s),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof A?d:new A("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var xu="match_ended:",Pu="server_shutdown:",Eu="kicked:",rb=123;function ib(t){if(typeof t!="string"||t.length===0||t.length>rb)return {kind:"other"};if(t.startsWith(xu)){let e=Ze(t.slice(xu.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Pu)?{kind:"server_shutdown",cause:t.slice(Pu.length)}:t.startsWith(Eu)?{kind:"kicked",detail:t.slice(Eu.length)}:{kind:"other"}}function Pa(t,e,n){let r=ib(n),i=r.kind==="kicked"?"kicked":"link_closed";t.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&t.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function Ea(){return {exchange(){return Promise.reject(new A("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See docs/dedicated-server-flow.md \xA72."))},close(){}}}var ob=3e3,ab=1e4,sb=15e3;async function hi(t){let e=t.peerConnection;try{Iu(t,"before the handshake started"),Ta(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let s of t.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});t.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await cb(e,t),Ta(t);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new A("invalid_sdp","the offer carried no SDP");Ue(i,"offer"),Tu(i,"offer");let o=await db(t,i);if(Ta(t),typeof o?.sdp!="string")throw new A("invalid_sdp","the signaling channel answered without an SDP");return Ue(o.sdp,"answer"),Tu(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await ub(n,t),Iu(t,"before the channel opened"),n}catch(n){throw e.close(),lb(n)}}function lb(t){return t instanceof A?t:Ou(t)?ft():new A("connection_failed",Gu(t),{cause:t})}function Tu(t,e){if(ai(t))throw new A("media_refused",`the ${e} carries an active audio or video section. This path carries a data channel only; voice belongs to the platform voice service.`)}async function db(t,e){let n=t.exchangeTimeoutMs??ab,r=Mu(t,n),i=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(o=>{throw o instanceof A?o:Ou(o)?ft():new A("signaling_failed",Gu(o),{cause:o})});return mb(i,t,r,()=>r.exhausted?Ia("while the offer was in flight"):new A("timeout",`no answer arrived within ${n}ms`))}function cb(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let i=()=>{n.clearTimeout(s),t.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{t.iceGatheringState==="complete"&&i();},s=n.setTimeout(i,e.gatherTimeoutMs??ob);t.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function ub(t,e){if(e.signal?.aborted)return Promise.reject(ft());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new A("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??sb,i=Mu(e,r);return new Promise((o,s)=>{let a=()=>{n.clearTimeout(g),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",u);},l=()=>{a(),o();},d=p=>{a(),s(new A("connection_failed","the data channel failed before it opened",Cu(p)===void 0?void 0:{cause:Cu(p)}));},u=()=>{a(),s(ft());},c=()=>{a(),s(i.exhausted?Ia("while the channel was still opening"):new A("timeout",`the data channel did not open within ${r}ms`));},g=n.setTimeout(c,i.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",u);})}function Mu(t,e){if(t.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let n=t.credentialExpiresAt-t.clock.now();return n<=e?{ms:Math.max(0,n),exhausted:true}:{ms:e,exhausted:false}}function mb(t,e,n,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(ft()):new Promise((s,a)=>{let l=c=>{i.clearTimeout(u),o?.removeEventListener("abort",d),c();},d=()=>l(()=>a(ft())),u=i.setTimeout(()=>l(()=>a(r())),n.ms);o?.addEventListener("abort",d),t.then(c=>l(()=>s(c)),c=>l(()=>a(c)));})}function Iu(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw Ia(`already ${e}`)}function Ia(t){return new A("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function Ta(t){if(t.signal?.aborted)throw ft()}function ft(){return new A("aborted","the caller aborted the connection attempt")}function Ou(t){return t?.name==="AbortError"}function Cu(t){return t?.error}function Gu(t){return t instanceof Error?t.message:String(t)}Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"}));Object.freeze(Object.assign(Object.create(null),{answer:[J("sdp","sdp",K(10240)),z("sessionId","session_id",K(64))],error:[z("code","code",K(64)),z("message","message",K(256))],matchEnded:[z("reason","reason",K(64))]}));function Bu(t){let{client:e,clock:n,rooms:r}=t,i=t.signaling??Ea,o=t.log??(h=>console.warn(h)),s=new Dt({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(h,_)=>{let I=a.get(h)??new Set;I.add(_),a.set(h,I);},d=(h,_)=>{let I=a.get(h);I!==void 0&&(I.delete(_),I.size===0&&a.delete(h));},u=async h=>{if(r.isHost&&!Ma(r)&&r.currentRoom?.matchId===void 0){let _=Se(h.clusterTargetId);await r.startMatch({..._===void 0?{}:{clusterTargetId:_},...h.retry===void 0?{}:{retry:h.retry},...h.signal===void 0?{}:{signal:h.signal}});}return Nu(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Ca(h)):await r.awaitMatch(Ca(h)))},c=async h=>Nu(await r.pollMatchStatus(Ca(h))),g=async(h,_)=>{let I=false;try{let T=await u(h),W=r.currentRoom?.transports;if(W!==void 0&&!W.includes("webrtc"))throw new A("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 N=h.peerConnection??ju();I=!0;let U=await hi({peerConnection:N,signaling:_,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...bi(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),C=null;if(h.presentCredential!==!1)try{C=await bn({channel:U,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...bi(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(L){throw Ie(U),Ie(N),L}return wb(r,T,U,N,_,h.reportDisconnect!==!1,h.reportConnected!==!1,C,{remember:l,forget:d},h.onMatchEnded)}catch(T){throw I&&qu(s,T),Ie(_),T}},p=async(h,_,I,T,W,N)=>{if(h==="webtransport"){let x=T?.webtransport;if(x===void 0)throw new A("misconfigured","webtransport is not advertised");let G={credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n};if(typeof x.named_url=="string"&&x.named_url!==""){let ne=Math.max(Math.floor(N/2),1e3);try{return await Sn({url:x.named_url,timeoutMs:ne,log:o,...G})}catch(fe){if(Qr()!==null)throw fe;return o(`[gem] webtransport named dial failed (${Xr(fe)}); retrying the pinned dial`),Sn({url:x.url,certHashBase64:x.cert_sha256_b64,timeoutMs:ne,log:o,...G})}}return Sn({url:x.url,certHashBase64:x.cert_sha256_b64,timeoutMs:N,...G})}if(h==="websocket"){let x=T?.websocket;if(x===void 0)throw new A("misconfigured","websocket is not advertised");return jo({url:x.url,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n,timeoutMs:N})}let U=_.peerConnection??ju(),C,L=await hi({peerConnection:U,signaling:W,clock:n,matchId:I.matchId,credentialExpiresAt:I.credentialExpiresAt,extraChannels:[{label:_n,ordered:false,maxRetransmits:0}],onExtraChannel:(x,G)=>{x===_n&&(C=G);},...bi(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),..._.exchangeTimeoutMs===void 0&&_.redial===true?{exchangeTimeoutMs:fb}:{}}),D;try{D=await bn({channel:L,clock:n,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,wire:zr,heartbeat:!0,...bi(_,"signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(x){throw Ie(L),Ie(U),x}let H=D.welcome.heartbeatIntervalMs;return {link:Uo(L,U,C,H===void 0?void 0:{clock:n,intervalMs:H}),welcome:D.welcome,channel:L,peerConnection:U}},f=(h,_,I,T,W)=>{let N=false,U;T.link.onClose(H=>{!N&&h.reportDisconnect!==false&&Pa(r,_.matchId,H),U?.(H);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(_.matchId);let C={transport:T.link.transport,send:(H,x)=>T.link.send(H,x),onMessage:H=>T.link.onMessage(H),onClose:H=>{U=H;},close:()=>T.link.close()},L=()=>{N||(N=true,Ie(T.link),Ie(W));},D=H=>{if(!N){try{h.onMatchEnded?.(H);}catch{}L();}};return l(_.matchId,D),{matchId:_.matchId,transport:I,link:C,joinCredential:_.joinCredential,credentialExpiresAt:_.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(_.matchId,D),L();}}},y=async(h,_)=>{let I=r.currentRoom?.id,T=r.gameId,W=()=>({advert:wn(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(I===void 0||T===null)return W();try{let N=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(I)}`,_);return {advert:wn(N.settings,h),template:Gt(N.transports)??r.currentRoom?.transports??null}}catch{return W()}},S=(h,_)=>{let I=h??Lu;return _.length===0?I:I.filter(T=>_.includes(T))},b=async(h,_,I)=>{try{let T=await u(h),{advert:W,template:N}=await y(T.matchId,h.signal),U=S(N,_),C=U.filter(Q=>bb(Q,W)),L=Qr();if(L!==null&&U.includes("webtransport")&&W?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${L} (learned on an earlier dial in this page)`),C.length===0){let Q=N===null?`the default order (${Lu.join(", ")})`:`the room template's transports (${N.join(", ")||"none"})`;throw new A("misconfigured",`none of ${Q}`+(_.length>0?`, narrowed to (${_.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let D=h.transportAttemptTimeoutMs??gb,H=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-n.now(),x=Q=>t.signalingReady===void 0||Q<=0?Promise.resolve(!0):t.signalingReady(Q),G=[],ne=[];for(let Q of C){if(H()<$u){o(`[gem] ${Q} rung not tried: the reconnect budget is spent`);break}ne.length>0&&T.credentialExpiresAt-n.now()<Fu&&(T=await c(h)),ne.push(Q);let Pe=!1,we=!1,Ce={attempts:0,waitedMs:0};for(;;){if(Q==="webrtc"&&h.redial===!0){let te=Math.min(Du,H());await x(te)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(te)}ms; offering anyway`);}let ke=Math.max(Math.min(D,H()),$u);try{return f(h,T,Q,await p(Q,h,T,W,I,ke),I)}catch(te){let X=te instanceof A?te:new A("connection_failed",te instanceof Error?te.message:String(te),{cause:te});if(Q==="webrtc"&&qu(s,X),(X.reason==="credential_expired"||X.reason==="credential_reused")&&!Pe){Pe=!0,T=await c(h);continue}if(Q==="webrtc"&&X.reason==="signaling_failed"&&X.platformCode===Aa&&!we){we=!0;let ae=Math.min(Du,H());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ae)}ms for the socket before offering again`),await x(ae))continue}if(X.reason==="join_rate_limited"){let ae=hb(Ce,Math.random,H());if(ae!==null){if(Ce.attempts+=1,Ce.waitedMs+=ae,o(`[gem] ${Q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ae)}ms before presenting again (retry ${Ce.attempts} of ${Wu.maxAttempts})`),await Hr(n,ae,h.signal),h.signal?.aborted)throw new A("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<Fu&&(T=await c(h));continue}}if(yb.has(X.reason)||X.reason==="credential_expired"||Q==="webrtc"&&Uu(X)){o(`[gem] ${Q} rung failed (${X.reason}): ${Xr(X.cause??X)} \u2014 `+(ne.length<C.length?`falling through to ${C[ne.length]}`:"no rungs left")),G.push(X);break}throw o(`[gem] ${Q} rung refused the session (${X.reason}): ${X.message}`),X}}}let fe=G[G.length-1];throw fe===void 0?new A("timeout",`the reconnect budget ran out before any transport (${C.join(", ")}) could be tried`):new A(fe.reason,`every transport tried (${ne.join(", ")}) failed; the last said: ${fe.message}`,{cause:G,platformCode:fe.platformCode})}catch(T){throw Ie(I),T}};return {listClusterTargets:async(h={})=>xo({client:e,...h}),handleMatchEnded(h,_){let I=a.get(h);if(I!==void 0){a.delete(h);for(let T of I)T(_);}},connect:(async(h={})=>{let _=h.signaling??i();return h.transports===void 0?g(h,_):b(h,h.transports,_)})}}var Lu=["webtransport","webrtc","websocket"],gb=1e4,fb=5e3,Du=3e3,$u=1e3,Fu=1e4,yb=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Uu(t){return t.platformCode!==void 0&&xa.has(t.platformCode)}var Wu={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function hb(t,e=Math.random,n=1/0){let r=Wu;if(t.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-t.waitedMs,n);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**t.attempts;return Math.min(o+e()*r.jitterMs,i)}function bb(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Yr():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||vb(e.websocket.url)}function vb(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return Xe(e)}function Ca(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var _b=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function qu(t,e){e instanceof A&&(!_b.has(e.reason)&&!Uu(e)||t.report([{type:"connection_failures_total",value:1}]));}function wb(t,e,n,r,i,o,s,a,l,d){let u=false,c=()=>{u||Pa(t,e.matchId,void 0);};o&&(n.addEventListener("close",c),s&&t.notifyMatchConnected(e.matchId));let g=()=>{u||(u=true,n.removeEventListener("close",c),a?.detach(),Ie(n),Ie(r),Ie(i));},p=f=>{if(!u){try{d?.(f);}catch{}g();}};return l.remember(e.matchId,p),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,p),g();}}}function Ma(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Nu(t){if(t.status==="failed")throw new A("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new A("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==Wr)throw new A("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Wr}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:n}=t;if(e===void 0||n===void 0)throw new A("connection_failed",`match ${t.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...t,joinCredential:e,credentialExpiresAt:n}}function ju(){let t=globalThis.RTCPeerConnection;if(!t)throw new A("misconfigured","this environment has no RTCPeerConnection. Pass `peerConnection` to connect against a stand-in, which is how the flow is tested outside a browser.");return new t({iceServers:[]})}function Ie(t){try{t.close();}catch{}}function bi(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var Sb=1e4;function Hu(t,e){return Oa(t,e)}function Oa(t,e){if(typeof t.serverToken!="function"||typeof t.onServerToken!="function")throw new Error("this runtime delivers no game-server token: host.serverToken/onServerToken are missing. The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let n=s=>({token:s.token,expiresAt:s.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,i=new kt({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??Sb);r={resolve:d=>{e.clock.clearTimeout(l),s(d);},reject:a,timer:l};})}),o=t.onServerToken(s=>{let a=n(s),l=r;if(l){r=null,l.resolve(a);return}i.accept(a);});return {source:i,dispose(){o(),i.dispose(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var La={};xp(La,{acceptTransfer:()=>Rb,addEntityProgression:()=>kb,adminAction:()=>Ab,cancelInventoryTransfer:()=>xb,claimEntityProgressionRewards:()=>Pb,closeGameRoom:()=>Eb,createEntityBatchOrder:()=>Tb,createEntityOrder:()=>Ib,createSession:()=>Cb,deleteEntityGameSetting:()=>Mb,deleteEntitySave:()=>Ob,deleteSession:()=>Gb,deleteShowcaseValue:()=>Lb,executeEntityRecipe:()=>Db,finalizeSaveUpload:()=>$b,getChannelAssignment:()=>Fb,getDropRates:()=>qb,getEntityCurrency:()=>Nb,getEntityGameSetting:()=>jb,getEntityInventory:()=>Bb,getEntityInventoryItem:()=>Ub,getEntityLeaderboard:()=>Wb,getEntityOrder:()=>Hb,getEntityProgression:()=>Vb,getEntityRecipeAvailability:()=>Kb,getEntityRecipeUsage:()=>Jb,getEntitySave:()=>zb,getEvent:()=>Xb,getGameRoomV2:()=>Yb,getLeaderboard:()=>Qb,getPlayerGameProfile:()=>Zb,getPurchaseCatalog:()=>ev,getResolvedTemplate:()=>tv,getRoomArgs:()=>nv,getShowcaseValue:()=>rv,getTransferDetails:()=>iv,ingestAnalyticsEvents:()=>Ga,initiateInventoryTransfer:()=>ov,invokeFunction:()=>av,kickPlayer:()=>sv,listChallenges:()=>lv,listEntityGameSettings:()=>dv,listEntityOrders:()=>cv,listEntityProgressions:()=>uv,listEntitySaves:()=>mv,listEvents:()=>pv,listGameRooms:()=>gv,listResolvedTemplates:()=>fv,listTransfers:()=>yv,maxEntityProgression:()=>hv,putEntityGameSetting:()=>bv,putRoomArgs:()=>vv,putShowcaseValue:()=>_v,rejectTransfer:()=>wv,reportMatchPlayers:()=>Sv,requestSaveUploadUrl:()=>Rv,resetEntityProgression:()=>kv,setMatchBackfill:()=>Av,simulateEntityOrder:()=>xv,transferHostV2:()=>Pv,updateGameRoomV2:()=>Ev});function w(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function Rb(t,e,n){let r=`/v1/inventory/transfers/${w(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function kb(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}/add`;return t.client.post(s,i,o?.signal)}async function Ab(t,e,n,r){let i=`/v1/voice/sessions/${w(e)}/admin`;return t.client.post(i,n,r?.signal)}async function xb(t,e,n){let r=`/v1/inventory/transfers/${w(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Pb(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}/claim`;return t.client.post(s,i,o?.signal)}async function Eb(t,e,n){let r=`/v1/games/${w(t.gameId())}/game-rooms/${w(e)}`;return t.client.delete(r,n?.signal)}async function Tb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Ib(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Cb(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Mb(t,e,n,r,i){let o=`/v1/settings/${w(e)}/${w(n)}/${w(r)}`;return t.client.delete(o,i?.signal)}async function Ob(t,e,n,r,i){let o=`/v1/saves/${w(e)}/${w(n)}/${w(r)}`;return t.client.delete(o,i?.signal)}async function Gb(t,e,n){let r=`/v1/voice/sessions/${w(e)}`;return t.client.delete(r,n?.signal)}async function Lb(t,e,n,r){let i=`/v1/showcase/players/${w(e)}/${w(n)}`;return t.client.delete(i,r?.signal)}async function Db(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function $b(t,e,n,r,i,o){let s=`/v1/saves/${w(e)}/${w(n)}/${w(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function Fb(t,e,n){let r=`/v1/games/${w(t.gameId())}/config/channels/${w(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function qb(t,e,n){let r=`/v1/inventory/loot-tables/${w(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Nb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/currencies/${w(r)}`;return t.client.get(o,i?.signal)}async function jb(t,e,n,r,i){let o=`/v1/settings/${w(e)}/${w(n)}/${w(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Bb(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${w(e)}/${w(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Ub(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/items/${w(r)}`;return t.client.get(o,i?.signal)}async function Wb(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${w(e)}/${w(n)}/${w(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function Hb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/orders/${w(r)}`;return t.client.get(o,i?.signal)}async function Vb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}`;return t.client.get(o,i?.signal)}async function Kb(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/catalogs/${w(r)}/recipes/${w(i)}/availability`;return t.client.get(s,o?.signal)}async function Jb(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${w(e)}/${w(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function zb(t,e,n,r,i){let o=`/v1/saves/${w(e)}/${w(n)}/${w(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Xb(t,e,n){let r=`/v1/events/${w(e)}`;return t.client.get(r,n?.signal)}async function Yb(t,e,n){let r=`/v2/games/${w(t.gameId())}/game-rooms/${w(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Qb(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${w(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function Zb(t,e,n){let r=`/v1/profiles/players/${w(e)}`;return t.client.get(r,n?.signal)}async function ev(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function tv(t,e,n){let r=`/v1/game-room-templates/${w(e)}`;return t.client.get(r,n?.signal)}async function nv(t,e,n){let r=`/v1/games/${w(t.gameId())}/game-rooms/${w(e)}/room-args`;return t.client.get(r,n?.signal)}async function rv(t,e,n,r){let i=`/v1/showcase/players/${w(e)}/${w(n)}`;return t.client.get(i,r?.signal)}async function iv(t,e,n){let r=`/v1/inventory/transfers/${w(e)}`;return t.client.get(r,n?.signal)}async function Ga(t,e,n){let r=`/v1/games/${w(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function ov(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function av(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function sv(t,e,n,r){let i=`/v1/games/${w(t.gameId())}/game-rooms/${w(e)}/kick/${w(n)}`;return t.client.post(i,void 0,r?.signal)}async function lv(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function dv(t,e,n,r){let i=`/v1/settings/${w(e)}/${w(n)}`;return t.client.get(i,r?.signal)}async function cv(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${w(e)}/${w(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function uv(t,e,n,r){let i=`/v1/inventory/${w(e)}/${w(n)}/progressions`;return t.client.get(i,r?.signal)}async function mv(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${w(e)}/${w(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function pv(t,e){let n=new URLSearchParams;e?.include_inactive!==void 0&&n.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.offset!==void 0&&n.set("offset",String(e?.offset));let r=n.toString(),i="/v1/events"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function gv(t,e){let n=new URLSearchParams;e?.status!==void 0&&n.set("status",String(e?.status)),e?.game_channel!==void 0&&n.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&n.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&n.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&n.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),i=`/v1/games/${w(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function fv(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function yv(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function hv(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}/max`;return t.client.post(s,i,o?.signal)}async function bv(t,e,n,r,i,o){let s=`/v1/settings/${w(e)}/${w(n)}/${w(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function vv(t,e,n,r){let i=`/v1/games/${w(t.gameId())}/game-rooms/${w(e)}/room-args`;return t.client.put(i,n,r?.signal)}async function _v(t,e,n,r,i){let o=`/v1/showcase/players/${w(e)}/${w(n)}`;return t.client.put(o,r,i?.signal)}async function wv(t,e,n){let r=`/v1/inventory/transfers/${w(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Sv(t,e,n,r){let i=`/v1/games/${w(t.gameId())}/matches/${w(e)}/players/report`;return t.client.post(i,n,r?.signal)}async function Rv(t,e,n,r,i,o){let s=`/v1/saves/${w(e)}/${w(n)}/${w(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function kv(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}/reset`;return t.client.post(s,i,o?.signal)}async function Av(t,e,n,r){let i=`/v1/games/${w(t.gameId())}/matches/${w(e)}/backfill`;return t.client.put(i,n,r?.signal)}async function xv(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/orders/simulate`;return t.client.post(o,r,i?.signal)}async function Pv(t,e,n,r){let i=`/v2/games/${w(t.gameId())}/game-rooms/${w(e)}/transfer/${w(n)}`;return t.client.post(i,void 0,r?.signal)}async function Ev(t,e,n,r){let i=`/v2/games/${w(t.gameId())}/game-rooms/${w(e)}`;return t.client.patch(i,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Tv=1e4,Iv=50,Cv=1e3,Mv=65536-4*1024,Vu=t=>typeof t=="number"?t:0,Ov=t=>typeof t=="string"?t:"";function Ku(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.floor(Math.random()*16);return (e==="x"?n:n&3|8).toString(16)})}function Gv(t){return t?.retryable===true}function Lv(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:Vu(o.index),code:Ov(o.code)}}):[];return {accepted:Vu(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Ju(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,player_id:t.playerId,dimensions:t.dimensions,measures:t.measures}}function zu(t){let e=Math.max(1,Math.floor(t.maxQueue??Cv)),n={client:t.client,gameId:()=>t.gameId},r=[],i=0,o=null,s=false,a=null,l=0,d=0,u=false,c=false,g=h=>{t.log?.(h);},p=()=>{o!==null&&(t.clock.clearTimeout(o),o=null);},f=()=>Math.max(0,d-t.clock.now()),y=()=>{o!==null||s||a!==null||(o=t.clock.setTimeout(()=>{o=null,b().catch(()=>{});},Math.max(Tv,f())));},S=()=>{let h=Math.min(r.length,100),_=128;for(let I=0;I<h;I+=1){let T=r[I];if(T===void 0)break;if(_+=JSON.stringify(Ju(T,0)).length+1,_>Mv)return Math.max(1,I)}return h};async function b(h){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let _=R(h);a=_;try{return await _}finally{a===_&&(a=null),r.length>0&&y();}}async function R(h){p();let _=r.splice(0,S()),I=i;i=0;let T=Math.round(t.clock.now()),W={batch_id:Ku(),sent_at_ms:T,events:_.map(N=>Ju(N,T))};try{let N=await Ga(n,W,h===void 0?void 0:{signal:h}),U=Lv(N,I);l=0,d=0;for(let C of U.rejected)g(`[gem] analytics: an event was refused (${C.code}). See the analytics_events section of your game config.`);return U}catch(N){if(Gv(N)){for(r=[..._,...r],i+=I;r.length>e;)r.shift(),i+=1;l+=1,d=t.clock.now()+jr(l,N);}else g(`[gem] analytics: ${_.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(N)}`);throw N}}return {track(h,_,I={}){if(s)return;if(typeof h!="string"||h===""){c||(c=true,g(`[gem] analytics: '${_}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(_.startsWith(fo)){u||(u=true,g(`[gem] analytics: '${_}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let T={},W={};for(let[N,U]of Object.entries(I))typeof U=="string"?T[N]=U:typeof U=="number"&&Number.isFinite(U)&&(W[N]=U);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:Ku(),playerId:h,name:_,atMs:t.clock.now(),dimensions:T,measures:W}),r.length>=Iv&&a===null&&f()===0?b().catch(()=>{}):y();},flush:h=>b(h),get pending(){return r.length},dispose(){s=true,p(),r=[],i=0;}}}function Xu(t){return {async list(e){let{playerId:n,periodsBack:r,signal:i}=e??{};if(typeof n!="string"||n==="")throw new TypeError("gem.challenges.list needs { playerId }: a game-server token names no player, so the platform cannot tell whose period you mean. Pass the id from join() or gem.players().");It(r);let o=await t({player_id:n,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return Lr(o)}}}function Dv(t){let e={};for(let[n,r]of Object.entries(La))if(typeof r=="function"){let i=r;e[n]=(...o)=>i(t,...o);}return e}function Ut(t,e={}){let n=e.clock??ce,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let i=Oa(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=kr({baseUrl:r,tokenSource:i.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new Je({transport:o,clock:n}),a={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=Dv({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,u=t.endMatch,c=t.log,g=zu({client:s,clock:n,gameId:a.gameId,...typeof c=="function"?{log:f=>c.call(t,f)}:{}});return {identity:a,client:s,api:l,match:{end:async()=>{if(u===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await u.call(t);},setBackfill:async(f,y)=>{let S=await l.setMatchBackfill(a.matchId,{open:f.open,...f.seats===void 0?{}:{seats:f.seats}},y===void 0?{}:{signal:y});return {open:S.open,seats:S.seats??null}},reportPlayers:async(f,y)=>(await l.reportMatchPlayers(a.matchId,{players:f.map(b=>({player_id:b.playerId,state:b.state}))},y===void 0?{}:{signal:y})).players.map(b=>({playerId:b.player_id,outcome:b.outcome}))},analytics:g,functions:new Qe(l.invokeFunction),challenges:Xu(l.listChallenges),...d===void 0?{}:{room:{get:f=>l.getGameRoomV2(d,f),args:async f=>{let y=await l.getGameRoomV2(d,f?.signal===void 0?{}:{signal:f.signal}),S=y.modified?y.body:void 0;if(S?.room_args==null||S.room_args_template==null)throw new O("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:S.room_args,room_args_template:S.room_args_template}}}},dispose:()=>{g.dispose(),i.dispose();}}}function yt(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function Wt(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function qn(t){return typeof t=="string"?t:t.slice().buffer}function vi(t){if(typeof t=="string")return {data:t,isText:true};if(t instanceof ArrayBuffer)return {data:new Uint8Array(t),isText:false};if(ArrayBuffer.isView(t)){let e=t;return {data:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),isText:false}}return null}var $v=5e3,Yu=3e4,Qu=2e3,Fv=1e4,qv=3,Zu=1;async function em(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let i=e.log===void 0?v=>console.info(v):e.log,o=v=>i?.(`[gem host] ${v}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,u=(v,M)=>{l&&(a=a.then(async()=>{if(!d)try{await M();}catch(B){o(`the bundle's ${v} handler threw: ${ht(B)}. Serving continues.`);}}));},c=true,g,p,f,y=v=>{if(!c)return;c=false,u("leave",()=>s.leave?.(r,{cause:v??"left"}));let M=p;M&&queueMicrotask(()=>M(v));},S={send(v,M){if(!c)return;let B=Wt(yt(M));u("message",()=>s.message?.(r,v,typeof v=="string",{reliable:B.reliable,ordered:B.ordered}));},onMessage(v){g=v;},onClose(v){p=v;},close(){y("closed");}},b=(v,M)=>{if(!c)return;let B=Wt(yt(M));queueMicrotask(()=>{c&&g?.(v,B);});},R=new Map,h=v=>{let M=[];for(let B of We){let Z=v.channels[B];try{Z.binaryType="arraybuffer";}catch{}let be=Wt(B),Jn=Ke=>{let rt=vi(Ke?.data);rt!==null&&u("message",()=>s.message?.(v.playerId,rt.data,rt.isText,{reliable:be.reliable,ordered:be.ordered}));};Z.addEventListener("message",Jn),M.push(()=>Z.removeEventListener("message",Jn));}R.get(v.playerId)?.forEach(B=>B()),R.set(v.playerId,M);},_=v=>{R.get(v)?.forEach(M=>M()),R.delete(v);},I=new Set,T=new Map,W=(v,M,B)=>({playerNumber:v.assignedPeerId,transport:"webrtc_p2p",...M?{rejoin:true}:{},...B?{superseded:true}:{}}),N=v=>{let M=R.has(v.playerId),B=I.has(v.playerId);I.add(v.playerId),h(v),M&&u("leave",()=>s.leave?.(v.playerId,{cause:"superseded"})),u("join",()=>s.join?.(v.playerId,W(v,B,M)));},U=new Set,C=(v,M,B)=>{if(v===r){b(M,B);return}let Z=n.peer(v);if(Z===null){let be=T.get(v);if(be!==void 0&&e.clock.now()-be<Qu)return;U.has(v)||(U.add(v),o(`send to '${v}' dropped: no such connected player`));return}Z.send(qn(M),yt(B));},L={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:v=>e.tokens.subscribe(v),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(v=>v.playerId)??[],players(){let v=c?[r]:[];for(let M of n.peers)v.push(M.playerId);return v},profile(v){let M=e.room()?.members.find(B=>B.playerId===v);if(!(!M||M.displayName===void 0))return {displayName:st.toPlain(M.displayName),...M.displayTag===void 0?{}:{displayTag:st.toPlain(M.displayTag)},...M.discriminator===void 0?{}:{discriminator:M.discriminator}}},playerNumber(v){return v===r?Zu:n.peer(v)?.assignedPeerId},send(v,M,B){C(v,M,B);},broadcast(v,M){let B=M?.except;c&&r!==B&&b(v,M);for(let Z of n.peers)Z.playerId!==B&&Z.send(qn(v),yt(M));},async endMatch(){let v=await ke();return v.answer!=="ok"&&o(v.cause),v.answer},kick(v,M){if(v===r){y(M??"kicked");return}n.kick(v).catch(B=>{o(`kick of '${v}' failed: ${ht(B)}`);});},log(v){o(v);},warn(v){o(`\u26A0 ${v}`);}},D=()=>{},H=new Promise(v=>{D=v;}),x=[],G=null,ne=async(v,M)=>{l=false;let B=a.then(async()=>{try{await s.shutdown(v);}catch(Z){o(`the bundle's shutdown threw: ${ht(Z)}`);}});a=B,await B,He();for(let Z of x.splice(0))Z();for(let Z of [...R.keys()])_(Z);y(M);},fe=(v,M)=>G||(G=(async()=>{await ne(M,v),n.close(),D();})(),G),Q=()=>G||(G=(async()=>{await ne({reason:"signal"},"left"),await n.leave().catch(v=>o(`leaving the match failed: ${ht(v)}`)),D();})(),G),Pe=()=>G||(G=(async()=>{l=false;let v=await ke();v.answer==="ok"?(await ne({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(o(`${v.cause}; leaving instead`),await ne({reason:"signal"},"left"),await n.leave().catch(M=>o(`leaving the match failed: ${ht(M)}`))),D();})(),G),we=null,Ce=()=>(we??=Ut(L,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),we),ke=async()=>{try{return await Ll({client:Ce().client,gameId:()=>L.gameId},L.matchId,{},{signal:AbortSignal.timeout($v)}),{answer:"ok"}}catch(v){return v instanceof O&&(v.reason==="forbidden"||v.reason==="not_found")?{answer:v.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${v.reason})`}:{answer:"failed",cause:`ending the match failed: ${ht(v)}`}}},te=null,X=false,ae=0,Me,Oe=null,He=()=>{X=true,te!==null&&(e.clock.clearTimeout(te),te=null),Oe?.(),Oe=null;},_t=v=>{o(`heartbeats paused: ${v}; they resume when a fresh play token arrives`),Vt();let M=Me,B=false,Z=e.tokens.subscribe(be=>{B||X||be.token===M||Kt(be)||(B=true,Oe?.(),Oe=null,ae=0,Me=void 0,Vt(),o("a fresh play token arrived; heartbeats resume"),te=e.clock.setTimeout(()=>{Ve();},0));});B?Z():Oe=Z;},Vt=()=>{let v=we;we=null,v?.dispose();},Kt=v=>v.expiresAt*1e3<=e.clock.now(),Ve=async()=>{if(te=null,!X){try{await Ce().client.post(`/v1/games/${encodeURIComponent(L.gameId)}/matches/${encodeURIComponent(L.matchId)}/heartbeat`,void 0,AbortSignal.timeout(Fv)),ae=0,Me=void 0;}catch(v){if(v instanceof O&&(v.reason==="forbidden"||v.reason==="not_found")){o(`the platform no longer holds this match under this host (${v.reason}); heartbeats stop`),He();return}if(Nv(v)){if(X)return;ae+=1;let M=e.tokens.current(),B=M===void 0?"this host holds no play token":Kt(M)?"this host's play token has expired":M.token===Me?"the platform refused this host's play token again":ae>=qv?`the platform refused this host's play token ${ae} times in a row`:null;if(Me=M?.token,B!==null){_t(B);return}}else ae=0,Me=void 0;o(`heartbeat failed: ${ht(v)}`);}X||(te=e.clock.setTimeout(()=>{Ve();},Yu));}},wt=()=>{X||te!==null||(te=e.clock.setTimeout(()=>{Ve();},Yu));};{let v=D;D=()=>{He(),we?.dispose(),we=null,v();};}let Ge=Promise.resolve().then(()=>s.init(L));a=Ge.then(()=>{},()=>{}),u("join",()=>s.join?.(r,{playerNumber:Zu,transport:"loopback"})),x.push(n.on("peerJoined",N)),x.push(n.on("peerLeft",(v,M)=>{_(v);let B=e.clock.now();for(let[Z,be]of T)B-be>=Qu&&T.delete(Z);T.set(v,B),U.delete(v),u("leave",()=>s.leave?.(v,{cause:M}));})),x.push(n.on("error",v=>{o(`\u26A0 session error: ${v.message}`);})),x.push(n.on("matchEnded",v=>{G||Da(f,v),fe("match ended",{reason:"match_ended",platform_reason:v});})),x.push(n.on("hostChanged",v=>{v!==r&&fe("host migrated",{reason:"host_migrated"});}));for(let v of n.peers)N(v);try{await Ge,wt();}catch(v){l=false,He(),d=true;for(let M of x.splice(0))M();for(let M of [...R.keys()])_(M);throw n.leave().catch(()=>{}),D(),v}return {matchId:n.matchId,localLink:S,onMatchEnded(v){f=v;},end:Pe,leave:Q,stop:v=>fe(v,{reason:"stopped"}),done:H}}function Da(t,e){try{t?.(e);}catch{}}function Nv(t){return t instanceof O&&t.status===401||re.isAuthError(t)}function ht(t){return t instanceof Error?t.message:String(t)}function $a(t,e){let n=async()=>{throw new A("misconfigured",`this seat is \`${t}\`, not the match's authority: `+(t==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:t,matchId:e,end:n,leave:n,stop:async()=>{}}}function tm(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,i=new Map,o=async a=>{r.isHost&&!Ma(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...a.signal===void 0?{}:{signal:a.signal}});let l={...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},s=a=>({...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0?{}:{clusterTargetId:a.clusterTargetId}});return {async serve(a,l={}){let d=await o(l);if(d.protocol!==gt)return $a("dedicated",d.matchId);let u=t.p2p.session?.(d.matchId)??null;if(u===null&&!r.isHost||u!==null&&!u.isHost)return $a("peer",d.matchId);let c=t.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let g=u??await t.p2p.connect(s(l)),p=await em(a,{session:g,clock:t.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:g.playerId!==""?g.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return i.set(d.matchId,p),p.done.then(()=>{i.get(d.matchId)===p&&i.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>p.end(),leave:()=>p.leave(),stop:()=>p.stop()}},async connect(a={}){let l=await o(a),d=a.onMatchEnded;if(l.protocol===gt){let p=i.get(l.matchId);if(p!==void 0)return r.notifyMatchConnected(l.matchId),Wv(l.matchId,p,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let f=await En(),y=async()=>t.p2p.connect({...s(a),certificate:f}),S=await y(),b=Vv(S,y,d,R=>{r.notifyMatchDisconnected(R).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(S.matchId,{redial:b.redial,abandon:b.abandon}),b.onClosed(()=>{e.get(S.matchId)?.abandon===b.abandon&&e.delete(S.matchId);})),b}let u=async(p=null)=>await t.dedicated.connect({...p===null?{}:{reportConnected:false,redial:true,...p.deadlineAt===void 0?{}:{deadlineAt:p.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),c=await u(),g=Hv(c,u,r,n);return n&&(e.set(c.matchId,{redial:g.redial,abandon:g.abandon}),g.onClosed(()=>{e.get(c.matchId)?.abandon===g.abandon&&e.delete(c.matchId);})),g},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var nm="link_closed",jv="host_unreachable",Bv=new Set(["failed","closed","relay_deadline","restart_mismatch"]);function Uv(t){return Bv.has(t)?nm:jv}function Wv(t,e,n){let r=e.localLink;e.onMatchEnded(n);let i="connected";r.onClose(()=>{i="closed";});let o;return {matchId:t,protocol:"loopback",get state(){return i},send:(s,a)=>r.send(s,a),onMessage:s=>r.onMessage(s),onClose:s=>{o=s,r.onClose(a=>{i="closed",o?.(a);});},close:()=>r.close()}}function Hv(t,e,n,r){let i=t.matchId,o=t,s="connected",a,l,d=[],u=false,c=false,g=f=>{if(s!=="closed"){s="closed";for(let y of d.splice(0))y();l?.(f);}},p=f=>{f.link.onMessage((y,S)=>a?.(y,S)),f.link.onClose(y=>{if(f!==o||s==="closed")return;if(u||!r){g(y);return}let S=n.matchSession;if(S.phase==="suspended"&&S.matchId===i){s="suspended";return}g(y);});};return p(t),{matchId:i,protocol:"dedicated",get transport(){return o.transport},get state(){return s},send(f,y){s==="connected"&&o.link.send(f,y);},onMessage(f){a=f;},onClose(f){l=f;},close(){if(s!=="closed"){if(u=true,s==="suspended"){g("closed");return}o.close(),g("closed");}},async redial(f){if(s==="closed"||u)return "closed";if(c)return "connected";c=true;let y;try{y=await e(f===void 0?{}:{deadlineAt:f});}finally{c=false;}return u||s==="closed"?(y.close(),"closed"):(o=y,p(y),s="connected",n.notifyMatchConnected(i),"connected")},abandon(f){s!=="closed"&&(s==="connected"&&o.close(),g(f));},onClosed(f){s==="closed"?f():d.push(f);}}}function Vv(t,e,n,r,i,o=false){let s=t.matchId,a=t,l,d,u=[],c=[],g=[],p=false,f=false,y=false,S=false,b="connected",R=C=>{if(p)return;p=true,b="closed";for(let D of u.splice(0))D();for(let D of c.splice(0))D();for(let D of g.splice(0))D();let L=d;L&&queueMicrotask(()=>L(C));},h=C=>{for(let L of u.splice(0))L();for(let L of We){let D=C.channels[L];try{D.binaryType="arraybuffer";}catch{}let H=Wt(L),x=G=>{let ne=vi(G?.data);ne!==null&&l?.(ne.data,H);};D.addEventListener("message",x),u.push(()=>D.removeEventListener("message",x));}},_=()=>a.peer(a.hostPlayerId),I=C=>{if(!(p||a.isHost)&&b!=="suspended"){if(r?.(C),o){b="suspended";return}R(C);}},T=C=>{for(let L of We){let D=C.channels[L];if(typeof D.addEventListener!="function")continue;let H=()=>{_()===C&&I(nm);};D.addEventListener("close",H),u.push(()=>D.removeEventListener?.("close",H));}},W=C=>{h(C),T(C),!p&&(b="connected",i?.());},N=C=>{for(let L of c.splice(0))L();c.push(C.on("migrating",()=>{S=true;})),c.push(C.on("hostChanged",L=>{if(S=false,L===C.playerId){R("host_migrated_here");return}let D=_();D!==null&&W(D);})),c.push(C.on("peerJoined",L=>{L.playerId===C.hostPlayerId&&W(L);})),c.push(C.on("matchEnded",L=>{p||Da(n,L),R(L);})),c.push(C.on("peerLeft",(L,D)=>{L===C.hostPlayerId&&I(Uv(D));}));};N(a);let U=_();return U!==null&&W(U),{matchId:s,protocol:"p2p",get state(){return b},send(C,L){b==="connected"&&_()?.send(qn(C),yt(L));},onMessage(C){l=C;},onClose(C){d=C;},close(){f=true,R("closed"),a.leave().catch(()=>{});},async redial(){if(b==="closed")return "closed";if(b==="connected"||y)return "connected";if(S)throw new q("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");y=true;let C;try{for(let D of u.splice(0))D();for(let D of c.splice(0))D();a.close(),C=await e();}finally{y=false;}if(p)return f?C.leave().catch(()=>{}):C.close(),"closed";a=C,N(a);let L=_();if(L===null)throw a.close(),new q("connection_failed","this peer rejoined the match but the host never answered with a link");return W(L),"connected"},abandon(C){R(C);},onClosed(C){p?C():g.push(C);}}}function rm(t){let e=0,n=new Map;return {resolve(){if(!t.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},s=l=>{n.delete(r)&&(t.clock.clearTimeout(o.timer),i(l));};n.set(r,s),o.timer=t.clock.setTimeout(()=>s(void 0),t.timeoutMs??2e3);let a=false;try{a=t.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){n.get(r)?.(i);}}}var Kv=12e4;function bt(t,e){return {outcome:t,reason:e}}function im(t){let e=false,n=new Map,r=new Set,i=l=>{for(let d of [...r])try{d(l);}catch(u){t.onListenerError?.(u);}},o=async l=>{try{return await t.confirm(l)}catch{return "unknown"}},s=(l,d,u,c)=>{if(!t.bridge.parentSupports(l))return Promise.resolve(bt("unavailable","error"));if(e)return Promise.resolve(bt("declined","busy"));let g=`purchase-${ge()}`;return new Promise(p=>{let f={},y=b=>{n.delete(g)&&(e=false,t.clock.clearTimeout(f.timer),p(b));};e=true,n.set(g,{finish:y,check:u,label:c}),f.timer=t.clock.setTimeout(()=>y(bt("unavailable","error")),t.timeoutMs??Kv);let S=false;try{S=d(g);}catch{}S||y(bt("unavailable","error"));})},a=l=>l===void 0?null:t.confirm(l);return {api:{request(l){return s("purchases",d=>t.bridge.requestPurchase(d,l.kind,l.targetId,l.currencySlug,l.quantity,l.catalogId),a,d=>`purchase ${JSON.stringify(d)}`)},onSettled(l){return r.add(l),()=>{r.delete(l);}}},handOffRefused(l){s("purchases",d=>t.bridge.requestPurchase(d,l.kind,l.targetId,l.currencySlug,l.quantity,l.catalogId,"direct_refused"),a,d=>`purchase ${JSON.stringify(d)}`).then(d=>{d.outcome!=="ok"||d.purchaseId===void 0||(t.onInventoryStale?.(),i(Object.freeze({kind:l.kind,targetId:l.targetId,...l.catalogId===void 0?{}:{catalogId:l.catalogId},quantity:l.quantity,purchaseId:d.purchaseId})));});},settled(l){if(!t.bridge.parentSupports("purchaseSettled")){t.onDropped?.("gem.purchaseSettled from a parent that did not advertise purchaseSettled; ignored");return}let{purchaseId:d}=l;(async()=>{let u=d===void 0?"unknown":await o(d);if(u==="absent"){t.onDropped?.(`gem.purchaseSettled for purchase ${JSON.stringify(d)}, which the platform has no grant for; ignored`);return}t.onInventoryStale?.(),!(u!=="granted"||d===void 0)&&i(Object.freeze({kind:l.purchaseKind,targetId:l.targetId,...l.catalogId===void 0?{}:{catalogId:l.catalogId},quantity:l.quantity,purchaseId:d}));})();},requestAvatar3d(l){return s("avatar3dPurchases",d=>t.bridge.requestAvatar3dPurchase(d,l.itemId,l.currencySlug),()=>t.confirmAvatar3d(l.itemId),()=>`3D avatar ${JSON.stringify(l.itemId)}`)},settle(l){let d=l.outcome==="ok"||l.outcome==="declined"?l.outcome:"unavailable",u=n.get(l.requestId);if(u===void 0){t.onDropped?.(`gem.purchaseResult (${d}) for an unknown requestId: `+JSON.stringify(l.requestId));return}let{finish:c}=u;if(d!=="ok"){c(bt(d,Zl(l.reason)));return}let g=l.purchaseId,p;try{p=u.check(g);}catch{p=Promise.resolve("unknown");}if(p===null){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),c(bt("unavailable","error"));return}(async()=>{let f;try{f=await p;}catch{f="unknown";}if(f==="granted"){c(g===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:g});return}f==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+u.label(g)),c(bt("unavailable","error"));})();}}}async function om(t,e){try{return (await hl(t,e)).granted?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}var Jv="small_human",am=/^[a-z][a-z0-9_]{0,31}$/,sm=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,zv=8;function Fa(t){if(t===null)return [];if(t.avatars3d!==void 0)return t.avatars3d;let{avatar3dId:e,avatar3dModelUrl:n,avatar3dIconUrl:r}=t;return e===void 0||n===void 0||r===void 0?[]:[{family:Jv,id:e,modelUrl:n,iconUrl:r}]}function Xv(t,e){return t.length===e.length&&t.every((n,r)=>{let i=e[r];return n.family===i.family&&n.id===i.id&&n.modelUrl===i.modelUrl})}function Yv(t){let e=t??{},n=typeof e.item_id=="string"&&sm.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&am.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=Ct(e.icon_url),l=Ct(e.model_url),d=[];for(let u of Array.isArray(e.prices)?e.prices:[]){let c=u??{};typeof c.currency_slug=="string"&&c.currency_slug!==""&&typeof c.price=="number"&&Number.isSafeInteger(c.price)&&c.price>0&&d.push({currencySlug:c.currency_slug,price:c.price});}if(!(n===void 0||r===void 0||i===void 0||o===void 0||a===void 0||l===void 0||d.length===0))return {itemId:n,slug:i,family:r,displayName:o,...s===void 0?{}:{description:s},iconUrl:a,modelUrl:l,prices:d}}function Qv(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&am.test(n)&&!e.includes(n)&&e.push(n),e.length===zv)break;return e}function lm(t){let e=new Set,n=Fa(t.player()),r=i=>{t.log?.(`[gem] an avatars3d onChange listener threw: ${i instanceof Error?i.message:String(i)}`);};return t.subscribe(i=>{let o=Fa(i);if(!Xv(n,o)){n=o;for(let s of [...e])try{s(o);}catch(a){r(a);}}}),{async families(){return Qv(await t.configFamilies())},worn(i){let o=Fa(t.player());if(i!==void 0)return o.find(l=>l.family===i);let a=t.player()?.avatar3dId;return (a===void 0?void 0:o.find(l=>l.id===a))??o[0]},async offers(){let i=await t.readOffers(),o=[];for(let s of Array.isArray(i?.offers)?i.offers:[]){let a=Yv(s);a!==void 0&&o.push(a);}return o},purchase(i){let o=i?.itemId,s=i?.currencySlug;return typeof o!="string"||!sm.test(o)?Promise.resolve({outcome:"declined",reason:"not_purchasable"}):typeof s!="string"||s===""?Promise.resolve({outcome:"declined",reason:"unknown_currency"}):t.purchase({itemId:o,currencySlug:s})},onChange(i){return e.add(i),()=>{e.delete(i);}}}}async function dm(t,e){try{return (await Xs(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}function cm(t){return cl(t)}var Zv=6e5;function um(t){let e=null,n=new Map;return {api:{requestSignIn(){if(!t.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${ge()}`;return e=new Promise(i=>{let o={},s=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(o.timer),i(l));};n.set(r,s),o.timer=t.clock.setTimeout(()=>{s({outcome:"unavailable"});},t.timeoutMs??Zv);let a=false;try{a=t.bridge.requestSignIn(r);}catch{}a||s({outcome:"unavailable"});}),e}},settle(r){let i=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",o=n.get(r.requestId);if(o===void 0){t.onDropped?.(`gem.signInResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}o({outcome:i});}}}var e_=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","invite","_s","fbclid","ttclid","gclid","gbraid","wbraid","msclkid","gem_test_ads","moments","ads"]),t_=["utm_"];function qa(t){return e_.has(t)||t_.some(e=>t.startsWith(e))}var n_=new Set(["_s","embedder"]),mm="gemEsc_",pm=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Na=64,ja=16,Ba=512,Ua=Na-mm.length;function gm(t){return n_.has(t)?"reserved_key":(qa(t)||t.startsWith(mm))&&t.length>Ua?"round_trip":null}var r_=1e4,i_=/[\p{Cc}\p{Cf}]/u,o_=/\p{Cs}/u,Re="[gem] gem.share.request:",_i=class extends Error{reason;constructor(e,n){super(`${Re} the arcade refused the share: ${e}`+(n===void 0?"":` (param ${JSON.stringify(n)})`)),this.name="ShareRefusal",this.reason=e,n!==void 0&&(this.key=n);}};function fm(t){let e=new Map;return {wait(n){let r=()=>{};return {answer:new Promise(o=>{let s={};r=a=>{e.delete(n)&&("timer"in s&&t.clearTimeout(s.timer),o(a));},e.set(n,r),s.timer=t.setTimeout(()=>r(null),r_);}),cancel:()=>r(null)}},settle(n){let r=e.get(n.requestId);return r===void 0?false:(r(n),true)},abandon(){for(let n of [...e.values()])n(null);}}}function ym(t){let{frame:e,log:n,answers:r}=t,i=false,o=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,s=a=>{n!==null&&(n===void 0?console.warn(a):n(a));};return {get available(){return o()!==null},request(a){let l=o();if(l===null)throw new Error(`${Re} the arcade does not handle share here \u2014 check gem.share.available first`);if(a!==void 0&&(typeof a!="object"||a===null))throw new TypeError(`${Re} pass { params }, or nothing`);let d=a?.params===void 0?{}:a.params;if(!a_(d))throw new TypeError(`${Re} params must be a plain object of string values`);let u=Object.entries(d);if(u.length>ja)throw new TypeError(`${Re} at most ${ja} params; got ${u.length}`);let c=l.parentSupports("shareRemap"),g=[];for(let[y,S]of u){let b=JSON.stringify(y);if(!pm.test(y))throw new TypeError(`${Re} param ${b}: a key is a letter followed by up to ${Na-1} letters, digits, _ or -`);let R=c?gm(y):qa(y)?"reserved_key":null;if(R==="reserved_key")throw new TypeError(c?`${Re} param ${b} is reserved: the arcade never carries it in a share link`:`${Re} param ${b} is reserved: this arcade reads it itself and never forwards it`);if(R==="round_trip")throw new TypeError(`${Re} param ${b}: a reserved key is carried escaped, and this one is too long to stay a valid key \u2014 keep it to ${Ua} characters`);if(typeof S!="string")throw new TypeError(`${Re} param ${b}: values must be strings`);if(S.length>Ba)throw new TypeError(`${Re} param ${b}: a value is at most ${Ba} characters`);if(i_.test(S))throw new TypeError(`${Re} param ${b}: control and format characters are not allowed`);if(o_.test(S))throw new TypeError(`${Re} param ${b}: a value must be well-formed text`);g.push({key:y,value:S});}let p=l.parentSupports("shareResult")?`share-${ge()}`:void 0,f=p===void 0?null:r.wait(p);return l.requestShare(g,p)?f===null?Promise.resolve():f.answer.then(y=>{if(y?.outcome==="refused")throw new _i(y.reason??"error",y.key)}):(f?.cancel(),i||(i=true,s("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop.")),Promise.resolve())}}}function a_(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Nn=3e4,Wa=12e4;function jn(t,e,n){return t.held?Promise.resolve(n):(t.held=true,e().then(r=>(t.held=false,r)))}function ue(t,e,n){return {outcome:t,reason:e,...n}}function tt(t){let e=t.outcome==="ok"||t.outcome==="declined"?t.outcome:"unavailable";return typeof t.reason=="string"?{outcome:e,reason:t.reason}:{outcome:e}}function hm(t){let e=new Map;return {ask(n,r,i,o){let s=`arcade-${ge()}`;return new Promise(a=>{let l={},d=c=>{e.delete(s)&&("timer"in l&&t.clearTimeout(l.timer),a(i(c)));};e.set(s,{expect:n,finish:d}),o!==void 0&&(l.timer=t.setTimeout(()=>d(null),o));let u=false;try{u=r(s);}catch{}u||d(null);})},settle(n){let r=e.get(n.requestId);return r===void 0||r.expect!==n.type?false:(r.finish(n),true)},abandon(){for(let n of [...e.values()])n.finish(null);}}}var s_=12,l_=24,Ha=Object.freeze({games:Object.freeze([])});function d_(t){let e=(n,r)=>he(n,`GameCard.${r}`);return Object.freeze({gameId:t.gameId,...t.slug===void 0?{}:{slug:t.slug},name:e(t.untrusted.name,"name"),tagline:e(t.untrusted.tagline,"tagline"),shortDescription:e(t.untrusted.shortDescription,"shortDescription"),tags:Object.freeze(t.untrusted.tags.map(n=>e(n,"tags"))),iconUrl:t.iconUrl,capsuleLandscapeUrl:t.capsuleLandscapeUrl,capsulePortraitUrl:t.capsulePortraitUrl,...t.previewVideoUrl===void 0?{}:{previewVideoUrl:t.previewVideoUrl},...t.previewPosterUrl===void 0?{}:{previewPosterUrl:t.previewPosterUrl}})}function wi(t){return ue("unavailable","error",t)}function bm(t){let{bridge:e,asker:n,acting:r}=t,i=a=>e.currentState==="connected"&&e.parentSupports(a),o=new Map,s=(a,l)=>{let d=o.get(a);if(d!==void 0)return d;let u=l().then(c=>(o.delete(a),c));return o.set(a,u),u};return {get available(){return {appLinks:i("appLinks"),openGame:i("openGame")}},appLinks(){return e.parentSupports("appLinks")?s("appLinks",()=>n.ask("gem.appLinksResult",a=>e.requestArcade({type:"gem.requestAppLinks",requestId:a}),a=>{if(a===null)return wi({});let l=a;return {...tt(a),...l.arcade===void 0?{}:{arcade:{store:l.arcade.store}},...l.game===void 0?{}:{game:{store:l.game.store}}}},Nn)):Promise.resolve(ue("unavailable","unsupported",{}))},openApp(a){return e.parentSupports("appLinks")?a!=="arcade"&&a!=="game"?Promise.resolve(ue("unavailable","invalid_argument",{})):jn(r,()=>n.ask("gem.openAppResult",l=>e.requestArcade({type:"gem.requestOpenApp",requestId:l,target:a}),l=>l===null?wi({}):tt(l),Wa),ue("declined","busy",{})):Promise.resolve(ue("unavailable","unsupported",{}))},openGame(a){if(!e.parentSupports("openGame"))return Promise.resolve(ue("unavailable","unsupported",{}));let l=typeof a=="string"?a.toLowerCase():"";return zl({gem:j,type:"gem.requestOpenGame",requestId:"-",ref:l})!==null?Promise.resolve(ue("unavailable","invalid_argument",{})):jn(r,()=>n.ask("gem.openGameResult",u=>e.requestArcade({type:"gem.requestOpenGame",requestId:u,ref:l}),u=>u===null?wi({}):tt(u),Wa),ue("declined","busy",{}))},similarGames(a){if(!e.parentSupports("openGame"))return Promise.resolve(ue("unavailable","unsupported",Ha));let l=a?.limit;return l!==void 0&&(typeof l!="number"||!Number.isInteger(l)||l<1||l>l_)?Promise.resolve(ue("unavailable","invalid_argument",Ha)):s(`similar:${l??s_}`,()=>n.ask("gem.similarGamesResult",d=>e.requestArcade({type:"gem.requestSimilarGames",requestId:d,...l===void 0?{}:{limit:l}}),d=>{if(d===null)return wi(Ha);let u=tt(d),c=d,g=u.outcome==="ok"?Object.freeze(c.games.map(d_)):[];return {...u,games:g}},Nn))}}}var c_=64,vm=Object.freeze({offers:Object.freeze([])});function u_(t){return Object.freeze({skuId:t.skuId,kind:t.kind,name:t.name,description:t.description,...t.imageUrl===void 0?{}:{imageUrl:t.imageUrl},priceDisplay:t.priceDisplay,...t.grant===void 0?{}:{grant:Object.freeze({currency:t.grant.currency,amount:t.grant.amount})}})}function _m(t){let{bridge:e,asker:n,acting:r}=t,i=new Set,o=null;function s(a,l,d,u){return e.parentSupports(a)?typeof u!="string"||u.length===0||u.length>c_?Promise.resolve(ue("unavailable","invalid_argument",{})):jn(r,()=>n.ask(d,c=>e.requestArcade({type:l,requestId:c,skuId:u}),c=>c===null?ue("unavailable","error",{}):tt(c)).then(c=>((c.outcome==="ok"||c.reason==="error")&&t.onPurchaseEnded?.(),c)),ue("declined","busy",{})):Promise.resolve(ue("unavailable","unsupported",{}))}return {api:{get available(){return e.currentState==="connected"&&e.parentSupports("store")},get showOfferAvailable(){return e.currentState==="connected"&&e.parentSupports("storeOfferSheet")},offers(){return e.parentSupports("store")?(o!==null||(o=n.ask("gem.storeOffersResult",a=>e.requestArcade({type:"gem.requestStoreOffers",requestId:a}),a=>{if(a===null)return ue("unavailable","error",vm);let l=tt(a),d=a,u=l.outcome==="ok"?Object.freeze(d.offers.map(u_)):[];return {...l,offers:u}},Nn).then(a=>(o=null,a))),o):Promise.resolve(ue("unavailable","unsupported",vm))},purchase(a){return s("store","gem.requestStorePurchase","gem.storePurchaseResult",a)},showOffer(a){return s("storeOfferSheet","gem.requestStoreOfferSheet","gem.storeOfferSheetResult",a)},onSettled(a){return i.add(a),()=>{i.delete(a);}}},settled(a){t.onPurchaseEnded?.();let l=Object.freeze({skuId:a.skuId});for(let d of [...i])try{d(l);}catch(u){t.onListenerError?.(u);}}}}var xm="https://gemarcade.com/branding/manifest.json",m_=1,wm=256*1024,p_=256,g_=64,f_=256,Sm=8e3,y_=6e4,h_=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Rm={GEMS:"gems-mark",ARCADE_TICKETS:"ticket-mark"},km=Object.freeze({outcome:"unavailable"}),Am=Object.freeze({outcome:"not_found"});function vt(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function Ri(t){return typeof t=="string"&&t!==""&&t.length<=f_}function b_(t,e){if(!Ri(t))return;let n;try{n=new URL(t,e);}catch{return}let r=Ct(n.href);if(r!==void 0)return n.origin===new URL(e).origin?r:lo(r)}function v_(t,e){let n=t??{},r=b_(n.url,e);if(!(r===void 0||!Ri(n.type))&&!(typeof n.bytes!="number"||!(n.bytes>=0))&&!(n.theme!==void 0&&n.theme!=="light"&&n.theme!=="dark"))return Object.freeze({url:r,type:n.type,bytes:n.bytes,...vt(n.width)?{width:n.width}:{},...vt(n.height)?{height:n.height}:{},...vt(n.size)?{size:n.size}:{},...vt(n.density)?{density:n.density}:{},...n.vector===true?{vector:true}:{},...n.theme===void 0?{}:{theme:n.theme}})}function __(t,e=xm){let n;try{n=JSON.parse(t);}catch{return null}let r=n??{};if(r.format!==m_||!Array.isArray(r.assets))return null;let i=[],o=new Set;for(let s of r.assets.slice(0,p_)){let a=s??{};if(!Ri(a.id)||!h_.test(a.id)||o.has(a.id)||!Ri(a.kind)||!Array.isArray(a.variants))continue;let l=[];for(let d of a.variants.slice(0,g_)){let u=v_(d,e);u!==void 0&&l.push(u);}l.length!==0&&(o.add(a.id),i.push(Object.freeze({id:a.id,kind:a.kind,variants:Object.freeze(l)})));}return Object.freeze(i)}function Si(t){let e;for(let n of t)(e===void 0||(n.width??0)>(e.width??0))&&(e=n);return e}function w_(t,e,n){let r=t.find(l=>l.vector===true),i=t.filter(l=>l.size===void 0);if(e===void 0)return r??Si(i)??Si(t);let o=t.filter(l=>l.size===e);if(o.length>0){let l=u=>u.density??1,d=o.filter(u=>l(u)>=n);return d.length>0?d.reduce((u,c)=>l(c)<l(u)?c:u):o.reduce((u,c)=>l(c)>l(u)?c:u)}if(r!==void 0)return r;let s=i.filter(l=>(l.width??0)>=e*n);return (s.length>0?s.reduce((l,d)=>(d.width??0)<(l.width??0)?d:l):void 0)??Si(i)??Si(t)}function S_(t,e){let n=e.theme===void 0?[]:t.variants.filter(a=>a.theme===e.theme),r=t.variants.filter(a=>a.theme===void 0),i=[n,r].filter(a=>a.length>0);if(t.kind!=="image")return i[0]?.[0];let s=(e.size===void 0?void 0:i.find(a=>a.some(l=>l.size===e.size)))??i[0];return s&&w_(s,e.size,e.density)}function R_(t,e){if(e!==void 0){if(e===null||typeof e!="object")throw new TypeError(`[gem] branding.${t}: options must be an object`);if(e.size!==void 0&&!vt(e.size))throw new RangeError(`[gem] branding.${t}: size must be a positive number of CSS px`);if(e.density!==void 0&&!vt(e.density))throw new RangeError(`[gem] branding.${t}: density must be a positive number`);if(e.theme!==void 0&&e.theme!=="light"&&e.theme!=="dark")throw new TypeError(`[gem] branding.${t}: theme must be 'light' or 'dark'`)}}function Pm(t){let e=t.manifestUrl??xm,n=null,r=null,i=-1/0,o=false,s=u=>(i=t.clock.now(),o||(o=true,t.log?.(`[gem] gem.branding could not read the platform's branding (${u}), so every lookup answers 'unavailable' and your bundled fallback shows. If your page sets a Content-Security-Policy, allow ${new URL(e).origin} in connect-src and img-src.`)),null),a=async()=>{if(t.fetch===null)return s("this page has no fetch");let u=t.fetch,c=typeof AbortController=="function"?new AbortController:null,g,p=new Promise(y=>{g=t.clock.setTimeout(()=>{c?.abort(),y(s(`no answer in ${Sm} ms`));},Sm);}),f=(async()=>{let y=await u(e,{credentials:"omit",redirect:"error",...c?{signal:c.signal}:{}});if(!y.ok)return s("the manifest answered an error");if(Number(y.headers.get("content-length"))>wm)return s("the manifest is too large");let S=await y.text();return S.length>wm?s("the manifest is too large"):__(S,e)??s("the manifest is not format 1 JSON")})().catch(()=>s("the request failed"));try{return await Promise.race([f,p])}finally{t.clock.clearTimeout(g);}},l=()=>n!==null?Promise.resolve(n):r!==null?r:t.clock.now()-i<y_?Promise.resolve(null):(r=a().then(u=>(r=null,u!==null&&(n=u),u)),r),d=async(u,c,g,p)=>{R_(u,p);let f=await l();if(f===null)return km;let y=f.find(R=>R.id===c&&R.kind===g);if(y===void 0)return Am;let S=t.devicePixelRatio(),b=S_(y,{...p?.size===void 0?{}:{size:p.size},density:p?.density??(vt(S)?S:1),...p?.theme===void 0?{}:{theme:p.theme}});return b===void 0?Am:Object.freeze({outcome:"ok",url:b.url,variant:b,asset:y})};return Object.freeze({get:async(u,c)=>{if(typeof u!="string"||u==="")throw new TypeError("[gem] branding.get: id must be a non-empty string");if(c===null||typeof c!="object"||typeof c.kind!="string")throw new TypeError("[gem] branding.get: options.kind must be a string, such as 'image'");return d("get",u,c.kind,c)},logo:u=>d("logo","gem-logo","image",u),wordmark:u=>d("wordmark","gem-wordmark","image",u),currencyMark:async(u,c)=>{let g=Object.prototype.hasOwnProperty.call(Rm,u)?Rm[u]:void 0;if(g===void 0)throw new TypeError("[gem] branding.currencyMark: currency must be 'GEMS' or 'ARCADE_TICKETS', not "+JSON.stringify(String(u).slice(0,40)));return d("currencyMark",g,"image",c)},trophy:u=>d("trophy","trophy-mark","image",u),list:async()=>{let u=await l();return u===null?km:Object.freeze({outcome:"ok",assets:u})}})}var P_="(any-pointer: coarse)";function E_(t){let e=Array.isArray(t)?t:[t],n=[],r=1e4;for(let i of e){if(typeof i!="number"||!Number.isFinite(i)||i<0)return null;if(n.length===99||r===0)continue;let o=Math.min(Math.trunc(i),1e4,r);n.push(o),r-=o;}return n.length%2===0&&n.pop(),n.every(i=>i===0)?[]:n}function Em(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?u=>matchMedia(u):void 0},i=r.navigator,o,s=new Set,a=()=>typeof i?.vibrate!="function"||r.matchMedia===void 0?false:(o??=r.matchMedia(P_),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(u,c)=>{s.has(u)||(s.add(u),n!==null&&(n===void 0?console.warn(c):n(c)));};return {get available(){return a()||l()},vibrate(u){let c=a();if(!c&&!l())return false;let g=E_(u);if(g===null)return d("pattern","[gem] gem.vibration.vibrate did nothing: a pattern is a number of milliseconds, or an array of them, each finite and not negative."),false;if(i?.userActivation?.hasBeenActive!==true)return d("activation","[gem] gem.vibration.vibrate did nothing: the player has not tapped or pressed a key in your game yet, and browsers allow vibration only after that."),false;if(c)try{return i.vibrate(g)===!0}catch{return false}let p=e.requestVibrate(g);return p||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),p}}}var Ht=Math.PI/180,qe=Object.freeze({touch:Object.freeze({yaw:1*Ht,pitch:.66*Ht}),mouse:Object.freeze({yaw:.5*Ht,pitch:.5*.77*Ht}),stick:Object.freeze({yaw:240*Ht,pitch:240*.77*Ht}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),Va="[gem.controls]",Ka=Object.freeze({yaw:0,pitch:0}),ki=t=>Number.isFinite(t)?t:0,Tm=(t,e)=>({yaw:t+0,pitch:e+0});function Im(t){let e=ki(t),n=(Math.abs(e)-qe.stickDeadzone)/(1-qe.stickDeadzone),r=qe.stickCurve,i=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,i))+0}function T_(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-qe.touchPitchMin)+qe.touchPitchMin}function Cm(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${Va} ${e} takes an options object`);let n=t;for(let r of ["sensitivity","gamepadSensitivity"]){let i=n[r];if(i!==void 0&&!(typeof i=="number"&&Number.isFinite(i)&&i>0))throw new TypeError(`${Va} ${e}: ${r} must be a finite number above 0 (1 = the base speed); got ${String(i)}`)}if(n.invertY!==void 0&&typeof n.invertY!="boolean")throw new TypeError(`${Va} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function I_(t,e){let n=Cm(e,"look()"),r=n.sensitivity,i=n.gamepadSensitivity,o=n.invertY,s=a=>o??a?.invertLookY??false;return {fromPointer(a,l,d,u){let c=ki(a),g=ki(l);if(c===0&&g===0)return Ka;let p=t(),f=r??(p===null?void 0:p.lookSensitivity/100)??1,y=d==="touch"||d==="pen",S=y?qe.touch:qe.mouse,b=c*S.yaw*f,R=-g*S.pitch*f;return s(p)&&(R=-R),y&&u!==void 0&&Number.isFinite(u)&&R*u>0&&(R*=T_(u)),Tm(b,R)},fromStick(a,l,d){let u=ki(d);if(u<=0)return Ka;let c=Im(a),g=Im(l);if(c===0&&g===0)return Ka;let p=t(),f=i??(p===null?void 0:p.gamepadLookSensitivity/100)??1,y=c*qe.stick.yaw*u*f,S=-g*qe.stick.pitch*u*f;return s(p)&&(S=-S),Tm(y,S)},set(a){let l=Cm(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(i=l.gamepadSensitivity),"invertY"in l&&(o=l.invertY);}}}function Mm(t){return {look:e=>I_(t.recommended,e),LOOK_BASE:qe}}var Om=Object.freeze(["music","sfx","voice","eye","text","hint","speed","bright","controls","star"]),Gm=/^[A-Za-z0-9_-]{1,40}$/;function Ja(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=1e6}function Lm(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e.slice(0,40)}function Dm(t,e,n,r){let i=a=>Number.parseFloat(a.toPrecision(12)),o=Math.min(n,Math.max(e,t)),s=i(e+Math.round((o-e)/r)*r);return s>n&&(s=i(s-r)),Math.min(n,Math.max(e,s))}function $m(t,e){switch(t.kind){case "toggle":return typeof e=="boolean"?e:void 0;case "slider":{if(typeof e!="number"||!Number.isFinite(e))return;let n=t.min??0,r=t.max??100;return Dm(e,n,r,t.step??1)}case "choice":return typeof e=="string"&&(t.options??[]).some(n=>n.id===e)?e:void 0;default:return}}function Fm(t,e=()=>{}){if(!Array.isArray(t))return null;let n=[],r=0;for(let i=0;i<t.length;i+=1){let o=t[i],s=`settings[${i}]`;if(n.length===8){e(`${s} and later were left out: at most 8 settings are shown.`);break}if(typeof o!="object"||o===null){e(`${s} was dropped: a setting is an object.`);continue}let a=o,l=a.id;if(typeof l!="string"||!Gm.test(l)){e(`${s} was dropped: its id must be 1 to 40 of A-Z a-z 0-9 _ -.`);continue}let d=`${s} (${JSON.stringify(l)})`;if(n.some(g=>g.id===l)){e(`${d} was dropped: an earlier setting has the same id.`);continue}let u=Lm(a.label);if(u===void 0){e(`${d} was dropped: its label is empty.`);continue}let c;switch(a.kind){case "toggle":{if(typeof a.value!="boolean"){e(`${d} was dropped: a toggle's value is true or false.`);continue}c={id:l,label:u,kind:"toggle",value:a.value},a.quick===true&&(r<2?(c.quick=true,r+=1):e(`${d} is not in the quick row: at most 2 toggles are, the first that ask.`));break}case "slider":{let g=a.min??0,p=a.max??100,f=a.step??1;if(!Ja(g)||!Ja(p)||!Ja(f)||g>=p||f<=0){e(`${d} was dropped: a slider needs finite numbers within \xB11000000 with min below max and a step above 0.`);continue}if(typeof a.value!="number"||!Number.isFinite(a.value)){e(`${d} was dropped: a slider's value is a number.`);continue}c={id:l,label:u,kind:"slider",value:Dm(a.value,g,p,f),min:g,max:p,step:f};break}case "choice":{let g=[];for(let p of Array.isArray(a.options)?a.options:[]){if(g.length===4)break;if(typeof p!="object"||p===null)continue;let f=p,y=Lm(f.label);typeof f.id!="string"||!Gm.test(f.id)||y===void 0||g.some(S=>S.id===f.id)||g.push({id:f.id,label:y});}if(g.length<2){e(`${d} was dropped: a choice needs 2 to 4 options, each with an id of 1 to 40 of A-Z a-z 0-9 _ - and a label.`);continue}if(typeof a.value!="string"||!g.some(p=>p.id===a.value)){e(`${d} was dropped: a choice's value is the id of one of its options.`);continue}c={id:l,label:u,kind:"choice",value:a.value,options:g};break}default:e(`${d} was dropped: its kind must be 'toggle', 'slider' or 'choice'.`);continue}a.icon!==void 0&&(Om.includes(a.icon)?c.icon=a.icon:e(`${d} keeps the Arcade's generic icon: ${JSON.stringify(a.icon)} is not one of ${Om.join(", ")}.`)),n.push(c);}return n}var C_=500;function qm(t){let{clock:e}=t,n=null,r=null,i=-1/0,o=null,s=new Set,a=new Set,l=c=>{a.has(c)||(a.add(c),t.log!==null&&(t.log===void 0?console.warn(c):t.log(c)));},d=()=>{let c=t.frame();return c.currentState==="connected"&&c.parentSupports("gameSettings")},u=()=>{if(n===null||o!==null)return;let c=JSON.stringify(n);if(c===r)return;let g=i+C_-e.now();if(g>0){o=e.setTimeout(()=>{o=null,u();},g);return}t.frame().declareSettings(n)&&(r=c,i=e.now());};return {api:{declare(c){let g=Fm(c,p=>l(`[gem] gem.settings.declare: ${p}`));return g===null?(l("[gem] gem.settings.declare did nothing: pass an array of settings, or [] for none."),false):(n=g,u(),d())},onChange(c){if(typeof c!="function")return ()=>{};let g=p=>c(p);return s.add(g),()=>{s.delete(g);}}},forgetSent(){r=null,i=-1/0;},flush:u,onSettingChange(c){let g=n?.findIndex(b=>b.id===c.id)??-1,p=n?.[g];if(n===null||p===void 0)return;let f=$m(p,c.value);if(f===void 0)return;let y=JSON.stringify(n);n=n.map((b,R)=>R===g?{...b,value:f}:b),r===y&&(r=JSON.stringify(n));let S={id:p.id,value:f};for(let b of [...s])try{b(S);}catch(R){console.error("[gem] a gem.settings.onChange handler threw:",R);}}}}function Nm(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var M_=/(?:Z|[+-]\d{2}:?\d{2})$/i;function jm(t){if(typeof t!="string"||!M_.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function Bn(){return {declared:false,grantable:false,heldLimitReached:false}}function Bm(t,e){let n=typeof t=="object"&&t!==null?t:{},r=jm(n.resets_at),i=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...Bn(),...i};let o=n.remaining_today,s=typeof o=="number"&&Number.isFinite(o)&&o>=0?Math.floor(o):void 0,a=n.next_eligible_at,l=jm(a),d=n.held_limit_reached===true,u=a!=null,c=o!=null&&s===void 0;return {declared:true,grantable:n.grantable===true&&e&&s!==0&&!c&&!u&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var O_=18e4,za=32,G_=/^[a-z0-9_-]+$/,L_="rewarded_requires_user_gesture";function D_(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var $_=1e3;function F_(){let t=globalThis,e=t.navigator?.getGamepads,n=t.performance?.now;if(typeof e!="function"||typeof n!="function")return;let r=n.call(t.performance),i=e.call(t.navigator);for(let o=0;o<i.length;o+=1){let s=i[o]?.timestamp;if(typeof s=="number"&&r-s>=0&&r-s<=$_)return true}return false}var Um=1e4;function q_(t){return t==="interstitial"||t==="rewarded"}function Wm(t){return typeof t=="string"&&t!==""&&t.length<=za&&G_.test(t)}function N_(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function Ai(t){return typeof t=="string"?JSON.stringify(t):typeof t}function Hm(t){let e=false,n=new Map,r=new Map,i=new Set,o=d=>{try{t.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let u=t.log;if(u!==null)try{u===void 0?console.warn(`[gem] ${d}`):u(`[gem] ${d}`);}catch{}},l=d=>{let u=t.readAvailability;if(u===void 0)return Promise.resolve(Bn());let c=r.get(d);if(c!==void 0)return c;let g=new Promise(p=>{let f={},y=h=>f.done===true?false:(f.done=true,t.clock.clearTimeout(f.timer),p(h),true),S=(h,_)=>{!y(Bn())||i.has(h)||(i.add(h),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${_}. Said once.`));},b=h=>{S(N_(h),`the read failed (${h instanceof Error?h.message:Ai(h)})`);},R;try{R=Promise.resolve(u(d,AbortSignal.timeout(Um)));}catch(h){R=Promise.reject(h);}f.timer=t.clock.setTimeout(()=>{S("timeout","no answer within 10 s");},Um),R.then(h=>{try{y(Bm(h,t.bridge.parentSupports("ads")));}catch(_){b(_);}},b);});return r.set(d,g),g.then(()=>{r.get(d)===g&&r.delete(d);}),g};return {api:{rewardedStatus(d){return Wm(d)?l(d):(o(`gem.ads.rewardedStatus(${Ai(d)}) answered not grantable: a placement is 1..${String(za)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(Bn()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let u=d?.placement,c=d?.format;if(!Wm(u)||!q_(c))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${Ai(u)}, format ${Ai(c)}. A placement is 1..${String(za)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});if(c==="rewarded"){let p;try{p=(t.userActivation??D_)();}catch{p=void 0;}if(p===false)try{(t.recentGamepadInput??F_)()===!0&&(p=!0);}catch{}if(p===false){let f=`${L_}: gem.ads.requestAd("${u}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return o(f),a(f),Promise.resolve({outcome:"no_ad"})}}let g=`ad-${ge()}`;return new Promise(p=>{let f={},y=b=>{n.delete(g)&&(e=false,t.clock.clearTimeout(f.timer),p(b));};e=true,n.set(g,y),f.timer=t.clock.setTimeout(()=>{y({outcome:"unavailable"});},t.timeoutMs??O_);let S=false;try{S=t.bridge.requestAd(g,u,c);}catch{}S||y({outcome:"no_ad"});})}},settle(d){let u=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",c=n.get(d.requestId);if(c===void 0){t.onDropped?.(`gem.adResult (${u}) for an unknown requestId: `+JSON.stringify(d.requestId));return}c({outcome:u});}}}var Vm=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),Km=18e4,j_=1e4,B_=/^[a-z0-9_-]{1,32}$/;function Xa(t){return typeof t=="string"?JSON.stringify(t):typeof t}var Un=Object.freeze({shown:false});function Jm(t){let e=new Map,n,r=false,i=o=>{try{t.onDropped?.(o);}catch{}return Un};return {api:{signal(o){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(Un):(r=!0,Promise.resolve(i("moments_unsupported: gem.moments.signal answered shown: false without asking: this arcade does not do platform moments. Keep the call; it costs nothing. Said once.")));let s=o?.kind,a=o?.placement,l=o?.wall;if(!Vm.includes(s)||a!==void 0&&(typeof a!="string"||!B_.test(a))||l!==void 0&&typeof l!="boolean")return Promise.resolve(i(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${Xa(s)}, placement ${Xa(a)}, wall ${Xa(l)}. A kind is one of ${Vm.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'; a wall, when given, is true or false. Answering shown: false.`));if(!t.bridge.readyCalled())return Promise.resolve(i(`moments_before_ready: gem.moments.signal({ kind: '${s}' }) before gem.frame.ready(): a moment is a break in play, and play has not started. Signal from the press that leaves a break, never on boot. Answering shown: false.`));if(e.size>0)return Promise.resolve(i(`moments_in_flight: gem.moments.signal({ kind: '${s}' }) while another moment is still waiting for its answer. Signal once per break, and await the answer before play resumes. Answering shown: false.`));let d=t.clock.now();if(n!==void 0&&d-n<j_)return Promise.resolve(i(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(d-n)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let u=`moment-${ge()}`;return new Promise(c=>{let g={},p=(y,S)=>{e.delete(u)&&(t.clock.clearTimeout(g.timer),S&&(n=t.clock.now()),c(y));};e.set(u,y=>p(y,!0)),g.timer=t.clock.setTimeout(()=>{e.has(u)&&(p(Un,!0),i(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??Km)/1e3)} s. Answering shown: false.`));},t.timeoutMs??Km);let f=!1;try{f=t.bridge.signalMoment(u,s,a,l===!0?!0:void 0);}catch{}f||p(Un,!1);})}catch{return Promise.resolve(Un)}}},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 Ya=16384;function zm(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e;try{e=JSON.stringify(t);}catch{return null}return typeof e!="string"?null:U_(e)}function U_(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(e+=4,n+=1):e+=3;}else e+=3;}return e}var W_=1e4,H_=5e3;function Xm(t){let e=null,n=false,r=[],i=new Map,o=()=>{for(let s of r.splice(0))s();};return {api:{get current(){return e},wait(s=H_){return n?Promise.resolve(e):new Promise(a=>{let l=()=>{let c=r.indexOf(d);c>=0&&r.splice(c,1);},d=()=>{t.clock.clearTimeout(u),l(),a(e);},u=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=zm(s);if(a===null)return t.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(a>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(s)),d=`device-settings-${ge()}`;return new Promise(u=>{let c={},g=f=>{i.delete(d)&&(t.clock.clearTimeout(c.timer),f==="stored"&&(e=l,n=true,o()),u(f));};i.set(d,g),c.timer=t.clock.setTimeout(()=>g("unavailable"),t.timeoutMs??W_);let p=false;try{p=t.bridge.putDeviceSettings(d,l);}catch{}p||g("unavailable");})}},receive(s){let a=s.settings;e=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,n=true,o();},settle(s){let a=s.outcome==="stored"||s.outcome==="too_large"?s.outcome:"unavailable",l=i.get(s.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var 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 V_=/^[a-z0-9][a-z0-9_-]{0,39}$/;function K_(t){return typeof t=="string"&&V_.test(t)}function xi(t){if(t===null||K_(t))return t;let e=typeof t=="string"?JSON.stringify(t.length>48?`${t.slice(0,48)}\u2026`:t):`a value of type ${typeof t}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}function Ym(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Za(t,e){if(t!==true)return {visible:false};let n=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!n.includes(i)&&n.push(i);return !r&&n.length===0?{visible:true}:{visible:true,currencies:n.slice(0,8),score:r}}function Pi(t){let e=[];for(let n of Array.isArray(t)?t:[]){if(e.length===4)break;if(typeof n!="object"||n===null)continue;let{id:r,label:i}=n;typeof r!="string"||r.length===0||r.length>32||typeof i!="string"||i.trim().length===0||e.some(o=>o.id===r)||e.push({id:r,label:i.trim().slice(0,40)});}return e.length===0?{settings:false}:{settings:false,items:e}}function Qm(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function J_(t){let e=t.untrusted,n=he(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,i=r?he(r,"gem.player.displayTag"):void 0,o=t.discriminator||t.displayTag,s=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,a=t.avatarIconUrl||t.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=t.avatarIconId,u=t.avatar3dId,c={displayName:n,displayHandle:i??n,badges:(t.badges??[]).map(y=>({itemId:y.itemId,iconUrl:y.iconUrl}))};t.playerId&&(c.playerId=t.playerId),s&&(c.discriminator=s),i&&(c.displayTag=i),a&&(c.avatarIconUrl=c.avatarUrl=a),d&&l.test(d)&&(c.avatarIconId=d),u&&l.test(u)&&(c.avatar3dId=u),t.avatar3dModelUrl&&(c.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(c.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(c.avatars3d=t.avatars3d.filter(y=>l.test(y.id)&&/^[a-z][a-z0-9_]*$/.test(y.family)).filter((y,S,b)=>b.findIndex(R=>R.family==y.family)==S).map(({family:y,id:S,modelUrl:b,iconUrl:R})=>({family:y,id:S,modelUrl:b,iconUrl:R})));let g=t.boost,p=(g?.multipliers??[]).map(y=>({currencyId:y.currencyId,currencySlug:y.currencySlug,multiplier:y.multiplierBp/1e4})),f=p.some(y=>y.multiplier>1);return c.boost=f&&g?.expiresInDays?{active:f,multipliers:p,expiresInDays:g.expiresInDays}:{active:f,multipliers:p},c}var z_=1e4,X_=["appLinks","openGame","store","storeOfferSheet"],Y_=["token","pause","menuSelect","settingChange","prefs","cohorts","viewport","willTerminate","localServer","roomEvent","seatedEvent","autoStartFailedEvent","ticketEvent","socketState","signalEvent","relayDraining","dedicatedEvent","clusterTarget","graphicsRoutes","partyResult","purchaseResult","purchaseSettled","shareResult","deviceSettings","adResult","momentResult","signInResult","friendChallengeResult"],Qa=new WeakMap;function ep(t,e){if(Qa.has(t))throw new Error("admitBuildEmbedders: already admitted");Qa.set(t,Object.freeze([...e]));}var Hn=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??ce,this.inbound=new tn(this.clock),this.outbound=new tn(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=>xt(a,e.origin))||yr(e.origin,this.options.selfOrigin)||(Qa.get(this)??[]).some(a=>xt(a,e.origin))))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=fr["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!xt(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=Xl(mr,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:j,type:"gem.error",code:"version_mismatch",message:`frame supports v${mr.min}..v${mr.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=s,o.onmessage=a=>this.receive(a.data,a.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:j,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:j,type:"gem.ready"});}settled(e=z_){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=o=>{this.clock.clearTimeout(i),n(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem:j,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:j,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:j,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:j,type:"gem.exit"}:{gem:j,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:j,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:j,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:j,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:j,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let n={gem:j,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(n.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(n.origin={x:Ym(e.origin.x),y:Ym(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=xi(e);return n===void 0||!this.gated("portraitBorders")?false:this.send(n===null?{gem:j,type:"gem.portraitBorders"}:{gem:j,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.gated("walletDisplay")?this.send({gem:j,type:"gem.walletDisplay",...Za(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:j,type:"gem.menu",...Pi(e)}):false}declareSettings(e){return this.gated("gameSettings")?this.send({gem:j,type:"gem.settingsDeclare",settings:e}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:j,type:"gem.gemCorner",corner:e}):false}setMenuStyle(e){return this.gated("menuStyle")?this.send(e===null?{gem:j,type:"gem.menuStyle"}:{gem:j,type:"gem.menuStyle",ground:e.ground,accent:e.accent}):false}requestShare(e,n){return this.gated("share")?this.send({gem:j,type:"gem.requestShare",...n===void 0?{}:{requestId:n},params:e.map(({key:r,value:i})=>({key:r,value:i}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:j,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:j,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:j,type:"gem.frameStats",fps:Qm(e.fps,1e3),frameTimeP95Ms:Qm(e.frameTimeP95Ms,1e5),counts:e.counts==="gameDraws"?"gameDraws":"pageFrames"}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:j,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:j,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:j,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:j,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,i,o,s,a){return this.send({gem:j,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s},...a===void 0?{}:{origin:a}})}requestAvatar3dPurchase(e,n,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:j,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:n,currencySlug:r}):false}putDeviceSettings(e,n){return this.send({gem:j,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:j,type:"gem.requestAd",requestId:e,placement:n,format:r})}signalMoment(e,n,r,i){return this.send({gem:j,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r},...i===true?{wall:true}:{}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:j,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,i){return this.send({gem:j,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...i===void 0?{}:{params:i}})}requestArcade(e){return this.gated(gr(e.type))&&this.send({gem:j,...e})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(pr)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(pr)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(pr)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:j,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}gated(e){return this.state==="connected"&&this.parentSupports(e)}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let n=e.type;if(!this.outbound.allow(n))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${n}`),false;let r=fr[n]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${n}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,n=[]){let r=false;try{r=this.dispatchInbound(e,n);}finally{r||Zm(n);}}dispatchInbound(e,n){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let i=fr[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=gr(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=n[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return Zm(n.slice(1)),this.options.onScreenshot(d,l,(u,c)=>this.screenshotDenied(u,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(J_(a));break}case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:if(Y_.includes(r.slice(4))){this.options[`on${r[4].toUpperCase()}${r.slice(5)}`]?.(a);break}if(X_.includes(gr(r))){this.options.onArcadeAnswer?.(a);break}this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:j,type:"gem.screenshot.denied",reason:e,retryable:n});}};function Zm(t){for(let e of t)try{e?.close?.();}catch{}}var tp="https://api.gemarcade.com";function es(t){let e;try{e=new URL(t);}catch{return "it is not a valid URL"}return e.protocol!=="https:"&&e.protocol!=="http:"?`its scheme is ${e.protocol.replace(":","")}, and only http and https can be used`:e.username!==""||e.password!==""?"it carries credentials in the URL, which `fetch` will not send":e.href.includes("#")?"it carries a fragment. The transport joins the base and the path by concatenation, so the fragment would swallow the path and every request would go to the API root":e.href.includes("?")?"it carries a query string. The transport joins the base and the path by concatenation, so the query would swallow the path and every request would go to the API root":null}var Q_=new Set(["localhost","127.0.0.1","[::1]"]);function np(t){let e=es(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!Q_.has(n.hostname)?"it is a plaintext http address that is not loopback. An embedder may name an https root, or http on localhost for a rig running the whole stack on one machine \u2014 the play token travels on every request to it":null}var op="/gem-embedders.json",Ei=4096,rp=16,ip=5e3,Vn=Object.freeze({origins:Object.freeze([])});function nt(t){return {origins:[],refused:`[gem] ${op} was ignored: ${t}`}}function Z_(t){if(t.trim()==="")return Vn;let e;try{e=JSON.parse(t);}catch{return nt("it is not JSON.")}if(e===null||typeof e!="object"||Array.isArray(e))return nt('it must be an object, { "embedders": [...] }.');let n=e.embedders;if(n===void 0)return Vn;if(!Array.isArray(n))return nt('"embedders" must be an array of origins.');if(n.length>rp)return nt(`"embedders" has more than ${rp} entries.`);let r=n.filter(i=>typeof i!="string"||!At(i)||!i.toLowerCase().startsWith("https://")||Xe(new URL(i).hostname));if(r.length>0){let i=r.slice(0,3).map(o=>typeof o=="string"?JSON.stringify(o.slice(0,100)):String(o)).join(", ");return nt(`${r.length===1?"an entry is":"entries are"} not an https origin off this machine (${i}${r.length>3?", \u2026":""}).`)}return {origins:Object.freeze([...new Set(n)])}}async function ap(t){let e=typeof AbortController=="function"?new AbortController:null,n,r=new Promise(o=>{n=t.clock.setTimeout(()=>{e?.abort(),o(nt(`it took more than ${ip} ms to read.`));},ip);}),i=(async()=>{let o=await t.fetch(t.selfOrigin+op,{credentials:"omit",redirect:"error",...e?{signal:e.signal}:{}});if(!o.ok||(o.headers.get("content-type")??"").toLowerCase().includes("text/html"))return Vn;if(Number(o.headers.get("content-length"))>Ei)return nt(`it is larger than ${Ei} bytes.`);let a=await o.text();return a.length>Ei?nt(`it is larger than ${Ei} bytes.`):Z_(a)})().catch(()=>Vn);try{return await Promise.race([i,r])}finally{t.clock.clearTimeout(n);}}function sp(t){if(typeof t!="string"||!At(t))return null;let e=t.slice(0,t.indexOf(":")).toLowerCase();return e==="https"||e==="http"?t:null}function lp(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function ew(){let t=[["root",null],["hips","root"],["spine","hips"],["chest","spine"],["upper_chest","chest"],["neck","upper_chest"],["head","neck"],["head_socket","head"]];for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("shoulder"),"upper_chest"],[n("upper_arm"),n("shoulder")],[n("lower_arm"),n("upper_arm")],[n("hand"),n("lower_arm")],[n("hand_socket"),n("hand")]);for(let r of ["thumb","index","middle","ring","little"])for(let i=1;i<=3;i++)t.push([n(`${r}_${i}`),n(i===1?"hand":`${r}_${i-1}`)]);}for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("upper_leg"),"hips"],[n("lower_leg"),n("upper_leg")],[n("foot"),n("lower_leg")],[n("toes"),n("foot")]);}return t}var tw=Object.freeze({small_human:lp([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:lp(ew())});var rw=Object.freeze(["https://gemarcade.com","https://developer.gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),iw=tp,ow=["top-left","top-right","bottom-left","bottom-right"];function dp(t){let e=[1,3,5].map(n=>{let r=parseInt(t.slice(n,n+2),16)/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4});return .2126*e[0]+.7152*e[1]+.0722*e[2]}function aw(t){if(t===null)return null;let{ground:e,accent:n}=Object(t);for(let[s,a]of [["ground",e],["accent",n]]){if(typeof a=="string"&&/^#[0-9a-fA-F]{6}$/.test(a))continue;let l=typeof a=="string"?JSON.stringify(a.slice(0,48)):`a value of type ${typeof a}`;console.warn(`[gem] setMenuStyle: ${s} is ${l}, which is not #rrggbb, so nothing was sent.`);return}let r={ground:e.toLowerCase(),accent:n.toLowerCase()},i=[dp(r.ground),dp(r.accent)],o=(Math.max(...i)+.05)/(Math.min(...i)+.05);if(o>=3)return r;console.warn(`[gem] setMenuStyle: accent ${r.accent} reaches ${Math.floor(o*100)/100}:1 against ground ${r.ground}, under the 3:1 it needs, so nothing was sent.`);}var cp=8e3,Ti=15e3,sw=9e4,lw=1/0,dw=8e3,cw=5e3,uw=5e3;async function mw(t,e,n,r){if(t.isInRoom)try{await t.leave();}catch{}r?.endSession("session_ended"),e!==null&&e.currentState==="connected"&&e.exit(n);}function Kn(t){let e=null,n=false,r=[];return {get current(){return e},set(i){e=i;for(let o of r.splice(0))o(i);},release(){n=true;for(let i of r.splice(0))i(e);},wait(i){return e!==null||n?Promise.resolve(e):new Promise(o=>{let s=()=>{let d=r.indexOf(a);d>=0&&r.splice(d,1);},a=d=>{t.clearTimeout(l),s(),o(d);},l=t.setTimeout(()=>{s(),o(e);},i);r.push(a);})}}}function jI(t={}){let e=t.clock??ce,n=t.log===void 0?m=>console.info(m):t.log,r=t.baseUrl??void 0;if(r!=null){let m=es(r);if(m!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${m}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=typeof window>"u"?void 0:window.location?.search,o=Od(i),s=ac(i),a=eu(i),l=ma();l.mark("sdk created");let d=()=>Vr(se.gameVersion,t.clientVersion?.gameVersion),u=new yn({client:()=>Rt,clock:e,gameId:()=>se.identity?.gameId??null,playerId:()=>se.identity?.playerId??null,awaitPlayerId:async()=>(await ar(Ti)).playerId,declarations:async()=>(await or.load())?.analytics_events,environment:()=>{let m=d();return {sdk_version:Ps(),...m===null?{}:{game_version:m}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),c=Yc(()=>{l.mark("engaged"),u.release(),$.reportEngaged();},typeof window>"u"?{}:window),g=m=>{if(m===false)return null;let E=m?.attempts??lw,F=m?.budgetMs??sw;return !(E>0)||!(F>0)?null:{attempts:E,budgetMs:F,maxDelayMs:m?.maxDelayMs??dw}},p=m=>{m.on("created",()=>{l.mark("room created");}),m.on("joined",()=>{l.mark("room joined");}),m.on("matchAllocationStarted",()=>{l.mark("allocation started");}),m.on("matchReady",()=>{l.mark("match ready");}),m.on("matchFailed",()=>{l.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new Wn;let f=t.allowedEmbedders;if(f!=null&&!Array.isArray(f))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let y=Array.from(f??[]),S=y.filter(m=>typeof m!="string"||!At(m));if(S.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${S.length===1?"an entry":"entries"} that ${S.length===1?"is":"are"} not an origin: ${S.map(m=>typeof m=="string"?JSON.stringify(m):String(m)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let b=Object.freeze([...new Set([...rw,...y])]),R=Kn(e),h=new Set,_=Kn(e),I=false,T=Kn(e),W=qd(n),N=Kn(e),U=t.manageAudio===false?null:gu();t.selectableText!==true&&fu(),t.onScreenshot===void 0&&ru(window);let C=null,L=null,D=null,H=()=>{C===null||C===L||$.reportMuted(C)&&(L=C);},x,G,ne=-1/0,fe=null,Q=()=>{if(x===void 0||fe!==null||x===G)return;let m=ne+1e3-e.now();if(m>0){fe=e.setTimeout(()=>{fe=null,Q();},m);return}$.showPortraitBorders(x)&&(G=x,ne=e.now());},Pe=null,we=null,Ce=()=>{if(Pe===null)return false;let m=JSON.stringify(Za(Pe.visible,Pe.only));return m===we?$.parentSupports("walletDisplay"):$.setWalletVisible(Pe.visible,Pe)?(we=m,true):false},ke=null,te=null,X=()=>{if(ke===null)return false;let m=JSON.stringify(Pi(ke.items));return m===te?$.parentSupports("gameMenu"):$.setMenu(ke.items)?(te=m,true):false},ae=null,Me=null,Oe,He=null,_t=qm({frame:()=>$,clock:e,log:t.log}),Vt=()=>ae===null?false:ae===Me?$.parentSupports("gemCorner"):$.setGemCorner(ae)?(Me=ae,true):false,Kt=()=>{if(Oe===void 0)return false;let m=JSON.stringify(Oe);return m===He?$.parentSupports("menuStyle"):$.setMenuStyle(Oe)?(He=m,true):false},Ve=yu({report:m=>$.reportFrameStats(m)}),wt=false,Ge=Ru(()=>_s,()=>wt),v=m=>{let E=wt&&!m,F=wt!==m;if(wt=m,E&&Ge.close(),!!F)try{t.onDevToolsPermissionChange?.(m);}catch(ee){n?.(`[gem] onDevToolsPermissionChange threw: ${ee instanceof Error?ee.message:String(ee)}`),queueMicrotask(()=>{throw ee});}},M=r??iw,B=r!==void 0,Z,be=m=>(n?.(`[gem] token refused: ${m}`),t.onError?.("internal",m),false),Jn=(m,E)=>{if(m===void 0)return E!==void 0?be("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let F=np(m);return F!==null?be(`the embedder named an API root that cannot be used: ${F}. Its value is withheld here rather than written to logs.`):Z!==void 0&&Z!==m?be("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(Z=m,B||(M=m),true)},Ke=window.location?.origin,rt=null,ns=-1/0,gp=2e3,zn=new Set,fp=m=>rt!==false?Promise.resolve(true):new Promise(E=>{let F=e.setTimeout(()=>{zn.delete(ee),E(false);},m),ee=()=>{e.clearTimeout(F),zn.delete(ee),E(true);};zn.add(ee);}),Ii=()=>{},Ci=null,Xn=()=>{},Yn=hm(e),Mi=fm(e),rs=tu({bridge:{settled:m=>$.settled(m),parentSupports:m=>$.parentSupports(m)},clock:e,forced:a,log:n}),$=new Hn({allowedEmbedders:b,...typeof Ke=="string"&&Ke!==""?{selfOrigin:Ke}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","ticketEvents","clusterTarget","graphicsRoutes","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","portraitBorders","earnAllowance","share","shareResult","shareRemap","avatarPicker","vibration","frameStats","walletDisplay","gameMenu","gemCorner","menuStyle","gameSettings","engagement","reservedAreas","p2pRelayDrain","viewport","purchases","purchaseSettled","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges","appLinks","openGame","store","storeOfferSheet",...t.onFeedbackContext!==void 0?["feedbackContext"]:[],...t.onAudioChannels!==void 0?["audioChannels"]:[]],onRefused:m=>{Ci=m,t.onRefused?.(m);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:m=>{se.onBridgeState(m),m!=="connected"&&Yn.abandon(),m!=="connected"&&Mi.abandon(),m!=="connected"&&Ve.setRequested(false),L=null,we=null,te=null,Me=null,He=null,_t.forgetSent(),G=void 0,m==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Ci===null?"":` (${Ci})`)+", 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."),Ii()),m==="connected"&&(l.mark("bridge connected"),yp(),H(),Q(),Ce(),X(),Vt(),Kt(),_t.flush(),$.unbiddenLaunch&&!c.engaged&&u.hold(),u.startSession(),c.engaged&&$.reportEngaged()),t.onStateChange?.(m);},onPlayer:m=>{R.set(m);for(let E of [...h])E(m);t.onPlayer?.(m);},onPrefs:m=>{let E={reducedMotion:m.reducedMotion,muted:m.muted,locale:m.locale,showFrameStats:m.showFrameStats===true,music:m.music!==false,sounds:m.sounds!==false,recommended:m.recommended===void 0?null:Object.freeze({volume:m.recommended.volume,batterySaver:m.recommended.batterySaver,keyboardLayout:m.recommended.keyboardLayout,gamepadConfirm:m.recommended.gamepadConfirm,vibration:m.recommended.vibration,lookSensitivity:m.recommended.lookSensitivity??100,gamepadLookSensitivity:m.recommended.gamepadLookSensitivity??100,invertLookY:m.recommended.invertLookY??false,touchMovement:m.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:Nm(m.recommended.graphicsQuality,m.recommended.batterySaver),graphicsQualityAuto:m.recommended.graphicsQualityAuto??true,colorHelp:typeof m.recommended.colorHelp=="boolean"?m.recommended.colorHelp:null})};_.set(E),L=E.muted,U?.setMuted(E.muted),Ve.setRequested(E.showFrameStats&&$.parentSupports("frameStats")),t.onPrefs?.(E),t.onAudioChannels!==void 0&&(D===null||D.music!==E.music||D.sounds!==E.sounds)&&(D=Object.freeze({music:E.music,sounds:E.sounds}),t.onAudioChannels(D));},onCohorts:m=>{let E=Object.freeze(m.cohorts.map(F=>Object.freeze({experimentId:F.experimentId,variantKey:F.variantKey})));T.set(E),t.onCohorts?.(E);},onEarnAllowanceChanged:()=>W.emit(),onViewport:m=>{let E=Object.freeze({insets:Object.freeze({top:m.insets.top,right:m.insets.right,bottom:m.insets.bottom,left:m.insets.left}),reserved:Object.freeze((m.reserved??[]).map(({x:ee,y:ws,width:Ss,height:Rs,control:Xt})=>Object.freeze(Xt?{x:ee,y:ws,width:Ss,height:Rs,control:Object.freeze({x:Xt.x,y:Xt.y,width:Xt.width,height:Xt.height})}:{x:ee,y:ws,width:Ss,height:Rs})))});N.set(E);let F=bu();vu(F,E.insets),wu(F,E.reserved,_u()),t.onViewport?.(E);},onPause:m=>{m.paused||Xn(),I=m.paused,U?.setPaused?.(m.paused),u.setPaused(m.paused),Ve.setPaused(m.paused),t.onPause?.(m.paused);},onSettingChange:m=>_t.onSettingChange(m),onMenuSelect:m=>{ke===null||m.entry!=="item"||!(Pi(ke.items).items??[]).some(F=>F.id===m.id)||ke.items?.find(F=>F.id===m.id)?.onSelect?.();},onWillTerminate:m=>{u.endSession(m.reason),t.onWillTerminate?.({reason:m.reason,graceMs:m.graceMs});},onToken:m=>{let E=m.garden;if(v(m.allowDevTools===true),!Jn(m.apiBaseUrl,E))return;let F=m;se.onToken(F);let ee=se.identity;ee&&(Oi.set(ee),os||(os=true,me.reconcileSeats().catch(()=>{}))),as.push({token:F.token,expiresAt:F.expiresAt});},onTokenDenied:m=>{v(false),se.onDenied(m);},onScreenshot:(m,E,F)=>{cu(m,E,F,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{uu($,t.onFeedbackContext);},onDevtools:m=>{m==="close"?Ge.close():m==="open"?Ge.openFrom("platform").catch(()=>{}):Ge.isOpen?Ge.close():Ge.openFrom("platform").catch(()=>{});},onRoomEvent:m=>me.handleRoomEvent({event:m.event,roomId:m.roomId,...m.matchId===void 0?{}:{matchId:m.matchId},...m.version===void 0?{}:{version:m.version},...m.reason===void 0?{}:{reason:m.reason},...m.platform===void 0?{}:{platform:m.platform}}),onSeatedEvent:m=>me.handleSeated(m.roomId),onAutoStartFailedEvent:m=>me.handleAutoStartFailed(m.roomId,m.code),onTicketEvent:m=>me.handleTicketEvent({event:m.event,ticketId:m.ticketId,...m.partySize===void 0?{}:{partySize:m.partySize},...m.queuedAt===void 0?{}:{queuedAt:m.queuedAt},...m.expiresAt===void 0?{}:{expiresAt:m.expiresAt},...m.reason===void 0?{}:{reason:m.reason},...m.roomId===void 0?{}:{roomId:m.roomId}}),onSocketState:m=>{let E=rt;if(rt=m.connected,m.connected)for(let ee of [...zn])ee();if(!m.connected||E===true)return;let F=e.now();F-ns<gp||(ns=F,me.reconcile().catch(()=>{}));},onSignalEvent:m=>{let E=typeof m.data=="object"&&m.data!==null&&!Array.isArray(m.data)?m.data:{};ot.handleSignalEvent(m.matchId,m.event,E),m.event==="matchEnded"&&me.reconcile({matchId:m.matchId,...typeof E.reason=="string"?{reason:E.reason}:{}}).catch(()=>{});},onRelayDraining:m=>{ot.handleSignalEvent(m.matchId,"relayDraining",{clusterTargetId:m.clusterTargetId,relayIps:m.relayIps,drainingSince:m.drainingSince,deadline:m.deadline});},onDedicatedEvent:m=>{m.event==="matchEnded"&&(zt.handleMatchEnded(m.matchId,m.reason),me.reconcile({matchId:m.matchId,...m.reason===void 0?{}:{reason:m.reason}}).catch(()=>{})),is.handleEvent(m);},onClusterTarget:m=>er.accept(m.clusterTargetId,m.clusterTargetIds),onGraphicsRoutes:m=>rs.accept(m.entries),onLocalServer:m=>tr.accept(m),onLocalServerDenied:m=>tr.refuse(m),onPartyResult:m=>ls.settle(m.requestId,m.partyId),onPurchaseResult:m=>Jt.settle(m),onPurchaseSettled:m=>Jt.settled(m),onShareResult:m=>Mi.settle(m),onDeviceSettings:m=>{Zn.receive(m),t.onDeviceSettings?.(Zn.api.current);},onDeviceSettingsResult:m=>Zn.settle(m),onAdResult:m=>cs.settle(m),onMomentResult:m=>us.settle(m),onSignInResult:m=>{m.outcome==="signed_in"&&Xn(),ms.settle(m);},onFriendChallengeResult:m=>fs.settle(m),onArcadeAnswer:m=>{m.type==="gem.storePurchaseSettled"?gs.settled(m):bp(m);}}),is=new Fn({bridge:$}),Oi=Kn(e);Ii=()=>{Oi.release(),R.release(),T.release();},$.currentState==="refused"&&Ii();let os=false,Gi=new Set,Qn,as={current:()=>Qn,subscribe:m=>(Gi.add(m),Qn!==void 0&&m(Qn),()=>Gi.delete(m)),push:m=>{Qn=m;for(let E of [...Gi])try{E(m);}catch(F){n?.(`[gem] a server-token listener threw: ${F instanceof Error?F.message:String(F)}`);}}},se=Au({bridge:$,clock:e,onStateChange:(m,E)=>{if(m==="ready"){if(l.mark("token ready")){let F=l.marks.find(ee=>ee.name==="token ready")?.at;u.trackPlatform("gem_boot_ready",F===void 0?{}:{boot_ms:Math.max(0,Math.round(F))});}}else m==="lost"&&(l.mark("token lost"),u.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(m,E);}}),ss=()=>{let m=se.identity;return !m||se.source.currentState==="lost"?null:`${m.playerId}\0${m.gameId}\0${m.channel}`},yp=()=>{l.mark("token requested"),se.source.get().catch(()=>{});},ls=rm({bridge:$,clock:e}),St={},Jt=im({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m),confirm:async m=>St.confirm?.(m)??"unknown",confirmAvatar3d:async m=>St.confirmAvatar3d?.(m)??"unknown",onInventoryStale:()=>St.inventoryStale?.(),onListenerError:m=>t.onError?.("internal",`gem.purchases.onSettled listener threw: ${String(m)}`)}),Zn=Xm({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m)}),ds={},cs=Hm({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m),readAvailability:(m,E)=>ds.read?.(m,E)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),us=Jm({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m)}),ms=um({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m)}),ps={held:false},hp=bm({bridge:$,asker:Yn,acting:ps}),gs=_m({bridge:$,asker:Yn,acting:ps,onListenerError:m=>t.onError?.("internal",`gem.store.onSettled listener threw: ${String(m)}`),onPurchaseEnded:()=>Xn()}),bp=m=>{Yn.settle(m)||t.onError?.("internal",`${m.type} (${m.outcome}) for an unknown requestId: `+JSON.stringify(m.requestId));},fs=Fd({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m)}),er=Kd({bridge:$,clock:e}),tr=Su({bridge:$,clock:e}),Li=sp(Ke),ys=window.fetch,nr=Li!==null&&typeof ys=="function"?"unread":"read",rr=null,Di=false,vp=m=>{if(nr==="read"||m.source!==window.parent)return false;let E=m.origin;return typeof E!="string"||b.some(F=>xt(F,E))||yr(E,typeof Ke=="string"?Ke:void 0)?false:((rr===null||!Di)&&(rr=m),nr==="unread"&&Li!==null&&(nr="reading",ap({fetch:(F,ee)=>ys.call(window,F,ee),selfOrigin:Li,clock:e}).then(F=>{"refused"in F&&n?.(F.refused),F.origins.length>0&&ep($,F.origins),nr="read";let ee=rr;rr=null,ee!==null&&$.currentState==="waiting"&&ir(ee);})),true)},ir=m=>{if(vp(m))return false;let E=$.handleWindowMessage({data:m.data,origin:m.origin,source:m.source,ports:m.ports});return E&&window.removeEventListener("message",ir),E};window.addEventListener("message",ir),Di=true;let it;try{it=xs(window,ir);}finally{Di=false;}let _p=it?.capture,$i=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];$i?.domInteractive!==void 0&&$i.domInteractive>0&&l.mark("document parsed",$i.domInteractive),_p?.late&&n?.("[gem] the early-handshake capture installed after this document finished loading, so a handshake posted at iframe load may already have been missed. Load the capture script ahead of everything else in the document.");let Fi=t.handshakeWarningMs;Fi!==null&&n&&e.setTimeout(()=>{let m=it===null?"no capture script ran":`capture: ${it.delivered} offer(s) delivered, ${it.stale} stale, ${it.capture.dropped} evicted${it.capture.late?", installed late":""}`;if($.currentState==="connected"){n(`[gem] handshake connected. boot: ${l.timeline()} \xB7 ${m}`);return}n(`[gem] no completed handshake after ${Fi??cp}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: ${l.timeline()} \xB7 `+m);},Fi??cp);let wp=kr({get baseUrl(){return M},tokenSource:se.source,get defaultQuery(){let m=se.identity;return m?{game_id:m.gameId,channel:m.channel}:{}}}),Rt=new Je({transport:wp,clock:e}),ye={client:Rt,gameId:()=>se.identity?.gameId??""};St.confirm=m=>om(ye,m),St.confirmAvatar3d=m=>dm(ye,m),ds.read=(m,E)=>ql(ye,"players","me",m,{signal:E});let Sp=()=>se.identity?.channel??"release",or=new Gr(ye,Sp),Rp=lm({player:()=>R.current,subscribe:m=>(h.add(m),()=>{h.delete(m);}),configFamilies:async()=>(await or.load())?.avatar_3d_families,readOffers:()=>cm(ye),purchase:m=>Jt.requestAvatar3d(m),log:t.log}),hs=async m=>(await or.load())?.currency(m)?.id??void 0,bs=gd(ye,oo,{identity:ss,resolveCurrencyId:hs,watch:{clock:e,log:t.log},handOffRefusedPurchase:m=>Jt.handOffRefused(m)}),qi=bs.scope;St.inventoryStale=()=>qi.inventory.refresh(),Xn=bs.recheckPasses;let ar=async m=>{let E=await Oi.wait(m);if(E)return E;throw $.currentState==="refused"?new re("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new re("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},Ni=g(t.autoReconnect),me=kc(s===void 0?{}:{playWithTicket:s},{client:Rt,clock:e,gameId:()=>se.identity?.gameId??null,playerId:()=>se.identity?.playerId??null,awaitGameId:async()=>(await ar(Ti)).gameId,resolveParty:ls.resolve,resolveClusterTargets:er.resolveList,refreshClusterTargets:er.refresh,ensureLocalServer:tr.ensure,localHostAvailable:tr.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>se.gameVersion,...t.pollRooms===void 0?{}:{poll:t.pollRooms},...t.recoverStaleMembership===void 0?{}:{recoverStaleMembership:t.recoverStaleMembership},...t.retryAutoStart===void 0?{}:{retryAutoStart:t.retryAutoStart},...t.watchSeats===void 0?{}:{watchSeats:t.watchSeats},...t.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:t.seatPollIntervalMs},...Ni===null?{}:{autoReconnect:{...Ni,redial:(m,E)=>ji.redialMatch(m,E),abandon:(m,E)=>ji.abandonMatch(m,E)}}});p(me),Kc({analytics:u,rooms:me}),zc({analytics:u});let ot=Vc({client:Rt,clock:e,rooms:me,bridge:$,gameId:()=>se.identity?.gameId??"",baseUrl:()=>M,resolveClusterTargets:er.resolveList,boot:l,...t.log===void 0?{}:{log:t.log}}),vs=ua(l,n),zt=Bu({client:Rt,clock:e,rooms:me,signaling:()=>is.channel(),signalingReady:fp,log:n??(()=>{})}),ji=tm({rooms:me,p2p:{connect:m=>vs(ot.connect(m)),session:m=>ot.session(m)},dedicated:{connect:(m=>ci(l,"welcome",zt.connect(m),n))},clock:e,identity:()=>se.identity,apiBaseUrl:()=>M,tokens:as,room:()=>me.currentRoom,autoReconnect:Ni!==null,...t.log===void 0?{}:{log:t.log}}),kp=async()=>(await ar(Ti)).playerId,_s={client:Rt,boot:l,get identity(){return se.identity},awaitIdentity:(m=Ti)=>ar(m),awaitBridge:m=>$.settled(m),get player(){return R.current},awaitPlayer:(m=cw)=>R.wait(m),me:qi,characters:new Ir(ye,void 0,ss,hs),transfers:new Mr(ye,oo,qi.inventory),gameConfig:or,purchases:Jt.api,deviceSettings:Zn.api,graphics:rs.api,moments:us.api,ads:cs.api,account:ms.api,share:ym({frame:$,log:t.log,answers:Mi}),arcade:hp,store:gs.api,branding:Pm({fetch:typeof window.fetch=="function"?(m,E)=>window.fetch.call(window,m,E):null,clock:e,devicePixelRatio:()=>window.devicePixelRatio??1,log:n}),vibration:Em({frame:$,log:t.log}),get avatarPickerAvailable(){return $.currentState==="connected"&&$.parentSupports("avatarPicker")},openAvatarPicker:m=>$.requestAvatarPicker(m?.tab),avatars3d:Rp,settings:_t.api,controls:Mm({recommended:()=>_.current?.recommended??null}),analytics:u,leaderboards:new dn(ye),challenges:new an(ye),showcase:new cn(ye,kp),friends:new un(ye,{challenge:fs.challenge,...o===void 0?{}:{launchedChallengeId:o}}),platform:new pn(ye,W,n),profiles:new gn(ye),functions:new Qe((m,E)=>Al(ye,m,E)),get prefs(){return _.current},get paused(){return I},get cohorts(){return T.current},get viewport(){return N.current},awaitCohorts:(m=uw)=>T.wait(m),reportMuted:m=>{C=!!m,H();},showPortraitBorders:m=>{let E=xi(m);E!==void 0&&(x=E,Q());},cueReward:m=>$.cueReward(m),setWalletVisible:(m,E)=>{let F=Array.isArray(E?.only)?[...E.only]:void 0;return Pe=F===void 0?{visible:m===true}:{visible:m===true,only:F},Ce()},setMenu:m=>(ke=Array.isArray(m?.items)?{items:m.items.map(E=>({...E}))}:{},X()),setGemCorner:m=>{if(!ow.includes(m)){let E=typeof m=="string"?JSON.stringify(m.slice(0,48)):`a value of type ${typeof m}`;return console.warn(`[gem] setGemCorner: ${E} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return ae=m,Vt()},setMenuStyle:m=>{let E=aw(m);return E===void 0?false:(Oe=E,Kt())},reportFrame:()=>Ve.draw(),exit:m=>mw(me,$,m,u),frame:$,devtools:Ge,rooms:me,dedicatedServer:{listClusterTargets:m=>zt.listClusterTargets(m),connect:(m=>ci(l,"welcome",zt.connect(m),n)),handleMatchEnded:(m,E)=>zt.handleMatchEnded(m,E)},p2p:{handleSignalEvent:(m,E,F)=>ot.handleSignalEvent(m,E,F),session:m=>ot.session(m),connect:m=>vs(ot.connect(m))},match:ji};return _s}var up="the match has not started yet: the runtime hands over the host at `init`, and this was read before that. Read it from `init` or later \u2014 a bundle that needs a value at module scope is reading it one call too early.";function ts(t,e={}){let n=e.clock??ce,r=()=>{let a=t();if(a===null)throw new Error(up);return a},i=null,o=()=>{if(i===null)throw new Error(up);return i};return {server:{get identity(){return o().identity},get client(){return o().client},get api(){return o().api},get match(){return o().match},get analytics(){return o().analytics},get functions(){return o().functions},get challenges(){return o().challenges},get room(){return o().room},dispose(){i?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(a){let d=r().profile?.(a);if(!d)return null;let u=d.displayName;return typeof u!="string"||u===""?null:{displayName:he(u,"profile.displayName"),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:he(d.displayTag,"profile.displayTag")}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(a){return r().playerNumber?.(a)},send(a,l,d){d===void 0?r().send(a,l):r().send(a,l,d);},broadcast(a,l){l===void 0?r().broadcast(a):r().broadcast(a,l);},kick(a,l){l===void 0?r().kick(a):r().kick(a,l);},log(a){r().log(a);},warn(a){r().warn(a);}},attach:()=>{i=Ut(r(),{...e,clock:n});}}}function mp(t,e={}){let{server:n,attach:r}=ts(()=>t,e);return r(),n}function pw(t){if(t===void 0||typeof t.reason!="string"||t.reason==="")return;let e=t.platform_reason??t.endedReason;return {reason:t.reason,...e===void 0?{}:{endedReason:Ze(e)}}}var gw=1e4;function fw(t){let e=false;return n=>{if(e)return;let r;try{r=t.match.reportPlayers([{playerId:n,state:"connected"}],AbortSignal.timeout(gw));}catch{return}r.catch(i=>{i instanceof O&&i.status>=400&&i.status<500&&(e=i.status!==429);});}}function pp(t,e={}){return ()=>{let n=null,{server:r,attach:i}=ts(()=>n,e),o=t(r),s={async init(l){n=l,i(),await o.init?.();},async shutdown(l){let d=pw(l);try{await o.shutdown?.(d);}finally{r.dispose();}}},a=fw(r);return s.join=(l,d)=>(a(l),o.join?.(l,d)),o.leave&&(s.leave=(l,d)=>o.leave?.(l,d)),o.message&&(s.message=(l,d,u,c)=>o.message?.(l,d,u,c)),s}}As();
|
|
3
|
-
exports.ARCADE_EMBEDDERS=
|
|
1
|
+
var GemWebSdkGame=(function(exports){'use strict';var Ip=Object.defineProperty;var Cp=(t,e)=>{for(var n in e)Ip(t,n,{get:e[n],enumerable:true});};var Hi="GemWebSdkHandshake";function Mp(){return typeof document>"u"?void 0:document.readyState}var Es=()=>Date.now();function Ts(t={}){let e=t.win??window,n=e,r=n[Hi];if(r!==void 0)return r;let i=t.readyState??Mp,o=t.now??Es,s=[],a=[],l=u=>{let c=u.data;!c||c.type!=="gem.handshake"||(s.length>=4&&(s.shift(),a.shift(),d.dropped+=1),s.push(u),a.push(o()));};e.addEventListener("message",l);let d={events:s,times:a,dropped:0,late:i()==="complete",uninstall(){e.removeEventListener("message",l);}};return n[Hi]=d,d}function Is(t,e,n={}){let r=t[Hi];if(r===void 0)return null;let i=n.ttlMs??9500,o=n.now??Es,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,u=false,c=o()-i;for(let g=s.length-1;g>=0;g--){let p=a?.[g];if(p!==void 0&&p<c){d+=1;continue}if(l+=1,e(s[g])===true){u=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:u}}globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:22.0.0]";function Cs(){let t=globalThis.__gemWebSdkVersion;if(typeof t!="string")return "";let e=t.lastIndexOf(":"),n=t.lastIndexOf("]");return e<0||n<=e+1?"":t.slice(e+1,n)}var Op={initialDelayMs:2e3,maxDelayMs:6e4};function Gp(t,e){return e!==void 0?!e:t==="chain_exhausted"}var kt=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;retry=null;failures=0;notBefore=0;disposed=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new re(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.pastChainCeiling())throw new re("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new re(this.failure??"unavailable","the embedder asked for no new token yet; one is asked for when that wait is over");return this.refresh(this.nextReason())}pastChainCeiling(){return this.grant===null||this.seconds()<this.grant.chainEndsAt?false:(this.enter("lost","chain_exhausted"),true)}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}dispose(){this.disposed=true,this.cancelRetry();}scheduleRetry(e){if(this.cancelRetry(),this.failures+=1,this.notBefore=e===void 0?0:this.options.clock.now()+e,this.disposed)return;let{initialDelayMs:n,maxDelayMs:r}=Op,i=Math.min(r,n*2**(this.failures-1)),o=Math.max(i/2,e??0)+Math.random()*(i/2);this.retry={handle:this.options.clock.setTimeout(()=>this.retryNow(),o)};}retryNow(){this.retry=null,this.notBefore=0,!(this.state==="lost"||this.pastChainCeiling())&&this.refresh(this.nextReason()).catch(()=>{});}cancelRetry(){this.retry!==null&&(this.options.clock.clearTimeout(this.retry.handle),this.retry=null);}refresh(e){if(this.inFlight)return this.inFlight;this.cancelRetry();let n=this.generation;this.enter("pending");let r=this.options.request(e).then(i=>{if(n!==this.generation)throw new re("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=Lp(i),{retryable:s,retryAfterMs:a}=i??{};throw n===this.generation&&(Gp(o,typeof s=="boolean"?s:void 0)?this.enter("lost",o):(this.scheduleRetry(typeof a=="number"&&Number.isFinite(a)&&a>0?a:void 0),this.enter("degraded",o))),i instanceof re?i:new re(o,String(i))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){(e==="ready"||e==="lost")&&this.cancelRetry(),e==="ready"&&(this.failures=0,this.notBefore=0),this.failure=n??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,n));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},re=class t extends Error{constructor(n,r){super(`auth ${n}: ${r}`);this.reason=n;this.name="AuthError";}reason;static isAuthError(n){if(n instanceof t)return true;let r=n;return r?.name==="AuthError"&&typeof r.reason=="string"}};function Lp(t){if(t instanceof re)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var de=class t extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof t)return true;let n=e;return n?.name==="TransportRefusal"&&n.retryable===false}},lr=["if-match","if-none-match"],Ms=4096;function Dp(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let i=n.toLowerCase();if(!lr.includes(i)||r===void 0)continue;let o=typeof r=="string"?$p(r):r;if(typeof o!="string"||o.length>Ms||!Fp(o))throw new de(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${Ms} 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 $p(t){let e=i=>i===32||i===9||i===10||i===13,n=0,r=t.length;for(;n<r&&e(t.charCodeAt(n));)n++;for(;r>n&&e(t.charCodeAt(r-1));)r--;return t.slice(n,r)}function Fp(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n!==9&&(n<32||n===127||n>255))return false}return true}function qp(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new de("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new de("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function Os(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=Dp(i.headers),s=qp(i),a=Object.freeze({...i,headers:o,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await t(a,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let u=await e.tokenSource.get(),c=await t(a,u);if(c.status===401)throw e.tokenSource.close("unavailable"),new re("unavailable","the server refused a freshly minted token");return c}}}function dr(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Np(e))}function cr(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function Vi(t){return new TextDecoder().decode(cr(t))}function Np(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var O=class extends Error{constructor(n,r,i,o,s){super(`${n} (${r}): ${i}`);this.reason=n;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},Ds=new WeakMap;function $s(t){return Ds.get(t)??{}}var jp=new Set([408,429,500,502,503,504]),Bp=6e4,Fs=new WeakMap;function qs(t,e){Fs.set(t,e);}function Gs(t){return t!==null&&(t.reason==="rate_limited"||t.retryAfterSeconds!==void 0)}function Up(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new de(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(t)}. This is a configuration fault, not a server failure.`);return t}var He=class{constructor(e){this.options=e;}options;async get(e,n){return this.send({method:"GET",path:e,signal:n},true)}async getWithEtag(e,n={}){let r=await this.sendRaw({method:"GET",path:e,...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{headers:{"if-none-match":n.ifNoneMatch}}},true),i=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...i}:{modified:true,body:r.body,...i}}async put(e,n,r,i={}){return this.send({method:"PUT",path:e,body:n,signal:r,...Yt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async post(e,n,r,i={}){return this.send({method:"POST",path:e,body:n,signal:r,...Yt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async postBytes(e,n,r,i={}){let o=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...Yt(i)},i.replaySafe===true,i.retryRateLimited!==false);return {bytes:Wp(o.body),...o.invocationId===void 0?{}:{invocationId:o.invocationId}}}async patch(e,n,r,i={}){return this.send({method:"PATCH",path:e,body:n,signal:r,...Yt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...Yt(r)},r.replaySafe===true,r.retryRateLimited!==false)}async send(e,n,r=true){return (await this.sendRaw(e,n,r)).body}async sendRaw(e,n,r=true){let i=n?Up(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw Ls(e.signal);let s=e.signal===void 0?void 0:Fs.get(e.signal);for(let a=0;a<i;a++){if(a>0){let u=this.backoffMs(a,o);if(Gs(o)&&s!==void 0&&u>=s())throw o;await this.backoff(u,e.signal);}if(e.signal?.aborted)throw Gs(o)&&s!==void 0&&s()<=0?o:Ls(e.signal);let l;try{l=await this.options.transport.request(e);}catch(u){if(re.isAuthError(u)||de.isRefusal(u)||e.signal?.aborted||Hp(u))throw u;o=new O("unavailable",0,String(u));continue}if(l.status>=200&&l.status<300||l.status===304)return l;let d=Vp(l);if(!jp.has(l.status)||l.status===429&&!r)throw d;o=d;}throw o??new O("unavailable",0,"no attempt was made")}backoffMs(e,n){let r=n?.retryAfterSeconds,i=r!==void 0?r*1e3:2**(e-1)*250,o=2**(e-1)*250;return Math.min(Math.max(i,o),Bp)}backoff(e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=this.options.clock,o=false,s=false,a,l=()=>{o||(o=true,s&&i.clearTimeout(a),n?.removeEventListener("abort",l),r());};n?.addEventListener("abort",l,{once:true}),a=i.setTimeout(l,e),s=true,o&&i.clearTimeout(a);})}};function Wp(t){if(t instanceof Uint8Array)return t;if(t==null)return new Uint8Array(0);let e=typeof t=="string"?t:JSON.stringify(t);return new TextEncoder().encode(e)}function Yt(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function Ls(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Hp(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function Vp(t){let e=Jp(t),n=Xp(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&Ds.set(e,r),e}var Kp=new Map([["insufficient_funds","insufficient_funds"]]);function Jp(t){let{status:e,body:n}=t,r=zp(n),i=t.retryAfterSeconds??Qp(n),o=Yp(n),s=o===void 0?void 0:Kp.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 zp(t){if(typeof t=="string")return t;let e=t?.message;if(typeof e=="string")return e;let n=t?.error;if(typeof n=="string")return n;let r=n?.message;return typeof r=="string"?r:"no detail"}function Xp(t){let n=t?.error?.details;return n===null?void 0:n}function Yp(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Qp(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function k(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function Ns(t,e,n){let r=`/v1/inventory/transfers/${k(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function js(t,e,n,r,i,o){let s=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}/add`;return t.client.post(s,i,o?.signal)}async function Bs(t,e,n){let r=`/v1/inventory/transfers/${k(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Us(t,e,n){let r=`/v1/games/${k(t.gameId())}/matchmaking/tickets/${k(e)}`;return t.client.delete(r,n?.signal)}async function Ws(t,e,n,r,i,o){let s=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}/claim`;return t.client.post(s,i,o?.signal)}async function Hs(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function Vs(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Ks(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Js(t,e,n){let r=`/v1/games/${k(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function zs(t,e,n,r,i){let o=`/v1/settings/${k(e)}/${k(n)}/${k(r)}`;return t.client.delete(o,i?.signal)}async function Xs(t,e,n,r,i){let o=`/v1/saves/${k(e)}/${k(n)}/${k(r)}`;return t.client.delete(o,i?.signal)}async function Ys(t,e,n,r){let i=`/v1/showcase/players/${k(e)}/${k(n)}`;return t.client.delete(i,r?.signal)}async function Qs(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Zs(t,e,n,r,i,o){let s=`/v1/saves/${k(e)}/${k(n)}/${k(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function el(t,e,n){let r=`/v1/games/${k(t.gameId())}/avatars-3d/${k(e)}/owned`;return t.client.get(r,n?.signal)}async function tl(t,e,n){let r=`/v1/games/${k(t.gameId())}/config/channels/${k(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function nl(t,e,n){let r=`/v1/characters/${k(e)}`;return t.client.get(r,n?.signal)}async function rl(t,e,n){let r=`/v1/inventory/loot-tables/${k(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function il(t,e,n,r,i){let o=`/v1/settings/${k(e)}/${k(n)}/${k(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function ol(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${k(e)}/${k(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function al(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/items/${k(r)}`;return t.client.get(o,i?.signal)}async function sl(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${k(e)}/${k(n)}/${k(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function ll(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/orders/${k(r)}`;return t.client.get(o,i?.signal)}async function dl(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}`;return t.client.get(o,i?.signal)}async function cl(t,e,n,r,i,o){let s=`/v1/inventory/${k(e)}/${k(n)}/catalogs/${k(r)}/recipes/${k(i)}/availability`;return t.client.get(s,o?.signal)}async function ul(t,e,n,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${k(e)}/${k(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Ki(t,e,n,r,i){let o=`/v1/saves/${k(e)}/${k(n)}/${k(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function ml(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${k(e)}/friends`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function pl(t,e,n){let r=`/v1/showcase/friends/${k(e)}`;return t.client.get(r,n?.signal)}async function gl(t,e){let n=`/v1/games/${k(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function fl(t,e,n){let r=`/v1/inbox/friend-challenges/${k(e)}`;return t.client.get(r,n?.signal)}async function yl(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${k(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function hl(t,e){let n=`/v1/games/${k(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function bl(t,e){let n=`/v1/games/${k(t.gameId())}/players/me/passes`;return t.client.get(n,e?.signal)}async function ur(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function vl(t,e,n){let r=`/v1/profiles/players/${k(e)}`;return t.client.get(r,n?.signal)}async function _l(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function wl(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${k(e)}`;return t.client.get(r,n?.signal)}async function Sl(t,e,n,r){let i=`/v1/showcase/players/${k(e)}/${k(n)}`;return t.client.get(i,r?.signal)}async function Rl(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function kl(t,e,n){let r=`/v1/inventory/transfers/${k(e)}`;return t.client.get(r,n?.signal)}async function Al(t,e,n){let r=`/v1/games/${k(t.gameId())}/matchmaking/tickets/${k(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function xl(t,e,n){let r=`/v1/games/${k(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{...n?.keepalive===void 0?{}:{keepalive:n.keepalive},replaySafe:true,retryRateLimited:false})}async function Pl(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function El(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/platform-funded-game-inventory-purchases`;return t.client.post(o,r,i?.signal)}async function Tl(t,e,n){let r=new URLSearchParams;n?.cue_id!==void 0&&r.set("cue_id",String(n?.cue_id));let i=r.toString(),o="/v1/functions/invoke"+(i?`?${i}`:"");return t.client.postBytes(o,e,n?.signal)}async function Il(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Cl(t,e){return t.client.get("/v1/characters",e?.signal)}async function Ml(t,e,n,r){let i=`/v1/settings/${k(e)}/${k(n)}`;return t.client.get(i,r?.signal)}async function Ol(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${k(e)}/${k(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Gl(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${k(e)}/${k(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Ll(t,e){let n=new URLSearchParams;e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inbox/friend-challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Dl(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),i="/v1/friends"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function $l(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Fl(t,e,n){let r=`/v1/inbox/friend-challenges/${k(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function ql(t,e,n,r){let i=`/v1/games/${k(t.gameId())}/matches/${k(e)}/end`;return t.client.post(i,n,r?.signal)}async function Nl(t,e,n,r,i,o){let s=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}/max`;return t.client.post(s,i,o?.signal)}async function jl(t,e,n,r,i,o){let s=`/v1/settings/${k(e)}/${k(n)}/${k(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Bl(t,e,n,r,i){let o=`/v1/showcase/players/${k(e)}/${k(n)}`;return t.client.put(o,r,i?.signal)}async function Ul(t,e,n,r,i){let o=`/v1/inventory/${k(e)}/${k(n)}/rewarded-placements/${k(r)}/availability`;return t.client.get(o,i?.signal)}async function Wl(t,e,n){let r=`/v1/inventory/transfers/${k(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Hl(t,e,n,r){let i=`/v1/characters/${k(e)}`;return t.client.patch(i,n,r?.signal)}async function Vl(t,e,n,r,i,o){let s=`/v1/saves/${k(e)}/${k(n)}/${k(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function Kl(t,e,n,r,i,o){let s=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}/reset`;return t.client.post(s,i,o?.signal)}async function Jl(t,e,n){let r=`/v1/characters/${k(e)}`;return t.client.delete(r,n?.signal)}var B="gem-web-bridge",pr={min:1,max:1},Zp=65536,zl=8,mr=5e3,Xl=1024;var Qt=Object.create(null),gr="__malformed";var Xi=Object.create(null),eg=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"],["gem.prefs.","audioChannels"],["gem.share.","shareRemap"]]);function fr(t){let e=Xi[t];if(e!==void 0)return e;for(let[n,r]of eg)if(t.startsWith(n))return r}function At(t){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(t);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function tg(t){let e;try{e=new URL(t);}catch{return false}return e.username!==""||e.password!==""?false:e.protocol==="https:"?true:e.protocol==="http:"&&(e.hostname==="localhost"||e.hostname==="127.0.0.1")}function ng(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function rg(t){return /^[a-z_]+$/.test(t)}function ig(t){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(t)&&!t.includes("--")}function Ji(t,e,n){if(e>zl)return `nesting deeper than ${zl}`;if(++n.nodes>mr)return `more than ${mr} values`;if(n.bytes>n.cap)return `over the ${n.cap} byte limit`;if(t==null)return n.bytes+=4,null;let r=typeof t;if(r==="boolean")return n.bytes+=5,null;if(r==="number")return n.bytes+=8,null;if(r==="string")return n.bytes+=t.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=t;if(n.seen.has(i))return "a repeated or cyclic object reference";if(n.seen.add(i),Array.isArray(t)){if(t.length>Xl)return `an array of ${t.length} entries, over the ${Xl} limit`;n.bytes+=2;for(let a of t){let l=Ji(a,e+1,n);if(l)return l}return null}let o=Object.getPrototypeOf(t);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";n.bytes+=2;let s=t;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++n.nodes>mr)return `more than ${mr} values`;if(n.bytes+=a.length*3+4,n.bytes>n.cap)return `over the ${n.cap} byte limit`;let l=Ji(s[a],e+1,n);if(l)return l}return null}function og(t,e=Zp){let n={nodes:0,bytes:0,seen:new Set,cap:e},r=Ji(t,0,n);return r?`message contains ${r}`:n.bytes>e?`message is over the ${e} byte limit`:null}var ag={origin:[At,"not a well-formed origin"],url:[tg,"not a safe absolute http(s) URL"],bcp47:[ng,"not a well-formed BCP 47 tag"],code:[rg,"not a code of lower-case letters and underscores"],gameRef:[ig,"not a game id or web address"]};function Yl(t,e,n){for(let r of e){let i=n===""?r[0]:`${n}.${r[0]}`,o=t[r[0]];if(o==null){if(r[1]<"a")continue;return `${i}: required`}let s=zi(o,r,i);if(s)return s}return null}function zi(t,e,n){let r=e[1].toLowerCase();switch(r){case "u":return typeof t=="boolean"?null:zi(t,typeof t=="string"?[e[0],"s",e[2]]:[e[0],"n",e[3],e[4]],n);case "s":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e[2])return `${n}: exceeds ${e[2]} characters`;if(e[3]){let[i,o]=ag[e[3]];if(!i(t))return `${n}: ${o}`}return null}case "n":case "i":return typeof t!="number"||!(r=="i"?Number.isInteger:Number.isFinite)(t)?`${n}: expected ${r=="i"?"integer":"number"}`:t<e[2]||t>e[3]?`${n}: out of range ${e[2]}..${e[3]}`:null;case "b":return typeof t=="boolean"?null:`${n}: expected boolean`;case "e":{let i=e[2];return i.includes(t)?null:`${n}: not one of ${i.join("|")}`}case "o":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:Yl(t,e[2],n);case "j":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "a":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e[2])return `${n}: exceeds ${e[2]} items`;let i=e[3],o=`${n}[]`;for(let s of t){if(s==null){if(i[1]<"a")continue;return `${o}: required`}let a=zi(s,i,o);if(a)return a}return null}default:return `${n}: unknown kind ${String(r)}`}}var Ql=Object.create(null);function P(t,e,n,r,i){return Qt[t]=n,r&&(Xi[t]=r),Ql[t]=o=>{let s=og(o,i);if(s)return s;if(typeof o!="object"||o===null||Array.isArray(o))return "message: expected object";let a=o;return a.gem!==B?"gem: wrong protocol marker":a.type!==t?`type: expected ${t}`:Yl(a,e,"")}}var Zt=["","s",64],V=["requestId","s",64],en=["matchId","s",64],qe=["reason","S",64,"code"],Ve=["outcome","e",["ok","declined","unavailable"]];P("gem.handshake",[["versions","o",[["min","i",1,1e3],["max","i",1,1e3]]],["capabilities","A",64,Zt],["embedder","s",2048,"origin"],["unbidden","B"]],30);P("gem.handshake.accept",[["v","i",1,1e3],["capabilities","A",64,Zt]],5);P("gem.token",[["token","s",4096],["requestId","S",64],["generation","i",0,2147483647],["apiBaseUrl","S",512,"url"],["playerId","s",64],["gameId","s",64],["channel","e",["dev","test","release"]],["gameVersion","S",64],["expiresAt","i",0,4102444800],["chainEndsAt","i",0,4102444800],["allowDevTools","B"]],30);P("gem.token.denied",[V,["retryable","b"],["retryAfterMs","I",0,36e5],["reason","e",["chain_exhausted","unavailable"]],["correlationId","s",64]],30);P("gem.player",[["untrusted","o",[["displayName","s",64],["displayTag","S",80],["displayHandle","s",80]]],["playerId","S",64],["discriminator","S",8],["avatarIconUrl","S",2048,"url"],["avatarIconId","S",64],["avatar3dId","S",64],["avatar3dModelUrl","S",2048,"url"],["avatar3dIconUrl","S",2048,"url"],["avatars3d","A",8,["","o",[["family","s",32],["id","s",64],["modelUrl","s",256,"url"],["iconUrl","s",256,"url"]]]],["badges","A",2,["","o",[["itemId","s",64],["iconUrl","s",2048,"url"]]]],["displayTag","s",8],["avatarUrl","S",2048,"url"],["boost","O",[["multipliers","a",8,["","o",[["currencyId","s",64],["currencySlug","s",32],["multiplierBp","i",1e4,1e6]]]],["expiresInDays","I",1,7]]]],12);P("gem.pause",[["paused","b"]],120);P("gem.prefs",[["reducedMotion","b"],["muted","b"],["showFrameStats","B"],["music","B"],["sounds","B"],["locale","s",35,"bcp47"],["recommended","O",[["volume","i",0,100],["batterySaver","b"],["keyboardLayout","e",["wasd","arrows"]],["gamepadConfirm","e",["south","east"]],["vibration","b"],["lookSensitivity","I",20,400],["gamepadLookSensitivity","I",20,400],["invertLookY","B"],["touchMovement","S",16,"code"],["graphicsQuality","S",16,"code"],["graphicsQualityAuto","B"],["colorHelp","B"]]]],60);P("gem.cohorts",[["cohorts","a",8,["","o",[["experimentId","s",36],["variantKey","s",32]]]]],12,"cohorts");P("gem.earnAllowanceChanged",[],30,"earnAllowance");P("gem.viewport",[["insets","o",[["top","i",0,4096],["right","i",0,4096],["bottom","i",0,4096],["left","i",0,4096]]],["reserved","A",4,["","o",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384],["control","O",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384]]]]]]],60,"viewport");P("gem.deviceSettings",[["settings","J"]],12,"deviceSettings");P("gem.willTerminate",[["reason","e",["grant_expiring","session_ended","navigating","kill_switch"]],["graceMs","i",0,6e4]],10);P("gem.roomEvent",[["event","e",["updated","match_started","match_ready","match_failed","version_stale"]],["roomId","s",64],["matchId","S",64],["version","I",0,2147483647],["reason","S",64],["platform","E",["universal","mobile"]]],120,"rooms");P("gem.socketState",[["connected","b"],["reason","E",["connecting","dropped","watchdog","terminal"]]],12,"socketState");P("gem.seatedEvent",[["roomId","s",64]],60,"partySeating");P("gem.autoStartFailedEvent",[["roomId","s",64],["code","s",64]],30,"autoStartFailure");P("gem.ticketEvent",[["event","e",["queued","matched","expired","cancelled","failed"]],["ticketId","s",64],["partySize","I",1,64],["queuedAt","I",0,4102444800],["expiresAt","I",0,4102444800],["reason","S",64],["roomId","S",64]],60,"ticketEvents");P("gem.signalEvent",[["event","e",["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]],en,["data","j"]],1800,"p2p");P("gem.relayDraining",[en,["clusterTargetId","s",64],["relayIps","a",16,Zt],["drainingSince","s",40],["deadline","s",40]],60,"p2pRelayDrain");P("gem.dedicatedEvent",[["event","e",["answer","error","matchEnded"]],en,["sdp","S",10240],["sessionId","S",64],["code","S",64],["message","S",256],["reason","S",64]],120,"dedicated");P("gem.partyResult",[V,["partyId","S",64]],30,"parties");P("gem.clusterTarget",[["clusterTargetId","s",64],["clusterTargetIds","A",3,Zt]],12,"clusterTarget");P("gem.graphicsRoutes",[["entries","a",32,["","o",[["gpu","s",32],["route","S",32],["host","S",32]]]]],12,"graphicsRoutes");P("gem.devtools",[["action","e",["open","close","toggle"]]],30,"devtools");P("gem.screenshot",[["maxWidth","i",1,7680],["maxHeight","i",1,4320]],6,"screenshot");P("gem.screenshot.denied",[["reason","e",["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]],["retryable","b"]],12,"screenshot");P("gem.requestContext",[],12,"feedbackContext");P("gem.gameContext",[["context","j"]],12,"feedbackContext");P("gem.signal",[["signal","e",["join","offer","answer","ice","migrationAck","hostUnreachable"]],en,["data","j"]],1200,"p2p");P("gem.dedicatedOffer",[en,["sdp","s",10240],["intent","e",["initial","ice_restart","full_reconnect"]]],60,"dedicated");P("gem.partyRequest",[V],12,"parties");P("gem.ready",[],5);P("gem.engaged",[],5,"engagement");P("gem.progress",[["loaded","i",0,1099511627776],["total","i",0,1099511627776]],600);P("gem.requestToken",[V,["reason","e",["initial","expiring","rejected"]]],12);P("gem.requestLocalServer",[V,["gameRoomId","s",64]],6,"localHost");P("gem.localServer",[V,["serverId","S",128]],30,"localHost");P("gem.localServer.denied",[V,["retryable","b"],["reason","e",["refused","unavailable"]]],30,"localHost");P("gem.exit",[["reason","S",64]],5);P("gem.openExternal",[["url","s",2048,"url"]],6);P("gem.requestFullscreen",[["enabled","b"]],30);P("gem.audioState",[["muted","b"]],120,"audioState");P("gem.rewardCue",[["currencySlug","s",32],["cueId","S",64],["expected","I",1,1e9],["origin","O",[["x","i",0,16384],["y","i",0,16384]]]],60,"rewardCue");P("gem.rewardPresentation",[["mode","e",["arcade","game"]]],12,"rewardPresentation");P("gem.walletDisplay",[["visible","b"],["currencies","A",8,Zt],["score","B"]],60,"walletDisplay");P("gem.controlsDeclare",[["uses","o",[["lookSensitivity","S",16,"code"],["gamepadLookSensitivity","S",16,"code"],["invertLookY","S",16,"code"],["touchMovement","S",16,"code"]]]],60,"controls");P("gem.menu",[["settings","b"],["items","A",4,["","o",[["id","s",32],["label","s",40]]]]],60,"gameMenu");P("gem.menuSelect",[["entry","e",["settings","item"]],["id","S",32]],60,"gameMenu");P("gem.gemCorner",[["corner","e",["top-left","top-right","bottom-left","bottom-right"]]],12,"gemCorner");P("gem.menuStyle",[["ground","S",7],["accent","S",7]],12,"menuStyle");P("gem.settingsDeclare",[["settings","a",8,["","o",[["id","s",40],["label","s",40],["kind","e",["toggle","slider","choice"]],["value","u",40,-1e6,1e6],["quick","B"],["icon","S",16,"code"],["min","N",-1e6,1e6],["max","N",-1e6,1e6],["step","N",0,1e6],["options","A",4,["","o",[["id","s",40],["label","s",40]]]]]]]],120,"gameSettings");P("gem.settingChange",[["id","s",40],["value","u",40,-1e6,1e6]],120,"gameSettings");P("gem.requestShare",[["requestId","S",64],["params","a",16,["","o",[["key","s",64],["value","s",512]]]]],6,"share");P("gem.shareResult",[V,["outcome","e",["accepted","refused"]],qe,["key","S",64]],30,"shareResult");P("gem.requestAvatarPicker",[["tab","E",["2d","3d"]]],6,"avatarPicker");P("gem.vibrate",[["pattern","a",99,["","i",0,1e4]]],600,"vibration");P("gem.frameStats",[["fps","i",0,1e3],["frameTimeP95Ms","i",0,1e5],["counts","E",["pageFrames","gameDraws"]]],120,"frameStats");P("gem.portraitBorders",[["name","S",40]],60,"portraitBorders");P("gem.error",[["code","e",["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]],["message","S",256]],60);P("gem.requestPurchase",[V,["purchaseKind","e",["item","recipe"]],["targetId","s",64],["currencySlug","s",32],["quantity","I",1,10],["catalogId","S",64],["origin","E",["sheet","direct_refused"]]],12,"purchases");P("gem.requestAvatar3dPurchase",[V,["itemId","s",64],["currencySlug","s",32]],12,"avatar3dPurchases");P("gem.purchaseResult",[V,Ve,qe,["purchaseId","S",64]],30,"purchases");P("gem.purchaseSettled",[["purchaseKind","e",["item","recipe"]],["targetId","s",64],["catalogId","S",64],["quantity","i",1,10],["purchaseId","S",64]],30,"purchaseSettled");P("gem.deviceSettings.put",[V,["settings","j"]],30,"deviceSettings");P("gem.deviceSettings.result",[V,["outcome","e",["stored","too_large","unavailable"]]],30,"deviceSettings");P("gem.requestAd",[V,["placement","s",32],["format","e",["interstitial","rewarded"]]],6,"ads");P("gem.adResult",[V,["outcome","e",["shown","no_ad","unavailable"]]],12,"ads");P("gem.signalMoment",[V,["kind","e",["level_end","run_end","match_end","menu_return","other_break"]],["placement","S",32],["wall","B"]],6,"moments");P("gem.momentResult",[V,["shown","b"]],12,"moments");P("gem.requestSignIn",[V],6,"signIn");P("gem.signInResult",[V,["outcome","e",["signed_in","declined","unavailable"]]],12,"signIn");P("gem.requestFriendChallenge",[V,["playerId","s",64],["template","s",64],["params","J"]],12,"friendChallenges");P("gem.friendChallengeResult",[V,["outcome","e",["accepted","cancelled","refused","unavailable","rate_limited","invalid"]],["code","S",64],["param","S",64],["channel","S",16],["configVersion","I",0,9007199254740991],["retryAfterMs","I",0,864e5],["detail","S",300]],30,"friendChallenges");P("gem.requestAppLinks",[V],12,"appLinks");P("gem.appLinksResult",[V,Ve,qe,["arcade","O",[["store","e",["app_store","google_play"]]]],["game","O",[["store","e",["app_store","google_play"]]]]],30,"appLinks");P("gem.requestOpenApp",[V,["target","e",["arcade","game"]]],6,"appLinks");P("gem.openAppResult",[V,Ve,qe],30,"appLinks");var Zl=P("gem.requestOpenGame",[V,["ref","s",40,"gameRef"]],6,"openGame");P("gem.openGameResult",[V,Ve,qe],30,"openGame");P("gem.requestSimilarGames",[V,["limit","I",1,24]],12,"openGame");P("gem.similarGamesResult",[V,Ve,qe,["games","a",24,["","o",[["gameId","s",36,"gameRef"],["slug","S",40,"gameRef"],["iconUrl","s",1024,"url"],["capsuleLandscapeUrl","s",1024,"url"],["capsulePortraitUrl","s",1024,"url"],["previewVideoUrl","S",1024,"url"],["previewPosterUrl","S",1024,"url"],["untrusted","o",[["name","s",64],["tagline","s",64],["shortDescription","s",320],["tags","a",10,["","s",32]]]]]]]],30,"openGame",524288);P("gem.requestStoreOffers",[V],12,"store");P("gem.storeOffersResult",[V,Ve,qe,["offers","a",32,["","o",[["skuId","s",64],["kind","e",["gem_pack","boost","pass","bundle"]],["name","s",80],["description","s",400],["imageUrl","S",1024,"url"],["priceDisplay","s",32],["grant","O",[["currency","s",32],["amount","i",1,1e9]]]]]]],30,"store",262144);P("gem.requestStorePurchase",[V,["skuId","s",64]],12,"store");P("gem.storePurchaseResult",[V,Ve,qe],30,"store");P("gem.storePurchaseSettled",[["skuId","s",64]],30,"store");P("gem.requestStoreOfferSheet",[V,["skuId","s",64]],12,"storeOfferSheet");P("gem.storeOfferSheetResult",[V,Ve,qe],30,"storeOfferSheet");var yr=Object.freeze(Ql);Qt.__malformed=60;Object.freeze(Qt);Object.freeze(Xi);var ce={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},tn=class{constructor(e=ce){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Qt[e];if(n===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??n,s=Math.max(0,r-i),a=Math.min(n,o+s*n/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function xt(t,e){return t.toLowerCase()===e.toLowerCase()}function Ke(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function hr(t,e){if(typeof e!="string"||e==="")return false;let n,r;try{n=new URL(t),r=new URL(e);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||n.username!==""||n.password!==""||n.pathname!=="/"||n.search!==""||n.hash!==""||n.port===""?false:Ke(n.hostname)&&Ke(r.hostname)}function ed(t,e){if(e.min>e.max)return null;let n=Math.min(t.max,e.max),r=Math.max(t.min,e.min);return n>=r?n:null}var br=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,n={}){let i=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,o=i.find(a=>a.currencyId===e),s;return !o&&this.resolveCurrencyId&&(s=await this.resolveCurrencyId(e).catch(()=>{}),s!==void 0&&(o=i.find(a=>a.currencyId===s))),{currencyId:o?o.currencyId:s??e,total:o?o.total:null,...o?.buckets===void 0?{}:{buckets:o.buckets}}}};function Qi(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let i=r??{};typeof i.id!="string"||i.id===""||typeof i.threshold!="number"||!Number.isFinite(i.threshold)||n.push({id:i.id,threshold:i.threshold,points:typeof i.points=="number"?i.points:0,hidden:i.hidden===true,...typeof i.unlocked_at=="number"&&Number.isFinite(i.unlocked_at)?{unlockedAt:i.unlocked_at}:{},...i.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var td="inventory",Pt=t=>typeof t=="number"?t:0,nn=t=>typeof t=="string"?t:"";function Yi(t,e){let n=t??{},r=typeof n.next_cursor=="string"?n.next_cursor:void 0;return {data:Array.isArray(n.data)?n.data.map(e):[],...r===void 0?{}:{nextCursor:r}}}function nd(t){let e=t??{};return {itemDefinitionId:nn(e.item_definition_id),instanceId:nn(e.instance_id),quantity:Pt(e.quantity),acquiredAt:Pt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function sg(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Yi(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(s=>{let a=s??{};return {bucket:nn(a.bucket),balance:Pt(a.balance)}}):void 0;return {currencyId:nn(i.currency_id),total:Pt(i.total),...o===void 0?{}:{buckets:o}}}),items:Yi(e.items,nd),progressions:Yi(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:nn(i.progression_definition_id),currentValue:Pt(i.current_value),completionCount:Pt(i.completion_count),isCompleted:i.is_completed===true,...Qi(i)}}),...n===void 0?{}:{etag:n}}}var vr=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${td}#buckets`:td;return this.cache.read(n,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,n){let r=await this.snapshot();if(r.items.nextCursor===void 0){let o=r.items.data.filter(s=>s.itemDefinitionId===e);if(o.length>0)return o}let i=await al(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(i)?i.map(nd):[]}page(e){return this.fetch(e)}refresh(){this.invalidate();}onChanged(e){return this.cache.onInvalidate(e)}invalidate(){this.cache.invalidate();}async fetch(e){let n=await ol(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 sg(n)}};var lg={unknown_currency:1,currency_not_in_game_payable:1,not_purchasable:1,no_price_in_currency:1,busy:1,cancelled:1,insufficient_funds:1,price_mismatch:1,config_version_stale:1,platform_currency_unavailable:1,not_available:1,recipe_locked:1,already_owned:1,guest_upgrade_required:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},dg=new Set(Object.keys(lg));function rd(t){return typeof t=="string"&&dg.has(t)?t:"error"}var Je=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var ie=t=>typeof t=="string"?t:"",cg=t=>typeof t=="string"?t:ie(t&&typeof t=="object"?t.type:void 0),Ge=t=>typeof t=="number"?t:0;function ug(t){let e=t??{};return {prerequisiteType:ie(e.prerequisite_type),referenceId:ie(e.reference_id),required:Ge(e.required),current:Ge(e.current)}}function rn(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:ie(e.order_id),status:ie(e.status),...n===void 0?{}:{etag:n}}}function _r(){return crypto.randomUUID()}var mg="recipe-usage",id=100;function wr(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:ie(e.currency_id),bucket:ie(e.bucket),delta:Ge(e.delta),balanceAfter:Ge(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:ie(e.item_definition_id),instanceId:ie(e.instance_id),delta:Ge(e.delta),quantityAfter:Ge(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:ie(e.progression_definition_id),delta:Ge(e.delta),valueAfter:Ge(e.value_after),completed:e.completed===true};default:return {kind:"other",type:ie(e.type)}}}function pg(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:ie(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Ge(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(wr):[]}}function gg(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(pg):void 0;return {orderId:ie(e.order_id),status:ie(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(wr):[],consumed:Array.isArray(e.consumed)?e.consumed.map(wr):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(wr):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function fg(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:ie(e.target_order_id)||ie(e.source_order_id),status:ie(e.status),purchaseId:ie(e.purchase_id),sourceOrderId:ie(e.source_order_id),price:{currencyId:ie(n.platform_currency_id),amount:Ge(n.price)}}}function yg(t){let e=t??{},n=typeof e.last_used_at=="string"?e.last_used_at:void 0,r=typeof e.cooldown_expires_at=="string"?e.cooldown_expires_at:void 0;return {recipeId:ie(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...n===void 0?{}:{lastUsedAt:n},...r===void 0?{}:{cooldownExpiresAt:r}}}function od(t){switch(t.type){case "currency_grant":case "currency_consume":return {type:t.type,currency_id:t.currencyId,amount:t.amount};default:return {type:t.type,item_definition_id:t.itemDefinitionId,quantity:t.quantity}}}var Sr=class{constructor(e,n,r,i){this.api=e;this.entity=n;this.cache=r;this.handOffRefused=i;}api;entity;cache;handOffRefused;async create(e,n={}){let r=await this.write(()=>Ks(this.api,this.entity.type,this.entity.id,{operations:e.map(od),source:n.source??"play",nonce:_r()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return rn(r)}async createMany(e,n={}){return this.write(()=>Vs(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(od),nonce:_r()})),source:n.source??"play"},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}))}async recipeAvailability(e,n,r){let o=await cl(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},s=typeof o.uses_remaining=="number"?o.uses_remaining:void 0,a=typeof o.cooldown_expires_at=="string"?o.cooldown_expires_at:void 0,l=Array.isArray(o.lock_reasons)?o.lock_reasons.map(ug):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>cg(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(mg,[],async()=>{let n=await ul(this.api,this.entity.type,this.entity.id,{limit:id})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(yg),truncated:r.length>=id}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let c=e,g=await this.write(()=>Qs(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:_r()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...gg(g)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,i]=await Promise.all([_l(this.api,n.signal===void 0?{}:{signal:n.signal}),ur(this.api,n.signal===void 0?{}:{signal:n.signal})]),o=e.payment.currencySlug.toLowerCase(),s=i.currencies.find(c=>c.currency_id.toLowerCase()===o||c.slug.toLowerCase()===o);if(s===void 0){let c=i.currencies.map(g=>g.slug);throw new Je("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${c.length===0?"none":c.join(", ")}`)}let a=e.kind==="item"?r.items.find(c=>c.item_id===e.targetId):r.recipes.find(c=>c.recipe_id===e.targetId&&c.catalog_id===e.catalogId);if(a===void 0)throw new Je("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=a.platform_prices.find(c=>c.platform_currency_id===s.currency_id);if(l===void 0){let c=p=>i.currencies.find(f=>f.currency_id===p)?.slug??p,g=a.platform_prices.map(p=>`${c(p.platform_currency_id)} ${p.price}`);throw new Je("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.slug} price. It is priced in: ${g.length===0?"nothing":g.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Je("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let u;try{u=await this.write(()=>El(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:_r(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));}catch(c){if(this.handOffRefused!==void 0&&c instanceof O&&c.status===403&&c.code==="guest_upgrade_required")try{this.handOffRefused({kind:e.kind,targetId:e.targetId,...e.kind==="recipe"?{catalogId:e.catalogId}:{},currencySlug:s.slug,quantity:d});}catch{}throw c}return fg(u)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let i=await this.write(()=>js(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return rn(i)}async maxProgression(e,n,r){let i=await this.write(()=>Nl(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return rn(i)}async claimProgression(e,n){let r=await this.write(()=>Ws(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return rn(r)}async resetProgression(e,n){let r=await this.write(()=>Kl(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return rn(r)}async write(e){return this.cache.invalidate(),e()}};var Zi=t=>typeof t=="string"?t:"",hg=t=>typeof t=="number"?t:0;function ad(t){let e=t??{};return {orderId:Zi(e.order_id),status:Zi(e.status),source:Zi(e.source),createdAt:hg(e.created_at)}}var Rr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await Ol(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(ad):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await ll(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return ad(r)}};var bg=["live"],eo=6e4,sd=864e5;function vg(t){let e=t?.passes;if(!Array.isArray(e))return Object.freeze([]);let n=e.flatMap(r=>{let i=r??{};if(typeof i.pass!="string"||i.pass==="")return [];let o=i.held===true,s=o&&typeof i.ends_at=="string"?i.ends_at:null;return [Object.freeze({pass:i.pass,held:o,endsAt:s})]});return Object.freeze(n)}function _g(t){let n=t.flatMap(r=>r.endsAt===null?[]:[Date.parse(r.endsAt)]).filter(r=>Number.isFinite(r));return n.length===0?null:Math.min(...n)}function ld(t,e,n={}){let{watch:r}=n,i=new Set,o=null,s=0,a=null,l=eo,d=()=>{a!==null&&r?.clock.clearTimeout(a.handle),a=null;},u=v=>{d(),!(r===void 0||i.size===0)&&(a={handle:r.clock.setTimeout(S,v)});},c=v=>{let R=_g(v);if(R===null||r===void 0){d();return}let h=R-r.clock.now();u(h>0?Math.min(h,sd):eo);},g=v=>{r?.log?.(`[gem] a passes 'changed' listener threw: ${v instanceof Error?v.message:String(v)}`);},p=v=>{let R=o!==null&&JSON.stringify(o)!==JSON.stringify(v);if(o=v,l=eo,c(v),!!R)for(let h of [...i])try{let _=h(v);typeof _?.then=="function"&&_.then(void 0,g);}catch(_){g(_);}},f=()=>{let v=s;return e.read("passes",bg,()=>bl(t)).then(R=>{if(v!==s)return f();let h=vg(R);return p(h),h})},y=()=>{f().catch(()=>{u(l),l=Math.min(l*2,sd);});};function S(){s+=1,e.invalidate(),d(),r!==void 0&&i.size>0&&y();}return {api:{list:f,async get(v){return (await f()).find(h=>h.pass===v)??Object.freeze({pass:v,held:false,endsAt:null})},on(v,R){let h=i.size===0;return i.add(R),h&&r!==void 0&&(o===null?y():c(o)),()=>{i.delete(R),i.size===0&&d();}}},recheck:S}}var dd=t=>typeof t=="number"?t:0,wg=t=>typeof t=="string"?t:"";function Sg(t){let e=t??{};return {progressionDefinitionId:wg(e.progression_definition_id),currentValue:dd(e.current_value),completionCount:dd(e.completion_count),isCompleted:e.is_completed===true,...Qi(e)}}var kr=class{constructor(e,n,r){this.api=e;this.entity=n;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,n){let i=(await this.inventory.snapshot()).progressions.data.find(o=>o.progressionDefinitionId===e);if(i&&i.achievementsUnavailable!==true)return i;try{let o=await dl(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Sg(o)}catch{return i??null}}};var on=class{constructor(e,n){this.clock=e;this.identity=n;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,n,r,i){this.rebind();let o=n.length===0,s=o?e:e+"\0"+n.join("\0"),a=this.slots.get(s);if(a){let c=a.filledAt;if(c!==void 0&&(i===void 0||this.clock.now()-c<=i))return Promise.resolve(a.value);if(a.inFlight)return a.inFlight}let l=a??{};this.slots.set(s,l);let d=this.generation,u=r().then(c=>(o&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===u&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=u,u}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function Rg(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var kg=new Set(lr);function Ag(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))kg.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function Ar(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return Os(async(n,r)=>{let i;try{i=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new de("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let o;try{o=new URL(i.href.replace(/\/+$/,"")+n.path);}catch{throw new de(`${JSON.stringify(typeof n.path=="string"?Rg(n.path):"(a non-string path)")} does not form a valid URL against ${i.protocol}//${i.host}. This is a malformed request, not a server failure.`)}if(o.protocol!==i.protocol||o.host!==i.host)throw new de(`${JSON.stringify(o.pathname)} resolves to ${o.protocol}//${o.host}, not ${i.protocol}//${i.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(o.username!==""||o.password!==""){let p=i.username!==""||i.password!=="",f=o.username!==i.username||o.password!==i.password,y=p?f?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new de(`the ${y} puts credentials in the URL, which cannot be fetched (${n.method} ${o.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[p,f]of Object.entries(t.defaultQuery??{}))o.searchParams.has(p)||o.searchParams.set(p,f);let s=n.bytes,a=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(s=JSON.stringify(n.body),a="application/json");}catch(p){throw new de(`the body of ${n.method} ${JSON.stringify(o.pathname)} could not be serialised to JSON: ${String(p)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(o.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...Ag(n.headers)},body:s,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let p=await l.text();if(p.length>0)try{d=JSON.parse(p);}catch{d=p;}}let u=l.headers.get("etag"),c=to(l.headers.get("retry-after")),g=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...u===null?{}:{etag:u},...c===void 0?{}:{retryAfterSeconds:c},...g===null||g===""?{}:{invocationId:g}}},t)}function to(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}function no(t){let e=i=>new RegExp(`<${i}>([^<]{0,300})</${i}>`).exec(t)?.[1]?.trim()||void 0,n=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(n.length>0)return n.join(" \u2014 ");let r=t.trim();return r?r.slice(0,300):""}async function xr(t){try{let e=no(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var oe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},xg=3e4,Pg=5e3,cd=6e4,Eg=2**31-1,ud="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",Tg=/^[A-Za-z0-9_]{1,64}$/;function Ne(t){let e=t.length===0?"a save key cannot be empty":t.length>64?`it is ${t.length} characters; a save key is at most 64`:t.startsWith("_")||t.startsWith("$")?`it begins with ${JSON.stringify(t[0])}, and \`_\` and \`$\` are reserved prefixes`:"a save key is ASCII letters, digits and underscores only \u2014 no hyphens, spaces or other punctuation, unlike a template slug";if(!Tg.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function md(t,e){let n=new AbortController,r=Date.now()+e;qs(n.signal,()=>r-Date.now());let i=AbortSignal.timeout(e),o=()=>n.abort(i.reason),s=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(i.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",s,{once:true})),{signal:n.signal,release:()=>{i.removeEventListener("abort",o),t?.removeEventListener("abort",s);}}}function ro(t,e){return t.aborted&&e?.aborted!==true}var Ig=new Set(["x-ms-blob-type"]),Cg=/^[ -~]+$/;function Mg(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(t)?"a list":typeof t}, which is not a set of headers.`);let n={};for(let[r,i]of Object.entries(t)){let o=r.toLowerCase();if(!Ig.has(o))throw new oe("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"||!Cg.test(i))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(o in n)throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);n[o]=i;}return n}function io(t){let e=typeof t.metadata=="object"&&t.metadata!==null&&!Array.isArray(t.metadata)?t.metadata:void 0;return {key:t.key,sizeBytes:t.size_bytes,etag:t.etag,...e===void 0?{}:{metadata:e},createdAt:t.created_at,updatedAt:t.updated_at}}function oo(t){return t?.reason==="not_found"}function Og(t){return t?.code==="save_conflict"}function pd(t){return t instanceof O&&t.reason==="rate_limited"}async function gd(t,e){let n=await xr(e);return new O("rate_limited",429,`the save ${t} answered 429: too many save calls. ${n}`.trim(),to(e.headers.get("retry-after")))}function Pr(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Gg(t,e,n,r,i){let o=false,s=()=>o?false:(o=true,a.detach?.(),true),a={signal:n.signal,budget:r,deadlineAt:Date.now()+r,teardown:n.teardown===true,overwrite:n.overwrite===true,identity:i,resolve:l=>{s()&&t(l);},reject:l=>{s()&&e(l);},detach:void 0};return a}function fd(t,e){return t!==null&&e!==null&&e!==t}function yd(t){return new oe("save_conflict",`save ${JSON.stringify(t)} was not written: the signed-in player changed while it waited for the write before it, and it holds the last player's progress.`)}var Er=class{constructor(e,n,r={},i){this.api=e;this.entity=n;this.options=r;this.identity=i;}api;entity;options;identity;versions=new Map;seq=0;versionsOf=null;writes=new Map;holdUntil=0;async put(e,n,r={}){let i;try{i=JSON.stringify(n);}catch(o){throw new oe("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 oe("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(i),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){if(Ne(e),r.signal?.aborted)throw Pr(r.signal);let i=this.budget(r.timeoutMs),o=this.slotWrites(e);return new Promise((s,a)=>{let l=o.queued;l?.release();let d=l?.waiters[l.waiters.length-1];d!==void 0&&this.holdOwn(o,d);let u=this.identity?.()??null;for(let c of l?.waiters.slice()??[])fd(c.identity,u)&&this.drop(o,c,yd(e));o.queued=this.queue(o,n,r,Gg(s,a,r,i,u),l?.waiters??[]),o.wake?.(),this.pump(e,o);})}holdOwn(e,n){let{signal:r}=n,i=n.deadlineAt-Date.now();if(r?.aborted)return this.drop(e,n,Pr(r));if(i<=0)return this.drop(e,n,this.timeout("save",n.budget));let o=AbortSignal.timeout(i),s=()=>this.drop(e,n,this.timeout("save",n.budget)),a=()=>{r&&this.drop(e,n,Pr(r));};o.addEventListener("abort",s,{once:true}),r?.addEventListener("abort",a,{once:true}),n.detach=()=>{o.removeEventListener("abort",s),r?.removeEventListener("abort",a);};}drop(e,n,r){let i=e.queued?.waiters,o=i?.indexOf(n)??-1;o>=0&&i?.splice(o,1),n.reject(r),e.wake?.();}queue(e,n,r,i,o){let{budget:s}=i,a=[...o,i],l=AbortSignal.timeout(s),d=p=>{if(e.queued===g){this.take(e,g);for(let f of a)f.reject(p);e.wake?.();}},u=()=>d(this.timeout("save",s)),c=()=>{r.signal&&d(Pr(r.signal));};l.addEventListener("abort",u,{once:true}),r.signal?.addEventListener("abort",c,{once:true});let g={bytes:n,options:r,budget:s,deadlineAt:i.deadlineAt,identity:i.identity,waiters:a,release:()=>{l.removeEventListener("abort",u),r.signal?.removeEventListener("abort",c);}};return g}async pump(e,n){if(!n.running){n.running=true;try{for(let r=n.queued;r!==void 0;r=n.queued){let i=Date.now(),o=this.holdUntil-i;if(o>0){if(o>=r.deadlineAt-i){this.take(n,r);for(let l of r.waiters)l.reject(this.held(e,o));continue}for(let l of r.waiters.slice(0,-1))o>=l.deadlineAt-i&&this.drop(n,l,this.held(e,o));}let s=Math.max(o,this.spacing(n,r,i));if(s>0){await this.pause(n,s);continue}this.take(n,r);let a;try{a=this.precondition(e,r);}catch(l){for(let d of r.waiters)d.reject(l);continue}n.lastSentAt=i;try{let l=await this.send(e,r,a);for(let d of r.waiters)d.resolve(l);}catch(l){for(let d of r.waiters)d.reject(l);}}}finally{n.running=false;}}}spacing(e,n,r){if(e.lastSentAt===void 0||n.waiters.some(s=>s.teardown))return 0;let i=this.options.minWriteIntervalMs??Pg,o=Math.min(...n.waiters.map(s=>s.deadlineAt-s.budget/2));return Math.min(e.lastSentAt+i,o)-r}pause(e,n){return new Promise(r=>{let i=()=>{clearTimeout(o),e.wake===i&&(e.wake=void 0),r();},o=setTimeout(i,Math.min(n,Eg));e.wake=i;})}take(e,n){e.queued===n&&(e.queued=void 0),n.release();}slotWrites(e){let n=this.writes.get(e);return n===void 0&&(n={running:false,queued:void 0,lastSentAt:void 0,wake:void 0},this.writes.set(e,n)),n}noteRateLimit(e){if(!pd(e))return;let n=e.retryAfterSeconds,r=n===void 0?cd:Math.min(n*1e3,cd);this.holdUntil=Math.max(this.holdUntil,Date.now()+r);}held(e,n){let r=Math.ceil(n/1e3);return new O("rate_limited",429,`save ${JSON.stringify(e)} was not sent: the platform refused a save call for the rate, and the wait it asked for ends in ${r}s, after this call's timeoutMs. Keep the state and write once the wait is over.`,r)}async send(e,n,r){let{bytes:i,options:o,budget:s}=n,a=o.contentType??"application/octet-stream",l=md(o.signal,Math.max(0,n.deadlineAt-Date.now()));try{let d=await Vl(this.api,this.entity.type,this.entity.id,e,{size_bytes:i.byteLength,content_type:a,...r,...o.metadata===void 0?{}:{metadata:o.metadata}},{signal:l.signal});if(typeof d.upload_url!="string"||typeof d.session_id!="string")throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let u=Mg(d.upload_headers,e),c,g=this.options.fetch??globalThis.fetch.bind(globalThis);try{c=await g(d.upload_url,{method:"PUT",headers:{"content-type":a,...u},body:i,credentials:"omit",signal:l.signal});}catch(f){throw ro(l.signal,o.signal)?this.timeout("upload",s):new oe("upload_failed",`${ud} for PUT. Underlying error: ${f}`)}if(c.status===429)throw await gd("upload",c);if(!c.ok){let f=await xr(c);throw new oe("upload_failed",c.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+f:`the save upload answered ${c.status}. `+(c.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+f)}let p=io(await Zs(this.api,this.entity.type,this.entity.id,e,{session_id:d.session_id},{signal:l.signal}));return this.remember(e,p.etag?{kind:"etag",etag:p.etag}:void 0),p}catch(d){throw Og(d)?new oe("save_conflict",`save ${JSON.stringify(e)} was not written: the stored save changed since this game last loaded or wrote it, so another device or tab saved in between. Load it again and decide what to write from what is stored, rather than resending this write.`):(this.noteRateLimit(d),this.rethrow(d,o.signal,l.signal,"save",s))}finally{l.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(i){throw new oe("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${i}`)}}async getBytes(e,n={}){Ne(e);let r=this.budget(n.timeoutMs),i=md(n.signal,r),o=this.seq;try{let s;try{let u=await Ki(this.api,this.entity.type,this.entity.id,e,{signal:i.signal});if(!u.modified)return this.remember(e,{kind:"empty"},o),null;s=u.body;}catch(u){if(oo(u))return this.remember(e,{kind:"empty"},o),null;throw u}if(typeof s.download_url!="string")throw new oe("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),l;try{l=await a(s.download_url,{credentials:"omit",signal:i.signal});}catch(u){throw ro(i.signal,n.signal)?this.timeout("download",r):new oe("download_failed",`${ud} for GET. Underlying error: ${u}`)}if(l.status===429)throw await gd("download",l);if(!l.ok){let u=await xr(l);throw new oe("download_failed",`the save download answered ${l.status}. `+(l.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+u)}let d=new Uint8Array(await l.arrayBuffer());return this.remember(e,s.etag?{kind:"etag",etag:s.etag}:void 0,o),d}catch(s){throw this.slots().get(e)===void 0&&this.remember(e,{kind:"failed"}),this.noteRateLimit(s),this.rethrow(s,n.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,n={}){try{let r=await Ki(this.api,this.entity.type,this.entity.id,Ne(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?io(r.body):null}catch(r){if(oo(r))return null;throw r}}async list(e={}){let n=await Gl(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}}),r=n.next_cursor;return {saves:(n.data??[]).map(io),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await Xs(this.api,this.entity.type,this.entity.id,Ne(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!oo(r))throw r}this.remember(e,{kind:"empty"});}precondition(e,n){if(fd(n.identity,this.identity?.()??null))throw yd(e);if(n.waiters.some(i=>i.overwrite))return {};let r=this.slots().get(e);if(r===void 0)return {};if(r.kind==="etag")return {if_match:r.etag};if(r.kind==="empty")return {if_none_match:"*"};throw new oe("load_failed",`save ${JSON.stringify(e)} was not written: the last load of this slot failed, so what this write would replace is unknown, and it could be the player's real progress. Load it again before saving, or pass overwrite: true if replacing whatever is stored is what you mean.`)}remember(e,n,r){let i=this.slots(),o=i.get(e);r!==void 0&&o!==void 0&&o.kind!=="failed"&&o.seq>r||(this.seq+=1,n===void 0?i.delete(e):i.set(e,{...n,seq:this.seq}));}slots(){let e=this.identity?.()??null;return e!==null&&e!==this.versionsOf&&(this.versionsOf!==null&&this.versions.clear(),this.versionsOf=e),this.versions}budget(e){return e??this.options.timeoutMs??xg}timeout(e,n){return new oe("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,i,o){return e instanceof oe||pd(e)?e:ro(r,n)?this.timeout(i,o):e}};function Lg(t){try{return Vi(t)}catch{return t}}function ao(t,e){let n=t??{},r=typeof n.etag=="string"?n.etag:e;return {key:typeof n.key=="string"?n.key:"",value:typeof n.value=="string"?Lg(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var Tr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await Ml(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>ao(i)):[]}async get(e,n={}){try{let r=await il(this.api,this.entity.type,this.entity.id,e,{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?ao(r.body,r.etag):null}catch(r){if(hd(r))return null;throw r}}async put(e,n,r={}){let i=await jl(this.api,this.entity.type,this.entity.id,e,{value:dr(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return ao(i)}async delete(e,n){try{await zs(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!hd(r))throw r}}};function hd(t){return t?.reason==="not_found"}function so(t,e,n={}){let r=new on(ce,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let i=new vr(t,e,r);return {settings:new Tr(t,e),inventory:i,saves:new Er(t,e,n.saves??{},n.identity),currencies:new br(i,n.resolveCurrencyId),mutations:new Sr(t,e,r,n.handOffRefusedPurchase),orders:new Rr(t,e),progressions:new kr(t,e,i)}}function bd(t,e,n={}){let r=new on(ce,n.identity),i=ld(t,r,n);return {scope:{...so(t,e,n),passes:i.api},recheckPasses:i.recheck}}var lo={type:"players",id:"me"};var it=t=>typeof t=="string"?t:"",Et=t=>typeof t=="number"?t:0;function Ir(t,e){let n=e??{},r=it(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:it(n.player_id),gameId:it(n.game_id),channel:it(n.channel)||"release",name:it(n.name),slotIndex:Et(n.slot_index),isActive:n.is_active!==false,createdAt:it(n.created_at),updatedAt:it(n.updated_at)}}var Cr=class{constructor(e,n,r,i){this.api=e;this.saves=n;this.identity=r;this.resolveCurrencyId=i;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let n=this.scopes.get(e);return n||(n=so(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,n)),n};async list(e){let r=(await Cl(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>Ir(this.scope,i)):[]}async get(e,n){let r=await nl(this.api,e,n===void 0?{}:{signal:n});return Ir(this.scope,r)}async create(e){let n=await Hs(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Ir(this.scope,n)}async update(e,n,r){let i=await Hl(this.api,e,{name:n},r===void 0?{}:{signal:r});return Ir(this.scope,i)}async delete(e,n){await Jl(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await Rl(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:Et(r?.total_slots),availableSlots:Et(r?.available_slots),activeCharacterCount:Et(r?.active_character_count),defaultMaxSlots:Et(r?.default_max_slots),purchasedExtraSlots:Et(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var wd="[gem: use gem.text.toPlain()]",vd=new Set,_d;function Dg(t){try{if(vd.has(t))return;let e=globalThis.location;if(_d??=!!e?.port&&Ke(e.hostname??""),!_d)return;vd.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${wd}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
|
|
2
|
+
${new Error().stack}`);}catch{}}var ve=class{#e;#n;constructor(e,n="player text"){this.#e=e,this.#n=n,Object.freeze(this);}toString(){return Dg(this.#n),wd}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function be(t,e){return new ve(t,e)}var ot={toPlain(t){return ve.unwrap(t)},compare(t,e,n){let r=t instanceof ve?ve.unwrap(t):t,i=e instanceof ve?ve.unwrap(e):e;if(typeof Intl>"u"||typeof Intl.Collator!="function")return r<i?-1:r>i?1:0;let o;try{o=new Intl.Collator(n);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(t,e){let n=t instanceof ve?ve.unwrap(t):t,r=e instanceof ve?ve.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var Tt=t=>typeof t=="string"?t:"";function Mr(t){let e=t??{},n=typeof e.message=="string"&&e.message.length>0?e.message:void 0,r=typeof e.resolved_at=="string"?e.resolved_at:void 0;return {id:Tt(e.transfer_id),status:Tt(e.status),sourceEntityId:Tt(e.source_entity_id),targetEntityId:Tt(e.target_entity_id),...n===void 0?{}:{message:be(n,"transfer.message")},createdAt:Tt(e.created_at),expiresAt:Tt(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function $g(){return crypto.randomUUID()}var Or=class{constructor(e,n,r){this.api=e;this.self=n;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let n=await Pl(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:$g()},e.signal===void 0?{}:{signal:e.signal});return Mr(n)}async list(e={}){let r=await $l(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(Mr):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await kl(this.api,e,n===void 0?{}:{signal:n});return Mr(r)}async accept(e,n){return this.resolve(()=>Ns(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>Wl(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>Bs(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Mr(await e())}};var Fg=t=>typeof t=="string"?t:"",qg=t=>typeof t=="string"&&t?t:void 0,Ng=t=>typeof t=="number"?t:void 0;function Sd(t){let e=new Map(t.map(r=>[r.id,r])),n=new Map(t.filter(r=>r.slug).map(r=>[r.slug,r]));return r=>e.get(r)??n.get(r)??null}function jg(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new pe("config_malformed",`the config document is ${t===null?"null":typeof t}, expected a JSON object`);let e=t,n=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new pe("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Ng(e.version);if(r===void 0)throw new pe("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let i=(l,d,u)=>{let c=Fg(l.id);if(!c)throw new pe("config_malformed",`${d}[${u}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return c},o=n("items");o.forEach((l,d)=>i(l??{},"items",d));let s=n("currencies");s.forEach((l,d)=>i(l??{},"currencies",d));let a=t;return {...a,version:r,hash:typeof a.hash=="string"?a.hash:"",items:o,currencies:s,catalogs:n("catalogs"),loot_tables:n("loot_tables"),affix_pools:n("affix_pools"),progressions:n("progressions"),game_room_templates:n("game_room_templates"),kv:typeof a.kv=="object"&&a.kv!==null&&!Array.isArray(a.kv)?a.kv:{},item:Sd(o),currency:Sd(s)}}var pe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},Rd=10*1024*1024,kd=15e3,Ad=new Set(["dev","test","release"]);function Bg(t){if(!Ad.has(t))throw new pe("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Ad].join(", ")}. gem-api would reject the assignment read.`);return t}var Gr=t=>typeof t=="number"?t:0,co=t=>typeof t=="string"?t:"";function Ug(t){let e=t??{},n=Array.isArray(e.entries)?e.entries.map(r=>{let i=r??{},o=typeof i.rarity_tier=="string"?i.rarity_tier:void 0;return {entryId:co(i.entry_id),weight:Gr(i.weight),dropRate:Gr(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:co(e.loot_table_id),name:co(e.name),rollCount:Gr(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Gr(e.total_weight),entries:n}}var Lr=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=void 0;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded!==void 0)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,n=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===n&&(this.inFlight=null);});return this.inFlight=n,n}refresh(){this.loaded=void 0,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new pe("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 rl(this.api,e,n===void 0?{}:{signal:n});return Ug(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??kd),n;try{let l=await tl(this.api,Bg(this.channel()),{signal:e});if(!l.modified)throw new pe("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof pe)throw l;if(l?.reason==="not_found")return null;throw l}let r=qg(n.config_url);if(r===void 0)return null;let i=this.options.fetch??globalThis.fetch.bind(globalThis),o;try{o=await i(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new pe("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??kd}ms`):new pe("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=>no(d)).catch(()=>"");throw new pe("config_unreachable",`the config document answered ${o.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await o.text();if(s.length>Rd)throw new pe("config_too_large",`the config document is ${s.length} bytes, over the ${Rd} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new pe("config_malformed",`config document is not JSON: ${String(l)}`)}return jg(a)}};var xd=400,Le=t=>typeof t=="string"?t:"",Wg=/(?:Z|[+-]\d{2}:?\d{2})$/i;function at(t){let e=Le(t);if(!Wg.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Hg=/^[0-9a-f]{1,64}$/,Vg=/^[0-9a-f]{16}$/,Kg=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Jg=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function uo(t){let e=Le(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,i,o]=[Number(n[1]),Number(n[2]),Number(n[3])],s=new Date(Date.UTC(r,i-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===i-1&&s.getUTCDate()===o?e:void 0}var zg=4096,Xg=new TextEncoder;function Yg(t){let e=Le(t.challenge_data),n=Le(t.challenge_data_hash);return e===""||!Vg.test(n)?{}:Xg.encode(e).length>zg?{}:{data:e,dataHash:n}}function Qg(t){let e=t??{},n=at(e.period_start_at),r=at(e.period_ends_at);if(n===0||r===0)return;let i=Le(e.slug),o=Le(e.seed),s=uo(e.period_local_date),a=Le(e.boundary),l=Le(e.reset_time);return {id:Le(e.progression_definition_id),...i===""?{}:{slug:i},window:Le(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:Kg.test(a)?a:"",resetTime:Jg.test(l)?l:"",seed:Hg.test(o)?o:"",...Yg(e)}}function It(t){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(t)}`)}function Dr(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Qg).filter(n=>n!==void 0):[]}var an=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;It(n);let r=await Il(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return Dr(r)}};function De(t){return typeof t=="string"&&t!==""?t:void 0}var Pd=new Set(["localhost","127.0.0.1","[::1]"]);function st(t){return Ct(t)}function Ct(t){let e=De(t);if(e===void 0)return;let n;try{n=new URL(e);}catch{return}if(!(n.username!==""||n.password!=="")&&(n.protocol==="https:"||n.protocol==="http:"&&Pd.has(n.hostname)))return e}var Zg=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,ef=/^[a-z][a-z0-9_]{0,31}$/;function tf(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let i=r??{},o=De(i.family),s=De(i.avatar_3d_id),a=st(i.model_url),l=st(i.icon_url);o===void 0||!ef.test(o)||n.has(o)||s===void 0||!Zg.test(s)||a===void 0||l===void 0||(n.add(o),e.push({family:o,id:s,modelUrl:a,iconUrl:l}));}return e}function nf(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},i=De(r.item_id),o=st(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function Te(t){let e=t??{},n=De(e.player_id),r=De(e.display_name),i=De(e.discriminator),o=De(e.display_tag),s=De(e.avatar_icon_id),a=st(e.avatar_icon_url),l=De(e.avatar_3d_id),d=st(e.avatar_3d_model_url),u=st(e.avatar_3d_icon_url),c=tf(e.avatars_3d);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:be(r,"displayName")},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:be(o,"displayTag")},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...u===void 0?{}:{avatar3dIconUrl:u},...c===void 0?{}:{avatars3d:c},badges:nf(e.badges)}}var rf=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function mo(t){if(t===void 0)return;let e=st(t);if(e===void 0)return;let n=new URL(e);return Pd.has(n.hostname)||rf.has(n.origin)?e:void 0}var Ed=100,Cd=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function po(t){let{periodsBack:e,period:n,playerId:r}=t;if(It(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!Cd.test(n)))throw new TypeError(`period must be a period id such as 2026-10-02 (a result's period.id), got ${String(n)}`);if(r!==void 0&&(typeof r!="string"||r===""))throw new TypeError("playerId must be a player id");return {...e===void 0?{}:{periods_back:e},...n===void 0?{}:{period:n},...r===void 0?{}:{player_id:r}}}function Md(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!Cd.test(e))return;let n=uo(t.period_local_date),r=at(t.period_start_at),i=at(t.period_ends_at),o=r>0&&i>0;return {id:e,...n===void 0?{}:{localDate:n},...o?{startAt:r,endsAt:i}:{},opensAt:at(t.opens_at),closesAt:at(t.closes_at),final:t.final===true}}var sn=t=>typeof t=="string"?t:"",Mt=t=>typeof t=="number"?t:0,ln=t=>typeof t=="string"?t:void 0,of=t=>typeof t=="number"?t:void 0,Od={player:"players",character:"characters"};function af(t,e){let n=t??{},r=ln(n.entity_id),i=typeof n.entity_type=="string"&&Object.hasOwn(Od,n.entity_type)?n.entity_type:void 0,o=Gd(n.stats),s=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,a=e?n.is_viewer===true:void 0;return {...Te(n),rank:Mt(n.rank),occurredAt:Mt(n.occurred_at),...a===void 0?{}:{isViewer:a},...r===void 0?{}:{entityId:r},...i===void 0?{}:{entityType:i},...o===void 0?{}:{stats:o},...s===void 0?{}:{properties:s}}}function Td(t,e){let n=t??{},r=ln(n.bucket_1),i=ln(n.bucket_2),o=of(n.update_frequency_seconds),s=Md(n);return {leaderboardType:sn(n.leaderboard_type),runType:sn(n.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(n.entries)?n.entries.map(a=>af(a,e)):[],generatedAt:Mt(n.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...s===void 0?{}:{period:s}}}function Id(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=Gd(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:Mt(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function Gd(t){if(t===null||typeof t!="object")return;let e={};for(let[n,r]of Object.entries(t))typeof r=="number"&&(e[n]=r);return e}function sf(t,e,n){let r=t??{},i=ln(r.bucket_1),o=ln(r.bucket_2),s=Md(r);return {leaderboardType:sn(r.leaderboard_type),runType:sn(r.run_type),entityType:e,entityId:n,...i===void 0?{}:{bucket1:i},...o===void 0?{}:{bucket2:o},entries:Array.isArray(r.entries)?r.entries.map(Id).filter(a=>a!==void 0):[],personalBest:Id(r.personal_best)??null,totalRuns:Mt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:Mt(r.generated_at),...s===void 0?{}:{period:s}}}var dn=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=po(n),i=await yl(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Td(i,false)}async friends(e,n={}){let r=po(n),i=await ml(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Td(i,true)}async mine(e,n={}){return this.#n(e,"player","me",n)}async character(e,n,r={}){return this.#n(e,"character",n,r)}async#n(e,n,r,i){if(i.limit!==void 0){let{limit:l}=i;if(!Number.isInteger(l)||l<1||l>Ed)throw new TypeError(`limit must be an integer between 1 and ${Ed}, got ${String(l)}`)}let o=po(i),s=await sl(this.#e,e,Od[n],r,{...o,...i.bucket1===void 0?{}:{bucket_1:i.bucket1},...i.bucket2===void 0?{}:{bucket_2:i.bucket2},...i.limit===void 0?{}:{limit:i.limit},...i.signal===void 0?{}:{signal:i.signal}}),a=n==="player"&&r==="me"&&sn((s??{}).entity_id)||r;return sf(s,n,a)}};var $r=t=>typeof t=="string"?t:"",go=t=>typeof t=="number"?t:0;function Ld(t){let e=t??{};return {playerId:$r(e.player_id),key:$r(e.key),value:e.value,updatedAt:go(e.updated_at)}}function lf(t){let e=t??{};return {...Te(e),playerId:$r(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:go(e.updated_at)}}function df(t){return t?.reason==="not_found"}var cn=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let i=await pl(this.api,Ne(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:$r(i.key),entries:Array.isArray(i.entries)?i.entries.map(lf):[],generatedAt:go(i.generated_at)}}async of(e,n,r={}){try{return Ld(await Sl(this.api,e,Ne(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(df(i))return null;throw i}}async set(e,n,r={}){if(Ne(e),n===void 0)throw new TypeError(`showcase value for ${JSON.stringify(e)} is undefined, which is not JSON. Use clear() to remove one.`);try{JSON.stringify(n);}catch(o){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}.`,{cause:o})}let i=await this.selfPlayerId();return Ld(await Bl(this.api,i,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await Ys(this.api,r,Ne(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var cf="gemChallenge",Dd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function $d(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(cf)??void 0}catch{return}}var lt=class extends O{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,i]of Object.entries(n))i!==void 0&&Object.assign(this,{[r]:i});}},Fr=t=>typeof t=="string"?t:void 0;function Fd(t){let e=t??{};return {...Te(e),playerId:Fr(e.player_id)??""}}function qd(t){let e=t.has_more===true?Fr(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function uf(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(Fd):[],...qd(e)}}var fo=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function mf(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"||typeof e[1]=="number"&&Number.isFinite(e[1])))}function Nd(t){let e=t??{},n=fo(e.opened_at),r=fo(e.answered_at);return {id:Fr(e.item_id)??"",from:Fd(e.sender),template:Fr(e.template)??"",params:mf(e.params),createdAt:fo(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function pf(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(Nd):[],...qd(e)}}function gf(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var un=class{#e;#n;#o;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#o=n.launchedChallengeId;}async list(e={}){let n=await Dl(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return uf(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let n=await Ll(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return pf(n)}async launchedChallenge(e={}){let n=this.#o;if(n===void 0||!Dd.test(n))return null;try{return Nd(await fl(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(gf(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!Dd.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 Fl(this.#e,e);}};var ff=0;function ge(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++ff)}-${String(Date.now())}-${t}`}}var yf=12e4,jd=8,hf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,bf=/^[a-z0-9][a-z0-9_-]{0,63}$/;function mn(t,e,n={}){return new lt(new O("invalid",400,e,void 0,t),n)}function vf(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function _f(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!hf.test(e))return {error:mn("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!bf.test(n))return {error:mn("unknown_template","template must be a friend_challenge_templates key from this game's config")};if(r===void 0)return {playerId:e,template:n,params:void 0};if(!vf(r))return {error:mn("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:mn("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return o.length>jd?{error:mn("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String(jd)}`)}:{playerId:e,template:n,params:i}}function wf(t){switch(t.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:t.outcome}};case "rate_limited":{let e=t.retryAfterMs,n=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new lt(new O("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new lt(new O("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function Sf(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function Bd(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=_f(n);if("error"in r)return Promise.reject(r.error);let i=`challenge-${ge()}`;return new Promise((o,s)=>{let a={},l=u=>{e.delete(i)&&(t.clock.clearTimeout(a.timer),"error"in u?s(u.error):o(u.outcome));};e.set(i,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??yf);let d=false;try{d=t.bridge.requestFriendChallenge(i,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(n){let r=e.get(n.requestId);if(r===void 0){t.onDropped?.(`gem.friendChallengeResult (${Sf(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(wf(n));}}}var qr=t=>typeof t=="string"?t:void 0;function Rf(t){let e=t??{},n=qr(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:qr(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Nr=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await ur(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=Rf(o);s!==void 0&&i.push(s);}return i}},yo=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function kf(t){let e=t??{},n=qr(e.currency_id);if(n===void 0||n==="")return;let r=yo(e.limit),i=Math.min(yo(e.earned),r),o=Math.min(yo(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:qr(e.currency_slug)??"",currencyId:n,limit:r,earned:i,remaining:o,period:e.period==="day"?"day":"window",periodDays:a,...d===void 0?{}:{resetsAt:d}}}function Ud(t){let e=new Set,n=r=>{t?.(`[gem] an earnAllowance 'changed' listener threw: ${r instanceof Error?r.message:String(r)}`);};return {on(r){return e.add(r),()=>{e.delete(r);}},emit(){for(let r of [...e])try{let i=r();typeof i?.then=="function"&&i.then(void 0,n);}catch(i){n(i);}}}}var jr=class{#e;#n;#o;constructor(e,n,r){this.#e=e,this.#n=n,this.#o=r;}async get(e={}){let r=(await hl(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=kf(o);s!==void 0&&i.push(s);}return i}on(e,n){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(n)??(()=>{})}},pn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Nr(e),this.earnAllowance=new jr(e,n,r);}};var ho=t=>typeof t=="string"?t:"",Wd=t=>typeof t=="number"?t:0;function Af(t){let e=t??{};return {key:ho(e.key),visibility:ho(e.visibility),value:e.value,updatedAt:Wd(e.updated_at)}}function xf(t){let e=t??{};return {...Te(e),playerId:ho(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Af):[],generatedAt:Wd(e.generated_at)}}function Pf(t){return t?.reason==="not_found"}var gn=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return xf(await vl(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(Pf(r))return null;throw r}}};function bo(t){return typeof t=="string"&&/^[\w-]{1,64}$/.test(t)}function Br(t,e){if(t===void 0||bo(t))return t;let n=typeof t=="string"?JSON.stringify(t.slice(0,72)):`a value of type ${typeof t}`;console.warn(`[gem] ${e}: cueId ${n} is not 1 to 64 letters, digits, _ or -, so it was left out. Use one crypto.randomUUID() per award.`);}var Ef=new Map([["function_error",false],["function_failed",false],["function_timeout",false],["function_not_published",false],["function_input_too_large",false],["invalid_cue_id",false],["functions_not_configured",false],["forbidden",false],["function_capacity_unavailable",true],["function_host_unreachable",true],["function_host_error",true],["rate_limited",true],["service_unavailable",true]]),fn=class extends O{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:Ef.get(this.code))??super.retryable}},ze=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=Tf(e),i=Br(n.cueId,"functions.invoke"),o;try{o=await this.#e(r,{...n.signal===void 0?{}:{signal:n.signal},...i===void 0?{}:{cue_id:i}});}catch(s){throw s instanceof O?Cf(s):s}return If(o)}};function Tf(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let e;try{e=JSON.stringify(t);}catch(n){throw new de(`the function input could not be serialised to JSON: ${String(n)}. Pass bytes, or a value JSON can carry. This is a bug in the call, not a server failure.`)}if(e===void 0)throw new de(`the function input is ${typeof t}, which JSON cannot carry. Pass bytes \u2014 an empty Uint8Array for no input \u2014 or a JSON value. This is a bug in the call, not a server failure.`);return new TextEncoder().encode(e)}function If(t){let{bytes:e}=t,n=()=>new TextDecoder("utf-8",{fatal:true}).decode(e);return {bytes:e,...t.invocationId===void 0?{}:{invocationId:t.invocationId},text:n,json:()=>JSON.parse(n())}}function Cf(t){let{details:e,invocationId:n}=$s(t),i=e?.untrusted?.message,o=e?.reason;return new fn(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof i=="string"?{functionMessage:i}:{},...t.code==="function_failed"&&typeof o=="string"?{failure:o}:{}})}function Ur(t,e){let n=e?.retryAfterSeconds,r=typeof n=="number"&&Number.isFinite(n)&&n>0?n*1e3:0,i=1e4*2**Math.min(Math.max(0,t-1),16);return Math.min(Math.max(r,i),3e5)}var Mf=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost","gem_graphics_context_lost"],vo="gem_";function _o(t){return t.startsWith(vo)}function Of(t){let e=2166136261;for(let n of new TextEncoder().encode(t))e^=n,e=Math.imul(e,16777619);return e>>>0}function Gf(t){let e=t;return e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^=e>>>16,e>>>0}function Wr(t,e,n){if(wo(t,n),typeof e!="string"||e==="")throw new TypeError("[gem] experiment: playerId must be a non-empty string");let r=typeof n=="number"?n:n.length,i=Gf(Of(`${t}:${e}`))%r;return typeof n=="number"?i:n[i]}function wo(t,e){if(typeof t!="string"||t==="")throw new TypeError("[gem] experiment: key must be a non-empty string");if(typeof e=="number"){if(!Number.isInteger(e)||e<1||e>2048)throw new RangeError(`[gem] experiment '${t}': the count must be an integer from 1 to 2048; got ${String(e)}`);return}if(!Array.isArray(e))throw new TypeError(`[gem] experiment '${t}': pass a count or a list of strings; got ${typeof e}`);let n=e;if(n.length<1||n.length>2048)throw new RangeError(`[gem] experiment '${t}': the list must hold 1 to 2048 strings; got ${n.length}`);if(!n.every(r=>typeof r=="string"))throw new TypeError(`[gem] experiment '${t}': every option must be a string`)}var Hd=1e4,Vd=50,Lf=500,Df=65536-4*1024,$f=24*1024;function Kd(t){let e={},n={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=i:typeof i=="number"&&Number.isFinite(i)&&(n[r]=i);return {dimensions:e,measures:n}}var Ff=6e4;function qf(t){let e=new Map;for(let n of t??[]){let r=new Set;for(let[i,o]of Object.entries(n.dimensions??{})){let s=o?.range;typeof s=="object"&&s!==null&&r.add(i);}r.size>0&&e.set(n.id,r);}return e}function Nf(t,e){if(e===void 0)return t;let n=null,r={};for(let[i,o]of Object.entries(t.measures))e.has(i)?(n??={...t.dimensions})[i]=String(o):r[i]=o;return n===null?t:{dimensions:n,measures:r}}var Jd=t=>typeof t=="number"?t:0,jf=t=>typeof t=="string"?t:"";function Hr(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function Bf(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:Jd(o.index),code:jf(o.code)}}):[];return {accepted:Jd(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function So(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.floor(Math.random()*16);return (e==="x"?n:n&3|8).toString(16)})}function Uf(t){return t?.retryable===true}var yn=class{#e;#n;#o;#h;#t=[];#b={};#a=0;#s=null;#v=false;#_=false;#m=0;#w=0;#S=0;#r=false;#R=null;#l=null;#c=false;#i=false;#p=false;#k=false;#A=false;#g=void 0;#x=false;#P=0;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#o=Math.max(Hd,e.options?.flushIntervalMs??Hd),this.#h=Math.max(1,Math.floor(e.options?.maxQueue??Lf));}track(e,n={}){if(!this.#n||this.#r)return;if(_o(e)){this.#A||(this.#A=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.#E(e,Kd({...this.#b,...n}));let r=this.#C();this.#g===void 0&&!this.#x&&r!==null&&r!==""&&(this.#x=true,this.#M());}setContext(e){this.#b={...this.#b,...e};}async experiment(e,n){wo(e,n);let r=this.#e.awaitPlayerId===void 0?this.#e.playerId():await this.#e.awaitPlayerId();if(r===null)throw new Error(`[gem] experiment '${e}': no player to select for \u2014 this call was not made by a player.`);return typeof n=="number"?Wr(e,r,n):Wr(e,r,n)}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#i)return Hr();let n=this.#C();if(n===null||n==="")return this.#t.length>0&&!this.#k&&(this.#k=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.")),Hr();let r=e.keepalive===true;if(!r&&this.#e.declarations!==void 0&&this.#t.some(d=>!_o(d.name))&&await this.#M(),this.#I(),this.#t.length===0||this.#m>0&&!r)return Hr();this.#u();let i=this.#t.splice(0,this.#G(r)),o=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:So(),sent_at_ms:s,events:i.map(d=>zd(d,s,this.#g?.get(d.name)))},l={client:this.#e.client(),gameId:()=>n};this.#m+=1;try{let d=await xl(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),u=Bf(d,o);return this.#w=0,this.#S=0,this.#L(u),u}catch(d){throw Uf(d)?(this.#O(i,o),this.#w+=1,this.#S=this.#e.clock.now()+Ur(this.#w,d)):this.#y(`[gem] analytics: ${i.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#m-=1,this.#t.length>0&&this.#d();}}trackPlatform(e,n={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#E(e,Kd(n));}hold(){this.#r||this.#l!==null||(this.#i=true,this.#u());}release(){if(!this.#i||this.#r)return;this.#i=false;let e=this.#e.clock.now(),n=this.#t.map(r=>({...r,atMs:e}));this.#t=n,this.#p&&(this.#p=false,this.#l=e,this.#c=false,this.#t.unshift({uid:So(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=Vd?this.#f():this.#t.length>0&&this.#d();}get held(){return this.#i}startSession(){if(!(this.#r||this.#l!==null)){if(this.#i){this.#p=true;return}this.#l=this.#e.clock.now(),this.#c=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#c)return;if(this.#c=true,this.#i){this.#p=false,this.#t=[],this.#a=0;return}let n=this.#l;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#f({keepalive:true});}setPaused(e){this.#r||e===this.#v||(this.#v=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#d());}setHidden(e){this.#r||e===this.#_||(this.#_=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}#E(e,n){let{dimensions:r,measures:i}=n;for(this.#I();this.#t.length>=this.#h;)this.#t.shift(),this.#a+=1;this.#t.push({uid:So(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#t.length>=Vd?this.#f():this.#d();}#f(e={}){if(e.keepalive!==true&&this.#T()>0){this.#d();return}this.flush(e).catch(()=>{});}#T(){return Math.max(0,this.#S-this.#e.clock.now())}#O(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#h;)this.#t.shift(),this.#a+=1;}#G(e){let n=e?$f:Df,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(zd(s,0,this.#g?.get(s.name))).length+1,i>n)return Math.max(1,o)}return r}#d(){this.#s!==null||this.#v||this.#_||this.#i||this.#r||this.#m>0||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#f();},Math.max(this.#o,this.#T())));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#I(){let e=this.#D();e===null||e===""||(this.#R!==null&&this.#R!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#c=false),this.#R=e);}#L(e){for(let n of e.rejected)this.#y(`[gem] analytics: an event was refused (${n.code}). `+Wf(n.code));}#y(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#C(){try{return this.#e.gameId()}catch{return null}}#D(){try{return this.#e.playerId()}catch{return null}}async#M(){let e=this.#e.declarations;if(e!==void 0&&!(this.#e.clock.now()<this.#P))try{this.#g=qf(await e());}catch{this.#P=this.#e.clock.now()+Ff;}}};function zd(t,e,n){let{dimensions:r,measures:i}=Nf(t,n);return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:r,measures:i}}function Wf(t){switch(t){case "analytics_not_declared":return "This channel has no analytics_events section at all \u2014 promote a game config that declares one. The gem_* events in the same batch were still recorded.";case "unknown_event":return "This channel declares a set of events and this name is not in it \u2014 check the spelling, or declare it in analytics_events.";case "unknown_dimension":return "A string property on this event is not declared as one of its dimensions.";case "missing_dimension":return "A dimension this event declares was not supplied.";case "dimension_value_not_declared":return "A dimension value is outside the closed set the config declares for it.";case "unknown_measure":return "A numeric property on this event is not declared as one of its measures.";case "measure_wrong_type":return "A measure was the wrong shape \u2014 an int measure refuses a fractional value.";case "source_not_permitted":return "This event is declared for the server only, so a client may not emit it.";default:return "See the analytics_events section of your game config."}}function Se(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function Ie(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=Se(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Hf=2e3,Vf=5e3;function Yd(t){let e=[],n=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let s,a=new Promise(l=>{let d=false,u=null;s=c=>{d||(d=true,r=null,t.clock.clearTimeout(u),l(c));},u=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??Hf);});return r={promise:a,settle:s},a};return {resolveList:o,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(s=>s[0])},refresh(s){return !Xd(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=u=>{i.delete(d)&&(t.clock.clearTimeout(l),a(u));};i.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??Vf);})},accept(s,a){let l=Ie(a),d=Se(s),u=l.length>0?l:d===void 0?[]:[d];if(u.length!==0){e=u,r?.settle(u);for(let[c,g]of [...i])Xd(u,g)||c(u);}}}}function Xd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Kf=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),A=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="DedicatedServerError",this.retryable=Kf.has(n),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var Qd=["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"],Jf=new Set(Qd);function Xe(t){return typeof t=="string"&&Jf.has(t)?t:"unknown"}var Vr="webrtc_dedicated",xo=["universal","mobile","web"];var zf="p2p_unavailable",Xf="capacity_unavailable",Yf=2,Zd=3e4,ec=1e3,tc=2e4;async function Po(t){let e=Se(t.clusterTargetId),n=t.nextClusterTarget,r=0,i=t.clock??ce,o=t.retry??{},s=o.budgetMs??Zd,a=o.maxDelayMs??tc,l=o.initialDelayMs??ec,d=i.now(),u=d+s,c=0;for(;;){c++;try{let g=await Co(t.signal,"while allocating",()=>t.client.post(`${ic(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:g.match_id,status:g.status}}catch(g){if(!Qf(g)||s<=0)throw g;if(g.status===503&&g.code===zf)throw new A("p2p_unavailable",`room ${t.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${g.message}`,{cause:g});if(r=g.code===Xf?r+1:0,n!==void 0&&r>=Yf){let v=n;n=void 0;let R=Se(await v());R!==void 0&&(e=R,r=0);}let p=Math.min(a,l*2**(c-1)),f=Math.min(a,(g.retryAfterSeconds??0)*1e3),S=Math.max(p/2,f)+Math.random()*(p/2);if(i.now()+S>u)throw Zf(t,g,c,i.now()-d,s);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-d,budgetMs:s,nextAttemptInMs:S,status:g.status,message:g.message}),await Kr(i,S,t.signal),t.signal?.aborted)throw Ao("while waiting to allocate")}}}function Qf(t){return t instanceof O?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function Zf(t,e,n,r,i){let o=`${n} attempt${n===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new A("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${o}: ${e.message}`,{cause:e}):new A("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${o}: ${e.message}`,{cause:e})}var ey=12e4,ty=1e3;async function Eo(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??ty,i=t.timeoutMs??ey,o=e.now()+i,s=nc(t),a={seen:t.knownToExist===true};for(;;){let l=await rc(t,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new A("timeout",`match ${n} was still ${l.status} after ${i}ms`);await Kr(e,r,t.signal);}}async function To(t){return (await rc(t,nc(t),{seen:t.knownToExist===true})).outcome}function nc(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${ic(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function rc(t,e,n){let{matchId:r}=t,i=t.clock.now(),o;try{o=await Co(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(s){if(s instanceof O&&s.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(n.seen=true,o.status==="ready")return {status:"ready",outcome:ny(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Xe(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function Io(t){let e=await Co(t.signal,"while listing cluster targets",()=>t.client.get("/v1/ping/targets",t.signal)),n=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||n.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return n}async function Co(t,e,n){if(t?.aborted)throw Ao(e);try{return await n()}catch(r){throw t?.aborted?Ao(e,r):r}}function Ao(t,e){return new A("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function ny(t,e,n){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:t,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:n+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function ic(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Kr(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{t.clearTimeout(o),n?.removeEventListener("abort",i),r();},o=t.setTimeout(i,e);n?.addEventListener("abort",i);})}function oc(t){return typeof t=="string"&&t.trim()!==""}function Jr(t,e){return oc(t)?t.trim():oc(e)?e:null}var zr="0.1.0-beta",ac="0-beta",Ot="web",ry=/^(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 iy(t){let e=ry.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function sc(t,e){let n=oy(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:zr};let i=iy(r);if(i===null)throw new A("misconfigured",`${e} refused: engineVersion '${r}' is not semver, so no engine line can be derived from it and gem-api answers 400. Omit it \u2014 a browser game has no engine version of its own, and the SDK reports '${zr}' for it.`);if(i!==ac)throw new A("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${ac}' 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 '${zr}' for it.`);return {...t,platform:n,engineVersion:r}}function oy(t,e){if(t===void 0||t===Ot)return Ot;if(!xo.includes(t))throw new A("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${xo.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${Ot}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${Ot}' 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.`),Ot}function hn(t){let e=t??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let n=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:lc(e.queued_at),expiresAt:lc(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function lc(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var ay=3,dc=1e3,Xr=class{constructor(e){this.options=e;this.snapshot=e.first;let n=new Promise((o,s)=>{this.resolve=o,this.reject=s;});n.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:n,cancel:()=>(this.requestCancel(),n)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let n=e?dc:Math.max(dc,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},n);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,n=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){n=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(n);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof O&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<ay){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let n=e instanceof O&&e.code==="matchmaking_unavailable";this.settle({status:n?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let n=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:n});}catch(n){this.busy=false,this.fail(n);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};var sy="gemPlayWith",ly=/^[A-Za-z0-9_-]{16,128}$/;function cc(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(sy);}catch{return}return e!==null&&ly.test(e)?e:void 0}function uc(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var dy="join",cy="welcome",uy="rejected",mc=25e3,my=1e3,Mo=1;function Oo(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var py={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 Go(t){let e=typeof t=="string"?t:"unknown";return new A(py[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function bn(t){let{channel:e,clock:n}=t;return new Promise((r,i)=>{let o=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??mc),a=n.setTimeout(()=>y(new A("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(s,my)),l=S=>{let v=S.data;if(typeof v!="string"){c(v);return}let R;try{R=JSON.parse(v);}catch{c(v);return}if(o){c(v);return}if(R.t===cy){let h=Oo(R.heartbeat_interval);f({...typeof R.player_id=="string"?{playerId:R.player_id}:{},...typeof R.match_id=="string"?{matchId:R.match_id}:{},...h===void 0?{}:{heartbeatIntervalMs:h}});return}if(R.t===uy){y(Go(R.reason));return}c(v);},d=()=>{y(new A("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},u=()=>{y(new A("aborted","the caller aborted during the join exchange"));},c=S=>{o&&t.onMessage?.(S);},g=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",u);},p=()=>{e.removeEventListener("message",l);},f=S=>{o=true,g(),t.onMessage===void 0&&p(),r({welcome:S,detach:p});},y=S=>{o||(o=true,g(),p(),i(S));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){u();return}t.signal?.addEventListener("abort",u);try{e.send(JSON.stringify({t:dy,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:Mo}:{}}));}catch(S){y(new A("connection_failed",`the join frame could not be sent on the open channel: ${String(S)}`,{cause:S}));}})}var dt=1,vn=2,Lo=4,Fo=8,gy=2,fy=1e3,qo="heartbeat timeout",_n="gem-uu",Yr=2,gc="gem_transports";function Gt(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!yy(r)||e.includes(r)||e.push(r);}return e}function yy(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function wn(t,e){if(typeof t!="object"||t===null)return null;let n=t[gc];if(typeof n!="object"||n===null)return null;let r=n;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function Qr(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var fc=new TextEncoder,yc=new TextDecoder;function No(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function jo(t){let e=0;return t?.reliable===false&&(e|=dt),t?.ordered===false&&(e|=vn),e}function Bo(t){return {reliable:(t&dt)===0,ordered:(t&vn)===0}}var Uo={reliable:true,ordered:true};function hc(t){return JSON.stringify({t:"join",credential:t,wire:Yr,heartbeat:Mo})}function bc(t){let e;try{e=JSON.parse(t);}catch{throw new A("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=Oo(e.heartbeat_interval);return {...e.player_id===void 0?{}:{playerId:e.player_id},...e.match_id===void 0?{}:{matchId:e.match_id},...n===void 0?{}:{heartbeatIntervalMs:n}}}throw e.t==="rejected"?Go(e.reason):new A("join_refused","the server answered the join out of protocol")}function Zr(){return typeof globalThis.WebTransport=="function"&&Wo===null}function ei(){return Wo}var Wo=null;var pc="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function hy(t){let e=cr(t);if(e.byteLength!==32)throw new A("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var Do=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new A("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let s=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function $o(t,e){let n=new Uint8Array(5+e.byteLength);return new DataView(n.buffer).setUint32(0,e.byteLength+1,true),n[4]=t,n.set(e,5),n}async function Sn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new A("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new a(t.url):new a(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:hy(t.certHashBase64)}]});}let r=n,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(Wo=pc,i(new A("connection_failed",`${pc}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new A("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([a.read(),s]);if(a.releaseLock(),l.done||l.value===void 0)return i(new A("connection_failed","the session ended before the control stream arrived"));let d=l.value,u=d.writable.getWriter();await u.write($o(Lo,fc.encode(hc(t.credential))));let c=new Do,g=d.readable.getReader(),p;for(;p===void 0;){let f=await Promise.race([g.read(),s]);if(f.done||f.value===void 0)return i(new A("connection_failed","the control stream closed before the join was answered"));for(let y of c.push(f.value)){p=bc(yc.decode(y.payload));break}}return {link:by(r,u,g,c,t.log??(f=>console.warn(f)),_c(p,t.clock)),welcome:p}}catch(a){return i(a)}}function by(t,e,n,r,i,o){let s,a,l=false,d=f=>{if(!l){l=true,u.stop();try{t.close();}catch{}a?.(f);}},u=Vo(o,()=>d(qo)),c=(f,y)=>{u.heard(),(f&Fo)===0&&s!==void 0&&((f&Lo)!==0?s(yc.decode(y),Uo):s(y,Bo(f)));};(async()=>{try{for(;;){let f=await n.read();if(f.done||f.value===void 0)break;for(let y of r.push(f.value))c(y.flags,y.payload);}}catch{}d("stream closed");})();let g,p;try{let f=t.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let y=f.readable.getReader();p=f.writable.getWriter(),g=f,(async()=>{try{for(;;){let S=await y.read();if(S.done||S.value===void 0)break;let v=S.value;v.byteLength!==0&&c((v[0]??0)|dt|vn,v.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(f){g=void 0,p=void 0,i(`[gem] webtransport datagram lane unusable (${Qr(f)}); unreliable sends ride the stream`);}return t.closed.then(f=>d(vc(f?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(f,y){if(l)return;if(typeof f=="string"){e.write($o(Lo,fc.encode(f))).catch(()=>d("write failed"));return}let S=jo(y);if((S&dt)!==0&&p!==void 0){let v=No(S,f),R=g?.maxDatagramSize;if(R===void 0||v.byteLength<=R){p.write(v).catch(()=>{});return}}e.write($o(S,f)).catch(()=>d("write failed"));},onMessage(f){s=f;},onClose(f){a=f;},close(){d("closed");}}}function Ho(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new A("connection_failed","this environment has no WebSocket"));n=new i(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new A("timeout","websocket did not come up in time")));},e),l=p=>{s||(s=true,clearTimeout(a),r.close(),o(p));},d=()=>{r.send(hc(t.credential));},u=p=>{if(s)return;if(typeof p.data!="string"){l(new A("join_refused","the server sent binary before answering the join"));return}let f;try{f=bc(p.data);}catch(y){l(y);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",u),r.removeEventListener("close",c),r.removeEventListener("error",g),i({link:vy(r,_c(f,t.clock)),welcome:f});},c=()=>{l(new A("connection_failed","the websocket closed before the join was answered"));},g=()=>{l(new A("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",u),r.addEventListener("close",c),r.addEventListener("error",g),r.readyState===1&&d();})}function vc(t){return typeof t=="string"&&t.length>0?t:void 0}function _c(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function Vo(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,fy)*gy,i=n.now(),o=null,s=()=>{o=null;let a=n.now()-i;if(a>=r){e();return}o=n.setTimeout(s,r-a);};return o=n.setTimeout(s,r),{heard:()=>{i=n.now();},stop:()=>{o!==null&&(n.clearTimeout(o),o=null);}}}function vy(t,e){let n,r,i=false,o=a=>{if(!i){i=true,s.stop();try{t.close();}catch{}r?.(a);}},s=Vo(e,()=>o(qo));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,Uo);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Fo)===0&&n?.(l.slice(1),Bo(d));})),t.addEventListener("close",(a=>o(vc(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!i){if(typeof a=="string"){t.send(a);return}t.send(No(jo(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){o("closed");}}}function Ko(t,e,n,r){let i,o,s=false,a=n,l=c=>{if(!s){s=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}o?.(c);}},d=Vo(r,()=>l(qo)),u=(c,g)=>{if(d.heard(),typeof c=="string"){i?.(c,Uo);return}let p=new Uint8Array(c);if(p.byteLength===0)return;let f=p[0]??0;(f&Fo)===0&&i?.(p.slice(1),Bo(f|g));};if(t.addEventListener("message",(c=>u(c.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),a!==void 0){let c=a;c.addEventListener("message",(g=>u(g.data,dt|vn))),c.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(c,g){if(s)return;if(typeof c=="string"){t.send(c);return}let p=jo(g),f=No(p,c);if((p&dt)!==0&&a!==void 0&&a.readyState==="open"){a.send(f);return}t.send(f);},onMessage(c){i=c;},onClose(c){o=c;},close(){l("closed");}}}function wc(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let i=Jo(r);i!==void 0&&(e[n]=i);}return e}function Sc(t){if(Array.isArray(t))return t.map(_y).filter(e=>!!e)}function Jo(t){if(zo(t)||Array.isArray(t)&&t.every(zo))return t}function zo(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function _y(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Jo(e.fixed),r=Jo(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...n===void 0?{}:{fixed:n},...r===void 0?{}:{default:r},...Lt("description",wy(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(zo)?{allowed:e.allowed}:{},...Lt("min",Rn(e.min)),...Lt("max",Rn(e.max)),...Lt("minItems",Rn(e.min_items)),...Lt("maxItems",Rn(e.max_items)),...Lt("maxLength",Rn(e.max_length))}}function wy(t){return typeof t=="string"&&t.length>0?t:void 0}function Rn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Lt(t,e){return e===void 0?{}:{[t]:e}}function je(t){let e=t??{},n=Y(e.id)??Y(e.game_room_id);if(n===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(Sy):[];return {id:n,gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:$e(e.max_players)??0,memberCount:$e(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...Ae("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...Ae("roomArgs",wc(e.room_args)),...Ae("roomArgsTemplate",Sc(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",...Ae("region",Y(e.region)),...Ae("clusterTargetId",Y(e.cluster_target_id)),selfHosted:e.self_hosted===true,...Ae("matchId",Y(e.match_id)),version:$e(e.version)??0,...Ae("templateId",Y(e.template_id)),...Ae("templateSlug",Y(e.template_slug)),roomType:Y(e.game_room_type)??"Standard",...Ae("transports",Gt(e.transports)??void 0),createdAt:$e(e.created_at)??0,updatedAt:$e(e.updated_at)??0,...Ae("startedAt",$e(e.started_at))}}function Sy(t){let e=t??{};return {...Te(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:$e(e.joined_at)??0,...Ae("groupId",Y(e.group_id)),...Ae("platform",Y(e.platform))}}function Xo(t){let e=t??{};return {id:Y(e.id)??Y(e.game_room_id)??"",gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:$e(e.max_players)??0,memberCount:$e(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Y(e.game_channel)??"release",roomType:Y(e.game_room_type)??"Standard",createdAt:$e(e.created_at)??0}}function Y(t){return typeof t=="string"&&t.length>0?t:void 0}function $e(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ae(t,e){return e===void 0?{}:{[t]:e}}var ti=class{constructor(e){this.options=e;}options;list(e){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.templateSlug&&n.set("template_slug",e.templateSlug),e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor&&n.set("cursor",e.cursor);let r=n.size>0?`?${n.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(Xo),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(n=>({rooms:(n.game_rooms??[]).map(Xo)}))}create(e,n,r){return ky(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},...kn(n)},e.signal).then(je)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(je)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...kn(r)},n.signal).then(je)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...kn(r)},n.signal).then(je)}quickJoin(e,n,r=[]){return Yo(this.options,e,n,r).then(i=>i.room)}createTicket(e,n,r=[]){return Js(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},...kn(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(hn)}heartbeatTicket(e){return Al(this.generated(),e).then(hn)}cancelTicket(e,n=false){return n?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(hn):Us(this.generated(),e).then(hn)}leave(e,n,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:n},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return kc(this.options,e)}close(e,n){return this.options.client.delete(this.roomV1(e),n).then(()=>{})}update(e,n){return this.options.client.patch(this.roomV2(e),{...n.name===void 0?{}:{name:n.name},...n.maxPlayers===void 0?{}:{max_players:n.maxPlayers},...n.isPublic===void 0?{}:{is_public:n.isPublic},...n.settings===void 0?{}:{settings:n.settings},...n.roomArgs===void 0?{}:{room_args:n.roomArgs}},n.signal).then(je)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(je)}kick(e,n,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(n)}`,{},r).then(()=>this.get(e,r))}transferHost(e,n,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(n)}`,{},r).then(je)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return Rc(this.options)}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Rc(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function kc(t,e){return e===void 0&&t.selfHosted?.()===true}function Yo(t,e,n,r=[],i){let o=kc(t,e.partyId);return t.client.post(`${Rc(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...Ry(e.templateSlugs,o),...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...o?{self_hosted:true}:{},...i===void 0?{}:{play_with_ticket:i},...kn(n)},e.signal).then(s=>({room:je(s),playWith:i===void 0?null:uc(s)}))}function Ry(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function kn(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function ky(t){t!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${t}) is deprecated and was not sent. A room's seats come from the room template published in your game config \u2014 name one with templateSlug \u2014 and a room created without a template seats 8. To change a room that already exists, call update({ maxPlayers }) as its host.`);}var ni=class{listeners=new Map;retainedMatch=null;on(e,n){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(n),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===i&&n(i);});}return ()=>this.off(e,n)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...i)=>{r(),n(...i);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};var ri=class{constructor(e){this.options=e;let n=e.first,r=new Promise(a=>{this.resolve=a;}),i=()=>this.status;this.ticket={id:n.ticketId,get status(){return i()},partySize:n.partySize??0,queuedAt:n.queuedAt??0,expiresAt:n.expiresAt??0,outcome:r};let o=n.queuedAt!==void 0&&n.expiresAt!==void 0?(n.expiresAt-n.queuedAt)*1e3:9e5,s=Math.min(Math.max(o,0),9e5)+5e3;this.timer=e.clock.setTimeout(()=>{this.timer=null,this.end({status:"lost"});},s);}options;ticket;status="queued";timer=null;resolve;get id(){return this.ticket.id}end(e){this.status==="queued"&&(this.status=e.status,this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null),this.options.onSettled(),this.resolve(e));}};function Ay(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var xy=1e3,Py=3e3,Ey=6e4,Ty=2,Ac=new Set(["game_room_closed","game_room_gone"]),Iy=12e4,Cy=5e3,My=new Set(["invalid_cluster_target","capacity_unavailable"]),Oy=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Ec(t,e){return new Zo(e,t)}var Zo=class{constructor(e,n={}){this.options=e;this.internals=n;this.autoFollow=e.followMatch!==false,this.apiOptions={client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true},this.api=new ti(this.apiOptions),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;internals;emitter=new ni;api;apiOptions;playWithAnswer=null;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await n,s=a=>this.api.create(r,this.version("create"),a);for(let a=0;;a++)try{return await s(o[a])}catch(l){if(!Qo(l))throw l;if(a+1<o.length)continue;let d=(await this.afterRefusedClusters(l,o)).find(u=>!o.includes(u));if(d===void 0)throw l;return s(d)}});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,n={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(n),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,n={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(n),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin"),Dy(e);let n=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.postQuickJoin(r,a).catch(l=>this.retryPastStaleMembership(l,r,a)),o=await this.run("quickJoin",async()=>{let a=await n;return i(a).catch(async l=>{let d=await this.afterRefusedClusters(l,a);if(d.length===0||Pc(d,a))throw l;return i(d)})}),{room:s}=o;return this.playWithAnswer=o.playWith,this.enter(s,"joined"),this.askForLocalServer(s),s}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Ly(e?.templateSlugs),this.queueing=true;try{let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let s=await n;return this.api.createTicket(r,this.version("queueForMatch"),s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||Pc(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 Xr({clock:this.options.clock,first:i,heartbeat:s=>this.track(this.api.heartbeatTicket(s)),cancel:(s,a)=>this.track(this.api.cancelTicket(s,a)),seat:s=>this.enterMatchedRoom(s),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;let n=this.heldQueued;this.heldQueued=null,n!==null&&this.showPartyTicket(n);}}async enterMatchedRoom(e){let n=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?n:(this.room!==null&&this.room.id!==n.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(n,"joined"),this.room?.id===n.id?this.room:n)}async list(e={}){let n=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",n),n}async myRooms(e){let n=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",n.rooms),n.rooms}async leave(e={}){let n=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(n.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let n=await this.myRooms(e),r=[];for(let i of n)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let n=this.requireRoom("close");await this.run("close",()=>this.api.close(n.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let n=this.room;if(!n)return null;let r;try{r=await this.track(this.api.get(n.id,e));}catch(i){if(i instanceof O&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let s=await this.askWhyEnded(o,e);this.endMatch(o,s??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let n=this.room,r=this.heldMatchId;if(!(n===null||r===null)&&!(n.status==="in_game"&&n.matchId===r)&&!(n.matchId!==void 0&&n.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>To({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...n===void 0?{}:{signal:n}})));}catch(s){return s instanceof O&&s.reason==="not_found"?i??null:(this.reportError("reconcile",s),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=Xe(n.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(i),i}async kick(e,n){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(i),i}async transferHost(e,n){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(i),i}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){let r=this.requireRoom("startMatch");if(!this.isHost)throw new A("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let i=Se(n.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(u,c)=>Po({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...u===void 0?{}:{clusterTargetId:u},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:g=>{this.emitter.emit("matchStartWaiting",g),n.retry?.onWaiting?.(g);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(o,[s]).catch(async u=>{if(i!==void 0||!Qo(u))throw u;let c=await this.nextCluster([s],true);if(c===void 0)throw u;return a(c,[s,c])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new A("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let n=this.emitter.retained;return n!==null&&this.session.phase==="ready"?n:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let n=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(i)}chase(e,n,r){return Eo({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:n,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(n),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new A("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!Ac.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new A("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,n){this.heldMatchId===e&&(this.abandonReconnect(e,n),this.emitter.emit("matchFailed",e,n),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,n,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:n,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:n,roomReopened:r}),this.abandonReconnect(e,n));}armReconnect(e,n){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),n==="kicked"){r.abandon(e,n);return}let i={matchId:e,cause:n,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,n){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),n());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,n){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,n));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!ct()){this.park(e,()=>this.reconnectStep(e));return}let n=this.options.autoReconnect;if(n===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=n.attempts||r<xy){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:n.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(Ay(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!ct()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>To({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,!Ac.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await n.redial(e.matchId,e.deadlineAt);}catch(s){this.reportError("reconcile",s),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let n=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):n&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new A("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let n=this.session.matchId;this.session={phase:"suspended",matchId:n,reason:e},this.emitter.emit("matchSuspended",{matchId:n,cause:e}),this.armReconnect(n,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new A("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let n=this.heldMatchId;if(n===null)throw new A("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:n},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let n=this.heldMatchId;if(n!==null)try{await this.api.leaveMatch(n,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}get playWith(){return this.playWithAnswer}on(e,n){let r=this.emitter.on(e,n);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}handleRoomEvent(e){if(this.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let n=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(n).catch(()=>{}));}handleAutoStartFailed(e,n){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(n);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:n,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!My.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let n=new ri({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===n&&(this.partyWatch=null);}});this.partyWatch=n,this.emitter.emit("partyQueued",n.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let n=new Set;for(let r of e)r.status!=="closed"&&(n.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])n.has(r)||this.reported.delete(r);}async reportSeat(e){let n=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||n===null||!r.members.some(i=>i.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&ct())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let n=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(n,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!ct())){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 ii)e.addEventListener(r,this.visibilityListener);let n=globalThis.document;typeof n?.addEventListener=="function"&&n.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let n=this.inFlight;this.inFlight=[],await Promise.allSettled(n);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of ii)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??Cy}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new A("misconfigured","the game id is not known yet. It comes from the play token, and this manager was given no way to wait for one \u2014 pass gameId, or awaitGameId so a call made before the first token waits for it the way createGem wires it.")}playerId(){return typeof this.options.playerId=="function"?this.options.playerId():this.options.playerId}version(e){let n=this.options.clientVersion,r=Jr(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new A("misconfigured",`${e} has no game version to report \u2014 gem-api requires platform, game_version and engine_version together on every room route, and refuses a request carrying two of the three. The arcade normally supplies it with the play token; an embedder that does not, or a build running outside the arcade, leaves nobody to ask. Pass \`clientVersion: { gameVersion }\` to createGem (or to createRoomManager) as the fallback. It has to name a build you actually published, and a wrong one pins the room to the wrong build \u2014 which is why the platform answers it wherever it can.`);return sc({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return Ie(await this.options.resolveClusterTargets());let e=Se(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Qo(e)||n.length===0?[]:Ie(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=s=>s.find(a=>!e.includes(a)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!n?o:r(Ie(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let n=this.options.resolveParty;if(n===void 0)return e;let r=await n();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,n,r){if(!(e instanceof O)||e.reason!=="conflict"||!Oy.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new O(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(n.signal);}catch{throw new O(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new O(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.postQuickJoin(n,r)}postQuickJoin(e,n){return Yo(this.apiOptions,e,this.version("quickJoin"),n,this.internals.playWithTicket)}assertNotInRoom(e){if(this.room!==null)throw new A("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new A("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new A("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,n){try{return await this.track(this.onceGameIdKnown(n))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,n){let r=n instanceof O?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof A?n.reason:"unavailable",message:n instanceof Error?n.message:String(n),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let n=this.options.ensureLocalServer;n===void 0||!e.selfHosted||e.status!=="open"||n(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,n){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(n,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let n=this.room;if(n===null||n.id!==e.id)return;let r=new Map(n.members.map(a=>[a.playerId,a])),i=new Map(e.members.map(a=>[a.playerId,a])),o=this.playerId();for(let a of i.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!i.has(a)){if(a===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,l]of i){let d=r.get(a);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",a,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=Gy(n,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let n=this.heldMatchId;n!==null&&n!==e&&this.endMatch(n,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,n=this.heldMatchId;if(e===null||n===null||this.followAbort!==null&&this.followingMatchId===n)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=n,this.track(this.onceGameIdKnown(()=>this.chase(e.id,n,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??Iy;return new Promise((i,o)=>{let s=c=>{a(),l(),this.options.clock.clearTimeout(u),e.signal?.removeEventListener("abort",d),c();},a=this.emitter.on("matchAllocationStarted",c=>s(()=>i(c))),l=this.emitter.on("matchFailed",(c,g)=>s(()=>o(new A("allocation_failed",`match ${c} did not come up: ${g}`)))),d=()=>s(()=>o(new A("aborted","the caller aborted while awaiting a match"))),u=this.options.clock.setTimeout(()=>s(()=>o(new A("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??Py}pushedInterval(){return this.options.pushedPollIntervalMs??Ey}pushed(){return this.options.clock.now()-this.lastPushAt<Ty*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=n=>{if(this.ticketWatch?.abandon(true),n?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function ct(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var ii=["visibilitychange","focus","pageshow","online"];function Gy(t,e){return t.version!==e.version||t.status!==e.status||t.matchId!==e.matchId||t.hostPlayerId!==e.hostPlayerId||t.name!==e.name||t.maxPlayers!==e.maxPlayers||t.isPublic!==e.isPublic||xc(t)!==xc(e)}function xc(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Qo(t){return t instanceof O&&t.code==="invalid_cluster_target"}var oi=8;function Ly(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=oi&&t.every(n=>typeof n=="string"&&n.length>0)))throw new A("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${oi} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function Dy(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=oi&&e.every(r=>typeof r=="string"&&r.length>0)))throw new A("misconfigured",`quickJoin's templateSlugs is an array naming one to ${oi} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(t?.templateSlug!==void 0||t?.templateId!==void 0)throw new A("misconfigured","quickJoin takes templateSlugs or a single templateSlug / templateId, not both. Put every template this player accepts in templateSlugs, with the one to create from first.")}function Pc(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var $y=["p2p","dedicated","unknown"],ea=["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 Dt=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let i=Fy(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},n);}report(e){this.post(e).catch(()=>{});}};function Fy(t,e,n){let r=Math.floor(n/1e3);return t.filter(i=>ea.includes(i.type)).slice(0,100).map(i=>{let o=Ny(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:{...qy(i.labels),...i.value===void 0?{}:{value:i.value}}}})}function qy(t){let e={};if(typeof t!="object"||t===null)return e;let n=0;for(let[r,i]of Object.entries(t)){if(n>=4)break;r==="value"||!Tc(r)||!Tc(i)||(e[r]=i,n+=1);}return e}function Tc(t){return typeof t=="string"&&t.length>0&&t.length<=32}function Ny(t){if(t!==void 0)return $y.includes(t)?t:"unknown"}var An=class{constructor(e){this.options=e;this.reporter=new Dt({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:ai(i.credential)??"",hostFingerprint:ai(i.host_fingerprint)??"",hostEpoch:si(i.host_epoch)??0,expiresAt:(si(i.expires_at)??0)*1e3}}async turnLease(e,n,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,u=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);u.length!==0&&o.push({urls:u,username:ai(d.username)??"",credential:ai(d.credential)??""});}let s=si(i.expires_at),a=si(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??0)*1e3}}async kick(e,n,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:n},r);}async leave(e,n=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:n});}async telemetry(e,n){await this.reporter.post(e,n);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}},jy=new Set(["cluster_hidden","invalid_cluster_target"]);async function Ic(t,e,n,r){let i=Ie(n);if(i.length===0)throw new Error("no cluster to lease TURN from");let o;for(let s of i)try{return {...await t.turnLease(e,s,r),clusterTargetId:s}}catch(a){if(!By(a))throw a;o=a;}throw o}function By(t){return t instanceof O&&jy.has(t.code??"")}function ai(t){return typeof t=="string"&&t.length>0?t:void 0}function si(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var Uy=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),N=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="P2pError",this.retryable=Uy.has(n);}reason;retryable};var Cc=10240,Mc=2048,Wy=new TextEncoder;function Oc(t){return Wy.encode(t).length}function Be(t,e){let n=i=>{throw new A("invalid_sdp",`the ${e} ${i}`)},r=Oc(t);r>=Cc&&n(`is ${r} bytes, over the ${Cc} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),t.startsWith("v=")||n("does not start with 'v=', so it is not SDP"),t.includes("\0")&&n("contains a null byte"),/\r(?!\n)/.test(t)&&n("contains a bare carriage return");for(let i of t.split(/\r\n|\n/)){let o=Oc(i);o>Mc&&n(`has a ${o}-byte line, over the ${Mc} limit`);}}function li(t){for(let e of t.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[n,r="0"]=e.slice(2).trim().split(/\s+/);if(!(n!=="audio"&&n!=="video")&&r.split("/")[0]!=="0")return true}return false}var di=class{listeners=new Map;on(e,n){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(n),()=>this.off(e,n)}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...i)=>{r(),n(...i);}));return r}emit(e,...n){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}clear(){this.listeners.clear();}};var Hy=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function Ft(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=ci(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function ci(t){let[e,...n]=t.trim().split(/\s+/);if(e===void 0||n.length===0)return null;let r=`${e.toLowerCase()} ${n.join("").toUpperCase()}`;return Hy.test(r)?r:null}function $t(t,e){if(t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}var ta=5e3,Vy=12e4+ta,Ky=1024,Jy=6e4,zy=1e4,Gc=64*1024,Lc=5;function na(t){let e=new Map,n=-1/0,r=null,i=(()=>{let a;try{a=new URL(`${t.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=t.subtle??globalThis.crypto?.subtle;if(!a)throw new N("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return a},s=async()=>{if(!i.ok)throw new N("keys_unavailable",i.reason);let a=t.fetch??((g,p)=>globalThis.fetch(g,p)),l;try{l=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(zy)});}catch{throw new N("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new N("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let g=await l.text();if(g.length>Gc)throw new N("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Gc} characters, which is not a key set this platform publishes.`);d=JSON.parse(g);}catch(g){throw g instanceof N?g:new N("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let u=Array.isArray(d.keys)?d.keys:[];if(u.length>Lc)throw new N("keys_unavailable",`the JWKS endpoint published ${u.length} keys, over the ${Lc} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let g of u){let p=g;if(p.kty==="RSA"&&!(p.alg!==void 0&&p.alg!=="RS256")&&!(p.use!==void 0&&p.use!=="sig")&&!(typeof p.kid!="string"||p.kid.length===0))try{let f=await c.importKey("jwk",{...g,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(p.kid,f);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!i.ok)throw new N("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new N("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<n&&(n=-1/0),d-n<Jy?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var xn=class{seen=new Map;admit(e,n){for(let[r,i]of this.seen)i<=n&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=Ky){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+Vy),true}};function $c(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}function Dc(t){try{let e=new TextDecoder().decode($c(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function ra(t,e,n,r,i){let o=H=>{throw new N("peer_unauthenticated",`the peer's join credential is not usable: ${H}`)},s=t.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,l,d]=s,u=Dc(a);u===null&&o("its header does not decode"),u.alg!=="RS256"&&o(`its alg is ${JSON.stringify(u.alg)}, not RS256`),u.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(u.typ)}, not p2p+jwt`);let c=u.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let g=await n.key(c);g===null&&o("it was signed by a key this build cannot resolve");let p=i.subtle??globalThis.crypto?.subtle;p||o("this environment has no WebCrypto");let f=new TextEncoder().encode(`${a}.${l}`),y;try{y=$c(d);}catch{o("its signature does not decode");}await p.verify({name:"RSASSA-PKCS1-v1_5"},g,y,f)||o("its signature does not verify");let v=Dc(l);v===null&&o("its payload does not decode");let R=v,h=H=>typeof R[H]=="string"?R[H]:"",_=H=>typeof R[H]=="number"&&Number.isFinite(R[H])?R[H]: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 I=_("exp")*1e3,T=_("nbf")*1e3;(!Number.isFinite(I)||e.now>I+ta)&&o("it has expired"),Number.isFinite(T)&&e.now<T-ta&&o("it is not valid yet");let W=h("role");W!=="host"&&W!=="client"&&o("it names no usable role");let j=_("host_epoch");j!==e.hostEpoch&&o("it names a different host epoch");let U=ci(h("fingerprint"));U===null&&o("its fingerprint claim is malformed"),$t(U,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let C=ci(h("host_fingerprint"));C===null&&o("its host fingerprint claim is malformed"),$t(C,e.hostFingerprint)||o("it was issued against a different host certificate");let L=h("jti");L.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(L,e.now)||o("it has already been used");let D=h("sub");return D.length===0&&o("it names no player"),{playerId:D.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:j,role:W,fingerprint:U,hostFingerprint:C,jti:L,expiresAt:I}}function ia(t){let e=new TextEncoder().encode(t.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let n=new ArrayBuffer(3+e.length+4+4),r=new DataView(n);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(n,3,e.length).set(e),r.setUint32(3+e.length,t.protocolVersion,true),r.setUint32(7+e.length,t.assignedPeerId,true),n}function oa(t){let e=new ArrayBuffer(9),n=new DataView(e);return n.setUint8(0,2),n.setUint32(1,t.protocolVersion,true),n.setUint32(5,t.assignedPeerId,true),e}function aa(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function sa(t){if(t.byteLength<1)return null;let e=new DataView(t);switch(e.getUint8(0)){case 1:{if(t.byteLength<3)return null;let n=e.getUint16(1,true);return n>8192||t.byteLength<3+n+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(t,3,n)),protocolVersion:e.getUint32(3+n,true),assignedPeerId:e.getUint32(7+n,true)}}case 2:return t.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return t.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function Fc(t){switch(t){case 1:return "the host did not accept this credential";case 2:return "the host speaks a different protocol version \u2014 an engine peer refuses a browser peer here, deliberately";case 3:return "the match is full";case 4:return "the host is rate-limiting joins";case 129:return "the host verified this credential but it names a different player than the one who signalled \u2014 the host has its own line saying which";case 130:return "the host has this player on the kicked list for the current host epoch";case 131:return "the host could not fetch the platform's signing keys, so it cannot verify anyone yet \u2014 the host's console says why";default:return `the host refused with an unrecognised code (${t})`}}function qc(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Pn=class{constructor(e,n,r){this.localPlayerId=e;this.hostPlayerId=n,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,n){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=n,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var la={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}},Ue=["reliable","ordered","unreliable"];function da(t){let e=globalThis.RTCPeerConnection;if(!e)throw new Error("[gem] this environment has no RTCPeerConnection. Pass `peerConnectionFactory` to connect against a stand-in, which is how this flow is tested outside a browser.");return new e({iceServers:t.iceServers,...t.certificates===void 0?{}:{certificates:t.certificates}})}async function En(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var jc=1,eh=3e4,Bc=2e3,th=5e3,Uc=6e4,nh=8,rh=12e4,ih=5e3,oh=8e3,Kc=18e5,ah=Kc+6e4,ua=class{constructor(e=nh){this.perMinute=e;}perMinute;sent=[];delayUntilAllowed(e){return this.prune(e),this.sent.length<this.perMinute?0:Math.max(0,(this.sent[0]??e)+6e4-e)}record(e){this.prune(e),this.sent.push(e);}prune(e){let n=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[n++]=r);this.sent.length=n;}},sh=new ua,lh=8,dh=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Mn=class{constructor(e){this.options=e;this.keys=e.keys??na({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new di;links=new Map;replays=new xn;keys;localPlayerId="";migration=null;lease=null;clusterTargetIds=[];leaseRenewal=null;leaseAskedAt=null;leaseRenewalWarned=false;credential=null;nextPeerId=jc+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;drainTimers=new Set;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let n of this.links.values())n.admitted&&e.push(this.expose(n));return e}peer(e){let n=this.links.get(e);return n&&n.admitted?this.expose(n):null}on(e,n){return this.emitter.on(e,n)}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}async start(e){let n=this.options.connectTimeoutMs??eh;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((s,a)=>{this.ready={resolve:s,reject:a};});if(this.clusterTargetIds=Ie([this.options.clusterTargetId,...this.options.clusterTargetIds??[]]),this.clusterTargetIds.length>0)try{await this.takeLease(e),this.mark("turn leased");}catch(s){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${In(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let i=this.options.clock.setTimeout(()=>{this.fail(new N("timeout",`no usable P2P connection after ${n}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},n),o=()=>this.fail(new N("aborted","the caller aborted while connecting"));e?.aborted?o():e?.addEventListener("abort",o);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",o),this.ready=null;}}async kick(e){if(!this.isHost)throw new N("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of this.drainTimers)this.options.clock.clearTimeout(e);this.drainTimers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,n){this.closed||this.route(e,n).catch(r=>this.report_(r));}async route(e,n){switch(e){case "hello":return this.onHello(n);case "offer":return this.onOffer(n);case "answer":return this.onAnswer(n);case "ice":return this.onIce(n);case "peerLeft":return this.onPeerLeft(n);case "migration":return this.onMigration(n);case "matchEnded":return this.onMatchEnded(n);case "error":return this.onSignalingError(n);case "relayDraining":return this.onRelayDraining(n);default:return}}async onHello(e){let n=le(e.playerId),r=le(e.hostPlayerId),i=Tn(e.hostEpoch);if(!(n===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new Pn(n,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let n of e)try{await this.onOffer(n);}catch(r){this.report_(r);}}async offerToHost(e){let n=this.hostPlayerId,r=this.openLink(n,jc),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new N("invalid_sdp","the browser produced an offer with no SDP");Be(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:Ft(r);if(i===null)throw new N("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let o=this.options.credentialPacing??sh,s=()=>this.closed||e!==this.credentialGeneration,a=th;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,s))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(s())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(s())return;let u=d.status,c;if(u===409)c=Bc;else if(u===429){let g=d.retryAfterSeconds;typeof g=="number"&&Number.isFinite(g)&&g>=0?c=g*1e3:(c=a,a=Math.min(a*2,Uc)),c=Math.min(Math.max(c,Bc),Uc);}else throw d;if(!await this.waitForCredential(c,s))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=le(e.fromPlayerId),r=le(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=lh){let l=this.pendingOffers.keys().next().value;l!==void 0&&this.pendingOffers.delete(l);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let i=le(e.sessionId);if(i!==null&&this.answeredSessions.get(n)===i)return;Be(r,"offer"),this.refuseMedia(r,"offer");let o=Ft(r);if(o===null)throw new N("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);if(this.mark("offer received"),i!==null&&this.answeredSessions.set(n,i),await this.refreshLease(false),this.closed||!this.isHost)return;let s=this.links.get(n);if(le(e.intent)==="ice_restart"&&s?.admitted===true&&s.remoteFingerprint!==null&&$t(s.remoteFingerprint,o)){await this.answer(s,r),this.mark("ice restart answered");return}s&&this.dropLink(s,"resignalled",false);let a=this.openLink(n,this.nextPeerId++);a.remoteFingerprint=o,await this.answer(a,r),this.mark("answer sent");}async answer(e,n){await e.connection.setRemoteDescription({type:"offer",sdp:n}),this.flushCandidates(e);let r=await e.connection.createAnswer();await e.connection.setLocalDescription(r);let i=e.connection.localDescription?.sdp??r.sdp;if(!i)throw new N("invalid_sdp","the browser produced an answer with no SDP");Be(i,"answer"),this.refuseMedia(i,"answer"),this.options.signaling.answer(e.playerId,i,e.assignedPeerId);}async onAnswer(e){if(this.isHost)return;let n=le(e.fromPlayerId),r=le(e.sdp);if(n===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||n!==this.hostPlayerId)return;Be(r,"answer"),this.refuseMedia(r,"answer");let o=Ft(r);if(o===null)throw new N("invalid_sdp","the host's answer carries no usable fingerprint");let s=Tn(e.assignedPeerId);if(i.restart!==void 0&&s!==null&&s!==i.assignedPeerId){this.warn(`the host answered the ICE restart from a new connection (peer id ${s}, this link is ${i.assignedPeerId}); dropping the link to re-dial`),this.dropLink(i,"restart_mismatch",true);return}this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:$t(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new N("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let n=e.pendingAnswer;n!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,n).catch(r=>this.report_(r));}async applyAnswer(e,n){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:n}),this.flushCandidates(e),e.restart!==void 0&&(e.restart.answered=true,this.progressRestart(e));}async onIce(e){let n=le(e.fromPlayerId),r=le(e.candidate);if(n===null||r===null)return;let i=this.links.get(n);if(!i)return;let o=le(e.sdpMid),s=Tn(e.sdpMLineIndex)??Tn(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a).catch(()=>{});}onPeerLeft(e){let n=le(e.playerId);if(n===null)return;let r=le(e.reason)??"left";if(n===this.localPlayerId){this.fail(new N("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(n);i&&this.dropLink(i,r,true);}async onMigration(e){let n=le(e.hostPlayerId),r=Tn(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:n,hostEpoch:r,...le(e.reason)===null?{}:{reason:le(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(s=>typeof s=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind==="duplicate")return;if(i.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(i.kind==="refused"){this.report_(new N("migration_failed",i.why));return}for(let s of [...this.links.values()])this.dropLink(s,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration();let o=this.hostEpoch;await this.refreshLease(false),!(this.closed||this.hostEpoch!==o)&&await this.offerToHost("full_reconnect");}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new N("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let n=le(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new N("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=le(e.code)??"unknown",r=le(e.message)??"the platform refused a signaling message",i=this.isHost?void 0:this.links.get(this.hostPlayerId)?.restart;if(i!==void 0){this.warn(`the platform refused an ICE restart (${n}: ${r})`),i.settle(false);return}this.report_(new N("signaling_failed",`${n}: ${r}`));}async onRelayDraining(e){if(this.migration===null)return;let n=new Set((Array.isArray(e.relayIps)?e.relayIps:[]).filter(c=>typeof c=="string").map(c=>c.toLowerCase())),r=this.isHost?void 0:this.links.get(this.hostPlayerId),i,o=this.options.clock.now(),s=Date.parse(le(e.deadline)??""),a=(Number.isFinite(s)?s:o+Kc)-o,l=this.options.clock.setTimeout(()=>{this.drainTimers.delete(l),this.onDrainDeadline(n,r,i).catch(c=>this.report_(c));},Math.max(0,Math.min(a,ah)));if(this.drainTimers.add(l),await this.refreshLease(true),this.closed||(this.withoutDrainingRelays(n),this.isHost))return;let d=this.links.get(this.hostPlayerId);if(d===void 0||!d.admitted)return this.reportRestart("skipped","announced");let u=await Wc(d.connection,n);if(!(this.closed||this.links.get(d.playerId)!==d)){if(u===false)return this.reportRestart("skipped","announced");await this.restartIceToHost(d,"announced")&&(i=d);}}async onDrainDeadline(e,n,r){if(this.closed||this.isHost)return;let i=this.links.get(this.hostPlayerId);if(i===void 0)return;let o=await Wc(i.connection,e);if(this.closed||this.links.get(i.playerId)!==i)return;(o===true||o===null&&i===n&&i!==r)&&this.dropLink(i,"relay_deadline",true);}withoutDrainingRelays(e){let n=this.lease;if(n===null||e.size===0)return;let r=false,i=[];for(let o of n.iceServers){let s=o.urls.filter(a=>{let l=ch(a),d=l===null||!e.has(l);return r||=!d,d});s.length>0&&i.push({...o,urls:s});}r&&(this.lease={iceServers:i,expiresAt:n.expiresAt},this.reconfigureLinks());}restartIceToHost(e,n){if(e.restart!==void 0)return e.restart.done;if(e.connection.restartIce===void 0)return this.reportRestart("skipped",n),Promise.resolve(false);let r=()=>{},i=new Promise(a=>{r=a;}),o=this.options.clock.setTimeout(()=>s.settle(false),oh),s={done:i,answered:false,settle:a=>{e.restart===s&&(e.restart=void 0,this.options.clock.clearTimeout(o),this.closed||this.reportRestart(a?"success":"failed",n),r(a));}};return e.restart=s,this.offerIceRestart(e).catch(a=>{this.warn(`could not restart ICE on the connection to the host: ${In(a)}`),s.settle(false);}),i}async offerIceRestart(e){let n=e.connection;n.restartIce?.();let r=await n.createOffer();await n.setLocalDescription(r);let i=n.localDescription?.sdp??r.sdp;if(!i)throw new N("invalid_sdp","the browser produced an offer with no SDP");Be(i,"offer"),this.refuseMedia(i,"offer"),!(e.restart===void 0||this.links.get(e.playerId)!==e)&&(this.options.signaling.offer(i,"ice_restart"),this.mark("ice restart offered"));}progressRestart(e){let n=e.restart;if(n===void 0)return;let r=e.connection.iceConnectionState;r==="failed"||r==="closed"?n.settle(false):n.answered&&ca(r)&&n.settle(true);}reportRestart(e,n){this.report([{type:"ice_restart_outcome_total",value:1,labels:{outcome:e,reason:n}}]);}async takeLease(e){this.leaseAskedAt=this.options.clock.now();let n=this.clusterTargetIds,r=await Ic(this.options.api,this.options.matchId,n,e);this.lease={iceServers:r.iceServers,expiresAt:r.expiresAt},this.clusterTargetIds=n.slice(Math.max(0,n.indexOf(r.clusterTargetId)));}refreshLease(e){if(this.clusterTargetIds.length===0||this.closed)return Promise.resolve();if(this.leaseRenewal!==null)return this.leaseRenewal;let n=this.options.clock.now();if(this.leaseAskedAt!==null&&n-this.leaseAskedAt<ih)return Promise.resolve();let r=this.lease;if(!e&&r!==null&&r.expiresAt-n>=rh)return Promise.resolve();let i=this.takeLease().then(()=>{this.closed||(this.mark("turn re-leased"),this.reconfigureLinks());},o=>{this.leaseRenewalWarned||(this.leaseRenewalWarned=true,this.warn(`could not renew the TURN lease for this match, so connections keep the relays they were given: ${In(o)}`));}).finally(()=>{this.leaseRenewal=null;});return this.leaseRenewal=i,i}reconfigureLinks(){for(let e of this.links.values()){let n=e.connection;if(n.setConfiguration!==void 0)try{n.setConfiguration({...n.getConfiguration?.(),iceServers:this.iceServers()});}catch{}}}iceServers(){return (this.lease?.iceServers??[]).map(e=>({urls:[...e.urls],username:e.username,credential:e.credential}))}openLink(e,n){let i=(this.options.peerConnectionFactory??da)({iceServers:this.iceServers(),...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let g of Ue){let p=i.createDataChannel(g,la[g]);p.binaryType="arraybuffer",o[g]=p;}let s={playerId:e,assignedPeerId:n,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=g=>{let p=g.candidate;p?.candidate&&this.options.signaling.candidate(e,p.candidate,p.sdpMid??void 0,p.sdpMLineIndex??void 0);},l=()=>this.onIceState(s),d=()=>this.onConnectionState(s),u=g=>{this.onHandshakeMessage(s,g.data).catch(p=>this.report_(p));},c=()=>{this.onReliableOpen(s).catch(g=>this.report_(g));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",u),s.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",u);},s.detachAll=()=>{s.detachHandshake(),i.removeEventListener("icecandidate",a),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,s),s}flushCandidates(e){let n=e.pendingCandidates;e.pendingCandidates=[];for(let r of n)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let n=this.credential;if(n===null)throw new N("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=n.expiresAt)throw new N("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(ia({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=sa(n);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new N(qc(r.reason),Fc(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,n,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=Ft(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 ra(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(s){let a=s instanceof N&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",In(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(oa({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send(aa(n));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){this.progressRestart(e);let n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(n==="disconnected"){if(e.recovering===true)return;if(e.admitted&&e.connection.restartIce!==void 0&&this.reportedUnreachableEpoch!==this.hostEpoch){this.recoverHostLink(e).catch(r=>this.report_(r));return}}this.voteHostUnreachable(n);}}async recoverHostLink(e){let n=this.hostEpoch,r=()=>!this.closed&&this.hostEpoch===n&&this.links.get(e.playerId)===e;e.recovering=true;try{if(await this.refreshLease(!0),!r())return;if(ca(e.connection.iceConnectionState))return this.reportRestart("skipped","disconnected");if(await this.restartIceToHost(e,"disconnected")||!r()||ca(e.connection.iceConnectionState))return;this.voteHostUnreachable(Hc(e.connection.iceConnectionState));}finally{e.recovering=false;}}voteHostUnreachable(e){if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,e);}catch(n){this.report_(n);}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||(e.recovering===true&&this.voteHostUnreachable(Hc(e.connection.iceConnectionState)),this.dropLink(e,n,true));}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.restart?.settle(false),e.detachAll();for(let i of Ue)Vc(e.channels[i]);Vc(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,n);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let n=this.ready;this.ready=null,n.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof N?e:new N("connection_failed",In(e),{cause:e}));}count(e){this.counted||!dh.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(li(e))throw new N("media_refused",`the ${n} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(n=>this.options.clock.setTimeout(n,e))}warn(e){let n=this.options.log;n!==null&&(n??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function le(t){return typeof t=="string"&&t.length>0?t:null}function Tn(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function In(t){return t instanceof Error?t.message:String(t)}async function Wc(t,e){if(t.getStats===void 0)return null;let n=new Map;try{(await t.getStats()).forEach((a,l)=>{typeof a=="object"&&a!==null&&n.set(l,a);});}catch{return null}let r=[...n.values()],i=r.find(a=>a.type==="transport")?.selectedCandidatePairId,o=(typeof i=="string"?n.get(i):void 0)??r.find(a=>a.type==="candidate-pair"&&a.selected===true)??r.find(a=>a.type==="candidate-pair"&&a.nominated===true&&a.state==="succeeded");if(o===void 0)return null;let s=[o.localCandidateId,o.remoteCandidateId].map(a=>typeof a=="string"?n.get(a):void 0);return s.every(a=>a===void 0)?null:s.some(a=>{let l=a?.address??a?.ip;return typeof l=="string"&&e.has(l.toLowerCase())})}function ch(t){let e=/^(?:turns?|stuns?):(?:\[([^\]]+)\]|([^:?/]+))/i.exec(t),n=e?.[1]??e?.[2];return n===void 0?null:n.toLowerCase()}function ca(t){return t==="connected"||t==="completed"}function Hc(t){return t==="failed"||t==="closed"?t:"disconnected"}function Vc(t){try{t.close();}catch{}}var uh=100,mh=50,On=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,n){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:n});}answer(e,n,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:n,assignedPeerId:r});}candidate(e,n,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??uh)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,n){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:n,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new N("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new N("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:n,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let n=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(n),this.dropListener?.(n);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??mh));}};function K(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function Ye(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function qt(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function Jc(t){return typeof t=="boolean"?t:void 0}var _e=K(64),Gn=Ye(0,2147483647);function ui(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=_e(n);typeof r=="string"&&e.push(r);}return e}function J(t,e,n){return {to:t,from:e,read:n,required:true}}function z(t,e,n){return {to:t,from:e,read:n,required:false}}var fh=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=qt("disconnected","failed","closed")(e.iceState),r=Ye(0,4102444800)(e.lastSeenAt);if(!(n===void 0&&r===void 0))return {...n===void 0?{}:{ice_state:n},...r===void 0?{}:{last_seen_timestamp:r}}};Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[J("sdp","sdp",K(10240)),J("signaling_intent","intent",qt("initial","ice_restart","full_reconnect")),z("sdp_hash","sdpHash",K(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[J("peer_id","peerId",_e),J("sdp","sdp",K(10240)),J("assigned_peer_id","assignedPeerId",Ye(0,4294967295)),z("sdp_hash","sdpHash",K(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[J("peer_id","peerId",_e),J("candidate","candidate",K(512)),z("sdp_mid","sdpMid",K(64)),z("sdp_mline_index","sdpMLineIndex",Ye(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[J("host_epoch","hostEpoch",Gn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[J("host_epoch","hostEpoch",Gn),z("evidence","evidence",fh)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error",p2p_relay_draining:"relayDraining"}));var yh=16,hh=t=>ui(t)?.slice(0,yh);Object.freeze(Object.assign(Object.create(null),{hello:[J("playerId","player_id",_e),J("hostPlayerId","host_player_id",_e),J("hostEpoch","host_epoch",Gn),z("members","members",ui)],offer:[J("fromPlayerId","from_player_id",_e),J("sdp","sdp",K(10240)),z("sessionId","signaling_session_id",K(128)),z("sdpHash","sdp_hash",K(128)),z("iceUfrag","ice_ufrag",K(64)),z("intent","signaling_intent",qt("initial","ice_restart","full_reconnect"))],answer:[J("fromPlayerId","from_player_id",_e),J("sdp","sdp",K(10240)),z("sessionId","signaling_session_id",K(128)),z("sdpHash","sdp_hash",K(128)),z("iceUfrag","ice_ufrag",K(64)),z("assignedPeerId","assigned_peer_id",Ye(0,4294967295))],ice:[J("fromPlayerId","from_player_id",_e),J("candidate","candidate",K(512)),z("sdpMid","sdp_mid",K(64)),z("sdpMLineIndex","sdp_m_line_index",Ye(0,255)),z("sdpMLineIndexAlt","sdp_mline_index",Ye(0,255))],peerJoined:[J("playerId","player_id",_e)],peerLeft:[J("playerId","player_id",_e),z("reason","reason",K(64))],migration:[J("hostPlayerId","new_host_player_id",_e),J("hostEpoch","host_epoch",Gn),z("reason","reason",K(64)),z("kickedPlayerIds","kicked_player_ids",ui),z("migrationComplete","migration_complete",Jc)],matchEnded:[z("reason","reason",K(64))],error:[z("code","code",K(64)),z("message","message",K(256))],relayDraining:[J("clusterTargetId","cluster_target_id",_e),J("relayIps","relay_ips",hh),J("drainingSince","draining_since",K(40)),J("deadline","deadline",K(40))]}));Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));var mt="webrtc_p2p";function Xc(t){let e=new An({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,i,o){n.get(r)?.handleSignal(i,o);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new N("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let i=Se(r.clusterTargetId),o=i===void 0?await bh(t):[i];t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let s=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==mt)throw new N("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${mt}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new On({bridge:t.bridge,matchId:s.matchId,clock:t.clock}),l=new Mn({api:e,clock:t.clock,matchId:s.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:a,...o.length===0?{}:{clusterTargetIds:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await En(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});a.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(s.matchId,l),l.on("matchEnded",()=>n.delete(s.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(s.matchId),l.close(),d}return l}}}async function bh(t){if(t.resolveClusterTargets!==void 0)return Ie(await t.resolveClusterTargets());let e=Se(await t.resolveClusterTarget?.());return e===void 0?[]:[e]}function Yc(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,i=t.document??globalThis.document,o=[];if(typeof r.addEventListener=="function"){let a=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",a),o.push(()=>r.removeEventListener?.("pagehide",a));let l=()=>e.setHidden(!ct());for(let d of ii)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(!ct());}let s=new Map;return o.push(n.on("matchReady",a=>{let l=a.protocol===mt?"p2p":"dedicated";s.set(a.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),o.push(n.on("matchEnded",a=>{let l=s.get(a.matchId);l!==void 0&&(s.delete(a.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let a of o.splice(0))try{a();}catch{}s.clear();}}var vh=[[/swiftshader|llvmpipe|softpipe|software|basic render driver/i,"software"],[/powervr d-series/i,"powervr_d_series"],[/powervr|imagination/i,"powervr_other"],[/adreno/i,"adreno"],[/mali|immortalis/i,"mali"],[/xclipse/i,"xclipse"],[/apple/i,"apple"],[/nvidia|geforce|quadro|tegra/i,"nvidia"],[/\bamd\b|radeon|\bati\b/i,"amd"],[/intel/i,"intel"]];function Ln(t){if(t===null||t==="")return "unknown";for(let[e,n]of vh)if(e.test(t))return n;return "other"}function ma(t){return t===null||t===""?"unknown":/^ANGLE \(/.test(t)?/vulkan/i.test(t)?"angle_vulkan":/opengl es/i.test(t)?"angle_gles":/direct3d11|d3d11/i.test(t)?"angle_d3d11":/direct3d9|d3d9/i.test(t)?"angle_d3d9":/metal/i.test(t)?"angle_metal":/opengl/i.test(t)?"angle_opengl":"angle_other":"native_gl"}function pa(t){return /Android/.test(t)&&/; wv\)/.test(t)?"android_webview":"other"}function ga(t){try{let e=t.getParameter(t.RENDERER);if(typeof e=="string"&&e!==""&&!/^WebKit WebGL$/i.test(e))return e;let n=t.getExtension("WEBGL_debug_renderer_info");if(n){let r=t.getParameter(n.UNMASKED_RENDERER_WEBGL);if(typeof r=="string"&&r!=="")return r}return typeof e=="string"&&e!==""?e:null}catch{return null}}function _h(t){try{let{vendor:e,architecture:n,description:r}=t??{},i=[e,n,r].filter(o=>typeof o=="string"&&o!=="").join(" ").replace(/img-tec/gi,"PowerVR").replace(/qualcomm/gi,"Adreno").replace(/\barm\b/gi,"Mali").replace(/samsung/gi,"Xclipse");return Ln(i)}catch{return "unknown"}}var wh=new Set(["webgl","webgl2","experimental-webgl"]),Qc=false;function Zc(t){let e=t.win??globalThis.window,n=e?.HTMLCanvasElement?.prototype;if(Qc||!e||!n)return;Qc=true;let r=t.now??(()=>performance.now()),i=pa(e.navigator?.userAgent??""),o=new WeakMap,s=null,a=0,l=(g,p,f)=>{try{if(a+=1,a>5)return;t.analytics.trackPlatform("gem_graphics_context_lost",{gpu:g,host:i,route:p,...f===void 0?{}:{context_ms:Math.max(0,Math.round(r()-f))},hidden:e.document?.visibilityState==="hidden"?1:0,nth_loss:a});}catch{}},d=g=>{let p=o.get(g),f=p?.renderer??s;l(Ln(f),ma(f),p?.createdAt);},u=n.getContext;n.getContext=function(g,...p){let f=u.call(this,g,...p);try{if(f&&typeof g=="string"&&wh.has(g)&&!o.has(this)){let y=ga(f);y!==null&&(s=y),o.set(this,{createdAt:r(),renderer:y}),this.addEventListener?.("webglcontextlost",()=>d(this));}}catch{}return f};let c=e.GPUAdapter?.prototype;if(c&&typeof c.requestDevice=="function"){let g=c.requestDevice;c.requestDevice=function(...p){let f=g.apply(this,p);try{let y=r(),S=_h(this.info),v=S==="unknown"?Ln(s):S;Promise.resolve(f).then(R=>R?.lost).then(R=>{R&&R.reason!=="destroyed"&&l(v,"webgpu",y);},()=>{});}catch{}return f};}e.addEventListener?.("webglcontextlost",g=>{let p=g.target;p&&!o.has(p)&&d(p);},true);}var eu=["pointerdown","keydown"];function tu(t,e=globalThis){let n=false,r=false,i=null,o=()=>{if(i!==null){try{e.cancelAnimationFrame?.(i);}catch{}i=null;}},s=()=>{if(!r){r=true,o();for(let p of eu)e.removeEventListener?.(p,l,{capture:true});e.removeEventListener?.("gamepadconnected",g,{capture:true});}},a=()=>{if(!(n||r)){n=true,s();try{t();}catch{}}};function l(p){p?.isTrusted===true&&a();}let d=()=>{let p;try{p=e.navigator?.getGamepads?.()??[];}catch{return false}return p.some(f=>f?.buttons.some(y=>y.pressed)===true)},u=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(p=>p!==null)}catch{return false}},c=()=>{if(i=null,!(n||r)){if(d()){a();return}u()&&(i=e.requestAnimationFrame?.(c)??null);}};function g(){i===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let p of eu)e.addEventListener(p,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",g,{capture:true,passive:true}),u()&&(i=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:s}}async function mi(t,e,n,r){let i=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),i}function fa(t,e){let n=false;return async r=>{let i=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),i}}function ya(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(i,o){return r.has(i)?false:(r.add(i),n.push({name:i,at:o??e()}),true)},timeline(){let i=[...n].sort((o,s)=>o.at-s.at);return i.map((o,s)=>{let a=i[s-1],l=a===void 0?"":` (+${Math.round(o.at-a.at)}ms)`;return `${o.name}@${Math.round(o.at)}ms${l}`}).join(" \u2192 ")}}}var Sh=["angle_gles","native_gl","angle_opengl","angle_other","angle_d3d11","angle_d3d9","angle_metal"],Rh=Object.freeze(Sh.map(t=>Object.freeze({gpu:"powervr_d_series",route:t}))),ru="gemGraphics",nu=1e3,kh=5e3,Ah=32,xh=32,Ph=300;function iu(t){if(typeof t!="string"||t==="")return null;try{let n=new URLSearchParams(t).get(ru)?.trim().toLowerCase();return n==="webgpu"||n==="webgl"||n==="safe"?n:null}catch{return null}}function Eh(t){if(!Array.isArray(t)||t.length>Ah)return null;let e=[];for(let n of t){if(n===null||typeof n!="object"||Array.isArray(n))return null;let{gpu:r,route:i,host:o}=n;if(!ha(r)||i!==void 0&&!ha(i)||o!==void 0&&!ha(o))return null;e.push(Object.freeze({gpu:r,...i===void 0?{}:{route:i},...o===void 0?{}:{host:o}}));}return Object.freeze(e)}function ha(t){return typeof t=="string"&&t!==""&&t.length<=xh}function Th(t,e){return e.some(n=>n.gpu===t.gpu&&(n.route===void 0||n.route===t.route)&&(n.host===void 0||n.host===t.host))}function Ih(t){let e=t?.navigator?.gpu;return e&&typeof e.requestAdapter=="function"?e:null}function Ch(t){try{let e=t?.OffscreenCanvas;if(typeof e!="function")return null;let n=new e(1,1).getContext("webgl");if(!n)return null;let r=ga(n);try{n.getExtension("WEBGL_lose_context")?.loseContext();}catch{}return r===null?null:{gpu:Ln(r),route:ma(r),host:pa(t?.navigator?.userAgent??"")}}catch{return null}}function ba(t,e){return Object.freeze({route:t,listed:e})}var pi=ba("webgl",false);function ou(t){let{bridge:e,clock:n,forced:r}=t,i=()=>t.win??globalThis.window,o=t.log??null,s=null,a=false,l=new Set,d,u=null,c=false,g=(v,R,h)=>new Promise(_=>{let I=n.setTimeout(()=>_(h),Math.max(0,R));v.then(T=>{n.clearTimeout(I),_(T);},()=>{n.clearTimeout(I),_(h);});}),p=(v,R)=>(u??=Promise.resolve().then(()=>v.requestAdapter()).then(h=>h!=null,()=>false),g(u,R,false)),f=async v=>{if(a||v<=0)return;let R=n.now(),h=await e.settled(v);if(a||h!=="connected"||!e.parentSupports("graphicsRoutes"))return;let _=v-(n.now()-R);_<=0||await new Promise(I=>{let T=()=>{l.delete(T),n.clearTimeout(W),I();},W=n.setTimeout(T,_);l.add(T);});},y=async(v,R)=>ba(v!==null&&await p(v,R)?"webgpu":"webgl",true),S=async v=>{let R=n.now()+v,h=()=>Math.max(0,R-n.now()),_=Ih(i());if(r!==null&&!c&&(c=true,o?.(`[gem] graphics route forced to ${r} by the ${ru} launch key`+(r==="webgpu"&&_===null?", but this browser has no WebGPU: webgl, listed":""))),r==="webgl")return pi;if(r==="safe")return ba("webgl",true);if(r==="webgpu")return y(_,h());await f(h()-(_===null?0:Math.min(Ph,v/2)));let I=s??Rh;return I.length===0||(d===void 0&&(d=Ch(i())),d===null||!Th(d,I))?pi:y(_,h())};return {api:{preferredRoute(v){let R=Number(v?.timeoutMs??nu),h=Number.isFinite(R)?Math.min(Math.max(0,R),kh):nu;return S(h).catch(()=>pi)}},accept(v){let R=Eh(v);a=true,R!==null&&(s=R);for(let h of [...l])h();}}}var va=new WeakMap,au=new WeakSet,_a=new Set,gi=new Set,fi=[],jt=null,wa=false,Mh=1920;function Sa(t){return va.get(t)}function Ra(t){return !wa||au.has(t)}function ka(t){return t.kind==="webgpu"?true:t.kind!=="webgl"&&t.kind!=="webgl2"&&t.kind!=="experimental-webgl"?false:t.context.getContextAttributes()?.preserveDrawingBuffer!==true}function su(t=globalThis.window){if(wa||!t?.HTMLCanvasElement||typeof t.requestAnimationFrame!="function")return;wa=true;for(let o of Array.from(t.document?.querySelectorAll("canvas")??[]))au.add(o);let e=t.HTMLCanvasElement.prototype,n=e.getContext;e.getContext=function(o,...s){let a=n.call(this,o,...s);if(a&&!va.has(this)){let l={kind:o,context:a};va.set(this,l),ka(l)&&_a.add(this);}return a};let r=t.requestAnimationFrame,i=t.cancelAnimationFrame;t.requestAnimationFrame=o=>{let s=r.call(t,a=>{gi.delete(s);try{o(a);}finally{Oh();}});return gi.add(s),cu(),s},t.cancelAnimationFrame=o=>{gi.delete(o),i.call(t,o);};}function lu(t,e){return new Promise(n=>{let r={canvas:t,done:o=>{clearTimeout(i),fi=fi.filter(s=>s!==r),n(o);}},i=setTimeout(()=>r.done(null),e);fi.push(r);})}function du(t){return jt?.canvas===t?jt.bitmap:null}function Oh(){for(let t of fi){let e;try{e=Aa(t.canvas);}catch(n){t.done(Promise.reject(n));continue}e&&t.done(createImageBitmap(t.canvas));}gi.size===0&&Gh();}function Gh(){let t=null;for(let r of _a)r.isConnected?(!t||r.width*r.height>t.width*t.height)&&(t=r):_a.delete(r);if(!t||t.width===0||t.height===0)return;let e=Math.min(1,Mh/Math.max(t.width,t.height)),n=e<1?{resizeWidth:Math.max(1,Math.floor(t.width*e)),resizeHeight:Math.max(1,Math.floor(t.height*e)),resizeQuality:"medium"}:{};cu(),jt={canvas:t,bitmap:createImageBitmap(t,n).catch(()=>null)};}function cu(){jt&&(jt.bitmap.then(t=>t?.close()),jt=null);}function Aa(t){let e=Lh();if(!e)return true;e.clearRect(0,0,8,8),e.drawImage(t,0,0,8,8);let n=e.getImageData(0,0,8,8).data;for(let r=0;r<n.length;r+=4){if(n[r]|n[r+1]|n[r+2])return true;let i=n[r+3];if(i!==0&&i!==255)return true}return false}var Dn;function Lh(){if(Dn!==void 0)return Dn;if(typeof OffscreenCanvas=="function")Dn=new OffscreenCanvas(8,8).getContext("2d",{willReadFrequently:true});else {let t=globalThis.document?.createElement("canvas");t&&(t.width=t.height=8),Dn=t?.getContext("2d",{willReadFrequently:true})??null;}return Dn??null}var xa=false;async function gu(t,e,n,r){if(xa){e.close(),n("busy",true);return}xa=true;let i=null;try{let o=await Fh(t,r);if(typeof o=="string"){e.close(),n(o,Dh(o));return}i=o;let a=await(r.encodeRef??(l=>Uh(l,r)))(i);if(i.close(),i=null,a===null){e.close(),n("failed",!0);return}if(a.size>Bh){e.close(),n("too_large",!1);return}e.postMessage(a);}catch(o){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",o);}finally{xa=false,i?.close();}}function Dh(t){switch(t){case "no_source":case "busy":case "failed":return true;case "not_wired":case "unsupported":case "unreadable":case "tainted":case "too_large":case "declined":return false}}var $h=600;async function Fh(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":uu(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=jh(n);if(!r)return "no_source";try{let i=await qh(r);return typeof i=="string"?i:uu(i,t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}async function qh(t){let e=Nh(t);if(typeof e=="string")return e;if(e.kind.includes("webgl")&&!e.context.getContextAttributes())return "unsupported";if(!ka(e))return createImageBitmap(t);let n=await lu(t,$h);if(n)return n;let r=await du(t);return r&&Aa(r)?createImageBitmap(r):e.kind==="webgpu"?"unreadable":"unsupported"}function Nh(t){let e=Sa(t);if(e)return e;if(!Ra(t))return "no_source";try{for(let n of ["webgl2","webgl","2d","webgpu"]){let r=t.getContext(n);if(r)return {kind:n,context:r}}}catch{return "unreadable"}return "unreadable"}function jh(t){let e=null,n=0;for(let r of Array.from(t.querySelectorAll("canvas"))){let i=r.width*r.height;i<=0||r.clientWidth<=0||r.clientHeight<=0||!Sa(r)&&!Ra(r)||i>n&&(e=r,n=i);}return e}async function uu(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let i=Math.min(n/t.width,r/t.height),o=Math.max(1,Math.floor(t.width*i)),s=Math.max(1,Math.floor(t.height*i));try{let a=await createImageBitmap(t,{resizeWidth:o,resizeHeight:s,resizeQuality:"high"});return t.close(),a}catch{return t.close(),"too_large"}}var Bh=8*1024*1024,mu="image/webp",pu=.92;async function Uh(t,e){try{if(typeof OffscreenCanvas=="function"){let o=new OffscreenCanvas(t.width,t.height),s=o.getContext("2d");if(s){s.drawImage(t,0,0);let a=await o.convertToBlob({type:mu,quality:pu});if(a&&a.size>0)return a}}}catch{}let n=e.documentRef??globalThis.document;if(!n)return null;let r=n.createElement("canvas");r.width=t.width,r.height=t.height;let i=r.getContext("2d");return !i||(i.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(o=>{r.toBlob(s=>o(s),mu,pu);})}async function fu(t,e){if(!e)return;let n;try{n=await Wh(e);}catch(r){console.error("[gem] onFeedbackContext threw; sending the report without context",r);return}if(n!=null){if(typeof n!="object"||Array.isArray(n)){console.error("[gem] onFeedbackContext must return a plain object or null; got",n);return}t.sendGameContext(n);}}function Wh(t){return new Promise((e,n)=>{let r=false,i=setTimeout(()=>{r||(r=true,console.warn("[gem] onFeedbackContext did not answer within 1000ms; sending the report without context. Gather cheaply, or keep a snapshot."),e(null));},1e3);(async()=>t())().then(o=>{r||(r=true,clearTimeout(i),e(o??null));},o=>{r||(r=true,clearTimeout(i),n(o instanceof Error?o:new Error(String(o))));});})}var yu=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function bu(t=globalThis){let n=t[yu];if(n!==void 0)return n;let r=false,i=()=>r,o=Kh(t),s=[],a=Hh(t,i,o.watch);a!==null&&s.push(a);let l=Vh(t,i,o.watch);l!==null&&s.push(l);let d={get muted(){return r},setMuted(u){let c=!!u;if(c!==r){r=c;for(let g of s)g();}},setPaused(u){o.setPaused(!!u);}};return Object.defineProperty(t,yu,{value:d,configurable:true}),d}function Hh(t,e,n){let r=t.AudioNode?.prototype,i=t.AudioDestinationNode;if(r===void 0||i===void 0)return null;let o=t.OfflineAudioContext,s=r.connect,a=r.disconnect,l=new Map,d=c=>{let g=c.gain,p=c.context.currentTime;g.cancelScheduledValues(p),e()?g.setValueAtTime(0,p):g.setTargetAtTime(1,p,.01);},u=c=>{let g=c.context;if(o!==void 0&&g instanceof o)return null;let p=l.get(g);return p===void 0&&(p=g.createGain(),p.gain.value=e()?0:1,s.call(p,c),l.set(g,p),n.context(g)),p};return r.connect=function(...g){let[p,...f]=g;if(p instanceof i){let y;try{y=u(p);}catch{y=null;}if(y!==null)return s.call(this,y,...f),p}return s.apply(this,g)},r.disconnect=function(...g){let[p,...f]=g;if(p instanceof i){let y=l.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...f)}catch{}}return a.apply(this,g)},()=>{for(let[c,g]of l){if(c.state==="closed"){l.delete(c);continue}try{d(g);}catch{}}}}function Vh(t,e,n){let r=t.HTMLMediaElement;if(r===void 0)return null;let i=r.prototype,o=Object.getOwnPropertyDescriptor(i,"muted"),s=o?.get,a=o?.set;if(s===void 0||a===void 0)return null;let l=i.play,d=new WeakMap,u=new WeakSet,c=new Set,g=p=>{d.has(p)||d.set(p,!!s.call(p)),u.has(p)||(u.add(p),c.add(new WeakRef(p)),n.element(p)),a.call(p,(d.get(p)??false)||e());};return Object.defineProperty(i,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=d.get(this);return p===void 0?!!s.call(this):p},set(p){d.set(this,!!p),g(this);}}),i.play=function(){try{g(this);}catch{}return l.call(this)},t.document?.addEventListener("play",p=>{let f=p.target;if(f instanceof r)try{g(f);}catch{}},true),()=>{for(let p of c){let f=p.deref();if(f===void 0){c.delete(p);continue}try{a.call(f,(d.get(f)??!1)||e());}catch{}}}}var hu=["pointerup","touchend","click","keydown"];function Kh(t){let e=t.document,n=new Set,r=new WeakSet,i=new WeakSet,o=new Set,s=new WeakSet,a=new Set,l=new Set,d=false,u=false,c=t.AudioContext?.prototype,g=c?.suspend,p=c?.resume,f=c!==void 0&&typeof g=="function"&&typeof p=="function";f&&(c.suspend=function(...G){try{i.add(this);}catch{}return g.apply(this,G)},c.resume=function(...G){try{i.delete(this);}catch{}return p.apply(this,G)});let y=t.HTMLMediaElement?.prototype,S=y?.pause;y!==void 0&&typeof S=="function"&&(y.pause=function(){l.delete(this),S.call(this);});let v=x=>x.state!=="running"&&x.state!=="closed"&&r.has(x)&&!i.has(x),R=x=>x.state==="running"&&o.has(x)&&!i.has(x),h=x=>x.paused&&!x.ended,_=()=>{for(let x of n)if(x.state==="closed")n.delete(x),o.delete(x);else if(v(x)||R(x))return true;for(let x of l){if(h(x))return true;l.delete(x);}return false},I=()=>{for(let x of a){let G=x.deref();if(G===void 0){a.delete(x);continue}try{!G.paused&&!G.ended&&l.add(G);}catch{}}},T=()=>{if(u){u=false,l.clear();for(let x of hu)e?.removeEventListener?.(x,j,true);}},W=()=>{try{u&&!_()&&T();}catch{}};function j(){if(!u||d)return;let x=[];try{for(let G of n){if(G.state==="closed"){n.delete(G),o.delete(G);continue}if(v(G)){o.delete(G);try{x.push(Promise.resolve(p?.call(G)));}catch{}}else if(R(G)){o.delete(G);try{x.push(Promise.resolve(g?.call(G))),s.add(G),x.push(Promise.resolve(p?.call(G)));}catch{}}}for(let G of l){if(!h(G)){l.delete(G);continue}try{x.push(Promise.resolve(G.play()).then(()=>l.delete(G),ne=>{ne?.name!=="NotAllowedError"&&l.delete(G);}));}catch{l.delete(G);}}}catch{}if(x.length===0){W();return}Promise.allSettled(x).then(W);}let U=()=>{if(!(u||e===void 0)){u=true;for(let x of hu)e.addEventListener(x,j,true);}},C=()=>{I(),e?.visibilityState!=="hidden"&&U();},L=()=>{for(let x of n)x.state!=="closed"&&r.has(x)&&o.add(x);U();},D=()=>{o.clear(),I();};try{e?.addEventListener("visibilitychange",()=>{try{e.visibilityState==="hidden"?D():L();}catch{}},!0),t.addEventListener?.("pagehide",()=>{try{D();}catch{}}),t.addEventListener?.("pageshow",x=>{try{x.persisted&&L();}catch{}});}catch{}return {watch:{context(x){if(f)try{n.add(x),(x.state==="running"||x.currentTime>0)&&r.add(x),x.addEventListener("statechange",()=>{try{let G=x.state;G==="running"?(r.add(x),s.delete(x),o.has(x)&&U(),W()):G!=="closed"&&r.has(x)&&!i.has(x)&&!s.has(x)&&C();}catch{}});}catch{}},element(x){try{a.add(new WeakRef(x));}catch{}}},setPaused(x){d=x;}}}var Jh=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",zh=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Xh=`${Jh}${zh}`,Pa=new WeakSet;function vu(t=globalThis.document){if(t==null||Pa.has(t))return null;try{let e=t.defaultView?.CSSStyleSheet??globalThis.CSSStyleSheet;if(Array.isArray(t.adoptedStyleSheets)&&typeof e=="function"){let r=new e;if(typeof r.replaceSync=="function")return r.replaceSync(Xh),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],Pa.add(t),"sheet"}let n=t.documentElement?.style;return n===void 0||typeof n.setProperty!="function"?null:(n.setProperty("-webkit-user-select","none"),n.setProperty("user-select","none"),n.setProperty("-webkit-tap-highlight-color","transparent"),Pa.add(t),"inline")}catch{return null}}function _u(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=t.now??(()=>globalThis.performance?.now()??Date.now()),i=false,o=false,s=false,a=null,l=null,d=null,u=[],c=false,g=0,p=null,f=[],y=()=>i&&!o&&!s,S=()=>{l=null,d=null,u=[],g=0,p=null,f=[];},v=_=>{if(a=null,!y()){S();return}if(d!==null&&u.push(_-d),d=_,l===null)l=_;else {let I=_-l;if(I>=e&&u.length>0){if(c){let T=p===null?I:r()-p;t.report(Qh(g,f,I,T));}else t.report(Yh(u,I));l=_,u=[],g=0,f=[];}}R();},R=()=>{let _=n.requestAnimationFrame;typeof _=="function"&&(a=_.call(n,v));},h=()=>{if(y()){a===null&&(S(),R());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),S();};return {setRequested(_){i=_,h();},setPaused(_){o=_,h();},draw(){if(!c){c=true,a!==null&&S();return}if(a===null||l===null)return;let _=r();p!==null&&f.length<1e3&&f.push(_-p),p=_,g+=1;},get running(){return a!==null},dispose(){s=true,h();}}}function Yh(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:wu(t),counts:"pageFrames"}}function Qh(t,e,n,r){let i=r;return e.length>0&&(i=wu(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:i,counts:"gameDraws"}}function wu(t){let e=[...t].sort((r,i)=>r-i),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var yi=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Su(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Ru(t,e){t!==null&&(t.style.setProperty(yi.top,`${e.top}px`),t.style.setProperty(yi.right,`${e.right}px`),t.style.setProperty(yi.bottom,`${e.bottom}px`),t.style.setProperty(yi.left,`${e.left}px`));}var hi=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height",centerY:"--gem-reserved-tl-center-y",controlHeight:"--gem-reserved-tl-control-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height",centerY:"--gem-reserved-tr-center-y",controlHeight:"--gem-reserved-tr-control-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height",centerY:"--gem-reserved-bl-center-y",controlHeight:"--gem-reserved-bl-control-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height",centerY:"--gem-reserved-br-center-y",controlHeight:"--gem-reserved-br-control-height"}});function ku(){let t=globalThis,e=t.innerWidth,n=t.innerHeight;return typeof e=="number"&&e>0&&typeof n=="number"&&n>0?{width:e,height:n}:null}function Zh(t,e){let n={tl:{width:0,height:0,control:null},tr:{width:0,height:0,control:null},bl:{width:0,height:0,control:null},br:{width:0,height:0,control:null}};for(let r of t){let i=e?r.x+r.width/2<=e.width/2:r.x===0,o=e?r.y+r.height/2<=e.height/2:r.y===0,s=i?r.x+r.width:e?e.width-r.x:r.width,a=o?r.y+r.height:e?e.height-r.y:r.height,l=n[`${o?"t":"b"}${i?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));let d=r.control;if(d){let u=l.control;l.control=u?{top:Math.min(u.top,d.y),bottom:Math.max(u.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function Au(t,e,n){if(t===null)return;let r=Zh(e,n);for(let i of ["tl","tr","bl","br"]){t.style.setProperty(hi[i].width,`${r[i].width}px`),t.style.setProperty(hi[i].height,`${r[i].height}px`);let o=r[i].control;t.style.setProperty(hi[i].centerY,o?`${(o.top+o.bottom)/2}px`:""),t.style.setProperty(hi[i].controlHeight,o?`${o.bottom-o.top}px`:"");}}var eb=3e4,bi=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function xu(t){let e=t.clock??ce,n=t.timeoutMs??eb,r=new Map,i=new Map,o=0,s=a=>{let l=r.get(a);return l?(r.delete(a),i.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(a){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=i.get(a);if(l)return l;let d=new Promise((u,c)=>{let g=`ls${++o}`,p=e.setTimeout(()=>{r.delete(g),i.delete(a),c(new bi("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(n)}ms`));},n);r.set(g,{room:a,resolve:u,reject:c,timer:p}),t.bridge.requestLocalServer(g,a)||(s(g),u());});return i.set(a,d),d.catch(()=>{}),d},accept(a){s(a.requestId)?.resolve();},refuse(a){let l=s(a.requestId);l&&l.reject(new bi(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 $n={url:"https://downloads.indiegems.games/sdk/v22.0.0/gem-web-sdk.devtools.min.js",integrity:"sha384-UAWe7ohEdmia7gzawnegu+mh9B7onGFd5fyU8l6vp2mFovbNKSrmt0Bciwjj8KQ/"};var Bt=null;function tb(){return Bt!==null||(Bt=new Promise((t,e)=>{let n=document.createElement("script");n.src=$n.url,n.integrity=$n.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Bt=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${$n.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{Bt=null,e(new Error(`gem devtools: could not load ${$n.url}. Either the network refused it or its Subresource Integrity check failed, or the CDN did not answer the CORS preflight this request needs \u2014 SRI is only checkable on bytes the page may read. A locally rebuilt SDK is the commonest cause: it produces panel bytes that do not match the hash compiled into this build.`));},document.head.append(n);})),Bt}function Pu(t,e){let n=null,r=0;async function i(o){if(n!==null)return true;let s=++r;if(!e())return false;let a=await tb();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:o,text:ot,onDismiss:()=>{n?.unmount(),n=null;}})),true)}return {get isOpen(){return n!==null},close(){r+=1,n?.unmount(),n=null;},open:()=>i("game"),openFrom:i}}var nb=1e4,Eu={reason:"unavailable",retryable:false};function Tu(t){let e=new Map,n=null,r=null,i=0,o=(d,u)=>{u.timer=t.clock.setTimeout(()=>{e.delete(d),u.reject({reason:"timeout",retryable:true});},t.timeoutMs??nb);},s=(d,u)=>{let c=a(d);c&&u(c);},a=d=>{let u=e.get(d);return u?(e.delete(d),t.clock.clearTimeout(u.timer),u):null},l=new kt({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((u,c)=>{let g=t.bridge.currentState;if(g==="refused"||g==="closed"){c(Eu);return}let p=`t${++i}`,f={resolve:u,reject:c,reason:d,timer:null,held:g!=="connected"};e.set(p,f),o(p,f),f.held||t.bridge.requestToken(p,d);})});return {source:l,onToken(d){let u={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){s(d.requestId,c=>c.resolve(u));return}l.accept(u);},onDenied(d){s(d.requestId,u=>u.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[u,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),o(u,c),t.bridge.requestToken(u,c.reason));else if(d==="refused"||d==="closed")for(let u of [...e.keys()])s(u,c=>c.reject(Eu));},get identity(){return n},get gameVersion(){return r}}}var rb=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Ta="embedder_relay_unavailable",ib="embedder_no_relay",ob=new Set([Ta]),Ia=new Set([ib]),Fn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Ea(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new A("match_ended",`the match ended while the offer was in flight (${e.reason??"no reason given"}), so no server is left to answer it`));return}if(e.event==="answer"){if(typeof e.sdp!="string"||e.sdp.length===0){n.refuse(new A("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(ab(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new A("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,n);}release(e,n){this.pending.get(e)===n&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new A("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new A("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function ab(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new A(sb(t),r,{platformCode:t})}function sb(t){return t===void 0||ob.has(t)?"signaling_failed":Ia.has(t)?"offer_refused":rb.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Ea=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new A("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return n?.aborted?Promise.reject(new A("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new A("aborted","the caller aborted the signaling exchange"));},a=()=>{n?.removeEventListener("abort",s),this.hub.release(e.matchId,l),this.teardown===a&&(this.teardown=null);},l={settle:d=>{a(),i(d);},refuse:d=>{a(),o(d);}};this.teardown=a,n?.addEventListener("abort",s),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof A?d:new A("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var Iu="match_ended:",Cu="server_shutdown:",Mu="kicked:",lb=123;function db(t){if(typeof t!="string"||t.length===0||t.length>lb)return {kind:"other"};if(t.startsWith(Iu)){let e=Xe(t.slice(Iu.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Cu)?{kind:"server_shutdown",cause:t.slice(Cu.length)}:t.startsWith(Mu)?{kind:"kicked",detail:t.slice(Mu.length)}:{kind:"other"}}function Ca(t,e,n){let r=db(n),i=r.kind==="kicked"?"kicked":"link_closed";t.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&t.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function Ma(){return {exchange(){return Promise.reject(new A("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See docs/dedicated-server-flow.md \xA72."))},close(){}}}var cb=3e3,ub=1e4,mb=15e3;async function vi(t){let e=t.peerConnection;try{Gu(t,"before the handshake started"),Oa(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let s of t.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});t.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await fb(e,t),Oa(t);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new A("invalid_sdp","the offer carried no SDP");Be(i,"offer"),Ou(i,"offer");let o=await gb(t,i);if(Oa(t),typeof o?.sdp!="string")throw new A("invalid_sdp","the signaling channel answered without an SDP");return Be(o.sdp,"answer"),Ou(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await yb(n,t),Gu(t,"before the channel opened"),n}catch(n){throw e.close(),pb(n)}}function pb(t){return t instanceof A?t:$u(t)?pt():new A("connection_failed",Fu(t),{cause:t})}function Ou(t,e){if(li(t))throw new A("media_refused",`the ${e} carries an active audio or video section. This path carries a data channel only; voice belongs to the platform voice service.`)}async function gb(t,e){let n=t.exchangeTimeoutMs??ub,r=Du(t,n),i=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(o=>{throw o instanceof A?o:$u(o)?pt():new A("signaling_failed",Fu(o),{cause:o})});return hb(i,t,r,()=>r.exhausted?Ga("while the offer was in flight"):new A("timeout",`no answer arrived within ${n}ms`))}function fb(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let i=()=>{n.clearTimeout(s),t.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{t.iceGatheringState==="complete"&&i();},s=n.setTimeout(i,e.gatherTimeoutMs??cb);t.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function yb(t,e){if(e.signal?.aborted)return Promise.reject(pt());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new A("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??mb,i=Du(e,r);return new Promise((o,s)=>{let a=()=>{n.clearTimeout(g),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",u);},l=()=>{a(),o();},d=p=>{a(),s(new A("connection_failed","the data channel failed before it opened",Lu(p)===void 0?void 0:{cause:Lu(p)}));},u=()=>{a(),s(pt());},c=()=>{a(),s(i.exhausted?Ga("while the channel was still opening"):new A("timeout",`the data channel did not open within ${r}ms`));},g=n.setTimeout(c,i.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",u);})}function Du(t,e){if(t.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let n=t.credentialExpiresAt-t.clock.now();return n<=e?{ms:Math.max(0,n),exhausted:true}:{ms:e,exhausted:false}}function hb(t,e,n,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(pt()):new Promise((s,a)=>{let l=c=>{i.clearTimeout(u),o?.removeEventListener("abort",d),c();},d=()=>l(()=>a(pt())),u=i.setTimeout(()=>l(()=>a(r())),n.ms);o?.addEventListener("abort",d),t.then(c=>l(()=>s(c)),c=>l(()=>a(c)));})}function Gu(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw Ga(`already ${e}`)}function Ga(t){return new A("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function Oa(t){if(t.signal?.aborted)throw pt()}function pt(){return new A("aborted","the caller aborted the connection attempt")}function $u(t){return t?.name==="AbortError"}function Lu(t){return t?.error}function Fu(t){return t instanceof Error?t.message:String(t)}Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"}));Object.freeze(Object.assign(Object.create(null),{answer:[J("sdp","sdp",K(10240)),z("sessionId","session_id",K(64))],error:[z("code","code",K(64)),z("message","message",K(256))],matchEnded:[z("reason","reason",K(64))]}));function Vu(t){let{client:e,clock:n,rooms:r}=t,i=t.signaling??Ma,o=t.log??(h=>console.warn(h)),s=new Dt({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(h,_)=>{let I=a.get(h)??new Set;I.add(_),a.set(h,I);},d=(h,_)=>{let I=a.get(h);I!==void 0&&(I.delete(_),I.size===0&&a.delete(h));},u=async h=>{if(r.isHost&&!Da(r)&&r.currentRoom?.matchId===void 0){let _=Se(h.clusterTargetId);await r.startMatch({..._===void 0?{}:{clusterTargetId:_},...h.retry===void 0?{}:{retry:h.retry},...h.signal===void 0?{}:{signal:h.signal}});}return Wu(r.matchConnectionState==="suspended"?await r.reconnectToMatch(La(h)):await r.awaitMatch(La(h)))},c=async h=>Wu(await r.pollMatchStatus(La(h))),g=async(h,_)=>{let I=false;try{let T=await u(h),W=r.currentRoom?.transports;if(W!==void 0&&!W.includes("webrtc"))throw new A("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 j=h.peerConnection??Hu();I=!0;let U=await vi({peerConnection:j,signaling:_,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,..._i(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),C=null;if(h.presentCredential!==!1)try{C=await bn({channel:U,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,..._i(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(L){throw Ce(U),Ce(j),L}return xb(r,T,U,j,_,h.reportDisconnect!==!1,h.reportConnected!==!1,C,{remember:l,forget:d},h.onMatchEnded)}catch(T){throw I&&Uu(s,T),Ce(_),T}},p=async(h,_,I,T,W,j)=>{if(h==="webtransport"){let x=T?.webtransport;if(x===void 0)throw new A("misconfigured","webtransport is not advertised");let G={credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n};if(typeof x.named_url=="string"&&x.named_url!==""){let ne=Math.max(Math.floor(j/2),1e3);try{return await Sn({url:x.named_url,timeoutMs:ne,log:o,...G})}catch(fe){if(ei()!==null)throw fe;return o(`[gem] webtransport named dial failed (${Qr(fe)}); retrying the pinned dial`),Sn({url:x.url,certHashBase64:x.cert_sha256_b64,timeoutMs:ne,log:o,...G})}}return Sn({url:x.url,certHashBase64:x.cert_sha256_b64,timeoutMs:j,...G})}if(h==="websocket"){let x=T?.websocket;if(x===void 0)throw new A("misconfigured","websocket is not advertised");return Ho({url:x.url,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n,timeoutMs:j})}let U=_.peerConnection??Hu(),C,L=await vi({peerConnection:U,signaling:W,clock:n,matchId:I.matchId,credentialExpiresAt:I.credentialExpiresAt,extraChannels:[{label:_n,ordered:false,maxRetransmits:0}],onExtraChannel:(x,G)=>{x===_n&&(C=G);},..._i(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),..._.exchangeTimeoutMs===void 0&&_.redial===true?{exchangeTimeoutMs:_b}:{}}),D;try{D=await bn({channel:L,clock:n,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,wire:Yr,heartbeat:!0,..._i(_,"signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(x){throw Ce(L),Ce(U),x}let H=D.welcome.heartbeatIntervalMs;return {link:Ko(L,U,C,H===void 0?void 0:{clock:n,intervalMs:H}),welcome:D.welcome,channel:L,peerConnection:U}},f=(h,_,I,T,W)=>{let j=false,U;T.link.onClose(H=>{!j&&h.reportDisconnect!==false&&Ca(r,_.matchId,H),U?.(H);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(_.matchId);let C={transport:T.link.transport,send:(H,x)=>T.link.send(H,x),onMessage:H=>T.link.onMessage(H),onClose:H=>{U=H;},close:()=>T.link.close()},L=()=>{j||(j=true,Ce(T.link),Ce(W));},D=H=>{if(!j){try{h.onMatchEnded?.(H);}catch{}L();}};return l(_.matchId,D),{matchId:_.matchId,transport:I,link:C,joinCredential:_.joinCredential,credentialExpiresAt:_.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(_.matchId,D),L();}}},y=async(h,_)=>{let I=r.currentRoom?.id,T=r.gameId,W=()=>({advert:wn(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(I===void 0||T===null)return W();try{let j=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(I)}`,_);return {advert:wn(j.settings,h),template:Gt(j.transports)??r.currentRoom?.transports??null}}catch{return W()}},S=(h,_)=>{let I=h??qu;return _.length===0?I:I.filter(T=>_.includes(T))},v=async(h,_,I)=>{try{let T=await u(h),{advert:W,template:j}=await y(T.matchId,h.signal),U=S(j,_),C=U.filter(Q=>Rb(Q,W)),L=ei();if(L!==null&&U.includes("webtransport")&&W?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${L} (learned on an earlier dial in this page)`),C.length===0){let Q=j===null?`the default order (${qu.join(", ")})`:`the room template's transports (${j.join(", ")||"none"})`;throw new A("misconfigured",`none of ${Q}`+(_.length>0?`, narrowed to (${_.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let D=h.transportAttemptTimeoutMs??vb,H=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-n.now(),x=Q=>t.signalingReady===void 0||Q<=0?Promise.resolve(!0):t.signalingReady(Q),G=[],ne=[];for(let Q of C){if(H()<ju){o(`[gem] ${Q} rung not tried: the reconnect budget is spent`);break}ne.length>0&&T.credentialExpiresAt-n.now()<Bu&&(T=await c(h)),ne.push(Q);let Pe=!1,we=!1,Me={attempts:0,waitedMs:0};for(;;){if(Q==="webrtc"&&h.redial===!0){let te=Math.min(Nu,H());await x(te)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(te)}ms; offering anyway`);}let ke=Math.max(Math.min(D,H()),ju);try{return f(h,T,Q,await p(Q,h,T,W,I,ke),I)}catch(te){let X=te instanceof A?te:new A("connection_failed",te instanceof Error?te.message:String(te),{cause:te});if(Q==="webrtc"&&Uu(s,X),(X.reason==="credential_expired"||X.reason==="credential_reused")&&!Pe){Pe=!0,T=await c(h);continue}if(Q==="webrtc"&&X.reason==="signaling_failed"&&X.platformCode===Ta&&!we){we=!0;let ae=Math.min(Nu,H());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ae)}ms for the socket before offering again`),await x(ae))continue}if(X.reason==="join_rate_limited"){let ae=Sb(Me,Math.random,H());if(ae!==null){if(Me.attempts+=1,Me.waitedMs+=ae,o(`[gem] ${Q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ae)}ms before presenting again (retry ${Me.attempts} of ${Ju.maxAttempts})`),await Kr(n,ae,h.signal),h.signal?.aborted)throw new A("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<Bu&&(T=await c(h));continue}}if(wb.has(X.reason)||X.reason==="credential_expired"||Q==="webrtc"&&Ku(X)){o(`[gem] ${Q} rung failed (${X.reason}): ${Qr(X.cause??X)} \u2014 `+(ne.length<C.length?`falling through to ${C[ne.length]}`:"no rungs left")),G.push(X);break}throw o(`[gem] ${Q} rung refused the session (${X.reason}): ${X.message}`),X}}}let fe=G[G.length-1];throw fe===void 0?new A("timeout",`the reconnect budget ran out before any transport (${C.join(", ")}) could be tried`):new A(fe.reason,`every transport tried (${ne.join(", ")}) failed; the last said: ${fe.message}`,{cause:G,platformCode:fe.platformCode})}catch(T){throw Ce(I),T}};return {listClusterTargets:async(h={})=>Io({client:e,...h}),handleMatchEnded(h,_){let I=a.get(h);if(I!==void 0){a.delete(h);for(let T of I)T(_);}},connect:(async(h={})=>{let _=h.signaling??i();return h.transports===void 0?g(h,_):v(h,h.transports,_)})}}var qu=["webtransport","webrtc","websocket"],vb=1e4,_b=5e3,Nu=3e3,ju=1e3,Bu=1e4,wb=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Ku(t){return t.platformCode!==void 0&&Ia.has(t.platformCode)}var Ju={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Sb(t,e=Math.random,n=1/0){let r=Ju;if(t.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-t.waitedMs,n);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**t.attempts;return Math.min(o+e()*r.jitterMs,i)}function Rb(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Zr():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||kb(e.websocket.url)}function kb(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return Ke(e)}function La(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var Ab=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Uu(t,e){e instanceof A&&(!Ab.has(e.reason)&&!Ku(e)||t.report([{type:"connection_failures_total",value:1}]));}function xb(t,e,n,r,i,o,s,a,l,d){let u=false,c=()=>{u||Ca(t,e.matchId,void 0);};o&&(n.addEventListener("close",c),s&&t.notifyMatchConnected(e.matchId));let g=()=>{u||(u=true,n.removeEventListener("close",c),a?.detach(),Ce(n),Ce(r),Ce(i));},p=f=>{if(!u){try{d?.(f);}catch{}g();}};return l.remember(e.matchId,p),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,p),g();}}}function Da(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Wu(t){if(t.status==="failed")throw new A("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new A("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==Vr)throw new A("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Vr}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:n}=t;if(e===void 0||n===void 0)throw new A("connection_failed",`match ${t.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...t,joinCredential:e,credentialExpiresAt:n}}function Hu(){let t=globalThis.RTCPeerConnection;if(!t)throw new A("misconfigured","this environment has no RTCPeerConnection. Pass `peerConnection` to connect against a stand-in, which is how the flow is tested outside a browser.");return new t({iceServers:[]})}function Ce(t){try{t.close();}catch{}}function _i(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var Pb=1e4;function zu(t,e){return $a(t,e)}function $a(t,e){if(typeof t.serverToken!="function"||typeof t.onServerToken!="function")throw new Error("this runtime delivers no game-server token: host.serverToken/onServerToken are missing. The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let n=s=>({token:s.token,expiresAt:s.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,i=new kt({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??Pb);r={resolve:d=>{e.clock.clearTimeout(l),s(d);},reject:a,timer:l};})}),o=t.onServerToken(s=>{let a=n(s),l=r;if(l){r=null,l.resolve(a);return}i.accept(a);});return {source:i,dispose(){o(),i.dispose(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var qa={};Cp(qa,{acceptTransfer:()=>Eb,addEntityProgression:()=>Tb,adminAction:()=>Ib,cancelInventoryTransfer:()=>Cb,claimEntityProgressionRewards:()=>Mb,closeGameRoom:()=>Ob,createEntityBatchOrder:()=>Gb,createEntityOrder:()=>Lb,createSession:()=>Db,deleteEntityGameSetting:()=>$b,deleteEntitySave:()=>Fb,deleteSession:()=>qb,deleteShowcaseValue:()=>Nb,executeEntityRecipe:()=>jb,finalizeSaveUpload:()=>Bb,getChannelAssignment:()=>Ub,getDropRates:()=>Wb,getEntityCurrency:()=>Hb,getEntityGameSetting:()=>Vb,getEntityInventory:()=>Kb,getEntityInventoryItem:()=>Jb,getEntityLeaderboard:()=>zb,getEntityOrder:()=>Xb,getEntityProgression:()=>Yb,getEntityRecipeAvailability:()=>Qb,getEntityRecipeUsage:()=>Zb,getEntitySave:()=>ev,getEvent:()=>tv,getGameRoomV2:()=>nv,getLeaderboard:()=>rv,getPlayerGameProfile:()=>iv,getPurchaseCatalog:()=>ov,getResolvedTemplate:()=>av,getRoomArgs:()=>sv,getShowcaseValue:()=>lv,getTransferDetails:()=>dv,ingestAnalyticsEvents:()=>Fa,initiateInventoryTransfer:()=>cv,invokeFunction:()=>uv,kickPlayer:()=>mv,listChallenges:()=>pv,listEntityGameSettings:()=>gv,listEntityOrders:()=>fv,listEntityProgressions:()=>yv,listEntitySaves:()=>hv,listEvents:()=>bv,listGameRooms:()=>vv,listResolvedTemplates:()=>_v,listTransfers:()=>wv,maxEntityProgression:()=>Sv,putEntityGameSetting:()=>Rv,putRoomArgs:()=>kv,putShowcaseValue:()=>Av,rejectTransfer:()=>xv,reportMatchPlayers:()=>Pv,requestSaveUploadUrl:()=>Ev,resetEntityProgression:()=>Tv,setMatchBackfill:()=>Iv,simulateEntityOrder:()=>Cv,transferHostV2:()=>Mv,updateGameRoomV2:()=>Ov});function w(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function Eb(t,e,n){let r=`/v1/inventory/transfers/${w(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Tb(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}/add`;return t.client.post(s,i,o?.signal)}async function Ib(t,e,n,r){let i=`/v1/voice/sessions/${w(e)}/admin`;return t.client.post(i,n,r?.signal)}async function Cb(t,e,n){let r=`/v1/inventory/transfers/${w(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Mb(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}/claim`;return t.client.post(s,i,o?.signal)}async function Ob(t,e,n){let r=`/v1/games/${w(t.gameId())}/game-rooms/${w(e)}`;return t.client.delete(r,n?.signal)}async function Gb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Lb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Db(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function $b(t,e,n,r,i){let o=`/v1/settings/${w(e)}/${w(n)}/${w(r)}`;return t.client.delete(o,i?.signal)}async function Fb(t,e,n,r,i){let o=`/v1/saves/${w(e)}/${w(n)}/${w(r)}`;return t.client.delete(o,i?.signal)}async function qb(t,e,n){let r=`/v1/voice/sessions/${w(e)}`;return t.client.delete(r,n?.signal)}async function Nb(t,e,n,r){let i=`/v1/showcase/players/${w(e)}/${w(n)}`;return t.client.delete(i,r?.signal)}async function jb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Bb(t,e,n,r,i,o){let s=`/v1/saves/${w(e)}/${w(n)}/${w(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function Ub(t,e,n){let r=`/v1/games/${w(t.gameId())}/config/channels/${w(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Wb(t,e,n){let r=`/v1/inventory/loot-tables/${w(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Hb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/currencies/${w(r)}`;return t.client.get(o,i?.signal)}async function Vb(t,e,n,r,i){let o=`/v1/settings/${w(e)}/${w(n)}/${w(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Kb(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${w(e)}/${w(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Jb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/items/${w(r)}`;return t.client.get(o,i?.signal)}async function zb(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${w(e)}/${w(n)}/${w(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function Xb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/orders/${w(r)}`;return t.client.get(o,i?.signal)}async function Yb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}`;return t.client.get(o,i?.signal)}async function Qb(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/catalogs/${w(r)}/recipes/${w(i)}/availability`;return t.client.get(s,o?.signal)}async function Zb(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${w(e)}/${w(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function ev(t,e,n,r,i){let o=`/v1/saves/${w(e)}/${w(n)}/${w(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function tv(t,e,n){let r=`/v1/events/${w(e)}`;return t.client.get(r,n?.signal)}async function nv(t,e,n){let r=`/v2/games/${w(t.gameId())}/game-rooms/${w(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function rv(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${w(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function iv(t,e,n){let r=`/v1/profiles/players/${w(e)}`;return t.client.get(r,n?.signal)}async function ov(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function av(t,e,n){let r=`/v1/game-room-templates/${w(e)}`;return t.client.get(r,n?.signal)}async function sv(t,e,n){let r=`/v1/games/${w(t.gameId())}/game-rooms/${w(e)}/room-args`;return t.client.get(r,n?.signal)}async function lv(t,e,n,r){let i=`/v1/showcase/players/${w(e)}/${w(n)}`;return t.client.get(i,r?.signal)}async function dv(t,e,n){let r=`/v1/inventory/transfers/${w(e)}`;return t.client.get(r,n?.signal)}async function Fa(t,e,n){let r=`/v1/games/${w(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function cv(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function uv(t,e,n){let r=new URLSearchParams;n?.cue_id!==void 0&&r.set("cue_id",String(n?.cue_id));let i=r.toString(),o="/v1/functions/invoke"+(i?`?${i}`:"");return t.client.postBytes(o,e,n?.signal)}async function mv(t,e,n,r){let i=`/v1/games/${w(t.gameId())}/game-rooms/${w(e)}/kick/${w(n)}`;return t.client.post(i,void 0,r?.signal)}async function pv(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function gv(t,e,n,r){let i=`/v1/settings/${w(e)}/${w(n)}`;return t.client.get(i,r?.signal)}async function fv(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${w(e)}/${w(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function yv(t,e,n,r){let i=`/v1/inventory/${w(e)}/${w(n)}/progressions`;return t.client.get(i,r?.signal)}async function hv(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${w(e)}/${w(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function bv(t,e){let n=new URLSearchParams;e?.include_inactive!==void 0&&n.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.offset!==void 0&&n.set("offset",String(e?.offset));let r=n.toString(),i="/v1/events"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function vv(t,e){let n=new URLSearchParams;e?.status!==void 0&&n.set("status",String(e?.status)),e?.game_channel!==void 0&&n.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&n.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&n.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&n.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),i=`/v1/games/${w(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function _v(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function wv(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Sv(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}/max`;return t.client.post(s,i,o?.signal)}async function Rv(t,e,n,r,i,o){let s=`/v1/settings/${w(e)}/${w(n)}/${w(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function kv(t,e,n,r){let i=`/v1/games/${w(t.gameId())}/game-rooms/${w(e)}/room-args`;return t.client.put(i,n,r?.signal)}async function Av(t,e,n,r,i){let o=`/v1/showcase/players/${w(e)}/${w(n)}`;return t.client.put(o,r,i?.signal)}async function xv(t,e,n){let r=`/v1/inventory/transfers/${w(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Pv(t,e,n,r){let i=`/v1/games/${w(t.gameId())}/matches/${w(e)}/players/report`;return t.client.post(i,n,r?.signal)}async function Ev(t,e,n,r,i,o){let s=`/v1/saves/${w(e)}/${w(n)}/${w(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function Tv(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}/reset`;return t.client.post(s,i,o?.signal)}async function Iv(t,e,n,r){let i=`/v1/games/${w(t.gameId())}/matches/${w(e)}/backfill`;return t.client.put(i,n,r?.signal)}async function Cv(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/orders/simulate`;return t.client.post(o,r,i?.signal)}async function Mv(t,e,n,r){let i=`/v2/games/${w(t.gameId())}/game-rooms/${w(e)}/transfer/${w(n)}`;return t.client.post(i,void 0,r?.signal)}async function Ov(t,e,n,r){let i=`/v2/games/${w(t.gameId())}/game-rooms/${w(e)}`;return t.client.patch(i,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Gv=1e4,Lv=50,Dv=1e3,$v=65536-4*1024,Xu=t=>typeof t=="number"?t:0,Fv=t=>typeof t=="string"?t:"";function Yu(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.floor(Math.random()*16);return (e==="x"?n:n&3|8).toString(16)})}function qv(t){return t?.retryable===true}function Nv(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:Xu(o.index),code:Fv(o.code)}}):[];return {accepted:Xu(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Qu(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,player_id:t.playerId,dimensions:t.dimensions,measures:t.measures}}function Zu(t){let e=Math.max(1,Math.floor(t.maxQueue??Dv)),n={client:t.client,gameId:()=>t.gameId},r=[],i=0,o=null,s=false,a=null,l=0,d=0,u=false,c=false,g=h=>{t.log?.(h);},p=()=>{o!==null&&(t.clock.clearTimeout(o),o=null);},f=()=>Math.max(0,d-t.clock.now()),y=()=>{o!==null||s||a!==null||(o=t.clock.setTimeout(()=>{o=null,v().catch(()=>{});},Math.max(Gv,f())));},S=()=>{let h=Math.min(r.length,100),_=128;for(let I=0;I<h;I+=1){let T=r[I];if(T===void 0)break;if(_+=JSON.stringify(Qu(T,0)).length+1,_>$v)return Math.max(1,I)}return h};async function v(h){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let _=R(h);a=_;try{return await _}finally{a===_&&(a=null),r.length>0&&y();}}async function R(h){p();let _=r.splice(0,S()),I=i;i=0;let T=Math.round(t.clock.now()),W={batch_id:Yu(),sent_at_ms:T,events:_.map(j=>Qu(j,T))};try{let j=await Fa(n,W,h===void 0?void 0:{signal:h}),U=Nv(j,I);l=0,d=0;for(let C of U.rejected)g(`[gem] analytics: an event was refused (${C.code}). See the analytics_events section of your game config.`);return U}catch(j){if(qv(j)){for(r=[..._,...r],i+=I;r.length>e;)r.shift(),i+=1;l+=1,d=t.clock.now()+Ur(l,j);}else g(`[gem] analytics: ${_.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(j)}`);throw j}}return {track(h,_,I={}){if(s)return;if(typeof h!="string"||h===""){c||(c=true,g(`[gem] analytics: '${_}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(_.startsWith(vo)){u||(u=true,g(`[gem] analytics: '${_}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let T={},W={};for(let[j,U]of Object.entries(I))typeof U=="string"?T[j]=U:typeof U=="number"&&Number.isFinite(U)&&(W[j]=U);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:Yu(),playerId:h,name:_,atMs:t.clock.now(),dimensions:T,measures:W}),r.length>=Lv&&a===null&&f()===0?v().catch(()=>{}):y();},flush:h=>v(h),get pending(){return r.length},dispose(){s=true,p(),r=[],i=0;}}}function em(t){return {async list(e){let{playerId:n,periodsBack:r,signal:i}=e??{};if(typeof n!="string"||n==="")throw new TypeError("gem.challenges.list needs { playerId }: a game-server token names no player, so the platform cannot tell whose period you mean. Pass the id from join() or gem.players().");It(r);let o=await t({player_id:n,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return Dr(o)}}}function jv(t){let e={};for(let[n,r]of Object.entries(qa))if(typeof r=="function"){let i=r;e[n]=(...o)=>i(t,...o);}return e}function Ut(t,e={}){let n=e.clock??ce,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let i=$a(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=Ar({baseUrl:r,tokenSource:i.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new He({transport:o,clock:n}),a={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=jv({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,u=t.endMatch,c=t.log,g=Zu({client:s,clock:n,gameId:a.gameId,...typeof c=="function"?{log:f=>c.call(t,f)}:{}});return {identity:a,client:s,api:l,match:{end:async()=>{if(u===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await u.call(t);},setBackfill:async(f,y)=>{let S=await l.setMatchBackfill(a.matchId,{open:f.open,...f.seats===void 0?{}:{seats:f.seats}},y===void 0?{}:{signal:y});return {open:S.open,seats:S.seats??null}},reportPlayers:async(f,y)=>(await l.reportMatchPlayers(a.matchId,{players:f.map(v=>({player_id:v.playerId,state:v.state}))},y===void 0?{}:{signal:y})).players.map(v=>({playerId:v.player_id,outcome:v.outcome}))},analytics:g,functions:new ze(l.invokeFunction),challenges:em(l.listChallenges),...d===void 0?{}:{room:{get:f=>l.getGameRoomV2(d,f),args:async f=>{let y=await l.getGameRoomV2(d,f?.signal===void 0?{}:{signal:f.signal}),S=y.modified?y.body:void 0;if(S?.room_args==null||S.room_args_template==null)throw new O("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:S.room_args,room_args_template:S.room_args_template}}}},dispose:()=>{g.dispose(),i.dispose();}}}function gt(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function Wt(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function qn(t){return typeof t=="string"?t:t.slice().buffer}function wi(t){if(typeof t=="string")return {data:t,isText:true};if(t instanceof ArrayBuffer)return {data:new Uint8Array(t),isText:false};if(ArrayBuffer.isView(t)){let e=t;return {data:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),isText:false}}return null}var Bv=5e3,tm=3e4,nm=2e3,Uv=1e4,Wv=3,rm=1;async function im(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let i=e.log===void 0?b=>console.info(b):e.log,o=b=>i?.(`[gem host] ${b}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,u=(b,M)=>{l&&(a=a.then(async()=>{if(!d)try{await M();}catch(q){o(`the bundle's ${b} handler threw: ${ft(q)}. Serving continues.`);}}));},c=true,g,p,f,y=b=>{if(!c)return;c=false,u("leave",()=>s.leave?.(r,{cause:b??"left"}));let M=p;M&&queueMicrotask(()=>M(b));},S={send(b,M){if(!c)return;let q=Wt(gt(M));u("message",()=>s.message?.(r,b,typeof b=="string",{reliable:q.reliable,ordered:q.ordered}));},onMessage(b){g=b;},onClose(b){p=b;},close(){y("closed");}},v=(b,M)=>{if(!c)return;let q=Wt(gt(M));queueMicrotask(()=>{c&&g?.(b,q);});},R=new Map,h=b=>{let M=[];for(let q of Ue){let Z=b.channels[q];try{Z.binaryType="arraybuffer";}catch{}let ye=Wt(q),zn=Kt=>{let tt=wi(Kt?.data);tt!==null&&u("message",()=>s.message?.(b.playerId,tt.data,tt.isText,{reliable:ye.reliable,ordered:ye.ordered}));};Z.addEventListener("message",zn),M.push(()=>Z.removeEventListener("message",zn));}R.get(b.playerId)?.forEach(q=>q()),R.set(b.playerId,M);},_=b=>{R.get(b)?.forEach(M=>M()),R.delete(b);},I=new Set,T=new Map,W=(b,M,q)=>({playerNumber:b.assignedPeerId,transport:"webrtc_p2p",...M?{rejoin:true}:{},...q?{superseded:true}:{}}),j=b=>{let M=R.has(b.playerId),q=I.has(b.playerId);I.add(b.playerId),h(b),M&&u("leave",()=>s.leave?.(b.playerId,{cause:"superseded"})),u("join",()=>s.join?.(b.playerId,W(b,q,M)));},U=new Set,C=(b,M,q)=>{if(b===r){v(M,q);return}let Z=n.peer(b);if(Z===null){let ye=T.get(b);if(ye!==void 0&&e.clock.now()-ye<nm)return;U.has(b)||(U.add(b),o(`send to '${b}' dropped: no such connected player`));return}Z.send(qn(M),gt(q));},L={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:b=>e.tokens.subscribe(b),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(b=>b.playerId)??[],players(){let b=c?[r]:[];for(let M of n.peers)b.push(M.playerId);return b},profile(b){let M=e.room()?.members.find(q=>q.playerId===b);if(!(!M||M.displayName===void 0))return {displayName:ot.toPlain(M.displayName),...M.displayTag===void 0?{}:{displayTag:ot.toPlain(M.displayTag)},...M.discriminator===void 0?{}:{discriminator:M.discriminator}}},playerNumber(b){return b===r?rm:n.peer(b)?.assignedPeerId},send(b,M,q){C(b,M,q);},broadcast(b,M){let q=M?.except;c&&r!==q&&v(b,M);for(let Z of n.peers)Z.playerId!==q&&Z.send(qn(b),gt(M));},async endMatch(){let b=await ke();return b.answer!=="ok"&&o(b.cause),b.answer},kick(b,M){if(b===r){y(M??"kicked");return}n.kick(b).catch(q=>{o(`kick of '${b}' failed: ${ft(q)}`);});},log(b){o(b);},warn(b){o(`\u26A0 ${b}`);}},D=()=>{},H=new Promise(b=>{D=b;}),x=[],G=null,ne=async(b,M)=>{l=false;let q=a.then(async()=>{try{await s.shutdown(b);}catch(Z){o(`the bundle's shutdown threw: ${ft(Z)}`);}});a=q,await q,We();for(let Z of x.splice(0))Z();for(let Z of [...R.keys()])_(Z);y(M);},fe=(b,M)=>G||(G=(async()=>{await ne(M,b),n.close(),D();})(),G),Q=()=>G||(G=(async()=>{await ne({reason:"signal"},"left"),await n.leave().catch(b=>o(`leaving the match failed: ${ft(b)}`)),D();})(),G),Pe=()=>G||(G=(async()=>{l=false;let b=await ke();b.answer==="ok"?(await ne({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(o(`${b.cause}; leaving instead`),await ne({reason:"signal"},"left"),await n.leave().catch(M=>o(`leaving the match failed: ${ft(M)}`))),D();})(),G),we=null,Me=()=>(we??=Ut(L,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),we),ke=async()=>{try{return await ql({client:Me().client,gameId:()=>L.gameId},L.matchId,{},{signal:AbortSignal.timeout(Bv)}),{answer:"ok"}}catch(b){return b instanceof O&&(b.reason==="forbidden"||b.reason==="not_found")?{answer:b.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${b.reason})`}:{answer:"failed",cause:`ending the match failed: ${ft(b)}`}}},te=null,X=false,ae=0,Oe,Ee=null,We=()=>{X=true,te!==null&&(e.clock.clearTimeout(te),te=null),Ee?.(),Ee=null;},bt=b=>{o(`heartbeats paused: ${b}; they resume when a fresh play token arrives`),vt();let M=Oe,q=false,Z=e.tokens.subscribe(ye=>{q||X||ye.token===M||et(ye)||(q=true,Ee?.(),Ee=null,ae=0,Oe=void 0,vt(),o("a fresh play token arrived; heartbeats resume"),te=e.clock.setTimeout(()=>{_t();},0));});q?Z():Ee=Z;},vt=()=>{let b=we;we=null,b?.dispose();},et=b=>b.expiresAt*1e3<=e.clock.now(),_t=async()=>{if(te=null,!X){try{await Me().client.post(`/v1/games/${encodeURIComponent(L.gameId)}/matches/${encodeURIComponent(L.matchId)}/heartbeat`,void 0,AbortSignal.timeout(Uv)),ae=0,Oe=void 0;}catch(b){if(b instanceof O&&(b.reason==="forbidden"||b.reason==="not_found")){o(`the platform no longer holds this match under this host (${b.reason}); heartbeats stop`),We();return}if(Hv(b)){if(X)return;ae+=1;let M=e.tokens.current(),q=M===void 0?"this host holds no play token":et(M)?"this host's play token has expired":M.token===Oe?"the platform refused this host's play token again":ae>=Wv?`the platform refused this host's play token ${ae} times in a row`:null;if(Oe=M?.token,q!==null){bt(q);return}}else ae=0,Oe=void 0;o(`heartbeat failed: ${ft(b)}`);}X||(te=e.clock.setTimeout(()=>{_t();},tm));}},Jn=()=>{X||te!==null||(te=e.clock.setTimeout(()=>{_t();},tm));};{let b=D;D=()=>{We(),we?.dispose(),we=null,b();};}let Vt=Promise.resolve().then(()=>s.init(L));a=Vt.then(()=>{},()=>{}),u("join",()=>s.join?.(r,{playerNumber:rm,transport:"loopback"})),x.push(n.on("peerJoined",j)),x.push(n.on("peerLeft",(b,M)=>{_(b);let q=e.clock.now();for(let[Z,ye]of T)q-ye>=nm&&T.delete(Z);T.set(b,q),U.delete(b),u("leave",()=>s.leave?.(b,{cause:M}));})),x.push(n.on("error",b=>{o(`\u26A0 session error: ${b.message}`);})),x.push(n.on("matchEnded",b=>{G||Na(f,b),fe("match ended",{reason:"match_ended",platform_reason:b});})),x.push(n.on("hostChanged",b=>{b!==r&&fe("host migrated",{reason:"host_migrated"});}));for(let b of n.peers)j(b);try{await Vt,Jn();}catch(b){l=false,We(),d=true;for(let M of x.splice(0))M();for(let M of [...R.keys()])_(M);throw n.leave().catch(()=>{}),D(),b}return {matchId:n.matchId,localLink:S,onMatchEnded(b){f=b;},end:Pe,leave:Q,stop:b=>fe(b,{reason:"stopped"}),done:H}}function Na(t,e){try{t?.(e);}catch{}}function Hv(t){return t instanceof O&&t.status===401||re.isAuthError(t)}function ft(t){return t instanceof Error?t.message:String(t)}function ja(t,e){let n=async()=>{throw new A("misconfigured",`this seat is \`${t}\`, not the match's authority: `+(t==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:t,matchId:e,end:n,leave:n,stop:async()=>{}}}function om(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,i=new Map,o=async a=>{r.isHost&&!Da(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!==mt)return ja("dedicated",d.matchId);let u=t.p2p.session?.(d.matchId)??null;if(u===null&&!r.isHost||u!==null&&!u.isHost)return ja("peer",d.matchId);let c=t.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let g=u??await t.p2p.connect(s(l)),p=await im(a,{session:g,clock:t.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:g.playerId!==""?g.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return i.set(d.matchId,p),p.done.then(()=>{i.get(d.matchId)===p&&i.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>p.end(),leave:()=>p.leave(),stop:()=>p.stop()}},async connect(a={}){let l=await o(a),d=a.onMatchEnded;if(l.protocol===mt){let p=i.get(l.matchId);if(p!==void 0)return r.notifyMatchConnected(l.matchId),zv(l.matchId,p,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let f=await En(),y=async()=>t.p2p.connect({...s(a),certificate:f}),S=await y(),v=Yv(S,y,d,R=>{r.notifyMatchDisconnected(R).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(S.matchId,{redial:v.redial,abandon:v.abandon}),v.onClosed(()=>{e.get(S.matchId)?.abandon===v.abandon&&e.delete(S.matchId);})),v}let u=async(p=null)=>await t.dedicated.connect({...p===null?{}:{reportConnected:false,redial:true,...p.deadlineAt===void 0?{}:{deadlineAt:p.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),c=await u(),g=Xv(c,u,r,n);return n&&(e.set(c.matchId,{redial:g.redial,abandon:g.abandon}),g.onClosed(()=>{e.get(c.matchId)?.abandon===g.abandon&&e.delete(c.matchId);})),g},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var am="link_closed",Vv="host_unreachable",Kv=new Set(["failed","closed","relay_deadline","restart_mismatch"]);function Jv(t){return Kv.has(t)?am:Vv}function zv(t,e,n){let r=e.localLink;e.onMatchEnded(n);let i="connected";r.onClose(()=>{i="closed";});let o;return {matchId:t,protocol:"loopback",get state(){return i},send:(s,a)=>r.send(s,a),onMessage:s=>r.onMessage(s),onClose:s=>{o=s,r.onClose(a=>{i="closed",o?.(a);});},close:()=>r.close()}}function Xv(t,e,n,r){let i=t.matchId,o=t,s="connected",a,l,d=[],u=false,c=false,g=f=>{if(s!=="closed"){s="closed";for(let y of d.splice(0))y();l?.(f);}},p=f=>{f.link.onMessage((y,S)=>a?.(y,S)),f.link.onClose(y=>{if(f!==o||s==="closed")return;if(u||!r){g(y);return}let S=n.matchSession;if(S.phase==="suspended"&&S.matchId===i){s="suspended";return}g(y);});};return p(t),{matchId:i,protocol:"dedicated",get transport(){return o.transport},get state(){return s},send(f,y){s==="connected"&&o.link.send(f,y);},onMessage(f){a=f;},onClose(f){l=f;},close(){if(s!=="closed"){if(u=true,s==="suspended"){g("closed");return}o.close(),g("closed");}},async redial(f){if(s==="closed"||u)return "closed";if(c)return "connected";c=true;let y;try{y=await e(f===void 0?{}:{deadlineAt:f});}finally{c=false;}return u||s==="closed"?(y.close(),"closed"):(o=y,p(y),s="connected",n.notifyMatchConnected(i),"connected")},abandon(f){s!=="closed"&&(s==="connected"&&o.close(),g(f));},onClosed(f){s==="closed"?f():d.push(f);}}}function Yv(t,e,n,r,i,o=false){let s=t.matchId,a=t,l,d,u=[],c=[],g=[],p=false,f=false,y=false,S=false,v="connected",R=C=>{if(p)return;p=true,v="closed";for(let D of u.splice(0))D();for(let D of c.splice(0))D();for(let D of g.splice(0))D();let L=d;L&&queueMicrotask(()=>L(C));},h=C=>{for(let L of u.splice(0))L();for(let L of Ue){let D=C.channels[L];try{D.binaryType="arraybuffer";}catch{}let H=Wt(L),x=G=>{let ne=wi(G?.data);ne!==null&&l?.(ne.data,H);};D.addEventListener("message",x),u.push(()=>D.removeEventListener("message",x));}},_=()=>a.peer(a.hostPlayerId),I=C=>{if(!(p||a.isHost)&&v!=="suspended"){if(r?.(C),o){v="suspended";return}R(C);}},T=C=>{for(let L of Ue){let D=C.channels[L];if(typeof D.addEventListener!="function")continue;let H=()=>{_()===C&&I(am);};D.addEventListener("close",H),u.push(()=>D.removeEventListener?.("close",H));}},W=C=>{h(C),T(C),!p&&(v="connected",i?.());},j=C=>{for(let L of c.splice(0))L();c.push(C.on("migrating",()=>{S=true;})),c.push(C.on("hostChanged",L=>{if(S=false,L===C.playerId){R("host_migrated_here");return}let D=_();D!==null&&W(D);})),c.push(C.on("peerJoined",L=>{L.playerId===C.hostPlayerId&&W(L);})),c.push(C.on("matchEnded",L=>{p||Na(n,L),R(L);})),c.push(C.on("peerLeft",(L,D)=>{L===C.hostPlayerId&&I(Jv(D));}));};j(a);let U=_();return U!==null&&W(U),{matchId:s,protocol:"p2p",get state(){return v},send(C,L){v==="connected"&&_()?.send(qn(C),gt(L));},onMessage(C){l=C;},onClose(C){d=C;},close(){f=true,R("closed"),a.leave().catch(()=>{});},async redial(){if(v==="closed")return "closed";if(v==="connected"||y)return "connected";if(S)throw new N("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");y=true;let C;try{for(let D of u.splice(0))D();for(let D of c.splice(0))D();a.close(),C=await e();}finally{y=false;}if(p)return f?C.leave().catch(()=>{}):C.close(),"closed";a=C,j(a);let L=_();if(L===null)throw a.close(),new N("connection_failed","this peer rejoined the match but the host never answered with a link");return W(L),"connected"},abandon(C){R(C);},onClosed(C){p?C():g.push(C);}}}function sm(t){let e=0,n=new Map;return {resolve(){if(!t.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},s=l=>{n.delete(r)&&(t.clock.clearTimeout(o.timer),i(l));};n.set(r,s),o.timer=t.clock.setTimeout(()=>s(void 0),t.timeoutMs??2e3);let a=false;try{a=t.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){n.get(r)?.(i);}}}var Qv=12e4;function yt(t,e){return {outcome:t,reason:e}}function lm(t){let e=false,n=new Map,r=new Set,i=l=>{for(let d of [...r])try{d(l);}catch(u){t.onListenerError?.(u);}},o=async l=>{try{return await t.confirm(l)}catch{return "unknown"}},s=(l,d,u,c)=>{if(!t.bridge.parentSupports(l))return Promise.resolve(yt("unavailable","error"));if(e)return Promise.resolve(yt("declined","busy"));let g=`purchase-${ge()}`;return new Promise(p=>{let f={},y=v=>{n.delete(g)&&(e=false,t.clock.clearTimeout(f.timer),p(v));};e=true,n.set(g,{finish:y,check:u,label:c}),f.timer=t.clock.setTimeout(()=>y(yt("unavailable","error")),t.timeoutMs??Qv);let S=false;try{S=d(g);}catch{}S||y(yt("unavailable","error"));})},a=l=>l===void 0?null:t.confirm(l);return {api:{request(l){return s("purchases",d=>t.bridge.requestPurchase(d,l.kind,l.targetId,l.currencySlug,l.quantity,l.catalogId),a,d=>`purchase ${JSON.stringify(d)}`)},onSettled(l){return r.add(l),()=>{r.delete(l);}}},handOffRefused(l){s("purchases",d=>t.bridge.requestPurchase(d,l.kind,l.targetId,l.currencySlug,l.quantity,l.catalogId,"direct_refused"),a,d=>`purchase ${JSON.stringify(d)}`).then(d=>{d.outcome!=="ok"||d.purchaseId===void 0||(t.onInventoryStale?.(),i(Object.freeze({kind:l.kind,targetId:l.targetId,...l.catalogId===void 0?{}:{catalogId:l.catalogId},quantity:l.quantity,purchaseId:d.purchaseId})));});},settled(l){if(!t.bridge.parentSupports("purchaseSettled")){t.onDropped?.("gem.purchaseSettled from a parent that did not advertise purchaseSettled; ignored");return}let{purchaseId:d}=l;(async()=>{let u=d===void 0?"unknown":await o(d);if(u==="absent"){t.onDropped?.(`gem.purchaseSettled for purchase ${JSON.stringify(d)}, which the platform has no grant for; ignored`);return}t.onInventoryStale?.(),!(u!=="granted"||d===void 0)&&i(Object.freeze({kind:l.purchaseKind,targetId:l.targetId,...l.catalogId===void 0?{}:{catalogId:l.catalogId},quantity:l.quantity,purchaseId:d}));})();},requestAvatar3d(l){return s("avatar3dPurchases",d=>t.bridge.requestAvatar3dPurchase(d,l.itemId,l.currencySlug),()=>t.confirmAvatar3d(l.itemId),()=>`3D avatar ${JSON.stringify(l.itemId)}`)},settle(l){let d=l.outcome==="ok"||l.outcome==="declined"?l.outcome:"unavailable",u=n.get(l.requestId);if(u===void 0){t.onDropped?.(`gem.purchaseResult (${d}) for an unknown requestId: `+JSON.stringify(l.requestId));return}let{finish:c}=u;if(d!=="ok"){c(yt(d,rd(l.reason)));return}let g=l.purchaseId,p;try{p=u.check(g);}catch{p=Promise.resolve("unknown");}if(p===null){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),c(yt("unavailable","error"));return}(async()=>{let f;try{f=await p;}catch{f="unknown";}if(f==="granted"){c(g===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:g});return}f==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+u.label(g)),c(yt("unavailable","error"));})();}}}async function dm(t,e){try{return (await wl(t,e)).granted?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}var Zv="small_human",cm=/^[a-z][a-z0-9_]{0,31}$/,um=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,e_=8;function Ba(t){if(t===null)return [];if(t.avatars3d!==void 0)return t.avatars3d;let{avatar3dId:e,avatar3dModelUrl:n,avatar3dIconUrl:r}=t;return e===void 0||n===void 0||r===void 0?[]:[{family:Zv,id:e,modelUrl:n,iconUrl:r}]}function t_(t,e){return t.length===e.length&&t.every((n,r)=>{let i=e[r];return n.family===i.family&&n.id===i.id&&n.modelUrl===i.modelUrl})}function n_(t){let e=t??{},n=typeof e.item_id=="string"&&um.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&cm.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=Ct(e.icon_url),l=Ct(e.model_url),d=[];for(let u of Array.isArray(e.prices)?e.prices:[]){let c=u??{};typeof c.currency_slug=="string"&&c.currency_slug!==""&&typeof c.price=="number"&&Number.isSafeInteger(c.price)&&c.price>0&&d.push({currencySlug:c.currency_slug,price:c.price});}if(!(n===void 0||r===void 0||i===void 0||o===void 0||a===void 0||l===void 0||d.length===0))return {itemId:n,slug:i,family:r,displayName:o,...s===void 0?{}:{description:s},iconUrl:a,modelUrl:l,prices:d}}function r_(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&cm.test(n)&&!e.includes(n)&&e.push(n),e.length===e_)break;return e}function mm(t){let e=new Set,n=Ba(t.player()),r=i=>{t.log?.(`[gem] an avatars3d onChange listener threw: ${i instanceof Error?i.message:String(i)}`);};return t.subscribe(i=>{let o=Ba(i);if(!t_(n,o)){n=o;for(let s of [...e])try{s(o);}catch(a){r(a);}}}),{async families(){return r_(await t.configFamilies())},worn(i){let o=Ba(t.player());if(i!==void 0)return o.find(l=>l.family===i);let a=t.player()?.avatar3dId;return (a===void 0?void 0:o.find(l=>l.id===a))??o[0]},async offers(){let i=await t.readOffers(),o=[];for(let s of Array.isArray(i?.offers)?i.offers:[]){let a=n_(s);a!==void 0&&o.push(a);}return o},purchase(i){let o=i?.itemId,s=i?.currencySlug;return typeof o!="string"||!um.test(o)?Promise.resolve({outcome:"declined",reason:"not_purchasable"}):typeof s!="string"||s===""?Promise.resolve({outcome:"declined",reason:"unknown_currency"}):t.purchase({itemId:o,currencySlug:s})},onChange(i){return e.add(i),()=>{e.delete(i);}}}}async function pm(t,e){try{return (await el(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}function gm(t){return gl(t)}var i_=6e5;function fm(t){let e=null,n=new Map;return {api:{requestSignIn(){if(!t.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${ge()}`;return e=new Promise(i=>{let o={},s=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(o.timer),i(l));};n.set(r,s),o.timer=t.clock.setTimeout(()=>{s({outcome:"unavailable"});},t.timeoutMs??i_);let a=false;try{a=t.bridge.requestSignIn(r);}catch{}a||s({outcome:"unavailable"});}),e}},settle(r){let i=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",o=n.get(r.requestId);if(o===void 0){t.onDropped?.(`gem.signInResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}o({outcome:i});}}}var o_=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","invite","_s","fbclid","ttclid","gclid","gbraid","wbraid","msclkid","gem_test_ads","moments","ads"]),a_=["utm_"];function Ua(t){return o_.has(t)||a_.some(e=>t.startsWith(e))}var s_=new Set(["_s","embedder"]),ym="gemEsc_",hm=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Wa=64,Ha=16,Va=512,Ka=Wa-ym.length;function bm(t){return s_.has(t)?"reserved_key":(Ua(t)||t.startsWith(ym))&&t.length>Ka?"round_trip":null}var l_=1e4,d_=/[\p{Cc}\p{Cf}]/u,c_=/\p{Cs}/u,Re="[gem] gem.share.request:",Si=class extends Error{reason;constructor(e,n){super(`${Re} the arcade refused the share: ${e}`+(n===void 0?"":` (param ${JSON.stringify(n)})`)),this.name="ShareRefusal",this.reason=e,n!==void 0&&(this.key=n);}};function vm(t){let e=new Map;return {wait(n){let r=()=>{};return {answer:new Promise(o=>{let s={};r=a=>{e.delete(n)&&("timer"in s&&t.clearTimeout(s.timer),o(a));},e.set(n,r),s.timer=t.setTimeout(()=>r(null),l_);}),cancel:()=>r(null)}},settle(n){let r=e.get(n.requestId);return r===void 0?false:(r(n),true)},abandon(){for(let n of [...e.values()])n(null);}}}function _m(t){let{frame:e,log:n,answers:r}=t,i=false,o=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,s=a=>{n!==null&&(n===void 0?console.warn(a):n(a));};return {get available(){return o()!==null},request(a){let l=o();if(l===null)throw new Error(`${Re} the arcade does not handle share here \u2014 check gem.share.available first`);if(a!==void 0&&(typeof a!="object"||a===null))throw new TypeError(`${Re} pass { params }, or nothing`);let d=a?.params===void 0?{}:a.params;if(!u_(d))throw new TypeError(`${Re} params must be a plain object of string values`);let u=Object.entries(d);if(u.length>Ha)throw new TypeError(`${Re} at most ${Ha} params; got ${u.length}`);let c=l.parentSupports("shareRemap"),g=[];for(let[y,S]of u){let v=JSON.stringify(y);if(!hm.test(y))throw new TypeError(`${Re} param ${v}: a key is a letter followed by up to ${Wa-1} letters, digits, _ or -`);let R=c?bm(y):Ua(y)?"reserved_key":null;if(R==="reserved_key")throw new TypeError(c?`${Re} param ${v} is reserved: the arcade never carries it in a share link`:`${Re} param ${v} is reserved: this arcade reads it itself and never forwards it`);if(R==="round_trip")throw new TypeError(`${Re} param ${v}: a reserved key is carried escaped, and this one is too long to stay a valid key \u2014 keep it to ${Ka} characters`);if(typeof S!="string")throw new TypeError(`${Re} param ${v}: values must be strings`);if(S.length>Va)throw new TypeError(`${Re} param ${v}: a value is at most ${Va} characters`);if(d_.test(S))throw new TypeError(`${Re} param ${v}: control and format characters are not allowed`);if(c_.test(S))throw new TypeError(`${Re} param ${v}: a value must be well-formed text`);g.push({key:y,value:S});}let p=l.parentSupports("shareResult")?`share-${ge()}`:void 0,f=p===void 0?null:r.wait(p);return l.requestShare(g,p)?f===null?Promise.resolve():f.answer.then(y=>{if(y?.outcome==="refused")throw new Si(y.reason??"error",y.key)}):(f?.cancel(),i||(i=true,s("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop.")),Promise.resolve())}}}function u_(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Nn=3e4,Ja=12e4;function jn(t,e,n){return t.held?Promise.resolve(n):(t.held=true,e().then(r=>(t.held=false,r)))}function ue(t,e,n){return {outcome:t,reason:e,...n}}function Qe(t){let e=t.outcome==="ok"||t.outcome==="declined"?t.outcome:"unavailable";return typeof t.reason=="string"?{outcome:e,reason:t.reason}:{outcome:e}}function wm(t){let e=new Map;return {ask(n,r,i,o){let s=`arcade-${ge()}`;return new Promise(a=>{let l={},d=c=>{e.delete(s)&&("timer"in l&&t.clearTimeout(l.timer),a(i(c)));};e.set(s,{expect:n,finish:d}),o!==void 0&&(l.timer=t.setTimeout(()=>d(null),o));let u=false;try{u=r(s);}catch{}u||d(null);})},settle(n){let r=e.get(n.requestId);return r===void 0||r.expect!==n.type?false:(r.finish(n),true)},abandon(){for(let n of [...e.values()])n.finish(null);}}}var m_=12,p_=24,za=Object.freeze({games:Object.freeze([])});function g_(t){let e=(n,r)=>be(n,`GameCard.${r}`);return Object.freeze({gameId:t.gameId,...t.slug===void 0?{}:{slug:t.slug},name:e(t.untrusted.name,"name"),tagline:e(t.untrusted.tagline,"tagline"),shortDescription:e(t.untrusted.shortDescription,"shortDescription"),tags:Object.freeze(t.untrusted.tags.map(n=>e(n,"tags"))),iconUrl:t.iconUrl,capsuleLandscapeUrl:t.capsuleLandscapeUrl,capsulePortraitUrl:t.capsulePortraitUrl,...t.previewVideoUrl===void 0?{}:{previewVideoUrl:t.previewVideoUrl},...t.previewPosterUrl===void 0?{}:{previewPosterUrl:t.previewPosterUrl}})}function Ri(t){return ue("unavailable","error",t)}function Sm(t){let{bridge:e,asker:n,acting:r}=t,i=a=>e.currentState==="connected"&&e.parentSupports(a),o=new Map,s=(a,l)=>{let d=o.get(a);if(d!==void 0)return d;let u=l().then(c=>(o.delete(a),c));return o.set(a,u),u};return {get available(){return {appLinks:i("appLinks"),openGame:i("openGame")}},appLinks(){return e.parentSupports("appLinks")?s("appLinks",()=>n.ask("gem.appLinksResult",a=>e.requestArcade({type:"gem.requestAppLinks",requestId:a}),a=>{if(a===null)return Ri({});let l=a;return {...Qe(a),...l.arcade===void 0?{}:{arcade:{store:l.arcade.store}},...l.game===void 0?{}:{game:{store:l.game.store}}}},Nn)):Promise.resolve(ue("unavailable","unsupported",{}))},openApp(a){return e.parentSupports("appLinks")?a!=="arcade"&&a!=="game"?Promise.resolve(ue("unavailable","invalid_argument",{})):jn(r,()=>n.ask("gem.openAppResult",l=>e.requestArcade({type:"gem.requestOpenApp",requestId:l,target:a}),l=>l===null?Ri({}):Qe(l),Ja),ue("declined","busy",{})):Promise.resolve(ue("unavailable","unsupported",{}))},openGame(a){if(!e.parentSupports("openGame"))return Promise.resolve(ue("unavailable","unsupported",{}));let l=typeof a=="string"?a.toLowerCase():"";return Zl({gem:B,type:"gem.requestOpenGame",requestId:"-",ref:l})!==null?Promise.resolve(ue("unavailable","invalid_argument",{})):jn(r,()=>n.ask("gem.openGameResult",u=>e.requestArcade({type:"gem.requestOpenGame",requestId:u,ref:l}),u=>u===null?Ri({}):Qe(u),Ja),ue("declined","busy",{}))},similarGames(a){if(!e.parentSupports("openGame"))return Promise.resolve(ue("unavailable","unsupported",za));let l=a?.limit;return l!==void 0&&(typeof l!="number"||!Number.isInteger(l)||l<1||l>p_)?Promise.resolve(ue("unavailable","invalid_argument",za)):s(`similar:${l??m_}`,()=>n.ask("gem.similarGamesResult",d=>e.requestArcade({type:"gem.requestSimilarGames",requestId:d,...l===void 0?{}:{limit:l}}),d=>{if(d===null)return Ri(za);let u=Qe(d),c=d,g=u.outcome==="ok"?Object.freeze(c.games.map(g_)):[];return {...u,games:g}},Nn))}}}var f_=64,Rm=Object.freeze({offers:Object.freeze([])});function y_(t){return Object.freeze({skuId:t.skuId,kind:t.kind,name:t.name,description:t.description,...t.imageUrl===void 0?{}:{imageUrl:t.imageUrl},priceDisplay:t.priceDisplay,...t.grant===void 0?{}:{grant:Object.freeze({currency:t.grant.currency,amount:t.grant.amount})}})}function km(t){let{bridge:e,asker:n,acting:r}=t,i=new Set,o=null;function s(a,l,d,u){return e.parentSupports(a)?typeof u!="string"||u.length===0||u.length>f_?Promise.resolve(ue("unavailable","invalid_argument",{})):jn(r,()=>n.ask(d,c=>e.requestArcade({type:l,requestId:c,skuId:u}),c=>c===null?ue("unavailable","error",{}):Qe(c)).then(c=>((c.outcome==="ok"||c.reason==="error")&&t.onPurchaseEnded?.(),c)),ue("declined","busy",{})):Promise.resolve(ue("unavailable","unsupported",{}))}return {api:{get available(){return e.currentState==="connected"&&e.parentSupports("store")},get showOfferAvailable(){return e.currentState==="connected"&&e.parentSupports("storeOfferSheet")},offers(){return e.parentSupports("store")?(o!==null||(o=n.ask("gem.storeOffersResult",a=>e.requestArcade({type:"gem.requestStoreOffers",requestId:a}),a=>{if(a===null)return ue("unavailable","error",Rm);let l=Qe(a),d=a,u=l.outcome==="ok"?Object.freeze(d.offers.map(y_)):[];return {...l,offers:u}},Nn).then(a=>(o=null,a))),o):Promise.resolve(ue("unavailable","unsupported",Rm))},purchase(a){return s("store","gem.requestStorePurchase","gem.storePurchaseResult",a)},showOffer(a){return s("storeOfferSheet","gem.requestStoreOfferSheet","gem.storeOfferSheetResult",a)},onSettled(a){return i.add(a),()=>{i.delete(a);}}},settled(a){t.onPurchaseEnded?.();let l=Object.freeze({skuId:a.skuId});for(let d of [...i])try{d(l);}catch(u){t.onListenerError?.(u);}}}}var Im="https://gemarcade.com/branding/manifest.json",h_=1,Am=256*1024,b_=256,v_=64,__=256,xm=8e3,w_=6e4,S_=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Pm={GEMS:"gems-mark",ARCADE_TICKETS:"ticket-mark"},Em=Object.freeze({outcome:"unavailable"}),Tm=Object.freeze({outcome:"not_found"});function ht(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function Ai(t){return typeof t=="string"&&t!==""&&t.length<=__}function R_(t,e){if(!Ai(t))return;let n;try{n=new URL(t,e);}catch{return}let r=Ct(n.href);if(r!==void 0)return n.origin===new URL(e).origin?r:mo(r)}function k_(t,e){let n=t??{},r=R_(n.url,e);if(!(r===void 0||!Ai(n.type))&&!(typeof n.bytes!="number"||!(n.bytes>=0))&&!(n.theme!==void 0&&n.theme!=="light"&&n.theme!=="dark"))return Object.freeze({url:r,type:n.type,bytes:n.bytes,...ht(n.width)?{width:n.width}:{},...ht(n.height)?{height:n.height}:{},...ht(n.size)?{size:n.size}:{},...ht(n.density)?{density:n.density}:{},...n.vector===true?{vector:true}:{},...n.theme===void 0?{}:{theme:n.theme}})}function A_(t,e=Im){let n;try{n=JSON.parse(t);}catch{return null}let r=n??{};if(r.format!==h_||!Array.isArray(r.assets))return null;let i=[],o=new Set;for(let s of r.assets.slice(0,b_)){let a=s??{};if(!Ai(a.id)||!S_.test(a.id)||o.has(a.id)||!Ai(a.kind)||!Array.isArray(a.variants))continue;let l=[];for(let d of a.variants.slice(0,v_)){let u=k_(d,e);u!==void 0&&l.push(u);}l.length!==0&&(o.add(a.id),i.push(Object.freeze({id:a.id,kind:a.kind,variants:Object.freeze(l)})));}return Object.freeze(i)}function ki(t){let e;for(let n of t)(e===void 0||(n.width??0)>(e.width??0))&&(e=n);return e}function x_(t,e,n){let r=t.find(l=>l.vector===true),i=t.filter(l=>l.size===void 0);if(e===void 0)return r??ki(i)??ki(t);let o=t.filter(l=>l.size===e);if(o.length>0){let l=u=>u.density??1,d=o.filter(u=>l(u)>=n);return d.length>0?d.reduce((u,c)=>l(c)<l(u)?c:u):o.reduce((u,c)=>l(c)>l(u)?c:u)}if(r!==void 0)return r;let s=i.filter(l=>(l.width??0)>=e*n);return (s.length>0?s.reduce((l,d)=>(d.width??0)<(l.width??0)?d:l):void 0)??ki(i)??ki(t)}function P_(t,e){let n=e.theme===void 0?[]:t.variants.filter(a=>a.theme===e.theme),r=t.variants.filter(a=>a.theme===void 0),i=[n,r].filter(a=>a.length>0);if(t.kind!=="image")return i[0]?.[0];let s=(e.size===void 0?void 0:i.find(a=>a.some(l=>l.size===e.size)))??i[0];return s&&x_(s,e.size,e.density)}function E_(t,e){if(e!==void 0){if(e===null||typeof e!="object")throw new TypeError(`[gem] branding.${t}: options must be an object`);if(e.size!==void 0&&!ht(e.size))throw new RangeError(`[gem] branding.${t}: size must be a positive number of CSS px`);if(e.density!==void 0&&!ht(e.density))throw new RangeError(`[gem] branding.${t}: density must be a positive number`);if(e.theme!==void 0&&e.theme!=="light"&&e.theme!=="dark")throw new TypeError(`[gem] branding.${t}: theme must be 'light' or 'dark'`)}}function Cm(t){let e=t.manifestUrl??Im,n=null,r=null,i=-1/0,o=false,s=u=>(i=t.clock.now(),o||(o=true,t.log?.(`[gem] gem.branding could not read the platform's branding (${u}), so every lookup answers 'unavailable' and your bundled fallback shows. If your page sets a Content-Security-Policy, allow ${new URL(e).origin} in connect-src and img-src.`)),null),a=async()=>{if(t.fetch===null)return s("this page has no fetch");let u=t.fetch,c=typeof AbortController=="function"?new AbortController:null,g,p=new Promise(y=>{g=t.clock.setTimeout(()=>{c?.abort(),y(s(`no answer in ${xm} ms`));},xm);}),f=(async()=>{let y=await u(e,{credentials:"omit",redirect:"error",...c?{signal:c.signal}:{}});if(!y.ok)return s("the manifest answered an error");if(Number(y.headers.get("content-length"))>Am)return s("the manifest is too large");let S=await y.text();return S.length>Am?s("the manifest is too large"):A_(S,e)??s("the manifest is not format 1 JSON")})().catch(()=>s("the request failed"));try{return await Promise.race([f,p])}finally{t.clock.clearTimeout(g);}},l=()=>n!==null?Promise.resolve(n):r!==null?r:t.clock.now()-i<w_?Promise.resolve(null):(r=a().then(u=>(r=null,u!==null&&(n=u),u)),r),d=async(u,c,g,p)=>{E_(u,p);let f=await l();if(f===null)return Em;let y=f.find(R=>R.id===c&&R.kind===g);if(y===void 0)return Tm;let S=t.devicePixelRatio(),v=P_(y,{...p?.size===void 0?{}:{size:p.size},density:p?.density??(ht(S)?S:1),...p?.theme===void 0?{}:{theme:p.theme}});return v===void 0?Tm:Object.freeze({outcome:"ok",url:v.url,variant:v,asset:y})};return Object.freeze({get:async(u,c)=>{if(typeof u!="string"||u==="")throw new TypeError("[gem] branding.get: id must be a non-empty string");if(c===null||typeof c!="object"||typeof c.kind!="string")throw new TypeError("[gem] branding.get: options.kind must be a string, such as 'image'");return d("get",u,c.kind,c)},logo:u=>d("logo","gem-logo","image",u),wordmark:u=>d("wordmark","gem-wordmark","image",u),currencyMark:async(u,c)=>{let g=Object.prototype.hasOwnProperty.call(Pm,u)?Pm[u]:void 0;if(g===void 0)throw new TypeError("[gem] branding.currencyMark: currency must be 'GEMS' or 'ARCADE_TICKETS', not "+JSON.stringify(String(u).slice(0,40)));return d("currencyMark",g,"image",c)},trophy:u=>d("trophy","trophy-mark","image",u),list:async()=>{let u=await l();return u===null?Em:Object.freeze({outcome:"ok",assets:u})}})}var M_="(any-pointer: coarse)";function O_(t){let e=Array.isArray(t)?t:[t],n=[],r=1e4;for(let i of e){if(typeof i!="number"||!Number.isFinite(i)||i<0)return null;if(n.length===99||r===0)continue;let o=Math.min(Math.trunc(i),1e4,r);n.push(o),r-=o;}return n.length%2===0&&n.pop(),n.every(i=>i===0)?[]:n}function Mm(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?u=>matchMedia(u):void 0},i=r.navigator,o,s=new Set,a=()=>typeof i?.vibrate!="function"||r.matchMedia===void 0?false:(o??=r.matchMedia(M_),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(u,c)=>{s.has(u)||(s.add(u),n!==null&&(n===void 0?console.warn(c):n(c)));};return {get available(){return a()||l()},vibrate(u){let c=a();if(!c&&!l())return false;let g=O_(u);if(g===null)return d("pattern","[gem] gem.vibration.vibrate did nothing: a pattern is a number of milliseconds, or an array of them, each finite and not negative."),false;if(i?.userActivation?.hasBeenActive!==true)return d("activation","[gem] gem.vibration.vibrate did nothing: the player has not tapped or pressed a key in your game yet, and browsers allow vibration only after that."),false;if(c)try{return i.vibrate(g)===!0}catch{return false}let p=e.requestVibrate(g);return p||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),p}}}var Ht=Math.PI/180,Fe=Object.freeze({touch:Object.freeze({yaw:1*Ht,pitch:.66*Ht}),mouse:Object.freeze({yaw:.5*Ht,pitch:.5*.77*Ht}),stick:Object.freeze({yaw:240*Ht,pitch:240*.77*Ht}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),Xa="[gem.controls]",Ya=Object.freeze({yaw:0,pitch:0}),xi=t=>Number.isFinite(t)?t:0,Om=(t,e)=>({yaw:t+0,pitch:e+0});function Gm(t){let e=xi(t),n=(Math.abs(e)-Fe.stickDeadzone)/(1-Fe.stickDeadzone),r=Fe.stickCurve,i=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,i))+0}function G_(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-Fe.touchPitchMin)+Fe.touchPitchMin}function Lm(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${Xa} ${e} takes an options object`);let n=t;for(let r of ["sensitivity","gamepadSensitivity"]){let i=n[r];if(i!==void 0&&!(typeof i=="number"&&Number.isFinite(i)&&i>0))throw new TypeError(`${Xa} ${e}: ${r} must be a finite number above 0 (1 = the base speed); got ${String(i)}`)}if(n.invertY!==void 0&&typeof n.invertY!="boolean")throw new TypeError(`${Xa} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function L_(t,e){let n=Lm(e,"look()"),r=n.sensitivity,i=n.gamepadSensitivity,o=n.invertY,s=a=>o??a?.invertLookY??false;return {fromPointer(a,l,d,u){let c=xi(a),g=xi(l);if(c===0&&g===0)return Ya;let p=t(),f=r??(p===null?void 0:p.lookSensitivity/100)??1,y=d==="touch"||d==="pen",S=y?Fe.touch:Fe.mouse,v=c*S.yaw*f,R=-g*S.pitch*f;return s(p)&&(R=-R),y&&u!==void 0&&Number.isFinite(u)&&R*u>0&&(R*=G_(u)),Om(v,R)},fromStick(a,l,d){let u=xi(d);if(u<=0)return Ya;let c=Gm(a),g=Gm(l);if(c===0&&g===0)return Ya;let p=t(),f=i??(p===null?void 0:p.gamepadLookSensitivity/100)??1,y=c*Fe.stick.yaw*u*f,S=-g*Fe.stick.pitch*u*f;return s(p)&&(S=-S),Om(y,S)},set(a){let l=Lm(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(i=l.gamepadSensitivity),"invertY"in l&&(o=l.invertY);}}}function Dm(t){return {look:e=>L_(t.recommended,e),LOOK_BASE:Fe}}var $m=Object.freeze(["music","sfx","voice","eye","text","hint","speed","bright","controls","star"]),Fm=/^[A-Za-z0-9_-]{1,40}$/;function Qa(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=1e6}function qm(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e.slice(0,40)}function Nm(t,e,n,r){let i=a=>Number.parseFloat(a.toPrecision(12)),o=Math.min(n,Math.max(e,t)),s=i(e+Math.round((o-e)/r)*r);return s>n&&(s=i(s-r)),Math.min(n,Math.max(e,s))}function jm(t,e){switch(t.kind){case "toggle":return typeof e=="boolean"?e:void 0;case "slider":{if(typeof e!="number"||!Number.isFinite(e))return;let n=t.min??0,r=t.max??100;return Nm(e,n,r,t.step??1)}case "choice":return typeof e=="string"&&(t.options??[]).some(n=>n.id===e)?e:void 0;default:return}}function Bm(t,e=()=>{}){if(!Array.isArray(t))return null;let n=[],r=0;for(let i=0;i<t.length;i+=1){let o=t[i],s=`settings[${i}]`;if(n.length===8){e(`${s} and later were left out: at most 8 settings are shown.`);break}if(typeof o!="object"||o===null){e(`${s} was dropped: a setting is an object.`);continue}let a=o,l=a.id;if(typeof l!="string"||!Fm.test(l)){e(`${s} was dropped: its id must be 1 to 40 of A-Z a-z 0-9 _ -.`);continue}let d=`${s} (${JSON.stringify(l)})`;if(n.some(g=>g.id===l)){e(`${d} was dropped: an earlier setting has the same id.`);continue}let u=qm(a.label);if(u===void 0){e(`${d} was dropped: its label is empty.`);continue}let c;switch(a.kind){case "toggle":{if(typeof a.value!="boolean"){e(`${d} was dropped: a toggle's value is true or false.`);continue}c={id:l,label:u,kind:"toggle",value:a.value},a.quick===true&&(r<2?(c.quick=true,r+=1):e(`${d} is not in the quick row: at most 2 toggles are, the first that ask.`));break}case "slider":{let g=a.min??0,p=a.max??100,f=a.step??1;if(!Qa(g)||!Qa(p)||!Qa(f)||g>=p||f<=0){e(`${d} was dropped: a slider needs finite numbers within \xB11000000 with min below max and a step above 0.`);continue}if(typeof a.value!="number"||!Number.isFinite(a.value)){e(`${d} was dropped: a slider's value is a number.`);continue}c={id:l,label:u,kind:"slider",value:Nm(a.value,g,p,f),min:g,max:p,step:f};break}case "choice":{let g=[];for(let p of Array.isArray(a.options)?a.options:[]){if(g.length===4)break;if(typeof p!="object"||p===null)continue;let f=p,y=qm(f.label);typeof f.id!="string"||!Fm.test(f.id)||y===void 0||g.some(S=>S.id===f.id)||g.push({id:f.id,label:y});}if(g.length<2){e(`${d} was dropped: a choice needs 2 to 4 options, each with an id of 1 to 40 of A-Z a-z 0-9 _ - and a label.`);continue}if(typeof a.value!="string"||!g.some(p=>p.id===a.value)){e(`${d} was dropped: a choice's value is the id of one of its options.`);continue}c={id:l,label:u,kind:"choice",value:a.value,options:g};break}default:e(`${d} was dropped: its kind must be 'toggle', 'slider' or 'choice'.`);continue}a.icon!==void 0&&($m.includes(a.icon)?c.icon=a.icon:e(`${d} keeps the Arcade's generic icon: ${JSON.stringify(a.icon)} is not one of ${$m.join(", ")}.`)),n.push(c);}return n}var D_=500;function Um(t){let{clock:e}=t,n=null,r=null,i=-1/0,o=null,s=new Set,a=new Set,l=c=>{a.has(c)||(a.add(c),t.log!==null&&(t.log===void 0?console.warn(c):t.log(c)));},d=()=>{let c=t.frame();return c.currentState==="connected"&&c.parentSupports("gameSettings")},u=()=>{if(n===null||o!==null)return;let c=JSON.stringify(n);if(c===r)return;let g=i+D_-e.now();if(g>0){o=e.setTimeout(()=>{o=null,u();},g);return}t.frame().declareSettings(n)&&(r=c,i=e.now());};return {api:{declare(c){let g=Bm(c,p=>l(`[gem] gem.settings.declare: ${p}`));return g===null?(l("[gem] gem.settings.declare did nothing: pass an array of settings, or [] for none."),false):(n=g,u(),d())},onChange(c){if(typeof c!="function")return ()=>{};let g=p=>c(p);return s.add(g),()=>{s.delete(g);}}},forgetSent(){r=null,i=-1/0;},flush:u,onSettingChange(c){let g=n?.findIndex(v=>v.id===c.id)??-1,p=n?.[g];if(n===null||p===void 0)return;let f=jm(p,c.value);if(f===void 0)return;let y=JSON.stringify(n);n=n.map((v,R)=>R===g?{...v,value:f}:v),r===y&&(r=JSON.stringify(n));let S={id:p.id,value:f};for(let v of [...s])try{v(S);}catch(R){console.error("[gem] a gem.settings.onChange handler threw:",R);}}}}function Wm(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var $_=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Hm(t){if(typeof t!="string"||!$_.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function Bn(){return {declared:false,grantable:false,heldLimitReached:false}}function Vm(t,e){let n=typeof t=="object"&&t!==null?t:{},r=Hm(n.resets_at),i=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...Bn(),...i};let o=n.remaining_today,s=typeof o=="number"&&Number.isFinite(o)&&o>=0?Math.floor(o):void 0,a=n.next_eligible_at,l=Hm(a),d=n.held_limit_reached===true,u=a!=null,c=o!=null&&s===void 0;return {declared:true,grantable:n.grantable===true&&e&&s!==0&&!c&&!u&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var F_=18e4,Za=32,q_=/^[a-z0-9_-]+$/,N_="rewarded_requires_user_gesture";function j_(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var B_=1e3;function U_(){let t=globalThis,e=t.navigator?.getGamepads,n=t.performance?.now;if(typeof e!="function"||typeof n!="function")return;let r=n.call(t.performance),i=e.call(t.navigator);for(let o=0;o<i.length;o+=1){let s=i[o]?.timestamp;if(typeof s=="number"&&r-s>=0&&r-s<=B_)return true}return false}var Km=1e4;function W_(t){return t==="interstitial"||t==="rewarded"}function Jm(t){return typeof t=="string"&&t!==""&&t.length<=Za&&q_.test(t)}function H_(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function Pi(t){return typeof t=="string"?JSON.stringify(t):typeof t}function zm(t){let e=false,n=new Map,r=new Map,i=new Set,o=d=>{try{t.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let u=t.log;if(u!==null)try{u===void 0?console.warn(`[gem] ${d}`):u(`[gem] ${d}`);}catch{}},l=d=>{let u=t.readAvailability;if(u===void 0)return Promise.resolve(Bn());let c=r.get(d);if(c!==void 0)return c;let g=new Promise(p=>{let f={},y=h=>f.done===true?false:(f.done=true,t.clock.clearTimeout(f.timer),p(h),true),S=(h,_)=>{!y(Bn())||i.has(h)||(i.add(h),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${_}. Said once.`));},v=h=>{S(H_(h),`the read failed (${h instanceof Error?h.message:Pi(h)})`);},R;try{R=Promise.resolve(u(d,AbortSignal.timeout(Km)));}catch(h){R=Promise.reject(h);}f.timer=t.clock.setTimeout(()=>{S("timeout","no answer within 10 s");},Km),R.then(h=>{try{y(Vm(h,t.bridge.parentSupports("ads")));}catch(_){v(_);}},v);});return r.set(d,g),g.then(()=>{r.get(d)===g&&r.delete(d);}),g};return {api:{rewardedStatus(d){return Jm(d)?l(d):(o(`gem.ads.rewardedStatus(${Pi(d)}) answered not grantable: a placement is 1..${String(Za)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(Bn()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let u=d?.placement,c=d?.format;if(!Jm(u)||!W_(c))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${Pi(u)}, format ${Pi(c)}. A placement is 1..${String(Za)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});if(c==="rewarded"){let p;try{p=(t.userActivation??j_)();}catch{p=void 0;}if(p===false)try{(t.recentGamepadInput??U_)()===!0&&(p=!0);}catch{}if(p===false){let f=`${N_}: gem.ads.requestAd("${u}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return o(f),a(f),Promise.resolve({outcome:"no_ad"})}}let g=`ad-${ge()}`;return new Promise(p=>{let f={},y=v=>{n.delete(g)&&(e=false,t.clock.clearTimeout(f.timer),p(v));};e=true,n.set(g,y),f.timer=t.clock.setTimeout(()=>{y({outcome:"unavailable"});},t.timeoutMs??F_);let S=false;try{S=t.bridge.requestAd(g,u,c);}catch{}S||y({outcome:"no_ad"});})}},settle(d){let u=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",c=n.get(d.requestId);if(c===void 0){t.onDropped?.(`gem.adResult (${u}) for an unknown requestId: `+JSON.stringify(d.requestId));return}c({outcome:u});}}}var Xm=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),Ym=18e4,V_=1e4,K_=/^[a-z0-9_-]{1,32}$/;function es(t){return typeof t=="string"?JSON.stringify(t):typeof t}var Un=Object.freeze({shown:false});function Qm(t){let e=new Map,n,r=false,i=o=>{try{t.onDropped?.(o);}catch{}return Un};return {api:{signal(o){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(Un):(r=!0,Promise.resolve(i("moments_unsupported: gem.moments.signal answered shown: false without asking: this arcade does not do platform moments. Keep the call; it costs nothing. Said once.")));let s=o?.kind,a=o?.placement,l=o?.wall;if(!Xm.includes(s)||a!==void 0&&(typeof a!="string"||!K_.test(a))||l!==void 0&&typeof l!="boolean")return Promise.resolve(i(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${es(s)}, placement ${es(a)}, wall ${es(l)}. A kind is one of ${Xm.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'; a wall, when given, is true or false. Answering shown: false.`));if(!t.bridge.readyCalled())return Promise.resolve(i(`moments_before_ready: gem.moments.signal({ kind: '${s}' }) before gem.frame.ready(): a moment is a break in play, and play has not started. Signal from the press that leaves a break, never on boot. Answering shown: false.`));if(e.size>0)return Promise.resolve(i(`moments_in_flight: gem.moments.signal({ kind: '${s}' }) while another moment is still waiting for its answer. Signal once per break, and await the answer before play resumes. Answering shown: false.`));let d=t.clock.now();if(n!==void 0&&d-n<V_)return Promise.resolve(i(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(d-n)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let u=`moment-${ge()}`;return new Promise(c=>{let g={},p=(y,S)=>{e.delete(u)&&(t.clock.clearTimeout(g.timer),S&&(n=t.clock.now()),c(y));};e.set(u,y=>p(y,!0)),g.timer=t.clock.setTimeout(()=>{e.has(u)&&(p(Un,!0),i(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??Ym)/1e3)} s. Answering shown: false.`));},t.timeoutMs??Ym);let f=!1;try{f=t.bridge.signalMoment(u,s,a,l===!0?!0:void 0);}catch{}f||p(Un,!1);})}catch{return Promise.resolve(Un)}}},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 ts=16384;function Zm(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e;try{e=JSON.stringify(t);}catch{return null}return typeof e!="string"?null:J_(e)}function J_(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(e+=4,n+=1):e+=3;}else e+=3;}return e}var z_=1e4,X_=5e3;function ep(t){let e=null,n=false,r=[],i=new Map,o=()=>{for(let s of r.splice(0))s();};return {api:{get current(){return e},wait(s=X_){return n?Promise.resolve(e):new Promise(a=>{let l=()=>{let c=r.indexOf(d);c>=0&&r.splice(c,1);},d=()=>{t.clock.clearTimeout(u),l(),a(e);},u=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=Zm(s);if(a===null)return t.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(a>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(s)),d=`device-settings-${ge()}`;return new Promise(u=>{let c={},g=f=>{i.delete(d)&&(t.clock.clearTimeout(c.timer),f==="stored"&&(e=l,n=true,o()),u(f));};i.set(d,g),c.timer=t.clock.setTimeout(()=>g("unavailable"),t.timeoutMs??z_);let p=false;try{p=t.bridge.putDeviceSettings(d,l);}catch{}p||g("unavailable");})}},receive(s){let a=s.settings;e=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,n=true,o();},settle(s){let a=s.outcome==="stored"||s.outcome==="too_large"?s.outcome:"unavailable",l=i.get(s.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var 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 Y_=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Q_(t){return typeof t=="string"&&Y_.test(t)}function Ei(t){if(t===null||Q_(t))return t;let e=typeof t=="string"?JSON.stringify(t.length>48?`${t.slice(0,48)}\u2026`:t):`a value of type ${typeof t}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}function tp(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function rs(t,e){if(t!==true)return {visible:false};let n=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!n.includes(i)&&n.push(i);return !r&&n.length===0?{visible:true}:{visible:true,currencies:n.slice(0,8),score:r}}function Ti(t){let e=[];for(let n of Array.isArray(t)?t:[]){if(e.length===4)break;if(typeof n!="object"||n===null)continue;let{id:r,label:i}=n;typeof r!="string"||r.length===0||r.length>32||typeof i!="string"||i.trim().length===0||e.some(o=>o.id===r)||e.push({id:r,label:i.trim().slice(0,40)});}return e.length===0?{settings:false}:{settings:false,items:e}}function np(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Z_(t){let e=t.untrusted,n=be(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,i=r?be(r,"gem.player.displayTag"):void 0,o=t.discriminator||t.displayTag,s=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,a=t.avatarIconUrl||t.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=t.avatarIconId,u=t.avatar3dId,c={displayName:n,displayHandle:i??n,badges:(t.badges??[]).map(y=>({itemId:y.itemId,iconUrl:y.iconUrl}))};t.playerId&&(c.playerId=t.playerId),s&&(c.discriminator=s),i&&(c.displayTag=i),a&&(c.avatarIconUrl=c.avatarUrl=a),d&&l.test(d)&&(c.avatarIconId=d),u&&l.test(u)&&(c.avatar3dId=u),t.avatar3dModelUrl&&(c.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(c.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(c.avatars3d=t.avatars3d.filter(y=>l.test(y.id)&&/^[a-z][a-z0-9_]*$/.test(y.family)).filter((y,S,v)=>v.findIndex(R=>R.family==y.family)==S).map(({family:y,id:S,modelUrl:v,iconUrl:R})=>({family:y,id:S,modelUrl:v,iconUrl:R})));let g=t.boost,p=(g?.multipliers??[]).map(y=>({currencyId:y.currencyId,currencySlug:y.currencySlug,multiplier:y.multiplierBp/1e4})),f=p.some(y=>y.multiplier>1);return c.boost=f&&g?.expiresInDays?{active:f,multipliers:p,expiresInDays:g.expiresInDays}:{active:f,multipliers:p},c}var ew=1e4,tw=["appLinks","openGame","store","storeOfferSheet"],nw=["token","pause","menuSelect","settingChange","prefs","cohorts","viewport","willTerminate","localServer","roomEvent","seatedEvent","autoStartFailedEvent","ticketEvent","socketState","signalEvent","relayDraining","dedicatedEvent","clusterTarget","graphicsRoutes","partyResult","purchaseResult","purchaseSettled","shareResult","deviceSettings","adResult","momentResult","signInResult","friendChallengeResult"],ns=new WeakMap;function ip(t,e){if(ns.has(t))throw new Error("admitBuildEmbedders: already admitted");ns.set(t,Object.freeze([...e]));}var Hn=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??ce,this.inbound=new tn(this.clock),this.outbound=new tn(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=>xt(a,e.origin))||hr(e.origin,this.options.selfOrigin)||(ns.get(this)??[]).some(a=>xt(a,e.origin))))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=yr["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!xt(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=ed(pr,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:B,type:"gem.error",code:"version_mismatch",message:`frame supports v${pr.min}..v${pr.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=ew){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=o=>{this.clock.clearTimeout(i),n(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem:B,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:B,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:B,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:B,type:"gem.exit"}:{gem:B,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:B,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:B,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:B,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:B,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let n={gem:B,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return bo(e.cueId)&&(n.cueId=e.cueId),e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(n.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(n.origin={x:tp(e.origin.x),y:tp(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=Ei(e);return n===void 0||!this.gated("portraitBorders")?false:this.send(n===null?{gem:B,type:"gem.portraitBorders"}:{gem:B,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.gated("walletDisplay")?this.send({gem:B,type:"gem.walletDisplay",...rs(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:B,type:"gem.menu",...Ti(e)}):false}declareSettings(e){return this.gated("gameSettings")?this.send({gem:B,type:"gem.settingsDeclare",settings:e}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:B,type:"gem.gemCorner",corner:e}):false}setRewardPresentation(e){return this.gated("rewardPresentation")?this.send({gem:B,type:"gem.rewardPresentation",mode:e}):false}setMenuStyle(e){return this.gated("menuStyle")?this.send(e===null?{gem:B,type:"gem.menuStyle"}:{gem:B,type:"gem.menuStyle",ground:e.ground,accent:e.accent}):false}requestShare(e,n){return this.gated("share")?this.send({gem:B,type:"gem.requestShare",...n===void 0?{}:{requestId:n},params:e.map(({key:r,value:i})=>({key:r,value:i}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:B,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:B,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:B,type:"gem.frameStats",fps:np(e.fps,1e3),frameTimeP95Ms:np(e.frameTimeP95Ms,1e5),counts:e.counts==="gameDraws"?"gameDraws":"pageFrames"}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:B,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:B,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:B,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:B,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,i,o,s,a){return this.send({gem:B,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s},...a===void 0?{}:{origin:a}})}requestAvatar3dPurchase(e,n,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:B,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:n,currencySlug:r}):false}putDeviceSettings(e,n){return this.send({gem:B,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:B,type:"gem.requestAd",requestId:e,placement:n,format:r})}signalMoment(e,n,r,i){return this.send({gem:B,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r},...i===true?{wall:true}:{}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:B,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,i){return this.send({gem:B,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...i===void 0?{}:{params:i}})}requestArcade(e){return this.gated(fr(e.type))&&this.send({gem:B,...e})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(gr)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(gr)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(gr)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:B,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}gated(e){return this.state==="connected"&&this.parentSupports(e)}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let n=e.type;if(!this.outbound.allow(n))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${n}`),false;let r=yr[n]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${n}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,n=[]){let r=false;try{r=this.dispatchInbound(e,n);}finally{r||rp(n);}}dispatchInbound(e,n){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let i=yr[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=fr(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=n[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return rp(n.slice(1)),this.options.onScreenshot(d,l,(u,c)=>this.screenshotDenied(u,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(Z_(a));break}case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:if(nw.includes(r.slice(4))){this.options[`on${r[4].toUpperCase()}${r.slice(5)}`]?.(a);break}if(tw.includes(fr(r))){this.options.onArcadeAnswer?.(a);break}this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:B,type:"gem.screenshot.denied",reason:e,retryable:n});}};function rp(t){for(let e of t)try{e?.close?.();}catch{}}var op="https://api.gemarcade.com";function is(t){let e;try{e=new URL(t);}catch{return "it is not a valid URL"}return e.protocol!=="https:"&&e.protocol!=="http:"?`its scheme is ${e.protocol.replace(":","")}, and only http and https can be used`:e.username!==""||e.password!==""?"it carries credentials in the URL, which `fetch` will not send":e.href.includes("#")?"it carries a fragment. The transport joins the base and the path by concatenation, so the fragment would swallow the path and every request would go to the API root":e.href.includes("?")?"it carries a query string. The transport joins the base and the path by concatenation, so the query would swallow the path and every request would go to the API root":null}var rw=new Set(["localhost","127.0.0.1","[::1]"]);function ap(t){let e=is(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!rw.has(n.hostname)?"it is a plaintext http address that is not loopback. An embedder may name an https root, or http on localhost for a rig running the whole stack on one machine \u2014 the play token travels on every request to it":null}var dp="/gem-embedders.json",Ii=4096,sp=16,lp=5e3,Vn=Object.freeze({origins:Object.freeze([])});function Ze(t){return {origins:[],refused:`[gem] ${dp} was ignored: ${t}`}}function iw(t){if(t.trim()==="")return Vn;let e;try{e=JSON.parse(t);}catch{return Ze("it is not JSON.")}if(e===null||typeof e!="object"||Array.isArray(e))return Ze('it must be an object, { "embedders": [...] }.');let n=e.embedders;if(n===void 0)return Vn;if(!Array.isArray(n))return Ze('"embedders" must be an array of origins.');if(n.length>sp)return Ze(`"embedders" has more than ${sp} entries.`);let r=n.filter(i=>typeof i!="string"||!At(i)||!i.toLowerCase().startsWith("https://")||Ke(new URL(i).hostname));if(r.length>0){let i=r.slice(0,3).map(o=>typeof o=="string"?JSON.stringify(o.slice(0,100)):String(o)).join(", ");return Ze(`${r.length===1?"an entry is":"entries are"} not an https origin off this machine (${i}${r.length>3?", \u2026":""}).`)}return {origins:Object.freeze([...new Set(n)])}}async function cp(t){let e=typeof AbortController=="function"?new AbortController:null,n,r=new Promise(o=>{n=t.clock.setTimeout(()=>{e?.abort(),o(Ze(`it took more than ${lp} ms to read.`));},lp);}),i=(async()=>{let o=await t.fetch(t.selfOrigin+dp,{credentials:"omit",redirect:"error",...e?{signal:e.signal}:{}});if(!o.ok||(o.headers.get("content-type")??"").toLowerCase().includes("text/html"))return Vn;if(Number(o.headers.get("content-length"))>Ii)return Ze(`it is larger than ${Ii} bytes.`);let a=await o.text();return a.length>Ii?Ze(`it is larger than ${Ii} bytes.`):iw(a)})().catch(()=>Vn);try{return await Promise.race([i,r])}finally{t.clock.clearTimeout(n);}}function up(t){if(typeof t!="string"||!At(t))return null;let e=t.slice(0,t.indexOf(":")).toLowerCase();return e==="https"||e==="http"?t:null}function mp(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function ow(){let t=[["root",null],["hips","root"],["spine","hips"],["chest","spine"],["upper_chest","chest"],["neck","upper_chest"],["head","neck"],["head_socket","head"]];for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("shoulder"),"upper_chest"],[n("upper_arm"),n("shoulder")],[n("lower_arm"),n("upper_arm")],[n("hand"),n("lower_arm")],[n("hand_socket"),n("hand")]);for(let r of ["thumb","index","middle","ring","little"])for(let i=1;i<=3;i++)t.push([n(`${r}_${i}`),n(i===1?"hand":`${r}_${i-1}`)]);}for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("upper_leg"),"hips"],[n("lower_leg"),n("upper_leg")],[n("foot"),n("lower_leg")],[n("toes"),n("foot")]);}return t}var aw=Object.freeze({small_human:mp([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:mp(ow())});var lw=Object.freeze(["https://gemarcade.com","https://developer.gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),dw=op,cw=["top-left","top-right","bottom-left","bottom-right"],uw=["arcade","game"];function pp(t){let e=[1,3,5].map(n=>{let r=parseInt(t.slice(n,n+2),16)/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4});return .2126*e[0]+.7152*e[1]+.0722*e[2]}function mw(t){if(t===null)return null;let{ground:e,accent:n}=Object(t);for(let[s,a]of [["ground",e],["accent",n]]){if(typeof a=="string"&&/^#[0-9a-fA-F]{6}$/.test(a))continue;let l=typeof a=="string"?JSON.stringify(a.slice(0,48)):`a value of type ${typeof a}`;console.warn(`[gem] setMenuStyle: ${s} is ${l}, which is not #rrggbb, so nothing was sent.`);return}let r={ground:e.toLowerCase(),accent:n.toLowerCase()},i=[pp(r.ground),pp(r.accent)],o=(Math.max(...i)+.05)/(Math.min(...i)+.05);if(o>=3)return r;console.warn(`[gem] setMenuStyle: accent ${r.accent} reaches ${Math.floor(o*100)/100}:1 against ground ${r.ground}, under the 3:1 it needs, so nothing was sent.`);}var gp=8e3,Ci=15e3,pw=9e4,gw=1/0,fw=8e3,yw=5e3,hw=5e3;async function bw(t,e,n,r){if(t.isInRoom)try{await t.leave();}catch{}r?.endSession("session_ended"),e!==null&&e.currentState==="connected"&&e.exit(n);}function Kn(t){let e=null,n=false,r=[];return {get current(){return e},set(i){e=i;for(let o of r.splice(0))o(i);},release(){n=true;for(let i of r.splice(0))i(e);},wait(i){return e!==null||n?Promise.resolve(e):new Promise(o=>{let s=()=>{let d=r.indexOf(a);d>=0&&r.splice(d,1);},a=d=>{t.clearTimeout(l),s(),o(d);},l=t.setTimeout(()=>{s(),o(e);},i);r.push(a);})}}}function QI(t={}){let e=t.clock??ce,n=t.log===void 0?m=>console.info(m):t.log,r=t.baseUrl??void 0;if(r!=null){let m=is(r);if(m!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${m}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=typeof window>"u"?void 0:window.location?.search,o=$d(i),s=cc(i),a=iu(i),l=ya();l.mark("sdk created");let d=()=>Jr(se.gameVersion,t.clientVersion?.gameVersion),u=new yn({client:()=>Rt,clock:e,gameId:()=>se.identity?.gameId??null,playerId:()=>se.identity?.playerId??null,awaitPlayerId:async()=>(await sr(Ci)).playerId,declarations:async()=>(await ar.load())?.analytics_events,environment:()=>{let m=d();return {sdk_version:Cs(),...m===null?{}:{game_version:m}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),c=tu(()=>{l.mark("engaged"),u.release(),$.reportEngaged();},typeof window>"u"?{}:window),g=m=>{if(m===false)return null;let E=m?.attempts??gw,F=m?.budgetMs??pw;return !(E>0)||!(F>0)?null:{attempts:E,budgetMs:F,maxDelayMs:m?.maxDelayMs??fw}},p=m=>{m.on("created",()=>{l.mark("room created");}),m.on("joined",()=>{l.mark("room joined");}),m.on("matchAllocationStarted",()=>{l.mark("allocation started");}),m.on("matchReady",()=>{l.mark("match ready");}),m.on("matchFailed",()=>{l.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new Wn;let f=t.allowedEmbedders;if(f!=null&&!Array.isArray(f))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let y=Array.from(f??[]),S=y.filter(m=>typeof m!="string"||!At(m));if(S.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${S.length===1?"an entry":"entries"} that ${S.length===1?"is":"are"} not an origin: ${S.map(m=>typeof m=="string"?JSON.stringify(m):String(m)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let v=Object.freeze([...new Set([...lw,...y])]),R=Kn(e),h=new Set,_=Kn(e),I=false,T=Kn(e),W=Ud(n),j=Kn(e),U=t.manageAudio===false?null:bu();t.selectableText!==true&&vu(),t.onScreenshot===void 0&&su(window);let C=null,L=null,D=null,H=()=>{C===null||C===L||$.reportMuted(C)&&(L=C);},x,G,ne=-1/0,fe=null,Q=()=>{if(x===void 0||fe!==null||x===G)return;let m=ne+1e3-e.now();if(m>0){fe=e.setTimeout(()=>{fe=null,Q();},m);return}$.showPortraitBorders(x)&&(G=x,ne=e.now());},Pe=null,we=null,Me=()=>{if(Pe===null)return false;let m=JSON.stringify(rs(Pe.visible,Pe.only));return m===we?$.parentSupports("walletDisplay"):$.setWalletVisible(Pe.visible,Pe)?(we=m,true):false},ke=null,te=null,X=()=>{if(ke===null)return false;let m=JSON.stringify(Ti(ke.items));return m===te?$.parentSupports("gameMenu"):$.setMenu(ke.items)?(te=m,true):false},ae=null,Oe=null,Ee=null,We=null,bt,vt=null,et=Um({frame:()=>$,clock:e,log:t.log}),_t=()=>ae===null?false:ae===Oe?$.parentSupports("gemCorner"):$.setGemCorner(ae)?(Oe=ae,true):false,Jn=()=>Ee===null?false:Ee===We?$.parentSupports("rewardPresentation"):$.setRewardPresentation(Ee)?(We=Ee,true):false,Vt=()=>{if(bt===void 0)return false;let m=JSON.stringify(bt);return m===vt?$.parentSupports("menuStyle"):$.setMenuStyle(bt)?(vt=m,true):false},b=_u({report:m=>$.reportFrameStats(m)}),M=false,q=Pu(()=>ks,()=>M),Z=m=>{let E=M&&!m,F=M!==m;if(M=m,E&&q.close(),!!F)try{t.onDevToolsPermissionChange?.(m);}catch(ee){n?.(`[gem] onDevToolsPermissionChange threw: ${ee instanceof Error?ee.message:String(ee)}`),queueMicrotask(()=>{throw ee});}},ye=r??dw,zn=r!==void 0,Kt,tt=m=>(n?.(`[gem] token refused: ${m}`),t.onError?.("internal",m),false),bp=(m,E)=>{if(m===void 0)return E!==void 0?tt("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let F=ap(m);return F!==null?tt(`the embedder named an API root that cannot be used: ${F}. Its value is withheld here rather than written to logs.`):Kt!==void 0&&Kt!==m?tt("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."):(Kt=m,zn||(ye=m),true)},wt=window.location?.origin,Mi=null,as=-1/0,vp=2e3,Xn=new Set,_p=m=>Mi!==false?Promise.resolve(true):new Promise(E=>{let F=e.setTimeout(()=>{Xn.delete(ee),E(false);},m),ee=()=>{e.clearTimeout(F),Xn.delete(ee),E(true);};Xn.add(ee);}),Oi=()=>{},Gi=null,Yn=()=>{},Qn=wm(e),Li=vm(e),ss=ou({bridge:{settled:m=>$.settled(m),parentSupports:m=>$.parentSupports(m)},clock:e,forced:a,log:n}),$=new Hn({allowedEmbedders:v,...typeof wt=="string"&&wt!==""?{selfOrigin:wt}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","ticketEvents","clusterTarget","graphicsRoutes","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","rewardPresentation","portraitBorders","earnAllowance","share","shareResult","shareRemap","avatarPicker","vibration","frameStats","walletDisplay","gameMenu","gemCorner","menuStyle","gameSettings","engagement","reservedAreas","p2pRelayDrain","viewport","purchases","purchaseSettled","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges","appLinks","openGame","store","storeOfferSheet",...t.onFeedbackContext!==void 0?["feedbackContext"]:[],...t.onAudioChannels!==void 0?["audioChannels"]:[]],onRefused:m=>{Gi=m,t.onRefused?.(m);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:m=>{se.onBridgeState(m),m!=="connected"&&Qn.abandon(),m!=="connected"&&Li.abandon(),m!=="connected"&&b.setRequested(false),L=null,we=null,te=null,Oe=null,We=null,vt=null,et.forgetSent(),G=void 0,m==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Gi===null?"":` (${Gi})`)+", 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."),Oi()),m==="connected"&&(l.mark("bridge connected"),wp(),H(),Q(),Me(),X(),_t(),Jn(),Vt(),et.flush(),$.unbiddenLaunch&&!c.engaged&&u.hold(),u.startSession(),c.engaged&&$.reportEngaged()),t.onStateChange?.(m);},onPlayer:m=>{R.set(m);for(let E of [...h])E(m);t.onPlayer?.(m);},onPrefs:m=>{let E={reducedMotion:m.reducedMotion,muted:m.muted,locale:m.locale,showFrameStats:m.showFrameStats===true,music:m.music!==false,sounds:m.sounds!==false,recommended:m.recommended===void 0?null:Object.freeze({volume:m.recommended.volume,batterySaver:m.recommended.batterySaver,keyboardLayout:m.recommended.keyboardLayout,gamepadConfirm:m.recommended.gamepadConfirm,vibration:m.recommended.vibration,lookSensitivity:m.recommended.lookSensitivity??100,gamepadLookSensitivity:m.recommended.gamepadLookSensitivity??100,invertLookY:m.recommended.invertLookY??false,touchMovement:m.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:Wm(m.recommended.graphicsQuality,m.recommended.batterySaver),graphicsQualityAuto:m.recommended.graphicsQualityAuto??true,colorHelp:typeof m.recommended.colorHelp=="boolean"?m.recommended.colorHelp:null})};_.set(E),L=E.muted,U?.setMuted(E.muted),b.setRequested(E.showFrameStats&&$.parentSupports("frameStats")),t.onPrefs?.(E),t.onAudioChannels!==void 0&&(D===null||D.music!==E.music||D.sounds!==E.sounds)&&(D=Object.freeze({music:E.music,sounds:E.sounds}),t.onAudioChannels(D));},onCohorts:m=>{let E=Object.freeze(m.cohorts.map(F=>Object.freeze({experimentId:F.experimentId,variantKey:F.variantKey})));T.set(E),t.onCohorts?.(E);},onEarnAllowanceChanged:()=>W.emit(),onViewport:m=>{let E=Object.freeze({insets:Object.freeze({top:m.insets.top,right:m.insets.right,bottom:m.insets.bottom,left:m.insets.left}),reserved:Object.freeze((m.reserved??[]).map(({x:ee,y:As,width:xs,height:Ps,control:Xt})=>Object.freeze(Xt?{x:ee,y:As,width:xs,height:Ps,control:Object.freeze({x:Xt.x,y:Xt.y,width:Xt.width,height:Xt.height})}:{x:ee,y:As,width:xs,height:Ps})))});j.set(E);let F=Su();Ru(F,E.insets),Au(F,E.reserved,ku()),t.onViewport?.(E);},onPause:m=>{m.paused||Yn(),I=m.paused,U?.setPaused?.(m.paused),u.setPaused(m.paused),b.setPaused(m.paused),t.onPause?.(m.paused);},onSettingChange:m=>et.onSettingChange(m),onMenuSelect:m=>{ke===null||m.entry!=="item"||!(Ti(ke.items).items??[]).some(F=>F.id===m.id)||ke.items?.find(F=>F.id===m.id)?.onSelect?.();},onWillTerminate:m=>{u.endSession(m.reason),t.onWillTerminate?.({reason:m.reason,graceMs:m.graceMs});},onToken:m=>{let E=m.garden;if(Z(m.allowDevTools===true),!bp(m.apiBaseUrl,E))return;let F=m;se.onToken(F);let ee=se.identity;ee&&(Di.set(ee),ds||(ds=true,me.reconcileSeats().catch(()=>{}))),cs.push({token:F.token,expiresAt:F.expiresAt});},onTokenDenied:m=>{Z(false),se.onDenied(m);},onScreenshot:(m,E,F)=>{gu(m,E,F,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{fu($,t.onFeedbackContext);},onDevtools:m=>{m==="close"?q.close():m==="open"?q.openFrom("platform").catch(()=>{}):q.isOpen?q.close():q.openFrom("platform").catch(()=>{});},onRoomEvent:m=>me.handleRoomEvent({event:m.event,roomId:m.roomId,...m.matchId===void 0?{}:{matchId:m.matchId},...m.version===void 0?{}:{version:m.version},...m.reason===void 0?{}:{reason:m.reason},...m.platform===void 0?{}:{platform:m.platform}}),onSeatedEvent:m=>me.handleSeated(m.roomId),onAutoStartFailedEvent:m=>me.handleAutoStartFailed(m.roomId,m.code),onTicketEvent:m=>me.handleTicketEvent({event:m.event,ticketId:m.ticketId,...m.partySize===void 0?{}:{partySize:m.partySize},...m.queuedAt===void 0?{}:{queuedAt:m.queuedAt},...m.expiresAt===void 0?{}:{expiresAt:m.expiresAt},...m.reason===void 0?{}:{reason:m.reason},...m.roomId===void 0?{}:{roomId:m.roomId}}),onSocketState:m=>{let E=Mi;if(Mi=m.connected,m.connected)for(let ee of [...Xn])ee();if(!m.connected||E===true)return;let F=e.now();F-as<vp||(as=F,me.reconcile().catch(()=>{}));},onSignalEvent:m=>{let E=typeof m.data=="object"&&m.data!==null&&!Array.isArray(m.data)?m.data:{};rt.handleSignalEvent(m.matchId,m.event,E),m.event==="matchEnded"&&me.reconcile({matchId:m.matchId,...typeof E.reason=="string"?{reason:E.reason}:{}}).catch(()=>{});},onRelayDraining:m=>{rt.handleSignalEvent(m.matchId,"relayDraining",{clusterTargetId:m.clusterTargetId,relayIps:m.relayIps,drainingSince:m.drainingSince,deadline:m.deadline});},onDedicatedEvent:m=>{m.event==="matchEnded"&&(zt.handleMatchEnded(m.matchId,m.reason),me.reconcile({matchId:m.matchId,...m.reason===void 0?{}:{reason:m.reason}}).catch(()=>{})),ls.handleEvent(m);},onClusterTarget:m=>tr.accept(m.clusterTargetId,m.clusterTargetIds),onGraphicsRoutes:m=>ss.accept(m.entries),onLocalServer:m=>nr.accept(m),onLocalServerDenied:m=>nr.refuse(m),onPartyResult:m=>ms.settle(m.requestId,m.partyId),onPurchaseResult:m=>Jt.settle(m),onPurchaseSettled:m=>Jt.settled(m),onShareResult:m=>Li.settle(m),onDeviceSettings:m=>{er.receive(m),t.onDeviceSettings?.(er.api.current);},onDeviceSettingsResult:m=>er.settle(m),onAdResult:m=>gs.settle(m),onMomentResult:m=>fs.settle(m),onSignInResult:m=>{m.outcome==="signed_in"&&Yn(),ys.settle(m);},onFriendChallengeResult:m=>vs.settle(m),onArcadeAnswer:m=>{m.type==="gem.storePurchaseSettled"?bs.settled(m):Rp(m);}}),ls=new Fn({bridge:$}),Di=Kn(e);Oi=()=>{Di.release(),R.release(),T.release();},$.currentState==="refused"&&Oi();let ds=false,$i=new Set,Zn,cs={current:()=>Zn,subscribe:m=>($i.add(m),Zn!==void 0&&m(Zn),()=>$i.delete(m)),push:m=>{Zn=m;for(let E of [...$i])try{E(m);}catch(F){n?.(`[gem] a server-token listener threw: ${F instanceof Error?F.message:String(F)}`);}}},se=Tu({bridge:$,clock:e,onStateChange:(m,E)=>{if(m==="ready"){if(l.mark("token ready")){let F=l.marks.find(ee=>ee.name==="token ready")?.at;u.trackPlatform("gem_boot_ready",F===void 0?{}:{boot_ms:Math.max(0,Math.round(F))});}}else m==="lost"&&(l.mark("token lost"),u.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(m,E);}}),us=()=>{let m=se.identity;return !m||se.source.currentState==="lost"?null:`${m.playerId}\0${m.gameId}\0${m.channel}`},wp=()=>{l.mark("token requested"),se.source.get().catch(()=>{});},ms=sm({bridge:$,clock:e}),St={},Jt=lm({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m),confirm:async m=>St.confirm?.(m)??"unknown",confirmAvatar3d:async m=>St.confirmAvatar3d?.(m)??"unknown",onInventoryStale:()=>St.inventoryStale?.(),onListenerError:m=>t.onError?.("internal",`gem.purchases.onSettled listener threw: ${String(m)}`)}),er=ep({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m)}),ps={},gs=zm({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m),readAvailability:(m,E)=>ps.read?.(m,E)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),fs=Qm({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m)}),ys=fm({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m)}),hs={held:false},Sp=Sm({bridge:$,asker:Qn,acting:hs}),bs=km({bridge:$,asker:Qn,acting:hs,onListenerError:m=>t.onError?.("internal",`gem.store.onSettled listener threw: ${String(m)}`),onPurchaseEnded:()=>Yn()}),Rp=m=>{Qn.settle(m)||t.onError?.("internal",`${m.type} (${m.outcome}) for an unknown requestId: `+JSON.stringify(m.requestId));},vs=Bd({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m)}),tr=Yd({bridge:$,clock:e}),nr=xu({bridge:$,clock:e}),Fi=up(wt),_s=window.fetch,rr=Fi!==null&&typeof _s=="function"?"unread":"read",ir=null,qi=false,kp=m=>{if(rr==="read"||m.source!==window.parent)return false;let E=m.origin;return typeof E!="string"||v.some(F=>xt(F,E))||hr(E,typeof wt=="string"?wt:void 0)?false:((ir===null||!qi)&&(ir=m),rr==="unread"&&Fi!==null&&(rr="reading",cp({fetch:(F,ee)=>_s.call(window,F,ee),selfOrigin:Fi,clock:e}).then(F=>{"refused"in F&&n?.(F.refused),F.origins.length>0&&ip($,F.origins),rr="read";let ee=ir;ir=null,ee!==null&&$.currentState==="waiting"&&or(ee);})),true)},or=m=>{if(kp(m))return false;let E=$.handleWindowMessage({data:m.data,origin:m.origin,source:m.source,ports:m.ports});return E&&window.removeEventListener("message",or),E};window.addEventListener("message",or),qi=true;let nt;try{nt=Is(window,or);}finally{qi=false;}let Ap=nt?.capture,Ni=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Ni?.domInteractive!==void 0&&Ni.domInteractive>0&&l.mark("document parsed",Ni.domInteractive),Ap?.late&&n?.("[gem] the early-handshake capture installed after this document finished loading, so a handshake posted at iframe load may already have been missed. Load the capture script ahead of everything else in the document.");let ji=t.handshakeWarningMs;ji!==null&&n&&e.setTimeout(()=>{let m=nt===null?"no capture script ran":`capture: ${nt.delivered} offer(s) delivered, ${nt.stale} stale, ${nt.capture.dropped} evicted${nt.capture.late?", installed late":""}`;if($.currentState==="connected"){n(`[gem] handshake connected. boot: ${l.timeline()} \xB7 ${m}`);return}n(`[gem] no completed handshake after ${ji??gp}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: ${l.timeline()} \xB7 `+m);},ji??gp);let xp=Ar({get baseUrl(){return ye},tokenSource:se.source,get defaultQuery(){let m=se.identity;return m?{game_id:m.gameId,channel:m.channel}:{}}}),Rt=new He({transport:xp,clock:e}),he={client:Rt,gameId:()=>se.identity?.gameId??""};St.confirm=m=>dm(he,m),St.confirmAvatar3d=m=>pm(he,m),ps.read=(m,E)=>Ul(he,"players","me",m,{signal:E});let Pp=()=>se.identity?.channel??"release",ar=new Lr(he,Pp),Ep=mm({player:()=>R.current,subscribe:m=>(h.add(m),()=>{h.delete(m);}),configFamilies:async()=>(await ar.load())?.avatar_3d_families,readOffers:()=>gm(he),purchase:m=>Jt.requestAvatar3d(m),log:t.log}),ws=async m=>(await ar.load())?.currency(m)?.id??void 0,Ss=bd(he,lo,{identity:us,resolveCurrencyId:ws,watch:{clock:e,log:t.log},handOffRefusedPurchase:m=>Jt.handOffRefused(m)}),Bi=Ss.scope;St.inventoryStale=()=>Bi.inventory.refresh(),Yn=Ss.recheckPasses;let sr=async m=>{let E=await Di.wait(m);if(E)return E;throw $.currentState==="refused"?new re("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new re("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},Ui=g(t.autoReconnect),me=Ec(s===void 0?{}:{playWithTicket:s},{client:Rt,clock:e,gameId:()=>se.identity?.gameId??null,playerId:()=>se.identity?.playerId??null,awaitGameId:async()=>(await sr(Ci)).gameId,resolveParty:ms.resolve,resolveClusterTargets:tr.resolveList,refreshClusterTargets:tr.refresh,ensureLocalServer:nr.ensure,localHostAvailable:nr.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>se.gameVersion,...t.pollRooms===void 0?{}:{poll:t.pollRooms},...t.recoverStaleMembership===void 0?{}:{recoverStaleMembership:t.recoverStaleMembership},...t.retryAutoStart===void 0?{}:{retryAutoStart:t.retryAutoStart},...t.watchSeats===void 0?{}:{watchSeats:t.watchSeats},...t.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:t.seatPollIntervalMs},...Ui===null?{}:{autoReconnect:{...Ui,redial:(m,E)=>Wi.redialMatch(m,E),abandon:(m,E)=>Wi.abandonMatch(m,E)}}});p(me),Yc({analytics:u,rooms:me}),Zc({analytics:u});let rt=Xc({client:Rt,clock:e,rooms:me,bridge:$,gameId:()=>se.identity?.gameId??"",baseUrl:()=>ye,resolveClusterTargets:tr.resolveList,boot:l,...t.log===void 0?{}:{log:t.log}}),Rs=fa(l,n),zt=Vu({client:Rt,clock:e,rooms:me,signaling:()=>ls.channel(),signalingReady:_p,log:n??(()=>{})}),Wi=om({rooms:me,p2p:{connect:m=>Rs(rt.connect(m)),session:m=>rt.session(m)},dedicated:{connect:(m=>mi(l,"welcome",zt.connect(m),n))},clock:e,identity:()=>se.identity,apiBaseUrl:()=>ye,tokens:cs,room:()=>me.currentRoom,autoReconnect:Ui!==null,...t.log===void 0?{}:{log:t.log}}),Tp=async()=>(await sr(Ci)).playerId,ks={client:Rt,boot:l,get identity(){return se.identity},awaitIdentity:(m=Ci)=>sr(m),awaitBridge:m=>$.settled(m),get player(){return R.current},awaitPlayer:(m=yw)=>R.wait(m),me:Bi,characters:new Cr(he,void 0,us,ws),transfers:new Or(he,lo,Bi.inventory),gameConfig:ar,purchases:Jt.api,deviceSettings:er.api,graphics:ss.api,moments:fs.api,ads:gs.api,account:ys.api,share:_m({frame:$,log:t.log,answers:Li}),arcade:Sp,store:bs.api,branding:Cm({fetch:typeof window.fetch=="function"?(m,E)=>window.fetch.call(window,m,E):null,clock:e,devicePixelRatio:()=>window.devicePixelRatio??1,log:n}),vibration:Mm({frame:$,log:t.log}),get avatarPickerAvailable(){return $.currentState==="connected"&&$.parentSupports("avatarPicker")},openAvatarPicker:m=>$.requestAvatarPicker(m?.tab),avatars3d:Ep,settings:et.api,controls:Dm({recommended:()=>_.current?.recommended??null}),analytics:u,leaderboards:new dn(he),challenges:new an(he),showcase:new cn(he,Tp),friends:new un(he,{challenge:vs.challenge,...o===void 0?{}:{launchedChallengeId:o}}),platform:new pn(he,W,n),profiles:new gn(he),functions:new ze((m,E)=>Tl(he,m,E)),get prefs(){return _.current},get paused(){return I},get cohorts(){return T.current},get viewport(){return j.current},awaitCohorts:(m=hw)=>T.wait(m),reportMuted:m=>{C=!!m,H();},showPortraitBorders:m=>{let E=Ei(m);E!==void 0&&(x=E,Q());},cueReward:m=>(Br(m.cueId,"cueReward"),$.cueReward(m)),setWalletVisible:(m,E)=>{let F=Array.isArray(E?.only)?[...E.only]:void 0;return Pe=F===void 0?{visible:m===true}:{visible:m===true,only:F},Me()},setMenu:m=>(ke=Array.isArray(m?.items)?{items:m.items.map(E=>({...E}))}:{},X()),setGemCorner:m=>{if(!cw.includes(m)){let E=typeof m=="string"?JSON.stringify(m.slice(0,48)):`a value of type ${typeof m}`;return console.warn(`[gem] setGemCorner: ${E} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return ae=m,_t()},setRewardPresentation:m=>{if(!uw.includes(m)){let E=typeof m=="string"?JSON.stringify(m.slice(0,48)):`a value of type ${typeof m}`;return console.warn(`[gem] setRewardPresentation: ${E} is not a presentation, so nothing was sent. Pass 'game' or 'arcade'.`),false}return Ee=m,Jn()},setMenuStyle:m=>{let E=mw(m);return E===void 0?false:(bt=E,Vt())},reportFrame:()=>b.draw(),exit:m=>bw(me,$,m,u),frame:$,devtools:q,rooms:me,dedicatedServer:{listClusterTargets:m=>zt.listClusterTargets(m),connect:(m=>mi(l,"welcome",zt.connect(m),n)),handleMatchEnded:(m,E)=>zt.handleMatchEnded(m,E)},p2p:{handleSignalEvent:(m,E,F)=>rt.handleSignalEvent(m,E,F),session:m=>rt.session(m),connect:m=>Rs(rt.connect(m))},match:Wi};return ks}var fp="the match has not started yet: the runtime hands over the host at `init`, and this was read before that. Read it from `init` or later \u2014 a bundle that needs a value at module scope is reading it one call too early.";function os(t,e={}){let n=e.clock??ce,r=()=>{let a=t();if(a===null)throw new Error(fp);return a},i=null,o=()=>{if(i===null)throw new Error(fp);return i};return {server:{get identity(){return o().identity},get client(){return o().client},get api(){return o().api},get match(){return o().match},get analytics(){return o().analytics},get functions(){return o().functions},get challenges(){return o().challenges},get room(){return o().room},dispose(){i?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(a){let d=r().profile?.(a);if(!d)return null;let u=d.displayName;return typeof u!="string"||u===""?null:{displayName:be(u,"profile.displayName"),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:be(d.displayTag,"profile.displayTag")}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(a){return r().playerNumber?.(a)},send(a,l,d){d===void 0?r().send(a,l):r().send(a,l,d);},broadcast(a,l){l===void 0?r().broadcast(a):r().broadcast(a,l);},kick(a,l){l===void 0?r().kick(a):r().kick(a,l);},log(a){r().log(a);},warn(a){r().warn(a);}},attach:()=>{i=Ut(r(),{...e,clock:n});}}}function yp(t,e={}){let{server:n,attach:r}=os(()=>t,e);return r(),n}function vw(t){if(t===void 0||typeof t.reason!="string"||t.reason==="")return;let e=t.platform_reason??t.endedReason;return {reason:t.reason,...e===void 0?{}:{endedReason:Xe(e)}}}var _w=1e4;function ww(t){let e=false;return n=>{if(e)return;let r;try{r=t.match.reportPlayers([{playerId:n,state:"connected"}],AbortSignal.timeout(_w));}catch{return}r.catch(i=>{i instanceof O&&i.status>=400&&i.status<500&&(e=i.status!==429);});}}function hp(t,e={}){return ()=>{let n=null,{server:r,attach:i}=os(()=>n,e),o=t(r),s={async init(l){n=l,i(),await o.init?.();},async shutdown(l){let d=vw(l);try{await o.shutdown?.(d);}finally{r.dispose();}}},a=ww(r);return s.join=(l,d)=>(a(l),o.join?.(l,d)),o.leave&&(s.leave=(l,d)=>o.leave?.(l,d)),o.message&&(s.message=(l,d,u,c)=>o.message?.(l,d,u,c)),s}}Ts();
|
|
3
|
+
exports.ARCADE_EMBEDDERS=lw;exports.AVATAR_RIGS=aw;exports.AnalyticsApi=yn;exports.AuthError=re;exports.CONDITIONAL_HEADERS=lr;exports.ChallengesApi=an;exports.DEVICE_SETTINGS_MAX_BYTES=ts;exports.DedicatedServerError=A;exports.FriendChallengeError=lt;exports.FriendsApi=un;exports.FunctionsApi=ze;exports.GemApiError=O;exports.GemClient=He;exports.GemConfigError=pe;exports.GemFrame=Hn;exports.GemFunctionError=fn;exports.GemSaveError=oe;exports.GemUnframedError=Wn;exports.LeaderboardsApi=dn;exports.MAX_PERIODS_BACK=xd;exports.PLATFORM_EVENTS=Mf;exports.PlatformApi=pn;exports.PlatformCurrenciesApi=Nr;exports.PlatformEarnAllowanceApi=jr;exports.PlayerText=ve;exports.ProfilesApi=gn;exports.PurchaseRefusal=Je;exports.ShareRefusal=Si;exports.ShowcaseApi=cn;exports.TransportRefusal=de;exports.UNRELIABLE_CHANNEL_LABEL=_n;exports.asPlayerText=be;exports.createBootTimeline=ya;exports.createGem=QI;exports.createGemServer=Ut;exports.createHostTokenSource=zu;exports.createMatchServer=yp;exports.defineServer=hp;exports.experimentSelection=Wr;exports.leaveAndExit=bw;exports.mapIdentity=Te;exports.markOnResolve=mi;exports.platformIconUrl=mo;exports.presentJoinCredential=bn;exports.readTemplateTransports=Gt;exports.readTransportAdvert=wn;exports.reportOnResolve=fa;exports.systemClock=ce;exports.text=ot;exports.toBase64=dr;exports.webTransportAvailable=Zr;return exports;})({});
|