@indiegems/gem-web-sdk 7.7.0 → 7.8.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/dist/game.d.ts +2 -0
- package/dist/gem-web-sdk.esm.js +2 -2
- package/dist/gem-web-sdk.function.js +1 -1
- package/dist/gem-web-sdk.game.js +2 -2
- package/dist/gem-web-sdk.min.js +2 -2
- package/dist/gem-web-sdk.sdk.js +2 -2
- package/dist/gem-web-sdk.server.js +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/sdk.d.ts +2 -0
- package/docs/api/api-reference-game.md +38 -1
- package/docs/api/api-reference-server.md +1 -1
- package/docs/api/reference.json +35 -1
- package/docs/dedicated-server-flow.md +23 -14
- package/docs/getting-started.md +1 -1
- package/docs/manifest.json +8 -8
- package/docs/server-bundles.md +2 -2
- package/docs/what-a-game-must-do.md +44 -21
- package/package.json +1 -1
package/dist/gem-web-sdk.sdk.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var wd=Object.defineProperty;var Sd=(t,e)=>{for(var n in e)wd(t,n,{get:e[n],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:7.7.0]";function hi(){let t=globalThis.__gemWebSdkVersion;if(typeof t!="string")return "";let e=t.lastIndexOf(":"),n=t.lastIndexOf("]");return e<0||n<=e+1?"":t.slice(e+1,n)}function Rd(t,e){return e!==void 0?!e:t==="chain_exhausted"}var on=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new ie(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.grant&&e>=this.grant.chainEndsAt)throw this.enter("lost","chain_exhausted"),new ie("chain_exhausted","the token chain reached its ceiling");return this.refresh(this.nextReason())}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}refresh(e){if(this.inFlight)return this.inFlight;let n=this.generation;this.enter("pending");let r=this.options.request(e).then(o=>{if(n!==this.generation)throw new ie("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=kd(o),a=o?.retryable;throw n===this.generation&&this.enter(Rd(i,typeof a=="boolean"?a:void 0)?"lost":"degraded",i),o instanceof ie?o:new ie(i,String(o))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){this.failure=n??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,n));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},ie=class t extends Error{constructor(n,r){super(`auth ${n}: ${r}`);this.reason=n;this.name="AuthError";}reason;static isAuthError(n){if(n instanceof t)return true;let r=n;return r?.name==="AuthError"&&typeof r.reason=="string"}};function kd(t){if(t instanceof ie)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var oe=class t extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof t)return true;let n=e;return n?.name==="TransportRefusal"&&n.retryable===false}},mt=["if-match","if-none-match"],bi=4096;function xd(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();if(!mt.includes(o)||r===void 0)continue;let i=typeof r=="string"?Ad(r):r;if(typeof i!="string"||i.length>bi||!Pd(i))throw new oe(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${bi} characters, or contains a character outside the range an HTTP header value may carry. This is a malformed request, not a server failure; the value is withheld here rather than written to logs.`);i!==""&&(e[o]=i);}return Object.freeze(e)}function Ad(t){let e=o=>o===32||o===9||o===10||o===13,n=0,r=t.length;for(;n<r&&e(t.charCodeAt(n));)n++;for(;r>n&&e(t.charCodeAt(r-1));)r--;return t.slice(n,r)}function Pd(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 Ed(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new oe("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new oe("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function vi(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=xd(o.headers),a=Ed(o),s=Object.freeze({...o,headers:i,...a===void 0?{}:{bytes:a}}),l=await e.tokenSource.get(),d=await t(s,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),c=await t(s,m);if(c.status===401)throw e.tokenSource.close("unavailable"),new ie("unavailable","the server refused a freshly minted token");return c}}}function pt(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Td(e))}function gt(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 wr(t){return new TextDecoder().decode(gt(t))}function Td(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var G=class extends Error{constructor(n,r,o,i,a){super(`${n} (${r}): ${o}`);this.reason=n;this.status=r;this.detail=o;this.retryAfterSeconds=i;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},wi=new WeakMap;function Si(t){return wi.get(t)??{}}var Id=new Set([408,429,500,502,503,504]),Cd=6e4;function Md(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new oe(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(t)}. This is a configuration fault, not a server failure.`);return t}var Le=class{constructor(e){this.options=e;}options;async get(e,n){return this.send({method:"GET",path:e,signal:n},true)}async getWithEtag(e,n={}){let r=await this.sendRaw({method:"GET",path:e,...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{headers:{"if-none-match":n.ifNoneMatch}}},true),o=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...o}:{modified:true,body:r.body,...o}}async put(e,n,r,o={}){return this.send({method:"PUT",path:e,body:n,signal:r,...kn(o)},o.replaySafe===true)}async post(e,n,r,o={}){return this.send({method:"POST",path:e,body:n,signal:r,...kn(o)},o.replaySafe===true)}async postBytes(e,n,r,o={}){let i=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...kn(o)},o.replaySafe===true);return {bytes:Od(i.body),...i.invocationId===void 0?{}:{invocationId:i.invocationId}}}async patch(e,n,r,o={}){return this.send({method:"PATCH",path:e,body:n,signal:r,...kn(o)},o.replaySafe===true)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...kn(r)},r.replaySafe===true)}async send(e,n){return (await this.sendRaw(e,n)).body}async sendRaw(e,n){let r=n?Md(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw _i(e.signal);for(let i=0;i<r;i++){if(i>0&&await this.backoff(i,o,e.signal),e.signal?.aborted)throw _i(e.signal);let a;try{a=await this.options.transport.request(e);}catch(l){if(ie.isAuthError(l)||oe.isRefusal(l)||e.signal?.aborted||Ld(l))throw l;o=new G("unavailable",0,String(l));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let s=Gd(a);if(!Id.has(a.status))throw s;o=s;}throw o??new G("unavailable",0,"no attempt was made")}backoff(e,n,r){if(r?.aborted)return Promise.resolve();let o=n?.retryAfterSeconds,i=o!==void 0?o*1e3:2**(e-1)*250,a=2**(e-1)*250,s=Math.min(Math.max(i,a),Cd);return new Promise(l=>{let d=this.options.clock,m=false,c=false,p,g=()=>{m||(m=true,c&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,s),c=true,m&&d.clearTimeout(p);})}};function Od(t){if(t instanceof Uint8Array)return t;if(t==null)return new Uint8Array(0);let e=typeof t=="string"?t:JSON.stringify(t);return new TextEncoder().encode(e)}function kn(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function _i(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Ld(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function Gd(t){let e=$d(t),n=jd(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&wi.set(e,r),e}var Dd=new Map([["insufficient_funds","insufficient_funds"]]);function $d(t){let{status:e,body:n}=t,r=Fd(n),o=t.retryAfterSeconds??Nd(n),i=qd(n),a=i===void 0?void 0:Dd.get(i);if(a!==void 0)return new G(a,e,r,void 0,i);switch(e){case 304:return new G("not_modified",e,r);case 400:case 422:return new G("invalid",e,r,void 0,i);case 403:return new G("forbidden",e,r,void 0,i);case 404:return new G("not_found",e,r,void 0,i);case 402:return new G("insufficient_funds",e,r,void 0,i);case 409:return new G("conflict",e,r,void 0,i);case 412:return new G("precondition_failed",e,r,void 0,i);case 413:return new G("too_large",e,r,void 0,i);case 429:return new G("rate_limited",e,r,o,i);default:return new G("unavailable",e,r,o,i)}}function Fd(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 jd(t){let n=t?.error?.details;return n===null?void 0:n}function qd(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Nd(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function v(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function Ri(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function ki(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/add`;return t.client.post(a,o,i?.signal)}async function xi(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Ai(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/claim`;return t.client.post(a,o,i?.signal)}async function Pi(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function Ei(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ti(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ii(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Ci(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Mi(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(o,r?.signal)}async function Oi(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Li(t,e,n,r,o,i){let a=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/finalize`;return t.client.post(a,o,i?.signal)}async function Gi(t,e,n){let r=`/v1/games/${v(t.gameId())}/config/channels/${v(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Di(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.get(r,n?.signal)}async function $i(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Fi(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function ji(t,e,n,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function qi(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/items/${v(r)}`;return t.client.get(i,o?.signal)}async function Ni(t,e,n,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let a=i.toString(),s=`/v1/leaderboards/${v(e)}/${v(n)}/${v(r)}`+(a?`?${a}`:"");return t.client.get(s,o?.signal)}async function Ui(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/${v(r)}`;return t.client.get(i,o?.signal)}async function Bi(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}`;return t.client.get(i,o?.signal)}async function Hi(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/catalogs/${v(r)}/recipes/${v(o)}/availability`;return t.client.get(a,i?.signal)}async function Vi(t,e,n,r){let o=new URLSearchParams;o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Sr(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Wi(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${v(e)}/friends`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Ki(t,e,n){let r=`/v1/showcase/friends/${v(e)}`;return t.client.get(r,n?.signal)}async function Ji(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${v(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function zi(t,e){let n=`/v1/games/${v(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function yt(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function Yi(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function Xi(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Qi(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${v(e)}`;return t.client.get(r,n?.signal)}async function Zi(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function es(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function ns(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function ts(t,e,n){let r=`/v1/games/${v(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{...n?.keepalive===void 0?{}:{keepalive:n.keepalive},replaySafe:true})}async function rs(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function os(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/platform-funded-game-inventory-purchases`;return t.client.post(i,r,o?.signal)}async function is(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function ss(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),o="/v1/challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function as(t,e){return t.client.get("/v1/characters",e?.signal)}async function ls(t,e,n,r){let o=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function ds(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(n)}/orders`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function cs(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${v(e)}/${v(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function us(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o="/v1/friends"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function ms(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function ps(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/matches/${v(e)}/end`;return t.client.post(o,n,r?.signal)}async function gs(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/max`;return t.client.post(a,o,i?.signal)}async function ys(t,e,n,r,o,i){let a=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function fs(t,e,n,r,o){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(i,r,o?.signal)}async function hs(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function bs(t,e,n,r){let o=`/v1/characters/${v(e)}`;return t.client.patch(o,n,r?.signal)}async function vs(t,e,n,r,o,i){let a=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/upload-url`;return t.client.post(a,o,i?.signal,{replaySafe:true})}async function _s(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/reset`;return t.client.post(a,o,i?.signal)}async function ws(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.delete(r,n?.signal)}var K="gem-web-bridge",ht={min:1,max:1},sn=65536,Ss=8,ft=5e3,Rs=1024;function kr(t){return Object.freeze(Object.assign(Object.create(null),t))}var ks=kr({"gem.handshake":30,"gem.handshake.accept":5,"gem.token":30,"gem.token.denied":30,"gem.player":12,"gem.pause":120,"gem.prefs":60,"gem.cohorts":12,"gem.earnAllowanceChanged":30,"gem.viewport":60,"gem.deviceSettings":12,"gem.willTerminate":10,"gem.roomEvent":120,"gem.socketState":12,"gem.seatedEvent":60,"gem.autoStartFailedEvent":30,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.engaged":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.walletDisplay":60,"gem.requestShare":6,"gem.frameStats":120,"gem.error":60,"gem.requestPurchase":12,"gem.purchaseResult":30,"gem.deviceSettings.put":30,"gem.deviceSettings.result":30,"gem.requestAd":6,"gem.adResult":12,"gem.requestSignIn":6,"gem.signInResult":12,"gem.requestFriendChallenge":12,"gem.friendChallengeResult":30,__malformed:60}),bt="__malformed";var Ud=kr({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.requestFriendChallenge":"friendChallenges","gem.friendChallengeResult":"friendChallenges","gem.devtools":"devtools","gem.screenshot":"screenshot","gem.screenshot.denied":"screenshot","gem.requestContext":"feedbackContext","gem.gameContext":"feedbackContext","gem.roomEvent":"rooms","gem.signal":"p2p","gem.signalEvent":"p2p","gem.dedicatedOffer":"dedicated","gem.dedicatedEvent":"dedicated","gem.clusterTarget":"clusterTarget","gem.partyRequest":"parties","gem.partyResult":"parties","gem.autoStartFailedEvent":"autoStartFailure","gem.seatedEvent":"partySeating","gem.socketState":"socketState","gem.audioState":"audioState","gem.rewardCue":"rewardCue","gem.frameStats":"frameStats","gem.engaged":"engagement","gem.viewport":"viewport","gem.walletDisplay":"walletDisplay","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.earnAllowanceChanged":"earnAllowance","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings","gem.requestShare":"share"}),Bd=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.viewport.","reservedAreas"]]);function xs(t){let e=Ud[t];if(e!==void 0)return e;for(let[n,r]of Bd)if(t.startsWith(n))return r}function xr(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 Hd(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 Vd(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function Wd(t){return /^[a-z_]+$/.test(t)}function Rr(t,e,n){if(e>Ss)return `nesting deeper than ${Ss}`;if(++n.nodes>ft)return `more than ${ft} values`;if(n.bytes>sn)return `over the ${sn} byte limit`;if(t==null)return n.bytes+=4,null;let r=typeof t;if(r==="boolean")return n.bytes+=5,null;if(r==="number")return n.bytes+=8,null;if(r==="string")return n.bytes+=t.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let o=t;if(n.seen.has(o))return "a repeated or cyclic object reference";if(n.seen.add(o),Array.isArray(t)){if(t.length>Rs)return `an array of ${t.length} entries, over the ${Rs} limit`;n.bytes+=2;for(let s of t){let l=Rr(s,e+1,n);if(l)return l}return null}let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)return "a value that is not a plain object";n.bytes+=2;let a=t;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++n.nodes>ft)return `more than ${ft} values`;if(n.bytes+=s.length*3+4,n.bytes>sn)return `over the ${sn} byte limit`;let l=Rr(a[s],e+1,n);if(l)return l}return null}function Kd(t){let e={nodes:0,bytes:0,seen:new Set},n=Rr(t,0,e);return n?`message contains ${n}`:e.bytes>sn?`message is over the ${sn} byte limit`:null}var Jd={origin:[xr,"not a well-formed origin"],url:[Hd,"not a safe absolute http(s) URL"],bcp47:[Vd,"not a well-formed BCP 47 tag"],code:[Wd,"not a code of lower-case letters and underscores"]};function As(t,e,n){for(let r of e){let o=n===""?r.n:`${n}.${r.n}`,i=t[r.n];if(i==null){if(r.o)continue;return `${o}: required`}let a=Ps(i,r,o);if(a)return a}return null}function Ps(t,e,n){switch(e.k){case "string":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e.max)return `${n}: exceeds ${e.max} characters`;if(e.f){let[r,o]=Jd[e.f];if(!r(t))return `${n}: ${o}`}return null}case "int":return typeof t!="number"||!Number.isInteger(t)?`${n}: expected integer`:t<e.lo||t>e.hi?`${n}: out of range ${e.lo}..${e.hi}`:null;case "boolean":return typeof t=="boolean"?null:`${n}: expected boolean`;case "enum":{let r=e.v;return r.includes(t)?null:`${n}: not one of ${r.join("|")}`}case "object":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:As(t,e.fs,n);case "json":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "array":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e.max)return `${n}: exceeds ${e.max} items`;let r=e.it,o=`${n}[]`;for(let i of t){if(i==null){if(r.o)continue;return `${o}: required`}let a=Ps(i,r,o);if(a)return a}return null}default:{let r=e.k;return `${n}: unknown kind ${String(r)}`}}}function I(t,e){return n=>{let r=Kd(n);if(r)return r;if(typeof n!="object"||n===null||Array.isArray(n))return "message: expected object";let o=n;return o.gem!==K?"gem: wrong protocol marker":o.type!==t?`type: expected ${t}`:As(o,e,"")}}var zd=I("gem.handshake",[{n:"versions",k:"object",fs:[{n:"min",k:"int",lo:1,hi:1e3},{n:"max",k:"int",lo:1,hi:1e3}]},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}},{n:"embedder",k:"string",max:2048,f:"origin"},{n:"unbidden",k:"boolean",o:1}]),Yd=I("gem.handshake.accept",[{n:"v",k:"int",lo:1,hi:1e3},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}}]),Xd=I("gem.token",[{n:"token",k:"string",max:4096},{n:"requestId",k:"string",o:1,max:64},{n:"generation",k:"int",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"string",o:1,max:512,f:"url"},{n:"playerId",k:"string",max:64},{n:"gameId",k:"string",max:64},{n:"channel",k:"enum",v:["dev","test","release"]},{n:"gameVersion",k:"string",o:1,max:64},{n:"expiresAt",k:"int",lo:0,hi:4102444800},{n:"chainEndsAt",k:"int",lo:0,hi:4102444800},{n:"allowDevTools",k:"boolean",o:1}]),Qd=I("gem.token.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:36e5},{n:"reason",k:"enum",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"string",max:64}]),Zd=I("gem.player",[{n:"untrusted",k:"object",fs:[{n:"displayName",k:"string",max:64},{n:"displayTag",k:"string",o:1,max:80},{n:"displayHandle",k:"string",max:80}]},{n:"playerId",k:"string",o:1,max:64},{n:"discriminator",k:"string",o:1,max:8},{n:"avatarIconUrl",k:"string",o:1,max:2048,f:"url"},{n:"badges",k:"array",o:1,max:2,it:{n:"",k:"object",fs:[{n:"itemId",k:"string",max:64},{n:"iconUrl",k:"string",max:2048,f:"url"}]}},{n:"displayTag",k:"string",max:8},{n:"avatarUrl",k:"string",o:1,max:2048,f:"url"},{n:"boost",k:"object",o:1,fs:[{n:"multipliers",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"currencyId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"multiplierBp",k:"int",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"int",o:1,lo:1,hi:7}]}]),ec=I("gem.pause",[{n:"paused",k:"boolean"}]),nc=I("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),tc=I("gem.cohorts",[{n:"cohorts",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"experimentId",k:"string",max:36},{n:"variantKey",k:"string",max:32}]}}]),rc=I("gem.earnAllowanceChanged",[]),oc=I("gem.viewport",[{n:"insets",k:"object",fs:[{n:"top",k:"int",lo:0,hi:4096},{n:"right",k:"int",lo:0,hi:4096},{n:"bottom",k:"int",lo:0,hi:4096},{n:"left",k:"int",lo:0,hi:4096}]},{n:"reserved",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384},{n:"width",k:"int",lo:0,hi:16384},{n:"height",k:"int",lo:0,hi:16384}]}}]),ic=I("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),sc=I("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),ac=I("gem.roomEvent",[{n:"event",k:"enum",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"string",max:64},{n:"matchId",k:"string",o:1,max:64},{n:"version",k:"int",o:1,lo:0,hi:2147483647},{n:"reason",k:"string",o:1,max:64},{n:"platform",k:"enum",o:1,v:["universal","mobile"]}]),lc=I("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),dc=I("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),cc=I("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),uc=I("gem.signalEvent",[{n:"event",k:"enum",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),mc=I("gem.dedicatedEvent",[{n:"event",k:"enum",v:["answer","error","matchEnded"]},{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",o:1,max:10240},{n:"sessionId",k:"string",o:1,max:64},{n:"code",k:"string",o:1,max:64},{n:"message",k:"string",o:1,max:256},{n:"reason",k:"string",o:1,max:64}]),pc=I("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),gc=I("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),yc=I("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),fc=I("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),hc=I("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),bc=I("gem.requestContext",[]),vc=I("gem.gameContext",[{n:"context",k:"json"}]),_c=I("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),wc=I("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),Sc=I("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),Rc=I("gem.ready",[]),kc=I("gem.engaged",[]),xc=I("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Ac=I("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),Pc=I("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),Ec=I("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),Tc=I("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),Ic=I("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),Cc=I("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),Mc=I("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),Oc=I("gem.audioState",[{n:"muted",k:"boolean"}]),Lc=I("gem.rewardCue",[{n:"currencySlug",k:"string",max:32},{n:"expected",k:"int",o:1,lo:1,hi:1e9},{n:"origin",k:"object",o:1,fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384}]}]),Gc=I("gem.walletDisplay",[{n:"visible",k:"boolean"},{n:"currencies",k:"array",o:1,max:8,it:{n:"",k:"string",max:64}},{n:"score",k:"boolean",o:1}]),Dc=I("gem.requestShare",[{n:"params",k:"array",max:16,it:{n:"",k:"object",fs:[{n:"key",k:"string",max:64},{n:"value",k:"string",max:512}]}}]),$c=I("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),Fc=I("gem.error",[{n:"code",k:"enum",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"string",o:1,max:256}]),jc=I("gem.requestPurchase",[{n:"requestId",k:"string",max:64},{n:"purchaseKind",k:"enum",v:["item","recipe"]},{n:"targetId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"quantity",k:"int",o:1,lo:1,hi:10},{n:"catalogId",k:"string",o:1,max:64}]),qc=I("gem.purchaseResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["ok","declined","unavailable"]},{n:"reason",k:"string",o:1,max:64,f:"code"},{n:"purchaseId",k:"string",o:1,max:64}]),Nc=I("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),Uc=I("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),Bc=I("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),Hc=I("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),Vc=I("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),Wc=I("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),Kc=I("gem.requestFriendChallenge",[{n:"requestId",k:"string",max:64},{n:"playerId",k:"string",max:64},{n:"template",k:"string",max:64},{n:"params",k:"json",o:1}]),Jc=I("gem.friendChallengeResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"string",o:1,max:64},{n:"param",k:"string",o:1,max:64},{n:"channel",k:"string",o:1,max:16},{n:"configVersion",k:"int",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:864e5},{n:"detail",k:"string",o:1,max:300}]),vt=kr({"gem.handshake":zd,"gem.handshake.accept":Yd,"gem.token":Xd,"gem.token.denied":Qd,"gem.player":Zd,"gem.pause":ec,"gem.prefs":nc,"gem.cohorts":tc,"gem.earnAllowanceChanged":rc,"gem.viewport":oc,"gem.deviceSettings":ic,"gem.willTerminate":sc,"gem.roomEvent":ac,"gem.socketState":lc,"gem.seatedEvent":dc,"gem.autoStartFailedEvent":cc,"gem.signalEvent":uc,"gem.dedicatedEvent":mc,"gem.partyResult":pc,"gem.clusterTarget":gc,"gem.devtools":yc,"gem.screenshot":fc,"gem.screenshot.denied":hc,"gem.requestContext":bc,"gem.gameContext":vc,"gem.signal":_c,"gem.dedicatedOffer":wc,"gem.partyRequest":Sc,"gem.ready":Rc,"gem.engaged":kc,"gem.progress":xc,"gem.requestToken":Ac,"gem.requestLocalServer":Pc,"gem.localServer":Ec,"gem.localServer.denied":Tc,"gem.exit":Ic,"gem.openExternal":Cc,"gem.requestFullscreen":Mc,"gem.audioState":Oc,"gem.rewardCue":Lc,"gem.walletDisplay":Gc,"gem.requestShare":Dc,"gem.frameStats":$c,"gem.error":Fc,"gem.requestPurchase":jc,"gem.purchaseResult":qc,"gem.deviceSettings.put":Nc,"gem.deviceSettings.result":Uc,"gem.requestAd":Bc,"gem.adResult":Hc,"gem.requestSignIn":Vc,"gem.signInResult":Wc,"gem.requestFriendChallenge":Kc,"gem.friendChallengeResult":Jc});var le={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},xn=class{constructor(e=le){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=ks[e];if(n===void 0)return false;let r=this.clock.now(),o=this.lastRefill.get(e)??r,i=this.tokens.get(e)??n,a=Math.max(0,r-o),s=Math.min(n,i+a*n/6e4);return s<1?(this.tokens.set(e,s),this.lastRefill.set(e,r),false):(this.tokens.set(e,s-1),this.lastRefill.set(e,r),true)}};function Ar(t,e){return t.toLowerCase()===e.toLowerCase()}function _t(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Es(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:_t(n.hostname)&&_t(r.hostname)}function Ts(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 wt=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,n={}){let o=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,i=o.find(s=>s.currencyId===e),a;return !i&&this.resolveCurrencyId&&(a=await this.resolveCurrencyId(e).catch(()=>{}),a!==void 0&&(i=o.find(s=>s.currencyId===a))),{currencyId:i?i.currencyId:a??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function Er(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let o=r??{};typeof o.id!="string"||o.id===""||typeof o.threshold!="number"||!Number.isFinite(o.threshold)||n.push({id:o.id,threshold:o.threshold,points:typeof o.points=="number"?o.points:0,hidden:o.hidden===true,...typeof o.unlocked_at=="number"&&Number.isFinite(o.unlocked_at)?{unlockedAt:o.unlocked_at}:{},...o.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var Is="inventory",an=t=>typeof t=="number"?t:0,An=t=>typeof t=="string"?t:"";function Pr(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 Cs(t){let e=t??{};return {itemDefinitionId:An(e.item_definition_id),instanceId:An(e.instance_id),quantity:an(e.quantity),acquiredAt:an(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function zc(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Pr(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(a=>{let s=a??{};return {bucket:An(s.bucket),balance:an(s.balance)}}):void 0;return {currencyId:An(o.currency_id),total:an(o.total),...i===void 0?{}:{buckets:i}}}),items:Pr(e.items,Cs),progressions:Pr(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:An(o.progression_definition_id),currentValue:an(o.current_value),completionCount:an(o.completion_count),isCompleted:o.is_completed===true,...Er(o)}}),...n===void 0?{}:{etag:n}}}var St=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Is}#buckets`:Is;return this.cache.read(n,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,n){let r=await this.snapshot();if(r.items.nextCursor===void 0){let i=r.items.data.filter(a=>a.itemDefinitionId===e);if(i.length>0)return i}let o=await qi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(o)?o.map(Cs):[]}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 ji(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 zc(n)}};var Yc={unknown_currency:1,currency_not_in_game_payable:1,not_purchasable:1,no_price_in_currency:1,busy:1,cancelled:1,insufficient_funds:1,price_mismatch:1,config_version_stale:1,platform_currency_unavailable:1,not_available:1,recipe_locked:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},Xc=new Set(Object.keys(Yc));function Ms(t){return typeof t=="string"&&Xc.has(t)?t:"error"}var Ge=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var Z=t=>typeof t=="string"?t:"",Qc=t=>typeof t=="string"?t:Z(t&&typeof t=="object"?t.type:void 0),Re=t=>typeof t=="number"?t:0;function Zc(t){let e=t??{};return {prerequisiteType:Z(e.prerequisite_type),referenceId:Z(e.reference_id),required:Re(e.required),current:Re(e.current)}}function Pn(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:Z(e.order_id),status:Z(e.status),...n===void 0?{}:{etag:n}}}function Rt(){return crypto.randomUUID()}var eu="recipe-usage",Os=100;function kt(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:Z(e.currency_id),bucket:Z(e.bucket),delta:Re(e.delta),balanceAfter:Re(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:Z(e.item_definition_id),instanceId:Z(e.instance_id),delta:Re(e.delta),quantityAfter:Re(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:Z(e.progression_definition_id),delta:Re(e.delta),valueAfter:Re(e.value_after),completed:e.completed===true};default:return {kind:"other",type:Z(e.type)}}}function nu(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:Z(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Re(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(kt):[]}}function tu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(nu):void 0;return {orderId:Z(e.order_id),status:Z(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(kt):[],consumed:Array.isArray(e.consumed)?e.consumed.map(kt):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(kt):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function ru(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:Z(e.target_order_id)||Z(e.source_order_id),status:Z(e.status),purchaseId:Z(e.purchase_id),sourceOrderId:Z(e.source_order_id),price:{currencyId:Z(n.platform_currency_id),amount:Re(n.price)}}}function ou(t){let e=t??{},n=typeof e.last_used_at=="string"?e.last_used_at:void 0,r=typeof e.cooldown_expires_at=="string"?e.cooldown_expires_at:void 0;return {recipeId:Z(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...n===void 0?{}:{lastUsedAt:n},...r===void 0?{}:{cooldownExpiresAt:r}}}function Ls(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 xt=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;async create(e,n={}){let r=await this.write(()=>Ti(this.api,this.entity.type,this.entity.id,{operations:e.map(Ls),source:n.source??"play",nonce:Rt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Pn(r)}async createMany(e,n={}){return this.write(()=>Ei(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Ls),nonce:Rt()})),source:n.source??"play"},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}))}async recipeAvailability(e,n,r){let i=await Hi(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},a=typeof i.uses_remaining=="number"?i.uses_remaining:void 0,s=typeof i.cooldown_expires_at=="string"?i.cooldown_expires_at:void 0,l=Array.isArray(i.lock_reasons)?i.lock_reasons.map(Zc):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>Qc(d)):[],...a===void 0?{}:{usesRemaining:a},...s===void 0?{}:{cooldownExpiresAt:s}}}async recipeUsageAll(){return this.cache.read(eu,[],async()=>{let n=await Vi(this.api,this.entity.type,this.entity.id,{limit:Os})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(ou),truncated:r.length>=Os}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let c=e,p=await this.write(()=>Oi(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:Rt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...tu(p)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,o]=await Promise.all([Xi(this.api,n.signal===void 0?{}:{signal:n.signal}),yt(this.api,n.signal===void 0?{}:{signal:n.signal})]),i=e.payment.currencySlug.toLowerCase(),a=o.currencies.find(c=>c.currency_id.toLowerCase()===i||c.slug.toLowerCase()===i);if(a===void 0){let c=o.currencies.map(p=>p.slug);throw new Ge("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${c.length===0?"none":c.join(", ")}`)}let s=e.kind==="item"?r.items.find(c=>c.item_id===e.targetId):r.recipes.find(c=>c.recipe_id===e.targetId&&c.catalog_id===e.catalogId);if(s===void 0)throw new Ge("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=s.platform_prices.find(c=>c.platform_currency_id===a.currency_id);if(l===void 0){let c=g=>o.currencies.find(y=>y.currency_id===g)?.slug??g,p=s.platform_prices.map(g=>`${c(g.platform_currency_id)} ${g.price}`);throw new Ge("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${a.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Ge("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>os(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:a.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:Rt(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return ru(m)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let o=await this.write(()=>ki(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Pn(o)}async maxProgression(e,n,r){let o=await this.write(()=>gs(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Pn(o)}async claimProgression(e,n){let r=await this.write(()=>Ai(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Pn(r)}async resetProgression(e,n){let r=await this.write(()=>_s(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Pn(r)}async write(e){return this.cache.invalidate(),e()}};var Tr=t=>typeof t=="string"?t:"",iu=t=>typeof t=="number"?t:0;function Gs(t){let e=t??{};return {orderId:Tr(e.order_id),status:Tr(e.status),source:Tr(e.source),createdAt:iu(e.created_at)}}var At=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await ds(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(Gs):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Ui(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Gs(r)}};var Ds=t=>typeof t=="number"?t:0,su=t=>typeof t=="string"?t:"";function au(t){let e=t??{};return {progressionDefinitionId:su(e.progression_definition_id),currentValue:Ds(e.current_value),completionCount:Ds(e.completion_count),isCompleted:e.is_completed===true,...Er(e)}}var Pt=class{constructor(e,n,r){this.api=e;this.entity=n;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,n){let o=(await this.inventory.snapshot()).progressions.data.find(i=>i.progressionDefinitionId===e);if(o&&o.achievementsUnavailable!==true)return o;try{let i=await Bi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return au(i)}catch{return o??null}}};var Et=class{constructor(e,n){this.clock=e;this.identity=n;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,n,r,o){this.rebind();let i=n.length===0,a=i?e:e+"\0"+n.join("\0"),s=this.slots.get(a);if(s){let c=s.filledAt;if(c!==void 0&&(o===void 0||this.clock.now()-c<=o))return Promise.resolve(s.value);if(s.inFlight)return s.inFlight}let l=s??{};this.slots.set(a,l);let d=this.generation,m=r().then(c=>(i&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(a)===l&&this.slots.delete(a));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function Ir(t){let e=o=>new RegExp(`<${o}>([^<]{0,300})</${o}>`).exec(t)?.[1]?.trim()||void 0,n=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(n.length>0)return n.join(" \u2014 ");let r=t.trim();return r?r.slice(0,300):""}async function Cr(t){try{let e=Ir(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var se=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},lu=3e4,$s="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",du=/^[A-Za-z0-9_]{1,64}$/;function ke(t){let e=t.length===0?"a save key cannot be empty":t.length>64?`it is ${t.length} characters; a save key is at most 64`:t.startsWith("_")||t.startsWith("$")?`it begins with ${JSON.stringify(t[0])}, and \`_\` and \`$\` are reserved prefixes`:"a save key is ASCII letters, digits and underscores only \u2014 no hyphens, spaces or other punctuation, unlike a template slug";if(!du.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Fs(t,e){let n=new AbortController,r=AbortSignal.timeout(e),o=()=>n.abort(r.reason),i=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(r.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",i,{once:true})),{signal:n.signal,release:()=>{r.removeEventListener("abort",o),t?.removeEventListener("abort",i);}}}function Mr(t,e){return t.aborted&&e?.aborted!==true}var cu=new Set(["x-ms-blob-type"]),uu=/^[ -~]+$/;function mu(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(t)?"a list":typeof t}, which is not a set of headers.`);let n={};for(let[r,o]of Object.entries(t)){let i=r.toLowerCase();if(!cu.has(i))throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof o!="string"||!uu.test(o))throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(i in n)throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);n[i]=o;}return n}function Or(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 Lr(t){return t?.reason==="not_found"}var Tt=class{constructor(e,n,r={}){this.api=e;this.entity=n;this.options=r;}api;entity;options;async put(e,n,r={}){let o;try{o=JSON.stringify(n);}catch(i){throw new se("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}. Retrying stores the same unserialisable value.`)}if(o===void 0)throw new se("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(o),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){let o=r.contentType??"application/octet-stream",i=this.budget(r.timeoutMs),a=Fs(r.signal,i);try{let s=await vs(this.api,this.entity.type,this.entity.id,ke(e),{size_bytes:n.byteLength,content_type:o,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:a.signal});if(typeof s.upload_url!="string"||typeof s.session_id!="string")throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=mu(s.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(s.upload_url,{method:"PUT",headers:{"content-type":o,...l},body:n,credentials:"omit",signal:a.signal});}catch(c){throw Mr(a.signal,r.signal)?this.timeout("upload",i):new se("upload_failed",`${$s} for PUT. Underlying error: ${c}`)}if(!d.ok){let c=await Cr(d);throw new se("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+c:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+c)}return Or(await Li(this.api,this.entity.type,this.entity.id,ke(e),{session_id:s.session_id},{signal:a.signal}))}catch(s){throw this.rethrow(s,r.signal,a.signal,"save",i)}finally{a.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(o){throw new se("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${o}`)}}async getBytes(e,n={}){let r=this.budget(n.timeoutMs),o=Fs(n.signal,r);try{let i;try{let l=await Sr(this.api,this.entity.type,this.entity.id,ke(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(Lr(l))return null;throw l}if(typeof i.download_url!="string")throw new se("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),s;try{s=await a(i.download_url,{credentials:"omit",signal:o.signal});}catch(l){throw Mr(o.signal,n.signal)?this.timeout("download",r):new se("download_failed",`${$s} for GET. Underlying error: ${l}`)}if(!s.ok){let l=await Cr(s);throw new se("download_failed",`the save download answered ${s.status}. `+(s.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await s.arrayBuffer())}catch(i){throw this.rethrow(i,n.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,n={}){try{let r=await Sr(this.api,this.entity.type,this.entity.id,ke(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Or(r.body):null}catch(r){if(Lr(r))return null;throw r}}async list(e={}){let n=await cs(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(Or),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await Ci(this.api,this.entity.type,this.entity.id,ke(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Lr(r))throw r}}budget(e){return e??this.options.timeoutMs??lu}timeout(e,n){return new se("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,o,i){return e instanceof se?e:Mr(r,n)?this.timeout(o,i):e}};function pu(t){try{return wr(t)}catch{return t}}function Gr(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"?pu(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var It=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await ls(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>Gr(o)):[]}async get(e,n={}){try{let r=await Fi(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?Gr(r.body,r.etag):null}catch(r){if(js(r))return null;throw r}}async put(e,n,r={}){let o=await ys(this.api,this.entity.type,this.entity.id,e,{value:pt(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Gr(o)}async delete(e,n){try{await Ii(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!js(r))throw r}}};function js(t){return t?.reason==="not_found"}function Ct(t,e,n={}){let r=new Et(le,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let o=new St(t,e,r);return {settings:new It(t,e),inventory:o,saves:new Tt(t,e,n.saves??{}),currencies:new wt(o,n.resolveCurrencyId),mutations:new xt(t,e,r),orders:new At(t,e),progressions:new Pt(t,e,o)}}var Dr={type:"players",id:"me"};var qe=t=>typeof t=="string"?t:"",ln=t=>typeof t=="number"?t:0;function Mt(t,e){let n=e??{},r=qe(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:qe(n.player_id),gameId:qe(n.game_id),channel:qe(n.channel)||"release",name:qe(n.name),slotIndex:ln(n.slot_index),isActive:n.is_active!==false,createdAt:qe(n.created_at),updatedAt:qe(n.updated_at)}}var Ot=class{constructor(e,n,r,o){this.api=e;this.saves=n;this.identity=r;this.resolveCurrencyId=o;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let n=this.scopes.get(e);return n||(n=Ct(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 as(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>Mt(this.scope,o)):[]}async get(e,n){let r=await Di(this.api,e,n===void 0?{}:{signal:n});return Mt(this.scope,r)}async create(e){let n=await Pi(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Mt(this.scope,n)}async update(e,n,r){let o=await bs(this.api,e,{name:n},r===void 0?{}:{signal:r});return Mt(this.scope,o)}async delete(e,n){await ws(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await es(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:ln(r?.total_slots),availableSlots:ln(r?.available_slots),activeCharacterCount:ln(r?.active_character_count),defaultMaxSlots:ln(r?.default_max_slots),purchasedExtraSlots:ln(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var pe=class{#e;constructor(e){this.#e=e,Object.freeze(this);}toString(){return "[gem: use gem.text.toPlain()]"}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function ye(t){return new pe(t)}var Ne={toPlain(t){return pe.unwrap(t)},compare(t,e,n){let r=t instanceof pe?pe.unwrap(t):t,o=e instanceof pe?pe.unwrap(e):e,i;try{i=new Intl.Collator(n);}catch{i=new Intl.Collator;}return i.compare(r,o)},equals(t,e){let n=t instanceof pe?pe.unwrap(t):t,r=e instanceof pe?pe.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var dn=t=>typeof t=="string"?t:"";function Lt(t){let e=t??{},n=typeof e.message=="string"&&e.message.length>0?e.message:void 0,r=typeof e.resolved_at=="string"?e.resolved_at:void 0;return {id:dn(e.transfer_id),status:dn(e.status),sourceEntityId:dn(e.source_entity_id),targetEntityId:dn(e.target_entity_id),...n===void 0?{}:{message:ye(n)},createdAt:dn(e.created_at),expiresAt:dn(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function gu(){return crypto.randomUUID()}var Gt=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 rs(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:gu()},e.signal===void 0?{}:{signal:e.signal});return Lt(n)}async list(e={}){let r=await ms(this.api,{entity_type:this.self.type,entity_id:this.self.id,...e.direction===void 0?{}:{direction:e.direction},...e.status===void 0?{}:{status:e.status},...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(Lt):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await ns(this.api,e,n===void 0?{}:{signal:n});return Lt(r)}async accept(e,n){return this.resolve(()=>Ri(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>hs(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>xi(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Lt(await e())}};var yu=t=>typeof t=="string"?t:"",fu=t=>typeof t=="string"&&t?t:void 0,hu=t=>typeof t=="number"?t:void 0;function qs(t){let e=new Map(t.map(r=>[r.id,r])),n=new Map(t.filter(r=>r.slug).map(r=>[r.slug,r]));return r=>e.get(r)??n.get(r)??null}function bu(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new ce("config_malformed",`the config document is ${t===null?"null":typeof t}, expected a JSON object`);let e=t,n=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new ce("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=hu(e.version);if(r===void 0)throw new ce("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let c=yu(l.id);if(!c)throw new ce("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return c},i=n("items");i.forEach((l,d)=>o(l??{},"items",d));let a=n("currencies");a.forEach((l,d)=>o(l??{},"currencies",d));let s=t;return {...s,version:r,hash:typeof s.hash=="string"?s.hash:"",items:i,currencies:a,catalogs:n("catalogs"),loot_tables:n("loot_tables"),affix_pools:n("affix_pools"),progressions:n("progressions"),game_room_templates:n("game_room_templates"),kv:typeof s.kv=="object"&&s.kv!==null&&!Array.isArray(s.kv)?s.kv:{},item:qs(i),currency:qs(a)}}var ce=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},Ns=10*1024*1024,Us=15e3,Bs=new Set(["dev","test","release"]);function vu(t){if(!Bs.has(t))throw new ce("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Bs].join(", ")}. gem-api would reject the assignment read.`);return t}var Dt=t=>typeof t=="number"?t:0,$r=t=>typeof t=="string"?t:"";function _u(t){let e=t??{},n=Array.isArray(e.entries)?e.entries.map(r=>{let o=r??{},i=typeof o.rarity_tier=="string"?o.rarity_tier:void 0;return {entryId:$r(o.entry_id),weight:Dt(o.weight),dropRate:Dt(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:$r(e.loot_table_id),name:$r(e.name),rollCount:Dt(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Dt(e.total_weight),entries:n}}var $t=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=null;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,n=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===n&&(this.inFlight=null);});return this.inFlight=n,n}refresh(){this.loaded=null,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new ce("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let o=this.dropRatesByConfig.get(r);o===void 0&&(o=new Map,this.dropRatesByConfig.set(r,o));let i=o.get(e);if(i!==void 0)return i;let a=(async()=>{let s=await $i(this.api,e,n===void 0?{}:{signal:n});return _u(s)})().catch(s=>{throw o?.get(e)===a&&o.delete(e),s});return o.set(e,a),a}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??Us),n;try{let l=await Gi(this.api,vu(this.channel()),{signal:e});if(!l.modified)throw new ce("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof ce)throw l;if(l?.reason==="not_found")return null;throw l}let r=fu(n.config_url);if(r===void 0)return null;let o=this.options.fetch??globalThis.fetch.bind(globalThis),i;try{i=await o(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new ce("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??Us}ms`):new ce("config_unreachable",`could not fetch the game config document. From a browser this is almost always the storage CORS rule: the storage account must allow this game origin for GET. It is NOT a CSP problem \u2014 game origins carry no fetch directives by design. Underlying error: ${String(l)}`)}if(!i.ok){let l=await i.text().then(d=>Ir(d)).catch(()=>"");throw new ce("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let a=await i.text();if(a.length>Ns)throw new ce("config_too_large",`the config document is ${a.length} bytes, over the ${Ns} cap`);let s;try{s=JSON.parse(a);}catch(l){throw new ce("config_malformed",`config document is not JSON: ${String(l)}`)}return bu(s)}};var Hs=400,xe=t=>typeof t=="string"?t:"",wu=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Ue(t){let e=xe(t);if(!wu.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Su=/^[0-9a-f]{1,64}$/,Ru=/^[0-9a-f]{16}$/,ku=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,xu=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Fr(t){let e=xe(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,o,i]=[Number(n[1]),Number(n[2]),Number(n[3])],a=new Date(Date.UTC(r,o-1,i));return a.getUTCFullYear()===r&&a.getUTCMonth()===o-1&&a.getUTCDate()===i?e:void 0}var Au=4096,Pu=new TextEncoder;function Eu(t){let e=xe(t.challenge_data),n=xe(t.challenge_data_hash);return e===""||!Ru.test(n)?{}:Pu.encode(e).length>Au?{}:{data:e,dataHash:n}}function Tu(t){let e=t??{},n=Ue(e.period_start_at),r=Ue(e.period_ends_at);if(n===0||r===0)return;let o=xe(e.slug),i=xe(e.seed),a=Fr(e.period_local_date),s=xe(e.boundary),l=xe(e.reset_time);return {id:xe(e.progression_definition_id),...o===""?{}:{slug:o},window:xe(e.window),periodStartAt:n,periodEndsAt:r,...a===void 0?{}:{periodLocalDate:a},boundary:ku.test(s)?s:"",resetTime:xu.test(l)?l:"",seed:Su.test(i)?i:"",...Eu(e)}}function cn(t){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(t)}`)}function Ft(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Tu).filter(n=>n!==void 0):[]}var En=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;cn(n);let r=await ss(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return Ft(r)}};function Be(t){return typeof t=="string"&&t!==""?t:void 0}var Vs=new Set(["localhost","127.0.0.1","[::1]"]);function jr(t){let e=Be(t);if(e===void 0)return;let n;try{n=new URL(e);}catch{return}if(!(n.username!==""||n.password!=="")&&(n.protocol==="https:"||n.protocol==="http:"&&Vs.has(n.hostname)))return e}function Iu(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},o=Be(r.item_id),i=jr(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function ve(t){let e=t??{},n=Be(e.player_id),r=Be(e.display_name),o=Be(e.discriminator),i=Be(e.display_tag),a=Be(e.avatar_icon_id),s=jr(e.avatar_icon_url);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:ye(r)},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:ye(i)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:Iu(e.badges)}}var Cu=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Mu(t){if(t===void 0)return;let e=jr(t);if(e===void 0)return;let n=new URL(e);return Vs.has(n.hostname)||Cu.has(n.origin)?e:void 0}var Ws=100,zs=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function qr(t){let{periodsBack:e,period:n,playerId:r}=t;if(cn(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!zs.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 Ys(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!zs.test(e))return;let n=Fr(t.period_local_date),r=Ue(t.period_start_at),o=Ue(t.period_ends_at),i=r>0&&o>0;return {id:e,...n===void 0?{}:{localDate:n},...i?{startAt:r,endsAt:o}:{},opensAt:Ue(t.opens_at),closesAt:Ue(t.closes_at),final:t.final===true}}var Tn=t=>typeof t=="string"?t:"",un=t=>typeof t=="number"?t:0,In=t=>typeof t=="string"?t:void 0,Ou=t=>typeof t=="number"?t:void 0,Xs={player:"players",character:"characters"};function Lu(t,e){let n=t??{},r=In(n.entity_id),o=typeof n.entity_type=="string"&&Object.hasOwn(Xs,n.entity_type)?n.entity_type:void 0,i=Qs(n.stats),a=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,s=e?n.is_viewer===true:void 0;return {...ve(n),rank:un(n.rank),occurredAt:un(n.occurred_at),...s===void 0?{}:{isViewer:s},...r===void 0?{}:{entityId:r},...o===void 0?{}:{entityType:o},...i===void 0?{}:{stats:i},...a===void 0?{}:{properties:a}}}function Ks(t,e){let n=t??{},r=In(n.bucket_1),o=In(n.bucket_2),i=Ou(n.update_frequency_seconds),a=Ys(n);return {leaderboardType:Tn(n.leaderboard_type),runType:Tn(n.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(n.entries)?n.entries.map(s=>Lu(s,e)):[],generatedAt:un(n.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...a===void 0?{}:{period:a}}}function Js(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=Qs(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:un(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function Qs(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 Gu(t,e,n){let r=t??{},o=In(r.bucket_1),i=In(r.bucket_2),a=Ys(r);return {leaderboardType:Tn(r.leaderboard_type),runType:Tn(r.run_type),entityType:e,entityId:n,...o===void 0?{}:{bucket1:o},...i===void 0?{}:{bucket2:i},entries:Array.isArray(r.entries)?r.entries.map(Js).filter(s=>s!==void 0):[],personalBest:Js(r.personal_best)??null,totalRuns:un(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:un(r.generated_at),...a===void 0?{}:{period:a}}}var Cn=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=qr(n),o=await Ji(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 Ks(o,false)}async friends(e,n={}){let r=qr(n),o=await Wi(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 Ks(o,true)}async mine(e,n={}){return this.#t(e,"player","me",n)}async character(e,n,r={}){return this.#t(e,"character",n,r)}async#t(e,n,r,o){if(o.limit!==void 0){let{limit:l}=o;if(!Number.isInteger(l)||l<1||l>Ws)throw new TypeError(`limit must be an integer between 1 and ${Ws}, got ${String(l)}`)}let i=qr(o),a=await Ni(this.#e,e,Xs[n],r,{...i,...o.bucket1===void 0?{}:{bucket_1:o.bucket1},...o.bucket2===void 0?{}:{bucket_2:o.bucket2},...o.limit===void 0?{}:{limit:o.limit},...o.signal===void 0?{}:{signal:o.signal}}),s=n==="player"&&r==="me"&&Tn((a??{}).entity_id)||r;return Gu(a,n,s)}};var jt=t=>typeof t=="string"?t:"",Nr=t=>typeof t=="number"?t:0;function Zs(t){let e=t??{};return {playerId:jt(e.player_id),key:jt(e.key),value:e.value,updatedAt:Nr(e.updated_at)}}function Du(t){let e=t??{};return {...ve(e),playerId:jt(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Nr(e.updated_at)}}function $u(t){return t?.reason==="not_found"}var Mn=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let o=await Ki(this.api,ke(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:jt(o.key),entries:Array.isArray(o.entries)?o.entries.map(Du):[],generatedAt:Nr(o.generated_at)}}async of(e,n,r={}){try{return Zs(await Zi(this.api,e,ke(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if($u(o))return null;throw o}}async set(e,n,r={}){if(ke(e),n===void 0)throw new TypeError(`showcase value for ${JSON.stringify(e)} is undefined, which is not JSON. Use clear() to remove one.`);try{JSON.stringify(n);}catch(i){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}.`,{cause:i})}let o=await this.selfPlayerId();return Zs(await fs(this.api,o,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await Mi(this.api,r,ke(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var He=class extends G{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,o]of Object.entries(n))o!==void 0&&Object.assign(this,{[r]:o});}},ea=t=>typeof t=="string"?t:void 0;function Fu(t){let e=t??{};return {...ve(e),playerId:ea(e.player_id)??""}}function ju(t){let e=t??{},n=e.has_more===true?ea(e.next_cursor):void 0;return {friends:Array.isArray(e.data)?e.data.map(Fu):[],...n===void 0?{}:{nextCursor:n}}}var On=class{#e;#t;constructor(e,n={}){this.#e=e,this.#t=n.challenge;}async list(e={}){let n=await us(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return ju(n)}challenge(e){return this.#t===void 0?Promise.resolve({outcome:"unavailable"}):this.#t(e)}};var qu=0;function Ae(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++qu)}-${String(Date.now())}-${t}`}}var Nu=12e4,na=8,Uu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Bu=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Ln(t,e,n={}){return new He(new G("invalid",400,e,void 0,t),n)}function Hu(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Vu(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!Uu.test(e))return {error:Ln("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!Bu.test(n))return {error:Ln("unknown_template","template must be a friend_challenge_templates key from this game's config")};if(r===void 0)return {playerId:e,template:n,params:void 0};if(!Hu(r))return {error:Ln("param_invalid","params must be a plain object of strings and integers")};let o={},i=Object.keys(r);for(let a of i){let s=r[a];if(typeof s=="string"||typeof s=="number"&&Number.isSafeInteger(s)){Object.defineProperty(o,a,{value:s,enumerable:true,writable:true,configurable:true});continue}return {error:Ln("param_invalid",`params.${a} must be a string or a safe integer`,{param:a})}}return i.length>na?{error:Ln("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(na)}`)}:{playerId:e,template:n,params:o}}function Wu(t){switch(t.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:t.outcome}};case "rate_limited":{let e=t.retryAfterMs,n=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new He(new G("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new He(new G("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function Ku(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function ta(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=Vu(n);if("error"in r)return Promise.reject(r.error);let o=`challenge-${Ae()}`;return new Promise((i,a)=>{let s={},l=m=>{e.delete(o)&&(t.clock.clearTimeout(s.timer),"error"in m?a(m.error):i(m.outcome));};e.set(o,l),s.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??Nu);let d=false;try{d=t.bridge.requestFriendChallenge(o,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(n){let r=e.get(n.requestId);if(r===void 0){t.onDropped?.(`gem.friendChallengeResult (${Ku(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(Wu(n));}}}var qt=t=>typeof t=="string"?t:void 0;function Ju(t){let e=t??{},n=qt(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:qt(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Nt=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await yt(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=Ju(i);a!==void 0&&o.push(a);}return o}},Ur=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function zu(t){let e=t??{},n=qt(e.currency_id);if(n===void 0||n==="")return;let r=Ur(e.limit),o=Math.min(Ur(e.earned),r),i=Math.min(Ur(e.remaining),r-o),a=e.period_days,s=typeof a=="number"&&Number.isInteger(a)&&a>=1?a:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:qt(e.currency_slug)??"",currencyId:n,limit:r,earned:o,remaining:i,period:e.period==="day"?"day":"window",periodDays:s,...d===void 0?{}:{resetsAt:d}}}function ra(t){let e=new Set,n=r=>{t?.(`[gem] an earnAllowance 'changed' listener threw: ${r instanceof Error?r.message:String(r)}`);};return {on(r){return e.add(r),()=>{e.delete(r);}},emit(){for(let r of [...e])try{let o=r();typeof o?.then=="function"&&o.then(void 0,n);}catch(o){n(o);}}}}var Ut=class{#e;#t;#l;constructor(e,n,r){this.#e=e,this.#t=n,this.#l=r;}async get(e={}){let r=(await zi(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=zu(i);a!==void 0&&o.push(a);}return o}on(e,n){return e!=="changed"?(this.#l?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#t?.on(n)??(()=>{})}},Gn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Nt(e),this.earnAllowance=new Ut(e,n,r);}};var Br=t=>typeof t=="string"?t:"",oa=t=>typeof t=="number"?t:0;function Yu(t){let e=t??{};return {key:Br(e.key),visibility:Br(e.visibility),value:e.value,updatedAt:oa(e.updated_at)}}function Xu(t){let e=t??{};return {...ve(e),playerId:Br(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Yu):[],generatedAt:oa(e.generated_at)}}function Qu(t){return t?.reason==="not_found"}var Dn=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return Xu(await Yi(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(Qu(r))return null;throw r}}};var Zu=new Map([["function_error",false],["function_failed",false],["function_timeout",false],["function_not_published",false],["function_input_too_large",false],["functions_not_configured",false],["forbidden",false],["function_capacity_unavailable",true],["function_host_unreachable",true],["function_host_error",true],["rate_limited",true],["service_unavailable",true]]),$n=class extends G{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:Zu.get(this.code))??super.retryable}},De=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=em(e),o;try{o=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(i){throw i instanceof G?tm(i):i}return nm(o)}};function em(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let e;try{e=JSON.stringify(t);}catch(n){throw new oe(`the function input could not be serialised to JSON: ${String(n)}. Pass bytes, or a value JSON can carry. This is a bug in the call, not a server failure.`)}if(e===void 0)throw new oe(`the function input is ${typeof t}, which JSON cannot carry. Pass bytes \u2014 an empty Uint8Array for no input \u2014 or a JSON value. This is a bug in the call, not a server failure.`);return new TextEncoder().encode(e)}function nm(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 tm(t){let{details:e,invocationId:n}=Si(t),o=e?.untrusted?.message,i=e?.reason;return new $n(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof o=="string"?{functionMessage:o}:{},...t.code==="function_failed"&&typeof i=="string"?{failure:i}:{}})}var rm=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Hr="gem_";function ia(t){return t.startsWith(Hr)}var sa=1e4,aa=50,om=500,im=65536-4*1024,sm=24*1024;function la(t){let e={},n={};for(let[r,o]of Object.entries(t))typeof o=="string"?e[r]=o:typeof o=="number"&&Number.isFinite(o)&&(n[r]=o);return {dimensions:e,measures:n}}var da=t=>typeof t=="number"?t:0,am=t=>typeof t=="string"?t:"";function Vr(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function lm(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:da(i.index),code:am(i.code)}}):[];return {accepted:da(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Wr(){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 dm(t){return t?.retryable===true}var Fn=class{#e;#t;#l;#y;#n=[];#f={};#i=0;#s=null;#h=false;#b=false;#v=false;#r=false;#_=null;#a=null;#d=false;#o=false;#m=false;#w=false;#S=false;constructor(e){this.#e=e,this.#t=e.options?.enabled!==false,this.#l=Math.max(sa,e.options?.flushIntervalMs??sa),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??om));}track(e,n={}){if(!(!this.#t||this.#r)){if(ia(e)){this.#S||(this.#S=true,this.#g(`[gem] analytics: '${e}' was not recorded \u2014 the gem_ prefix is reserved for the platform's own events, which the SDK emits for you. Name your event something else.`));return}this.#R(e,la({...this.#f,...n}));}}setContext(e){this.#f={...this.#f,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#o)return Vr();let n=this.#E();if(n===null||n==="")return this.#n.length>0&&!this.#w&&(this.#w=true,this.#g("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),Vr();if(this.#k(),this.#n.length===0)return Vr();let r=e.keepalive===true;this.#u();let o=this.#n.splice(0,this.#A(r)),i=this.#i;this.#i=0;let a=Math.round(this.#e.clock.now()),s={batch_id:Wr(),sent_at_ms:a,events:o.map(d=>ca(d,a))},l={client:this.#e.client(),gameId:()=>n};this.#v=true;try{let d=await ts(l,s,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=lm(d,i);return this.#P(m),m}catch(d){throw dm(d)?this.#x(o,i):this.#g(`[gem] analytics: ${o.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#v=false,this.#n.length>0&&this.#c();}}trackPlatform(e,n={}){this.#r||this.#o&&(e==="gem_pause"||e==="gem_resume")||this.#R(e,la(n));}hold(){this.#r||this.#a!==null||(this.#o=true,this.#u());}release(){if(!this.#o||this.#r)return;this.#o=false;let e=this.#e.clock.now(),n=this.#n.map(r=>({...r,atMs:e}));this.#n=n,this.#m&&(this.#m=false,this.#a=e,this.#d=false,this.#n.unshift({uid:Wr(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#n.length>=aa?this.#p():this.#n.length>0&&this.#c();}get held(){return this.#o}startSession(){if(!(this.#r||this.#a!==null)){if(this.#o){this.#m=true;return}this.#a=this.#e.clock.now(),this.#d=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#d)return;if(this.#d=true,this.#o){this.#m=false,this.#n=[],this.#i=0;return}let n=this.#a;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#p({keepalive:true});}setPaused(e){this.#r||e===this.#h||(this.#h=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#n.length>0&&this.#c());}setHidden(e){this.#r||e===this.#b||(this.#b=e,e?this.#u():this.#n.length>0&&this.#c());}dispose(){this.#r=true,this.#u(),this.#n=[],this.#i=0;}get pending(){return this.#n.length}#R(e,n){let{dimensions:r,measures:o}=n;for(this.#k();this.#n.length>=this.#y;)this.#n.shift(),this.#i+=1;this.#n.push({uid:Wr(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#n.length>=aa?this.#p():this.#c();}#p(e={}){this.flush(e).catch(()=>{});}#x(e,n){for(this.#n=[...e,...this.#n],this.#i+=n;this.#n.length>this.#y;)this.#n.shift(),this.#i+=1;}#A(e){let n=e?sm:im,r=Math.min(this.#n.length,100),o=128;for(let i=0;i<r;i+=1){let a=this.#n[i];if(a===void 0)break;if(o+=JSON.stringify(ca(a,0)).length+1,o>n)return Math.max(1,i)}return r}#c(){this.#s!==null||this.#h||this.#b||this.#o||this.#r||this.#v||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#p();},this.#l));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#k(){let e=this.#T();e===null||e===""||(this.#_!==null&&this.#_!==e&&(this.#n=[],this.#i=0,this.#a=null,this.#d=false),this.#_=e);}#P(e){for(let n of e.rejected)this.#g(`[gem] analytics: an event was refused (${n.code}). `+cm(n.code));}#g(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#E(){try{return this.#e.gameId()}catch{return null}}#T(){try{return this.#e.playerId()}catch{return null}}};function ca(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function cm(t){switch(t){case "analytics_not_declared":return "This channel has no analytics_events section at all \u2014 promote a game config that declares one. The gem_* events in the same batch were still recorded.";case "unknown_event":return "This channel declares a set of events and this name is not in it \u2014 check the spelling, or declare it in analytics_events.";case "unknown_dimension":return "A string property on this event is not declared as one of its dimensions.";case "missing_dimension":return "A dimension this event declares was not supplied.";case "dimension_value_not_declared":return "A dimension value is outside the closed set the config declares for it.";case "unknown_measure":return "A numeric property on this event is not declared as one of its measures.";case "measure_wrong_type":return "A measure was the wrong shape \u2014 an int measure refuses a fractional value.";case "source_not_permitted":return "This event is declared for the server only, so a client may not emit it.";default:return "See the analytics_events section of your game config."}}function me(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function jn(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=me(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var um=2e3,mm=5e3;function ma(t){let e=[],n=false,r=null,o=new Map,i=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let a,s=new Promise(l=>{let d=false,m=null;a=c=>{d||(d=true,r=null,t.clock.clearTimeout(m),l(c));},m=t.clock.setTimeout(()=>{n=true,a([]);},t.timeoutMs??um);});return r={promise:s,settle:a},s};return {resolveList:i,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):i().then(a=>a[0])},refresh(a){return !ua(e,a)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{o.delete(d)&&(t.clock.clearTimeout(l),s(m));};o.set(d,a),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??mm);})},accept(a,s){let l=jn(s),d=me(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...o])ua(m,p)||c(m);}}}}function ua(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var pm=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),b=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="DedicatedServerError",this.retryable=pm.has(n),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var pa=["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"],gm=new Set(pa);function $e(t){return typeof t=="string"&&gm.has(t)?t:"unknown"}var Bt="webrtc_dedicated",Yr=["universal","mobile","web"];var ym="p2p_unavailable",fm="capacity_unavailable",hm=2,ga=3e4,ya=1e3,fa=2e4;async function Xr(t){let e=me(t.clusterTargetId),n=t.nextClusterTarget,r=0,o=t.clock??le,i=t.retry??{},a=i.budgetMs??ga,s=i.maxDelayMs??fa,l=i.initialDelayMs??ya,d=o.now(),m=d+a,c=0;for(;;){c++;try{let p=await no(t.signal,"while allocating",()=>t.client.post(`${va(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!bm(p)||a<=0)throw p;if(p.status===503&&p.code===ym)throw new b("p2p_unavailable",`room ${t.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${p.message}`,{cause:p});if(r=p.code===fm?r+1:0,n!==void 0&&r>=hm){let C=n;n=void 0;let M=me(await C());M!==void 0&&(e=M,r=0);}let g=Math.min(s,l*2**(c-1)),y=Math.min(s,(p.retryAfterSeconds??0)*1e3),R=Math.max(g/2,y)+Math.random()*(g/2);if(o.now()+R>m)throw vm(t,p,c,o.now()-d,a);if(i.onWaiting?.({attempt:c,elapsedMs:o.now()-d,budgetMs:a,nextAttemptInMs:R,status:p.status,message:p.message}),await Ht(o,R,t.signal),t.signal?.aborted)throw zr("while waiting to allocate")}}}function bm(t){return t instanceof G?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function vm(t,e,n,r,o){let i=`${n} attempt${n===1?"":"s"} over ${r}ms of a ${o}ms budget`;return e.status===429?new b("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${i}: ${e.message}`,{cause:e}):new b("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${i}: ${e.message}`,{cause:e})}var _m=12e4,wm=1e3;async function Qr(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??wm,o=t.timeoutMs??_m,i=e.now()+o,a=ha(t),s={seen:t.knownToExist===true};for(;;){let l=await ba(t,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>i)throw new b("timeout",`match ${n} was still ${l.status} after ${o}ms`);await Ht(e,r,t.signal);}}async function Zr(t){return (await ba(t,ha(t),{seen:t.knownToExist===true})).outcome}function ha(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${va(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function ba(t,e,n){let{matchId:r}=t,o=t.clock.now(),i;try{i=await no(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(a){if(a instanceof G&&a.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(n.seen=true,i.status==="ready")return {status:"ready",outcome:Sm(r,i,o)};if(i.status==="failed"){let a=i.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:$e(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function eo(t){let e=await no(t.signal,"while listing cluster targets",()=>t.client.get("/v1/ping/targets",t.signal)),n=[];for(let r of e.targets??[]){let o=r?.cluster_target_id;typeof o!="string"||o.length===0||n.push({id:o,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return n}async function no(t,e,n){if(t?.aborted)throw zr(e);try{return await n()}catch(r){throw t?.aborted?zr(e,r):r}}function zr(t,e){return new b("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function Sm(t,e,n){let r=e.join_credential,o=e.expires_in_seconds,i=typeof r=="string"&&typeof o=="number";return {status:"ready",matchId:t,protocol:e.protocol??"unknown",...i?{joinCredential:r,credentialExpiresAt:n+o*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function va(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Ht(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let o=()=>{t.clearTimeout(i),n?.removeEventListener("abort",o),r();},i=t.setTimeout(o,e);n?.addEventListener("abort",o);})}function _a(t){return typeof t=="string"&&t.trim()!==""}function Vt(t,e){return _a(t)?t.trim():_a(e)?e:null}var Wt="0.1.0-beta",wa="0-beta",mn="web",Rm=/^(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 km(t){let e=Rm.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Sa(t,e){let n=xm(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:Wt};let o=km(r);if(o===null)throw new b("misconfigured",`${e} refused: engineVersion '${r}' is not semver, so no engine line can be derived from it and gem-api answers 400. Omit it \u2014 a browser game has no engine version of its own, and the SDK reports '${Wt}' for it.`);if(o!==wa)throw new b("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${wa}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${o}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${Wt}' for it.`);return {...t,platform:n,engineVersion:r}}function xm(t,e){if(t===void 0||t===mn)return mn;if(!Yr.includes(t))throw new b("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${Yr.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${mn}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${mn}' and is deprecated \u2014 remove the field. A browser game publishes its bundle in the web package dimension, so a client reporting anything else is version-checked against a dimension it has nothing in, and every blacklist, release and expiry check passes without looking at this build.`),mn}var Am="join",Pm="welcome",Em="rejected",Ra=25e3,Tm=1e3,to=1;function ro(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var Im={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 oo(t){let e=typeof t=="string"?t:"unknown";return new b(Im[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function qn(t){let{channel:e,clock:n}=t;return new Promise((r,o)=>{let i=false,a=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Ra),s=n.setTimeout(()=>w(new b("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(a,Tm)),l=R=>{let C=R.data;if(typeof C!="string"){c(C);return}let M;try{M=JSON.parse(C);}catch{c(C);return}if(i){c(C);return}if(M.t===Pm){let _=ro(M.heartbeat_interval);y({...typeof M.player_id=="string"?{playerId:M.player_id}:{},...typeof M.match_id=="string"?{matchId:M.match_id}:{},..._===void 0?{}:{heartbeatIntervalMs:_}});return}if(M.t===Em){w(oo(M.reason));return}c(C);},d=()=>{w(new b("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{w(new b("aborted","the caller aborted during the join exchange"));},c=R=>{i&&t.onMessage?.(R);},p=()=>{n.clearTimeout(s),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=R=>{i=true,p(),t.onMessage===void 0&&g(),r({welcome:R,detach:g});},w=R=>{i||(i=true,p(),g(),o(R));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){m();return}t.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:Am,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:to}:{}}));}catch(R){w(new b("connection_failed",`the join frame could not be sent on the open channel: ${String(R)}`,{cause:R}));}})}var Ve=1,Nn=2,io=4,lo=8,Cm=2,Mm=1e3,co="heartbeat timeout",Un="gem-uu",Kt=2,xa="gem_transports";function pn(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!Om(r)||e.includes(r)||e.push(r);}return e}function Om(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function Bn(t,e){if(typeof t!="object"||t===null)return null;let n=t[xa];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 Jt(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Aa=new TextEncoder,Pa=new TextDecoder;function uo(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function mo(t){let e=0;return t?.reliable===false&&(e|=Ve),t?.ordered===false&&(e|=Nn),e}function po(t){return {reliable:(t&Ve)===0,ordered:(t&Nn)===0}}var go={reliable:true,ordered:true};function Ea(t){return JSON.stringify({t:"join",credential:t,wire:Kt,heartbeat:to})}function Ta(t){let e;try{e=JSON.parse(t);}catch{throw new b("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=ro(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"?oo(e.reason):new b("join_refused","the server answered the join out of protocol")}function zt(){return typeof globalThis.WebTransport=="function"&&yo===null}function Yt(){return yo}var yo=null;var ka="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Lm(t){let e=gt(t);if(e.byteLength!==32)throw new b("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var so=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let i=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(i===0||i>1<<20)throw new b("connection_failed",`a control-stream record claims ${i} bytes`);if(this.buffered.byteLength<4+i)break;let a=this.buffered.slice(4,4+i);this.buffered=this.buffered.slice(4+i),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function ao(t,e){let n=new Uint8Array(5+e.byteLength);return new DataView(n.buffer).setUint32(0,e.byteLength+1,true),n[4]=t,n.set(e,5),n}async function Hn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let s=globalThis.WebTransport;if(s===void 0)throw new b("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new s(t.url):new s(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Lm(t.certHashBase64)}]});}let r=n,o=s=>{try{r.close();}catch{}throw s},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(yo=ka,o(new b("connection_failed",`${ka}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new b("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,a]);let s=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([s.read(),a]);if(s.releaseLock(),l.done||l.value===void 0)return o(new b("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(ao(io,Aa.encode(Ea(t.credential))));let c=new so,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),a]);if(y.done||y.value===void 0)return o(new b("connection_failed","the control stream closed before the join was answered"));for(let w of c.push(y.value)){g=Ta(Pa.decode(w.payload));break}}return {link:Gm(r,m,p,c,t.log??(y=>console.warn(y)),Ca(g,t.clock)),welcome:g}}catch(s){return o(s)}}function Gm(t,e,n,r,o,i){let a,s,l=false,d=y=>{if(!l){l=true,m.stop();try{t.close();}catch{}s?.(y);}},m=ho(i,()=>d(co)),c=(y,w)=>{m.heard(),(y&lo)===0&&a!==void 0&&((y&io)!==0?a(Pa.decode(w),go):a(w,po(y)));};(async()=>{try{for(;;){let y=await n.read();if(y.done||y.value===void 0)break;for(let w of r.push(y.value))c(w.flags,w.payload);}}catch{}d("stream closed");})();let p,g;try{let y=t.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let w=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let R=await w.read();if(R.done||R.value===void 0)break;let C=R.value;C.byteLength!==0&&c((C[0]??0)|Ve|Nn,C.slice(1));}}catch{}})();}else o("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,g=void 0,o(`[gem] webtransport datagram lane unusable (${Jt(y)}); unreliable sends ride the stream`);}return t.closed.then(y=>d(Ia(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,w){if(l)return;if(typeof y=="string"){e.write(ao(io,Aa.encode(y))).catch(()=>d("write failed"));return}let R=mo(w);if((R&Ve)!==0&&g!==void 0){let C=uo(R,y),M=p?.maxDatagramSize;if(M===void 0||C.byteLength<=M){g.write(C).catch(()=>{});return}}e.write(ao(R,y)).catch(()=>d("write failed"));},onMessage(y){a=y;},onClose(y){s=y;},close(){d("closed");}}}function fo(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let o=globalThis.WebSocket;if(o===void 0)return Promise.reject(new b("connection_failed","this environment has no WebSocket"));n=new o(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((o,i)=>{let a=false,s=setTimeout(()=>{a||(a=true,r.close(),i(new b("timeout","websocket did not come up in time")));},e),l=g=>{a||(a=true,clearTimeout(s),r.close(),i(g));},d=()=>{r.send(Ea(t.credential));},m=g=>{if(a)return;if(typeof g.data!="string"){l(new b("join_refused","the server sent binary before answering the join"));return}let y;try{y=Ta(g.data);}catch(w){l(w);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),o({link:Dm(r,Ca(y,t.clock)),welcome:y});},c=()=>{l(new b("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new b("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",c),r.addEventListener("error",p),r.readyState===1&&d();})}function Ia(t){return typeof t=="string"&&t.length>0?t:void 0}function Ca(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function ho(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,Mm)*Cm,o=n.now(),i=null,a=()=>{i=null;let s=n.now()-o;if(s>=r){e();return}i=n.setTimeout(a,r-s);};return i=n.setTimeout(a,r),{heard:()=>{o=n.now();},stop:()=>{i!==null&&(n.clearTimeout(i),i=null);}}}function Dm(t,e){let n,r,o=false,i=s=>{if(!o){o=true,a.stop();try{t.close();}catch{}r?.(s);}},a=ho(e,()=>i(co));return t.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){n?.(s.data,go);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&lo)===0&&n?.(l.slice(1),po(d));})),t.addEventListener("close",(s=>i(Ia(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!o){if(typeof s=="string"){t.send(s);return}t.send(uo(mo(l),s));}},onMessage(s){n=s;},onClose(s){r=s;},close(){i("closed");}}}function bo(t,e,n,r){let o,i,a=false,s=n,l=c=>{if(!a){a=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}i?.(c);}},d=ho(r,()=>l(co)),m=(c,p)=>{if(d.heard(),typeof c=="string"){o?.(c,go);return}let g=new Uint8Array(c);if(g.byteLength===0)return;let y=g[0]??0;(y&lo)===0&&o?.(g.slice(1),po(y|p));};if(t.addEventListener("message",(c=>m(c.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),s!==void 0){let c=s;c.addEventListener("message",(p=>m(p.data,Ve|Nn))),c.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(c,p){if(a)return;if(typeof c=="string"){t.send(c);return}let g=mo(p),y=uo(g,c);if((g&Ve)!==0&&s!==void 0&&s.readyState==="open"){s.send(y);return}t.send(y);},onMessage(c){o=c;},onClose(c){i=c;},close(){l("closed");}}}function wo(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let o=vo(r);o!==void 0&&(e[n]=o);}return e}function So(t){if(Array.isArray(t))return t.map($m).filter(e=>!!e)}function vo(t){if(_o(t)||Array.isArray(t)&&t.every(_o))return t}function _o(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function $m(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=vo(e.fixed),r=vo(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...n===void 0?{}:{fixed:n},...r===void 0?{}:{default:r},...gn("description",Fm(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(_o)?{allowed:e.allowed}:{},...gn("min",Vn(e.min)),...gn("max",Vn(e.max)),...gn("minItems",Vn(e.min_items)),...gn("maxItems",Vn(e.max_items)),...gn("maxLength",Vn(e.max_length))}}function Fm(t){return typeof t=="string"&&t.length>0?t:void 0}function Vn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function gn(t,e){return e===void 0?{}:{[t]:e}}function Ee(t){let e=t??{},n=X(e.id)??X(e.game_room_id);if(n===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(Ma):[];return {id:n,gameId:X(e.game_id)??"",name:X(e.name)??"",status:X(e.status)??"open",hostPlayerId:X(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,..._e("joinCode",X(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},..._e("roomArgs",wo(e.room_args)),..._e("roomArgsTemplate",So(e.room_args_template)),gameChannel:X(e.game_channel)??"release",..._e("region",X(e.region)),..._e("clusterTargetId",X(e.cluster_target_id)),..._e("matchId",X(e.match_id)),version:Pe(e.version)??0,..._e("templateId",X(e.template_id)),roomType:X(e.game_room_type)??"Standard",..._e("transports",pn(e.transports)??void 0),createdAt:Pe(e.created_at)??0,updatedAt:Pe(e.updated_at)??0,..._e("startedAt",Pe(e.started_at))}}function Ma(t){let e=t??{};return {...ve(e),playerId:X(e.player_id)??"",isReady:e.is_ready===true,role:X(e.role)??"member",joinedAt:Pe(e.joined_at)??0,..._e("groupId",X(e.group_id)),..._e("platform",X(e.platform))}}function Xt(t){let e=t??{};return {id:X(e.id)??X(e.game_room_id)??"",gameId:X(e.game_id)??"",name:X(e.name)??"",status:X(e.status)??"open",hostPlayerId:X(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:X(e.game_channel)??"release",roomType:X(e.game_room_type)??"Standard",createdAt:Pe(e.created_at)??0}}function X(t){return typeof t=="string"&&t.length>0?t:void 0}function Pe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function _e(t,e){return e===void 0?{}:{[t]:e}}var Wn=class{constructor(e){this.options=e;}options;list(e){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.templateSlug&&n.set("template_slug",e.templateSlug),e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor&&n.set("cursor",e.cursor);let r=n.size>0?`?${n.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(o=>({rooms:(o.game_rooms??[]).map(Xt),...typeof o.next_cursor=="string"?{nextCursor:o.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(n=>({rooms:(n.game_rooms??[]).map(Xt)}))}create(e,n,r){return jm(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},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...Qt(n)},e.signal).then(Ee)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Ee)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...Qt(r)},n.signal).then(Ee)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...Qt(r)},n.signal).then(Ee)}quickJoin(e,n,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...Qt(n)},e.signal).then(Ee)}leave(e,n,r,o=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:n},r,{keepalive:o}).then(()=>{})}close(e,n){return this.options.client.delete(this.roomV1(e),n).then(()=>{})}update(e,n){return this.options.client.patch(this.roomV2(e),{...n.name===void 0?{}:{name:n.name},...n.maxPlayers===void 0?{}:{max_players:n.maxPlayers},...n.isPublic===void 0?{}:{is_public:n.isPublic},...n.settings===void 0?{}:{settings:n.settings},...n.roomArgs===void 0?{}:{room_args:n.roomArgs}},n.signal).then(Ee)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Ee)}kick(e,n,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(n)}`,{},r).then(()=>this.get(e,r))}transferHost(e,n,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(n)}`,{},r).then(Ee)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Qt(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function jm(t){t!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${t}) is deprecated and was not sent. A room's seats come from the room template published in your game config \u2014 name one with templateSlug \u2014 and a room created without a template seats 8. To change a room that already exists, call update({ maxPlayers }) as its host.`);}var Kn=class{listeners=new Map;retainedMatch=null;on(e,n){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(n),e==="matchReady"&&this.retainedMatch!==null){let o=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===o&&n(o);});}return ()=>this.off(e,n)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...o)=>{r(),n(...o);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let o of [...r])o(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function qm(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var Nm=1e3,Um=3e3,Bm=6e4,Hm=2,Oa=new Set(["game_room_closed","game_room_gone"]),Vm=12e4,Wm=5e3,Km=new Set(["invalid_cluster_target","capacity_unavailable"]);function ko(t){return new Ro(t)}var Ro=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Wn({client:e.client,gameId:()=>this.requireGameId()}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Kn;api;room=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create");let n=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("create",async()=>{let i=await n;return this.api.create(r,this.version("create"),i[0]).catch(async a=>{let s=await this.afterRefusedClusters(a,i);if(s[0]===void 0||s[0]===i[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(o,"created"),o}async join(e,n={}){this.assertNotInRoom("join");let r=await this.attachParty(n),o=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(o,"joined"),o}async joinByCode(e,n={}){this.assertNotInRoom("joinByCode");let r=await this.attachParty(n),o=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(o,"joined"),o}async quickJoin(e){this.assertNotInRoom("quickJoin");let n=this.clusterTargets(),r=await this.attachParty(e),o=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),i=await this.run("quickJoin",async()=>{let a=await n;return o(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||zm(l,a))throw s;return o(l)})});return this.enter(i,"joined"),i}async list(e={}){let n=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",n),n}async myRooms(e){let n=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",n.rooms),n.rooms}async leave(e={}){let n=this.requireRoom("leave"),r=e.keepalive===true,o=()=>this.run("leave",()=>this.api.leave(n.id,e.asGroup!==false,e.signal,r));if(r){let i=o();this.track(this.notifyLeavingMatch({keepalive:true})),await i;}else await this.notifyLeavingMatch(),await o();this.exit(),this.emitter.emit("left");}async leaveAll(e){let n=await this.myRooms(e),r=[];for(let o of n)try{await this.run("leaveAll",()=>this.api.leave(o.id,!0,e)),r.push(o.id),this.room?.id===o.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let n=this.requireRoom("close");await this.run("close",()=>this.api.close(n.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let n=this.room;if(!n)return null;let r;try{r=await this.track(this.api.get(n.id,e));}catch(o){if(o instanceof G&&o.reason==="not_found"){let i=this.heldMatchId;if(i!==null){let a=await this.askWhyEnded(i,e);this.endMatch(i,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",o),o}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let n=this.room,r=this.heldMatchId;if(!(n===null||r===null)&&!(n.status==="in_game"&&n.matchId===r)&&!(n.matchId!==void 0&&n.matchId!==r)&&this.settling!==r){this.settling=r;try{let o=await this.askWhyEnded(r,e);o!==null&&this.endMatch(r,o,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let o=this.takeHint(e),i;try{i=await this.track(this.onceGameIdKnown(()=>Zr({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...n===void 0?{}:{signal:n}})));}catch(a){return a instanceof G&&a.reason==="not_found"?o??null:(this.reportError("reconcile",a),null)}return i===null?null:i.status==="ready"?(this.seenMatches.add(e),null):i.status==="failed"?(this.settleFailed(i.matchId,i.reason),null):i.reason==="unknown"&&o!==null?o:i.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=$e(n.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),o=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(o),o}async kick(e,n){let r=this.requireRoom("kick"),o=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(o),o}async transferHost(e,n){let r=this.requireRoom("transferHost"),o=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(o),o}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){let r=this.requireRoom("startMatch");if(!this.isHost)throw new b("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let o=me(n.clusterTargetId),i=o??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,c)=>Xr({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...o===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>s(i,[a]).catch(async m=>{if(o!==void 0||!Ga(m))throw m;let c=await this.nextCluster([a],true);if(c===void 0)throw m;return s(c,[a,c])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new b("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let n=this.emitter.retained;return n!==null&&this.session.phase==="ready"?n:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let n=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),o=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(o)}chase(e,n,r){return Qr({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:n,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(n),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new b("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!Oa.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new b("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,n){this.heldMatchId===e&&(this.abandonReconnect(e,n),this.emitter.emit("matchFailed",e,n),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,n,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:n,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:n,roomReopened:r}),this.abandonReconnect(e,n));}armReconnect(e,n){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),n==="kicked"){r.abandon(e,n);return}let o={matchId:e,cause:n,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=o,this.track(this.reconnectStep(o));}park(e,n){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),n());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,n){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,n));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!We()){this.park(e,()=>this.reconnectStep(e));return}let n=this.options.autoReconnect;if(n===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=n.attempts||r<Nm){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:n.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(qm(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!We()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let o=null;try{o=await this.track(this.onceGameIdKnown(()=>Zr({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e.matchId,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e.matchId)})));}catch(i){this.reportError("reconcile",i);}if(this.reconnecting(e)){if(o?.status==="ended"){this.endMatch(o.matchId,o.reason,!Oa.has(o.reason)),this.track(this.reconcile().catch(()=>{}));return}if(o?.status==="failed"){this.abandonReconnect(e.matchId,o.reason),this.settleFailed(o.matchId,o.reason);return}if(o?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(o);let i;try{i=await n.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),i="failed";}if(e.done||this.reconnect!==e)return;if(i==="closed"){this.finishReconnect();return}if(i==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let n=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):n&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new b("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let n=this.session.matchId;this.session={phase:"suspended",matchId:n,reason:e},this.emitter.emit("matchSuspended",{matchId:n,cause:e}),this.armReconnect(n,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new b("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let n=this.heldMatchId;if(n===null)throw new b("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:n},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let n=this.heldMatchId;if(n!==null)try{await this.api.leaveMatch(n,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,n){let r=this.emitter.on(e,n);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}handleRoomEvent(e){if(this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let n=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(n).catch(()=>{}));}handleAutoStartFailed(e,n){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(n);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:n,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let o=new AbortController;this.autoStartRetry=o,this.track(this.requestStart({signal:o.signal},false).then(()=>{},i=>{o.signal.aborted||this.reportError("startMatch",i);}).finally(()=>{this.autoStartRetry===o&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Km.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){this.disposed||!this.watchingSeats||this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}async reconcileSeats(){if(this.disposed||!this.watchingSeats)return;let e;try{e=await this.myRooms();}catch{return}let n=new Set;for(let r of e)r.status!=="closed"&&(n.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])n.has(r)||this.reported.delete(r);}async reportSeat(e){let n=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||n===null||!r.members.some(o=>o.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.seatPollMs>0&&We())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let n=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(n,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!We())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of Zt)e.addEventListener(r,this.visibilityListener);let n=globalThis.document;typeof n?.addEventListener=="function"&&n.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let n=this.inFlight;this.inFlight=[],await Promise.allSettled(n);}}dispose(){if(this.disposed=true,this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of Zt)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??Wm}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new b("misconfigured","the game id is not known yet. It comes from the play token, and this manager was given no way to wait for one \u2014 pass gameId, or awaitGameId so a call made before the first token waits for it the way createGem wires it.")}playerId(){return typeof this.options.playerId=="function"?this.options.playerId():this.options.playerId}version(e){let n=this.options.clientVersion,r=Vt(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new b("misconfigured",`${e} has no game version to report \u2014 gem-api requires platform, game_version and engine_version together on every room route, and refuses a request carrying two of the three. The arcade normally supplies it with the play token; an embedder that does not, or a build running outside the arcade, leaves nobody to ask. Pass \`clientVersion: { gameVersion }\` to createGem (or to createRoomManager) as the fallback. It has to name a build you actually published, and a wrong one pins the room to the wrong build \u2014 which is why the platform answers it wherever it can.`);return Sa({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return jn(await this.options.resolveClusterTargets());let e=me(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Ga(e)||n.length===0?[]:jn(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=a=>a.find(s=>!e.includes(s)),o=await this.clusterTargets(),i=r(o);return i!==void 0||!n?i:r(jn(await this.options.refreshClusterTargets?.(o)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let n=this.options.resolveParty;if(n===void 0)return e;let r=await n();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,n,r){if(!(e instanceof G)||e.reason!=="conflict")throw e;if(this.options.recoverStaleMembership===false)throw new G(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let o;try{o=await this.leaveAll(n.signal);}catch{throw new G(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(o.length===0)throw new G(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.api.quickJoin(n,this.version("quickJoin"),r)}assertNotInRoom(e){if(this.room!==null)throw new b("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}requireRoom(e){if(this.room===null)throw new b("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,n){try{return await this.track(this.onceGameIdKnown(n))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,n){let r=n instanceof G?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof b?n.reason:"unavailable",message:n instanceof Error?n.message:String(n),retryable:false};this.emitter.emit("error",r);}track(e){return this.inFlight.push(e),e}enter(e,n){this.room=e,this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(n,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let n=this.room;if(n===null||n.id!==e.id)return;let r=new Map(n.members.map(s=>[s.playerId,s])),o=new Map(e.members.map(s=>[s.playerId,s])),i=this.playerId();for(let s of o.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!o.has(s)){if(s===i){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of o){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=Jm(n,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),a&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let n=this.heldMatchId;n!==null&&n!==e&&this.endMatch(n,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,n=this.heldMatchId;if(e===null||n===null||this.followAbort!==null&&this.followingMatchId===n)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=n,this.track(this.onceGameIdKnown(()=>this.chase(e.id,n,{signal:r.signal})).then(o=>{if(!r.signal.aborted)try{this.settleOutcome(o);}catch{}}).catch(o=>{r.signal.aborted||this.reportError("pollMatchStatus",o);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??Vm;return new Promise((o,i)=>{let a=c=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},s=this.emitter.on("matchAllocationStarted",c=>a(()=>o(c))),l=this.emitter.on("matchFailed",(c,p)=>a(()=>i(new b("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>a(()=>i(new b("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>i(new b("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??Um}pushedInterval(){return this.options.pushedPollIntervalMs??Bm}pushed(){return this.options.clock.now()-this.lastPushAt<Hm*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=n=>{n?.persisted!==true&&this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{}));},e.addEventListener("pagehide",this.unloadListener));}};function We(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var Zt=["visibilitychange","focus","pageshow","online"];function Jm(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||La(t)!==La(e)}function La(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Ga(t){return t instanceof G&&t.code==="invalid_cluster_target"}function zm(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Ym=["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 yn=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let o=Xm(e,this.options.transport,(this.options.now??Date.now)());o.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:o},n);}report(e){this.post(e).catch(()=>{});}};function Xm(t,e,n){let r=Math.floor(n/1e3);return t.filter(o=>xo.includes(o.type)).slice(0,100).map(o=>{let i=Qm(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function Qm(t){if(t!==void 0)return Ym.includes(t)?t:"unknown"}var Jn=class{constructor(e){this.options=e;this.reporter=new yn({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let o=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:er(o.credential)??"",hostFingerprint:er(o.host_fingerprint)??"",hostEpoch:nr(o.host_epoch)??0,expiresAt:(nr(o.expires_at)??0)*1e3}}async turnLease(e,n,r){let o=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),i=[];for(let l of Array.isArray(o.ice_servers)?o.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&i.push({urls:m,username:er(d.username)??"",credential:er(d.credential)??""});}let a=nr(o.expires_at),s=nr(o.ttl_seconds);return {iceServers:i,expiresAt:a!==void 0?a*1e3:Date.now()+(s??0)*1e3}}async kick(e,n,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:n},r);}async leave(e,n=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:n});}async telemetry(e,n){await this.reporter.post(e,n);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function er(t){return typeof t=="string"&&t.length>0?t:void 0}function nr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var Zm=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),O=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="P2pError",this.retryable=Zm.has(n);}reason;retryable};var Da=10240,$a=2048,ep=new TextEncoder;function Fa(t){return ep.encode(t).length}function Fe(t,e){let n=o=>{throw new b("invalid_sdp",`the ${e} ${o}`)},r=Fa(t);r>=Da&&n(`is ${r} bytes, over the ${Da} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),t.startsWith("v=")||n("does not start with 'v=', so it is not SDP"),t.includes("\0")&&n("contains a null byte"),/\r(?!\n)/.test(t)&&n("contains a bare carriage return");for(let o of t.split(/\r\n|\n/)){let i=Fa(o);i>$a&&n(`has a ${i}-byte line, over the ${$a} limit`);}}function tr(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 rr=class{listeners=new Map;on(e,n){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(n),()=>this.off(e,n)}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...o)=>{r(),n(...o);}));return r}emit(e,...n){let r=this.listeners.get(e);if(r)for(let o of [...r])o(...n);}clear(){this.listeners.clear();}};var np=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function fn(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=or(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function or(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 np.test(r)?r:null}function zn(t,e){if(t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}var Ao=5e3,tp=12e4+Ao,rp=1024,op=6e4,ip=1e4,ja=64*1024,qa=5;function Po(t){let e=new Map,n=-1/0,r=null,o=(()=>{let s;try{s=new URL(`${t.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return s.username!==""||s.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:s.href,shown:`${s.protocol}//${s.host}`}})(),i=()=>{let s=t.subtle??globalThis.crypto?.subtle;if(!s)throw new O("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return s},a=async()=>{if(!o.ok)throw new O("keys_unavailable",o.reason);let s=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await s(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(ip)});}catch{throw new O("keys_unavailable",`the JWKS endpoint at ${o.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new O("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>ja)throw new O("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${ja} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof O?p:new O("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>qa)throw new O("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${qa} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=i();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let y=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,y);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!o.ok)throw new O("keys_unavailable",o.reason);if(r)return await r,e.get(s)??null;let d=t.now();if(!Number.isFinite(d))throw new O("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<n&&(n=-1/0),d-n<op?null:(n=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var Yn=class{seen=new Map;admit(e,n){for(let[r,o]of this.seen)o<=n&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=rp){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+tp),true}};function Ua(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function Na(t){try{let e=new TextDecoder().decode(Ua(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Eo(t,e,n,r,o){let i=D=>{throw new O("peer_unauthenticated",`the peer's join credential is not usable: ${D}`)},a=t.split(".");a.length!==3&&i("it is not a three-part JWT");let[s,l,d]=a,m=Na(s);m===null&&i("its header does not decode"),m.alg!=="RS256"&&i(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&i("it names no key");let p=await n.key(c);p===null&&i("it was signed by a key this build cannot resolve");let g=o.subtle??globalThis.crypto?.subtle;g||i("this environment has no WebCrypto");let y=new TextEncoder().encode(`${s}.${l}`),w;try{w=Ua(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,w,y)||i("its signature does not verify");let C=Na(l);C===null&&i("its payload does not decode");let M=C,_=D=>typeof M[D]=="string"?M[D]:"",S=D=>typeof M[D]=="number"&&Number.isFinite(M[D])?M[D]:NaN;_("iss")!==o.issuer&&i("it was issued by someone else"),_("aud")!==`${o.issuer}/p2p-match`&&i("its audience is not this platform"),_("match_id")!==e.matchId&&i("it is for another match"),_("game_id")!==e.gameId&&i("it is for another game");let P=S("exp")*1e3,x=S("nbf")*1e3;(!Number.isFinite(P)||e.now>P+Ao)&&i("it has expired"),Number.isFinite(x)&&e.now<x-Ao&&i("it is not valid yet");let V=_("role");V!=="host"&&V!=="client"&&i("it names no usable role");let N=S("host_epoch");N!==e.hostEpoch&&i("it names a different host epoch");let W=or(_("fingerprint"));W===null&&i("its fingerprint claim is malformed"),zn(W,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let k=or(_("host_fingerprint"));k===null&&i("its host fingerprint claim is malformed"),zn(k,e.hostFingerprint)||i("it was issued against a different host certificate");let A=_("jti");A.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(A,e.now)||i("it has already been used");let L=_("sub");return L.length===0&&i("it names no player"),{playerId:L.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:N,role:V,fingerprint:W,hostFingerprint:k,jti:A,expiresAt:P}}function To(t){let e=new TextEncoder().encode(t.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let n=new ArrayBuffer(3+e.length+4+4),r=new DataView(n);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(n,3,e.length).set(e),r.setUint32(3+e.length,t.protocolVersion,true),r.setUint32(7+e.length,t.assignedPeerId,true),n}function Io(t){let e=new ArrayBuffer(9),n=new DataView(e);return n.setUint8(0,2),n.setUint32(1,t.protocolVersion,true),n.setUint32(5,t.assignedPeerId,true),e}function Co(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function Mo(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 Ba(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 Ha(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Xn=class{constructor(e,n,r){this.localPlayerId=e;this.hostPlayerId=n,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,n){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=n,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var Oo={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},Me=["reliable","ordered","unreliable"];function Lo(t){let e=globalThis.RTCPeerConnection;if(!e)throw new Error("[gem] this environment has no RTCPeerConnection. Pass `peerConnectionFactory` to connect against a stand-in, which is how this flow is tested outside a browser.");return new e({iceServers:t.iceServers,...t.certificates===void 0?{}:{certificates:t.certificates}})}async function Qn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Wa=1,cp=3e4,Ka=2e3,up=5e3,Ja=6e4,mp=8,Do=class{constructor(e=mp){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;}},pp=new Do,gp=8,yp=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),et=class{constructor(e){this.options=e;this.keys=e.keys??Po({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new rr;links=new Map;replays=new Yn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Wa+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let n of this.links.values())n.admitted&&e.push(this.expose(n));return e}peer(e){let n=this.links.get(e);return n&&n.admitted?this.expose(n):null}on(e,n){return this.emitter.on(e,n)}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}async start(e){let n=this.options.connectTimeoutMs??cp;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),o=me(this.options.clusterTargetId);if(o!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,o,e);this.iceServers=s.iceServers,this.mark("turn leased");}catch(s){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Go(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let i=this.options.clock.setTimeout(()=>{this.fail(new O("timeout",`no usable P2P connection after ${n}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},n),a=()=>this.fail(new O("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",a),this.ready=null;}}async kick(e){if(!this.isHost)throw new O("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,n){this.closed||this.route(e,n).catch(r=>this.report_(r));}async route(e,n){switch(e){case "hello":return this.onHello(n);case "offer":return this.onOffer(n);case "answer":return this.onAnswer(n);case "ice":return this.onIce(n);case "peerLeft":return this.onPeerLeft(n);case "migration":return this.onMigration(n);case "matchEnded":return this.onMatchEnded(n);case "error":return this.onSignalingError(n);default:return}}async onHello(e){let n=ae(e.playerId),r=ae(e.hostPlayerId),o=ir(e.hostEpoch);if(!(n===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new Xn(n,r,o)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let n of e)try{await this.onOffer(n);}catch(r){this.report_(r);}}async offerToHost(e){let n=this.hostPlayerId,r=this.openLink(n,Wa),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new O("invalid_sdp","the browser produced an offer with no SDP");Fe(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,e),this.mark("offer sent"),this.fetchCredential().catch(a=>this.report_(a));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,o=r===void 0?null:fn(r);if(o===null)throw new O("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let i=this.options.credentialPacing??pp,a=()=>this.closed||e!==this.credentialGeneration,s=up;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,c;if(m===409)c=Ka;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?c=p*1e3:(c=s,s=Math.min(s*2,Ja)),c=Math.min(Math.max(c,Ka),Ja);}else throw d;if(!await this.waitForCredential(c,a))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=ae(e.fromPlayerId),r=ae(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=gp){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let o=ae(e.sessionId);if(o!==null&&this.answeredSessions.get(n)===o)return;Fe(r,"offer"),this.refuseMedia(r,"offer");let i=fn(r);if(i===null)throw new O("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);this.mark("offer received"),o!==null&&this.answeredSessions.set(n,o);let a=this.links.get(n);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(n,this.nextPeerId++);s.remoteFingerprint=i,await s.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(s);let l=await s.connection.createAnswer();await s.connection.setLocalDescription(l);let d=s.connection.localDescription?.sdp??l.sdp;if(!d)throw new O("invalid_sdp","the browser produced an answer with no SDP");Fe(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(n,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let n=ae(e.fromPlayerId),r=ae(e.sdp);if(n===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||n!==this.hostPlayerId)return;Fe(r,"answer"),this.refuseMedia(r,"answer");let i=fn(r);if(i===null)throw new O("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),o.remoteFingerprint=i,o.pendingAnswer=r,this.hostVerified(o)&&await this.applyAnswer(o,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:zn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new O("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let n=e.pendingAnswer;n!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,n).catch(r=>this.report_(r));}async applyAnswer(e,n){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:n}),this.flushCandidates(e);}async onIce(e){let n=ae(e.fromPlayerId),r=ae(e.candidate);if(n===null||r===null)return;let o=this.links.get(n);if(!o)return;let i=ae(e.sdpMid),a=ir(e.sdpMLineIndex)??ir(e.sdpMLineIndexAlt),s={candidate:r,...i===null?{}:{sdpMid:i},...a===null?{}:{sdpMLineIndex:a}};if(o.connection.remoteDescription===null){o.pendingCandidates.length<64&&o.pendingCandidates.push(s);return}await o.connection.addIceCandidate(s);}onPeerLeft(e){let n=ae(e.playerId);if(n===null)return;let r=ae(e.reason)??"left";if(n===this.localPlayerId){this.fail(new O("kicked",`this player was removed from the match (${r})`)),this.close();return}let o=this.links.get(n);o&&this.dropLink(o,r,true);}async onMigration(e){let n=ae(e.hostPlayerId),r=ir(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:n,hostEpoch:r,...ae(e.reason)===null?{}:{reason:ae(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(i=>typeof i=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(o.kind!=="duplicate"){if(o.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(o.kind==="refused"){this.report_(new O("migration_failed",o.why));return}for(let i of [...this.links.values()])this.dropLink(i,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),o.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new O("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let n=ae(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new O("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=ae(e.code)??"unknown",r=ae(e.message)??"the platform refused a signaling message";this.report_(new O("signaling_failed",`${n}: ${r}`));}openLink(e,n){let o=(this.options.peerConnectionFactory??Lo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of Me){let g=o.createDataChannel(p,Oo[p]);g.binaryType="arraybuffer",i[p]=g;}let a={playerId:e,assignedPeerId:n,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(g=>this.report_(g));},c=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",s),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",c),i.reliable.addEventListener("message",m),a.detachHandshake=()=>{i.reliable.removeEventListener("open",c),i.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),o.removeEventListener("icecandidate",s),o.removeEventListener("iceconnectionstatechange",l),o.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}flushCandidates(e){let n=e.pendingCandidates;e.pendingCandidates=[];for(let r of n)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let n=this.credential;if(n===null)throw new O("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=n.expiresAt)throw new O("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(To({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=Mo(n);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new O(Ha(r.reason),Ba(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,n,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let o=fn(e.connection.localDescription?.sdp??"");if(o===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let i;try{i=await Eo(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:o,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof O&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Go(a)),s&&this.fail(a);return}if(i.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${i.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(i.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Io({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,o){this.warn(`refused to admit ${e.playerId}: ${o}`);try{e.channels.reliable.send(Co(n));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let o of Me)za(e.channels[o]);za(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,n);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let n=this.ready;this.ready=null,n.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof O?e:new O("connection_failed",Go(e),{cause:e}));}count(e){this.counted||!yp.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(tr(e))throw new O("media_refused",`the ${n} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(n=>this.options.clock.setTimeout(n,e))}warn(e){let n=this.options.log;n!==null&&(n??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function ae(t){return typeof t=="string"&&t.length>0?t:null}function ir(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function Go(t){return t instanceof Error?t.message:String(t)}function za(t){try{t.close();}catch{}}var fp=100,hp=50,nt=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,n){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:n});}answer(e,n,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:n,assignedPeerId:r});}candidate(e,n,r,o){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??fp)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...r===void 0?{}:{sdpMid:r},...o===void 0?{}:{sdpMLineIndex:o}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,n){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:n,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new O("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new O("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:n,candidate:r,sdpMid:o,sdpMLineIndex:i}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...o===void 0?{}:{sdpMid:o},...i===void 0?{}:{sdpMLineIndex:i}});}if(this.dropped>0&&this.queue.length===0){let n=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(n),this.dropListener?.(n);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??hp));}};function B(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function je(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function hn(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function Ya(t){return typeof t=="boolean"?t:void 0}var fe=B(64),tt=je(0,2147483647);function $o(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=fe(n);typeof r=="string"&&e.push(r);}return e}function z(t,e,n){return {to:t,from:e,read:n,required:true}}function H(t,e,n){return {to:t,from:e,read:n,required:false}}var _p=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=hn("disconnected","failed","closed")(e.iceState),r=je(0,4102444800)(e.lastSeenAt);if(!(n===void 0&&r===void 0))return {...n===void 0?{}:{ice_state:n},...r===void 0?{}:{last_seen_timestamp:r}}};Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[z("sdp","sdp",B(10240)),z("signaling_intent","intent",hn("initial","ice_restart","full_reconnect")),H("sdp_hash","sdpHash",B(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[z("peer_id","peerId",fe),z("sdp","sdp",B(10240)),z("assigned_peer_id","assignedPeerId",je(0,4294967295)),H("sdp_hash","sdpHash",B(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[z("peer_id","peerId",fe),z("candidate","candidate",B(512)),H("sdp_mid","sdpMid",B(64)),H("sdp_mline_index","sdpMLineIndex",je(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[z("host_epoch","hostEpoch",tt)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[z("host_epoch","hostEpoch",tt),H("evidence","evidence",_p)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"}));Object.freeze(Object.assign(Object.create(null),{hello:[z("playerId","player_id",fe),z("hostPlayerId","host_player_id",fe),z("hostEpoch","host_epoch",tt),H("members","members",$o)],offer:[z("fromPlayerId","from_player_id",fe),z("sdp","sdp",B(10240)),H("sessionId","signaling_session_id",B(128)),H("sdpHash","sdp_hash",B(128)),H("iceUfrag","ice_ufrag",B(64)),H("intent","signaling_intent",hn("initial","ice_restart","full_reconnect"))],answer:[z("fromPlayerId","from_player_id",fe),z("sdp","sdp",B(10240)),H("sessionId","signaling_session_id",B(128)),H("sdpHash","sdp_hash",B(128)),H("iceUfrag","ice_ufrag",B(64)),H("assignedPeerId","assigned_peer_id",je(0,4294967295))],ice:[z("fromPlayerId","from_player_id",fe),z("candidate","candidate",B(512)),H("sdpMid","sdp_mid",B(64)),H("sdpMLineIndex","sdp_m_line_index",je(0,255)),H("sdpMLineIndexAlt","sdp_mline_index",je(0,255))],peerJoined:[z("playerId","player_id",fe)],peerLeft:[z("playerId","player_id",fe),H("reason","reason",B(64))],migration:[z("hostPlayerId","new_host_player_id",fe),z("hostEpoch","host_epoch",tt),H("reason","reason",B(64)),H("kickedPlayerIds","kicked_player_ids",$o),H("migrationComplete","migration_complete",Ya)],matchEnded:[H("reason","reason",B(64))],error:[H("code","code",B(64)),H("message","message",B(256))]}));Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));var Je="webrtc_p2p";function Qa(t){let e=new Jn({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,o,i){n.get(r)?.handleSignal(o,i);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new O("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let o=me(r.clusterTargetId),i=o??me(await t.resolveClusterTarget?.());t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...o===void 0?{}:{clusterTargetId:o},...r.signal===void 0?{}:{signal:r.signal}});let a=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==Je)throw new O("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${Je}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new nt({bridge:t.bridge,matchId:a.matchId,clock:t.clock}),l=new et({api:e,clock:t.clock,matchId:a.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:s,...i===void 0?{}:{clusterTargetId:i},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Qn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(a.matchId,l),l.on("matchEnded",()=>n.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(a.matchId),l.close(),d}return l}}}function Za(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,o=t.document??globalThis.document,i=[];if(typeof r.addEventListener=="function"){let s=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",s),i.push(()=>r.removeEventListener?.("pagehide",s));let l=()=>e.setHidden(!We());for(let d of Zt)r.addEventListener(d,l),i.push(()=>r.removeEventListener?.(d,l));typeof o?.addEventListener=="function"&&(o.addEventListener("resume",l),i.push(()=>o.removeEventListener?.("resume",l))),e.setHidden(!We());}let a=new Map;return i.push(n.on("matchReady",s=>{let l=s.protocol===Je?"p2p":"dedicated";a.set(s.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),i.push(n.on("matchEnded",s=>{let l=a.get(s.matchId);l!==void 0&&(a.delete(s.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let s of i.splice(0))try{s();}catch{}a.clear();}}var el=["pointerdown","keydown"];function nl(t,e=globalThis){let n=false,r=false,o=null,i=()=>{if(o!==null){try{e.cancelAnimationFrame?.(o);}catch{}o=null;}},a=()=>{if(!r){r=true,i();for(let g of el)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},s=()=>{if(!(n||r)){n=true,a();try{t();}catch{}}};function l(g){g?.isTrusted===true&&s();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(y=>y?.buttons.some(w=>w.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},c=()=>{if(o=null,!(n||r)){if(d()){s();return}m()&&(o=e.requestAnimationFrame?.(c)??null);}};function p(){o===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let g of el)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(o=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:a}}async function sr(t,e,n,r){let o=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),o}function Fo(t,e){let n=false;return async r=>{let o=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),o}}function jo(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(o,i){return r.has(o)?false:(r.add(o),n.push({name:o,at:i??e()}),true)},timeline(){let o=[...n].sort((i,a)=>i.at-a.at);return o.map((i,a)=>{let s=o[a-1],l=s===void 0?"":` (+${Math.round(i.at-s.at)}ms)`;return `${i.name}@${Math.round(i.at)}ms${l}`}).join(" \u2192 ")}}}var wp="GemWebSdkHandshake";var Sp=()=>Date.now();function tl(t,e,n={}){let r=t[wp];if(r===void 0)return null;let o=n.ttlMs??9500,i=n.now??Sp,a=r.events.splice(0),s=r.times?.splice(0),l=0,d=0,m=false,c=i()-o;for(let p=a.length-1;p>=0;p--){let g=s?.[p];if(g!==void 0&&g<c){d+=1;continue}if(l+=1,e(a[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var qo=false;async function sl(t,e,n,r){if(qo){e.close(),n("busy",true);return}qo=true;let o=null;try{let i=await kp(t,r);if(typeof i=="string"){e.close(),n(i,Rp(i));return}o=i;let s=await(r.encodeRef??(l=>Ep(l,r)))(o);if(o.close(),o=null,s===null){e.close(),n("failed",!0);return}if(s.size>Pp){e.close(),n("too_large",!1);return}e.postMessage(s);}catch(i){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",i);}finally{qo=false,o?.close();}}function Rp(t){switch(t){case "no_source":case "busy":case "failed":return true;case "not_wired":case "unsupported":case "unreadable":case "tainted":case "too_large":case "declined":return false}}async function kp(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":rl(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=Ap(n);if(!r)return "no_source";let o=xp(r);if(o!==null)return o;try{return rl(await createImageBitmap(r),t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}function xp(t){let e;try{e=t.getContext("webgl2")??t.getContext("webgl");}catch{return "unreadable"}if(e){let n=e.getContextAttributes();return !n||n.preserveDrawingBuffer!==true?"unsupported":null}try{if(t.getContext("2d"))return null}catch{return "unreadable"}return "unreadable"}function Ap(t){let e=null,n=0;for(let r of Array.from(t.querySelectorAll("canvas"))){let o=r.width*r.height;o<=0||r.clientWidth<=0||r.clientHeight<=0||o>n&&(e=r,n=o);}return e}async function rl(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let o=Math.min(n/t.width,r/t.height),i=Math.max(1,Math.floor(t.width*o)),a=Math.max(1,Math.floor(t.height*o));try{let s=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:"high"});return t.close(),s}catch{return t.close(),"too_large"}}var Pp=8*1024*1024,ol="image/webp",il=.92;async function Ep(t,e){try{if(typeof OffscreenCanvas=="function"){let i=new OffscreenCanvas(t.width,t.height),a=i.getContext("2d");if(a){a.drawImage(t,0,0);let s=await i.convertToBlob({type:ol,quality:il});if(s&&s.size>0)return s}}}catch{}let n=e.documentRef??globalThis.document;if(!n)return null;let r=n.createElement("canvas");r.width=t.width,r.height=t.height;let o=r.getContext("2d");return !o||(o.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(i=>{r.toBlob(a=>i(a),ol,il);})}async function al(t,e){if(!e)return;let n;try{n=await Tp(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 Tp(t){return new Promise((e,n)=>{let r=false,o=setTimeout(()=>{r||(r=true,console.warn("[gem] onFeedbackContext did not answer within 1000ms; sending the report without context. Gather cheaply, or keep a snapshot."),e(null));},1e3);(async()=>t())().then(i=>{r||(r=true,clearTimeout(o),e(i??null));},i=>{r||(r=true,clearTimeout(o),n(i instanceof Error?i:new Error(String(i))));});})}var ll=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function dl(t=globalThis){let n=t[ll];if(n!==void 0)return n;let r=false,o=()=>r,i=[],a=Ip(t,o);a!==null&&i.push(a);let s=Cp(t,o);s!==null&&i.push(s);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let c of i)c();}}};return Object.defineProperty(t,ll,{value:l,configurable:true}),l}function Ip(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let o=t.OfflineAudioContext,i=n.connect,a=n.disconnect,s=new Map,l=m=>{let c=m.gain,p=m.context.currentTime;c.cancelScheduledValues(p),e()?c.setValueAtTime(0,p):c.setTargetAtTime(1,p,.01);},d=m=>{let c=m.context;if(o!==void 0&&c instanceof o)return null;let p=s.get(c);return p===void 0&&(p=c.createGain(),p.gain.value=e()?0:1,i.call(p,m),s.set(c,p)),p};return n.connect=function(...c){let[p,...g]=c;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return i.call(this,y,...g),p}return i.apply(this,c)},n.disconnect=function(...c){let[p,...g]=c;if(p instanceof r){let y=s.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...g)}catch{}}return a.apply(this,c)},()=>{for(let[m,c]of s){if(m.state==="closed"){s.delete(m);continue}try{l(c);}catch{}}}}function Cp(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,o=Object.getOwnPropertyDescriptor(r,"muted"),i=o?.get,a=o?.set;if(i===void 0||a===void 0)return null;let s=r.play,l=new WeakMap,d=new WeakSet,m=new Set,c=p=>{l.has(p)||l.set(p,!!i.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),a.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!i.call(this):p},set(p){l.set(this,!!p),c(this);}}),r.play=function(){try{c(this);}catch{}return s.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{c(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{a.call(g,(l.get(g)??!1)||e());}catch{}}}}function cl(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=false,o=false,i=false,a=null,s=null,l=null,d=[],m=()=>r&&!o&&!i,c=()=>{s=null,l=null,d=[];},p=w=>{if(a=null,!m()){c();return}if(l!==null&&d.push(w-l),l=w,s===null)s=w;else {let R=w-s;R>=e&&d.length>0&&(t.report(Mp(d,R)),s=w,d=[]);}g();},g=()=>{let w=n.requestAnimationFrame;typeof w=="function"&&(a=w.call(n,p));},y=()=>{if(m()){a===null&&(c(),g());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),c();};return {setRequested(w){r=w,y();},setPaused(w){o=w,y();},get running(){return a!==null},dispose(){i=true,y();}}}function Mp(t,e){let n=[...t].sort((o,i)=>o-i),r=Math.max(1,Math.ceil(n.length*.95));return {fps:t.length*1e3/e,frameTimeP95Ms:n[r-1]}}var ar=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function ml(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function pl(t,e){t!==null&&(t.style.setProperty(ar.top,`${e.top}px`),t.style.setProperty(ar.right,`${e.right}px`),t.style.setProperty(ar.bottom,`${e.bottom}px`),t.style.setProperty(ar.left,`${e.left}px`));}var ul=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height"}});function gl(){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 Op(t,e){let n={tl:{width:0,height:0},tr:{width:0,height:0},bl:{width:0,height:0},br:{width:0,height:0}};for(let r of t){let o=e?r.x+r.width/2<=e.width/2:r.x===0,i=e?r.y+r.height/2<=e.height/2:r.y===0,a=o?r.x+r.width:e?e.width-r.x:r.width,s=i?r.y+r.height:e?e.height-r.y:r.height,l=n[`${i?"t":"b"}${o?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(a)),l.height=Math.max(l.height,Math.ceil(s));}return n}function yl(t,e,n){if(t===null)return;let r=Op(e,n);for(let o of ["tl","tr","bl","br"])t.style.setProperty(ul[o].width,`${r[o].width}px`),t.style.setProperty(ul[o].height,`${r[o].height}px`);}var Lp=3e4,lr=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function fl(t){let e=t.clock??le,n=t.timeoutMs??Lp,r=new Map,o=new Map,i=0,a=s=>{let l=r.get(s);return l?(r.delete(s),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(s){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(s);if(l)return l;let d=new Promise((m,c)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(s),c(new lr("timeout",true,`the embedder did not answer a local-server request for room ${s} within ${String(n)}ms`));},n);r.set(p,{room:s,resolve:m,reject:c,timer:g}),t.bridge.requestLocalServer(p,s)||(a(p),m());});return o.set(s,d),d.catch(()=>{}),d},accept(s){a(s.requestId)?.resolve();},refuse(s){let l=a(s.requestId);l&&l.reject(new lr(s.reason,s.retryable,s.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var rt={url:"https://downloads.indiegems.games/sdk/v7.7.0/gem-web-sdk.devtools.min.js",integrity:"sha384-otgem8CdmC7EUiO9mqONtrZW4/w2d13z5ek0EiTnkezTYw6xOwkeQR3djiFI4X68"};var vn=null;function Gp(){return vn!==null||(vn=new Promise((t,e)=>{let n=document.createElement("script");n.src=rt.url,n.integrity=rt.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){vn=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${rt.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{vn=null,e(new Error(`gem devtools: could not load ${rt.url}. Either the network refused it or its Subresource Integrity check failed, or the CDN did not answer the CORS preflight this request needs \u2014 SRI is only checkable on bytes the page may read. A locally rebuilt SDK is the commonest cause: it produces panel bytes that do not match the hash compiled into this build.`));},document.head.append(n);})),vn}function hl(t,e){let n=null,r=0;async function o(i){if(n!==null)return true;let a=++r;if(!e())return false;let s=await Gp();return !e()||a!==r?false:(n!==null||(n=s.mount(t(),{openedBy:i,text:Ne,onDismiss:()=>{n?.unmount(),n=null;}})),true)}return {get isOpen(){return n!==null},close(){r+=1,n?.unmount(),n=null;},open:()=>o("game"),openFrom:o}}var Dp=1e4,bl={reason:"unavailable",retryable:false};function vl(t){let e=new Map,n=null,r=null,o=0,i=(d,m)=>{m.timer=t.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},t.timeoutMs??Dp);},a=(d,m)=>{let c=s(d);c&&m(c);},s=d=>{let m=e.get(d);return m?(e.delete(d),t.clock.clearTimeout(m.timer),m):null},l=new on({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,c)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){c(bl);return}let g=`t${++o}`,y={resolve:m,reject:c,reason:d,timer:null,held:p!=="connected"};e.set(g,y),i(g,y),y.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){a(d.requestId,c=>c.resolve(m));return}l.accept(m);},onDenied(d){a(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),i(m,c),t.bridge.requestToken(m,c.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])a(m,c=>c.reject(bl));},get identity(){return n},get gameVersion(){return r}}}function $p(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var Fp=new Set(mt);function jp(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))Fp.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function dr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return vi(async(n,r)=>{let o;try{o=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new oe("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let i;try{i=new URL(o.href.replace(/\/+$/,"")+n.path);}catch{throw new oe(`${JSON.stringify(typeof n.path=="string"?$p(n.path):"(a non-string path)")} does not form a valid URL against ${o.protocol}//${o.host}. This is a malformed request, not a server failure.`)}if(i.protocol!==o.protocol||i.host!==o.host)throw new oe(`${JSON.stringify(i.pathname)} resolves to ${i.protocol}//${i.host}, not ${o.protocol}//${o.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(i.username!==""||i.password!==""){let g=o.username!==""||o.password!=="",y=i.username!==o.username||i.password!==o.password,w=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new oe(`the ${w} puts credentials in the URL, which cannot be fetched (${n.method} ${i.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,y]of Object.entries(t.defaultQuery??{}))i.searchParams.has(g)||i.searchParams.set(g,y);let a=n.bytes,s=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(a=JSON.stringify(n.body),s="application/json");}catch(g){throw new oe(`the body of ${n.method} ${JSON.stringify(i.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(i.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...s===void 0?{}:{"content-type":s},...jp(n.headers)},body:a,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),c=qp(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...c===void 0?{}:{retryAfterSeconds:c},...p===null||p===""?{}:{invocationId:p}}},t)}function qp(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}var Np=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Uo="embedder_relay_unavailable",Up="embedder_no_relay",Bp=new Set([Uo]),Bo=new Set([Up]),ot=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new No(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new b("match_ended",`the match ended while the offer was in flight (${e.reason??"no reason given"}), so no server is left to answer it`));return}if(e.event==="answer"){if(typeof e.sdp!="string"||e.sdp.length===0){n.refuse(new b("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(Hp(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new b("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,n);}release(e,n){this.pending.get(e)===n&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new b("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new b("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function Hp(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new b(Vp(t),r,{platformCode:t})}function Vp(t){return t===void 0||Bp.has(t)?"signaling_failed":Bo.has(t)?"offer_refused":Np.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var No=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new b("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(o){return Promise.reject(o)}return n?.aborted?Promise.reject(new b("aborted","the caller aborted before the offer was sent")):new Promise((o,i)=>{let a=()=>{s(),i(new b("aborted","the caller aborted the signaling exchange"));},s=()=>{n?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),o(d);},refuse:d=>{s(),i(d);}};this.teardown=s,n?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof b?d:new b("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var _l="match_ended:",wl="server_shutdown:",Sl="kicked:",Wp=123;function Kp(t){if(typeof t!="string"||t.length===0||t.length>Wp)return {kind:"other"};if(t.startsWith(_l)){let e=$e(t.slice(_l.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(wl)?{kind:"server_shutdown",cause:t.slice(wl.length)}:t.startsWith(Sl)?{kind:"kicked",detail:t.slice(Sl.length)}:{kind:"other"}}function Ho(t,e,n){let r=Kp(n),o=r.kind==="kicked"?"kicked":"link_closed";t.notifyMatchDisconnected(o).catch(()=>{}),r.kind==="match_ended"&&t.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function Vo(){return {exchange(){return Promise.reject(new b("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See docs/dedicated-server-flow.md \xA72."))},close(){}}}var Jp=3e3,zp=1e4,Yp=15e3;async function cr(t){let e=t.peerConnection;try{kl(t,"before the handshake started"),Wo(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let a of t.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});t.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await Zp(e,t),Wo(t);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new b("invalid_sdp","the offer carried no SDP");Fe(o,"offer"),Rl(o,"offer");let i=await Qp(t,o);if(Wo(t),typeof i?.sdp!="string")throw new b("invalid_sdp","the signaling channel answered without an SDP");return Fe(i.sdp,"answer"),Rl(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await eg(n,t),kl(t,"before the channel opened"),n}catch(n){throw e.close(),Xp(n)}}function Xp(t){return t instanceof b?t:Pl(t)?ze():new b("connection_failed",El(t),{cause:t})}function Rl(t,e){if(tr(t))throw new b("media_refused",`the ${e} carries an active audio or video section. This path carries a data channel only; voice belongs to the platform voice service.`)}async function Qp(t,e){let n=t.exchangeTimeoutMs??zp,r=Al(t,n),o=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(i=>{throw i instanceof b?i:Pl(i)?ze():new b("signaling_failed",El(i),{cause:i})});return ng(o,t,r,()=>r.exhausted?Ko("while the offer was in flight"):new b("timeout",`no answer arrived within ${n}ms`))}function Zp(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let o=()=>{n.clearTimeout(a),t.removeEventListener("icegatheringstatechange",i),e.signal?.removeEventListener("abort",o),r();},i=()=>{t.iceGatheringState==="complete"&&o();},a=n.setTimeout(o,e.gatherTimeoutMs??Jp);t.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function eg(t,e){if(e.signal?.aborted)return Promise.reject(ze());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new b("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??Yp,o=Al(e,r);return new Promise((i,a)=>{let s=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),i();},d=g=>{s(),a(new b("connection_failed","the data channel failed before it opened",xl(g)===void 0?void 0:{cause:xl(g)}));},m=()=>{s(),a(ze());},c=()=>{s(),a(o.exhausted?Ko("while the channel was still opening"):new b("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(c,o.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Al(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 ng(t,e,n,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(ze()):new Promise((a,s)=>{let l=c=>{o.clearTimeout(m),i?.removeEventListener("abort",d),c();},d=()=>l(()=>s(ze())),m=o.setTimeout(()=>l(()=>s(r())),n.ms);i?.addEventListener("abort",d),t.then(c=>l(()=>a(c)),c=>l(()=>s(c)));})}function kl(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw Ko(`already ${e}`)}function Ko(t){return new b("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function Wo(t){if(t.signal?.aborted)throw ze()}function ze(){return new b("aborted","the caller aborted the connection attempt")}function Pl(t){return t?.name==="AbortError"}function xl(t){return t?.error}function El(t){return t instanceof Error?t.message:String(t)}Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"}));Object.freeze(Object.assign(Object.create(null),{answer:[z("sdp","sdp",B(10240)),H("sessionId","session_id",B(64))],error:[H("code","code",B(64)),H("message","message",B(256))],matchEnded:[H("reason","reason",B(64))]}));function Dl(t){let{client:e,clock:n,rooms:r}=t,o=t.signaling??Vo,i=t.log??(_=>console.warn(_)),a=new yn({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(_,S)=>{let P=s.get(_)??new Set;P.add(S),s.set(_,P);},d=(_,S)=>{let P=s.get(_);P!==void 0&&(P.delete(S),P.size===0&&s.delete(_));},m=async _=>{if(r.isHost&&!zo(r)&&r.currentRoom?.matchId===void 0){let S=me(_.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},..._.retry===void 0?{}:{retry:_.retry},..._.signal===void 0?{}:{signal:_.signal}});}return Ll(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Jo(_)):await r.awaitMatch(Jo(_)))},c=async _=>Ll(await r.pollMatchStatus(Jo(_))),p=async(_,S)=>{let P=false;try{let x=await m(_),V=r.currentRoom?.transports;if(V!==void 0&&!V.includes("webrtc"))throw new b("misconfigured",`the room template offers (${V.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let N=_.peerConnection??Gl();P=!0;let W=await cr({peerConnection:N,signaling:S,clock:n,matchId:x.matchId,credentialExpiresAt:x.credentialExpiresAt,...ur(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),k=null;if(_.presentCredential!==!1)try{k=await qn({channel:W,clock:n,credential:x.joinCredential,credentialExpiresAt:x.credentialExpiresAt,...ur(_,"onMessage","signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(A){throw we(W),we(N),A}return cg(r,x,W,N,S,_.reportDisconnect!==!1,_.reportConnected!==!1,k,{remember:l,forget:d},_.onMatchEnded)}catch(x){throw P&&Ol(a,x),we(S),x}},g=async(_,S,P,x,V,N)=>{if(_==="webtransport"){let j=x?.webtransport;if(j===void 0)throw new b("misconfigured","webtransport is not advertised");let U={credential:P.joinCredential,credentialExpiresAt:P.credentialExpiresAt,clock:n};if(typeof j.named_url=="string"&&j.named_url!==""){let ee=Math.max(Math.floor(N/2),1e3);try{return await Hn({url:j.named_url,timeoutMs:ee,log:i,...U})}catch(ge){if(Yt()!==null)throw ge;return i(`[gem] webtransport named dial failed (${Jt(ge)}); retrying the pinned dial`),Hn({url:j.url,certHashBase64:j.cert_sha256_b64,timeoutMs:ee,log:i,...U})}}return Hn({url:j.url,certHashBase64:j.cert_sha256_b64,timeoutMs:N,...U})}if(_==="websocket"){let j=x?.websocket;if(j===void 0)throw new b("misconfigured","websocket is not advertised");return fo({url:j.url,credential:P.joinCredential,credentialExpiresAt:P.credentialExpiresAt,clock:n,timeoutMs:N})}let W=S.peerConnection??Gl(),k,A=await cr({peerConnection:W,signaling:V,clock:n,matchId:P.matchId,credentialExpiresAt:P.credentialExpiresAt,extraChannels:[{label:Un,ordered:false,maxRetransmits:0}],onExtraChannel:(j,U)=>{j===Un&&(k=U);},...ur(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:og}:{}}),L;try{L=await qn({channel:A,clock:n,credential:P.joinCredential,credentialExpiresAt:P.credentialExpiresAt,wire:Kt,heartbeat:!0,...ur(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(j){throw we(A),we(W),j}let D=L.welcome.heartbeatIntervalMs;return {link:bo(A,W,k,D===void 0?void 0:{clock:n,intervalMs:D}),welcome:L.welcome,channel:A,peerConnection:W}},y=(_,S,P,x,V)=>{let N=false,W;x.link.onClose(D=>{!N&&_.reportDisconnect!==false&&Ho(r,S.matchId,D),W?.(D);}),_.reportDisconnect!==false&&_.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let k={transport:x.link.transport,send:(D,j)=>x.link.send(D,j),onMessage:D=>x.link.onMessage(D),onClose:D=>{W=D;},close:()=>x.link.close()},A=()=>{N||(N=true,we(x.link),we(V));},L=D=>{if(!N){try{_.onMatchEnded?.(D);}catch{}A();}};return l(S.matchId,L),{matchId:S.matchId,transport:P,link:k,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:x.welcome,...x.channel===void 0?{}:{channel:x.channel},...x.peerConnection===void 0?{}:{peerConnection:x.peerConnection},close(){d(S.matchId,L),A();}}},w=async(_,S)=>{let P=r.currentRoom?.id,x=r.gameId,V=()=>({advert:Bn(r.currentRoom?.settings,_),template:r.currentRoom?.transports??null});if(P===void 0||x===null)return V();try{let N=await e.get(`/v2/games/${encodeURIComponent(x)}/game-rooms/${encodeURIComponent(P)}`,S);return {advert:Bn(N.settings,_),template:pn(N.transports)??r.currentRoom?.transports??null}}catch{return V()}},R=(_,S)=>{let P=_??Tl;return S.length===0?P:P.filter(x=>S.includes(x))},C=async(_,S,P)=>{try{let x=await m(_),{advert:V,template:N}=await w(x.matchId,_.signal),W=R(N,S),k=W.filter(Q=>ag(Q,V)),A=Yt();if(A!==null&&W.includes("webtransport")&&V?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${A} (learned on an earlier dial in this page)`),k.length===0){let Q=N===null?`the default order (${Tl.join(", ")})`:`the room template's transports (${N.join(", ")||"none"})`;throw new b("misconfigured",`none of ${Q}`+(S.length>0?`, narrowed to (${S.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let L=_.transportAttemptTimeoutMs??rg,D=()=>_.deadlineAt===void 0?1/0:_.deadlineAt-n.now(),j=Q=>t.signalingReady===void 0||Q<=0?Promise.resolve(!0):t.signalingReady(Q),U=[],ee=[];for(let Q of k){if(D()<Cl){i(`[gem] ${Q} rung not tried: the reconnect budget is spent`);break}ee.length>0&&x.credentialExpiresAt-n.now()<Ml&&(x=await c(_)),ee.push(Q);let Oe=!1,Se=!1,Ie={attempts:0,waitedMs:0};for(;;){if(Q==="webrtc"&&_.redial===!0){let re=Math.min(Il,D());await j(re)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(re)}ms; offering anyway`);}let Ce=Math.max(Math.min(L,D()),Cl);try{return y(_,x,Q,await g(Q,_,x,V,P,Ce),P)}catch(re){let Y=re instanceof b?re:new b("connection_failed",re instanceof Error?re.message:String(re),{cause:re});if(Q==="webrtc"&&Ol(a,Y),(Y.reason==="credential_expired"||Y.reason==="credential_reused")&&!Oe){Oe=!0,x=await c(_);continue}if(Q==="webrtc"&&Y.reason==="signaling_failed"&&Y.platformCode===Uo&&!Se){Se=!0;let de=Math.min(Il,D());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(de)}ms for the socket before offering again`),await j(de))continue}if(Y.reason==="join_rate_limited"){let de=sg(Ie,Math.random,D());if(de!==null){if(Ie.attempts+=1,Ie.waitedMs+=de,i(`[gem] ${Q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(de)}ms before presenting again (retry ${Ie.attempts} of ${Fl.maxAttempts})`),await Ht(n,de,_.signal),_.signal?.aborted)throw new b("aborted","the caller aborted while waiting out a join rate limit");x.credentialExpiresAt-n.now()<Ml&&(x=await c(_));continue}}if(ig.has(Y.reason)||Y.reason==="credential_expired"||Q==="webrtc"&&$l(Y)){i(`[gem] ${Q} rung failed (${Y.reason}): ${Jt(Y.cause??Y)} \u2014 `+(ee.length<k.length?`falling through to ${k[ee.length]}`:"no rungs left")),U.push(Y);break}throw i(`[gem] ${Q} rung refused the session (${Y.reason}): ${Y.message}`),Y}}}let ge=U[U.length-1];throw ge===void 0?new b("timeout",`the reconnect budget ran out before any transport (${k.join(", ")}) could be tried`):new b(ge.reason,`every transport tried (${ee.join(", ")}) failed; the last said: ${ge.message}`,{cause:U,platformCode:ge.platformCode})}catch(x){throw we(P),x}};return {listClusterTargets:async(_={})=>eo({client:e,..._}),handleMatchEnded(_,S){let P=s.get(_);if(P!==void 0){s.delete(_);for(let x of P)x(S);}},connect:(async(_={})=>{let S=_.signaling??o();return _.transports===void 0?p(_,S):C(_,_.transports,S)})}}var Tl=["webtransport","webrtc","websocket"],rg=1e4,og=5e3,Il=3e3,Cl=1e3,Ml=1e4,ig=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function $l(t){return t.platformCode!==void 0&&Bo.has(t.platformCode)}var Fl={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function sg(t,e=Math.random,n=1/0){let r=Fl;if(t.attempts>=r.maxAttempts)return null;let o=Math.min(r.budgetMs-t.waitedMs,n);if(o<r.initialDelayMs)return null;let i=r.initialDelayMs*r.factor**t.attempts;return Math.min(i+e()*r.jitterMs,o)}function ag(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&zt():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||lg(e.websocket.url)}function lg(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return _t(e)}function Jo(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var dg=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Ol(t,e){e instanceof b&&(!dg.has(e.reason)&&!$l(e)||t.report([{type:"connection_failures_total",value:1}]));}function cg(t,e,n,r,o,i,a,s,l,d){let m=false,c=()=>{m||Ho(t,e.matchId,void 0);};i&&(n.addEventListener("close",c),a&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",c),s?.detach(),we(n),we(r),we(o));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function zo(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Ll(t){if(t.status==="failed")throw new b("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new b("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==Bt)throw new b("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Bt}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:n}=t;if(e===void 0||n===void 0)throw new b("connection_failed",`match ${t.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...t,joinCredential:e,credentialExpiresAt:n}}function Gl(){let t=globalThis.RTCPeerConnection;if(!t)throw new b("misconfigured","this environment has no RTCPeerConnection. Pass `peerConnection` to connect against a stand-in, which is how the flow is tested outside a browser.");return new t({iceServers:[]})}function we(t){try{t.close();}catch{}}function ur(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var ug=1e4;function jl(t,e){return Yo(t,e)}function Yo(t,e){if(typeof t.serverToken!="function"||typeof t.onServerToken!="function")throw new Error("this runtime delivers no game-server token: host.serverToken/onServerToken are missing. The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let n=a=>({token:a.token,expiresAt:a.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,o=new on({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((a,s)=>{let l=e.clock.setTimeout(()=>{r=null,s({reason:"unavailable",retryable:true});},e.timeoutMs??ug);r={resolve:d=>{e.clock.clearTimeout(l),a(d);},reject:s,timer:l};})}),i=t.onServerToken(a=>{let s=n(a),l=r;if(l){r=null,l.resolve(s);return}o.accept(s);});return {source:o,dispose(){i(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var Qo={};Sd(Qo,{acceptTransfer:()=>mg,addEntityProgression:()=>pg,adminAction:()=>gg,cancelInventoryTransfer:()=>yg,claimEntityProgressionRewards:()=>fg,closeGameRoom:()=>hg,createEntityBatchOrder:()=>bg,createEntityOrder:()=>vg,createSession:()=>_g,deleteEntityGameSetting:()=>wg,deleteEntitySave:()=>Sg,deleteSession:()=>Rg,deleteShowcaseValue:()=>kg,executeEntityRecipe:()=>xg,finalizeSaveUpload:()=>Ag,getChannelAssignment:()=>Pg,getDropRates:()=>Eg,getEntityCurrency:()=>Tg,getEntityGameSetting:()=>Ig,getEntityInventory:()=>Cg,getEntityInventoryItem:()=>Mg,getEntityLeaderboard:()=>Og,getEntityOrder:()=>Lg,getEntityProgression:()=>Gg,getEntityRecipeAvailability:()=>Dg,getEntityRecipeUsage:()=>$g,getEntitySave:()=>Fg,getEvent:()=>jg,getGameRoomV2:()=>qg,getLeaderboard:()=>Ng,getPlayerGameProfile:()=>Ug,getPurchaseCatalog:()=>Bg,getResolvedTemplate:()=>Hg,getRoomArgs:()=>Vg,getShowcaseValue:()=>Wg,getTransferDetails:()=>Kg,ingestAnalyticsEvents:()=>Xo,initiateInventoryTransfer:()=>Jg,invokeFunction:()=>zg,kickPlayer:()=>Yg,listChallenges:()=>Xg,listEntityGameSettings:()=>Qg,listEntityOrders:()=>Zg,listEntityProgressions:()=>ey,listEntitySaves:()=>ny,listEvents:()=>ty,listGameRooms:()=>ry,listResolvedTemplates:()=>oy,listTransfers:()=>iy,maxEntityProgression:()=>sy,putEntityGameSetting:()=>ay,putRoomArgs:()=>ly,putShowcaseValue:()=>dy,rejectTransfer:()=>cy,requestSaveUploadUrl:()=>uy,resetEntityProgression:()=>my,simulateEntityOrder:()=>py,transferHostV2:()=>gy,updateGameRoomV2:()=>yy});function h(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function mg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function pg(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/add`;return t.client.post(a,o,i?.signal)}async function gg(t,e,n,r){let o=`/v1/voice/sessions/${h(e)}/admin`;return t.client.post(o,n,r?.signal)}async function yg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function fg(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/claim`;return t.client.post(a,o,i?.signal)}async function hg(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.delete(r,n?.signal)}async function bg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function vg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function _g(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function wg(t,e,n,r,o){let i=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(i,o?.signal)}async function Sg(t,e,n,r,o){let i=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(i,o?.signal)}async function Rg(t,e,n){let r=`/v1/voice/sessions/${h(e)}`;return t.client.delete(r,n?.signal)}async function kg(t,e,n,r){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.delete(o,r?.signal)}async function xg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ag(t,e,n,r,o,i){let a=`/v1/saves/${h(e)}/${h(n)}/${h(r)}/finalize`;return t.client.post(a,o,i?.signal)}async function Pg(t,e,n){let r=`/v1/games/${h(t.gameId())}/config/channels/${h(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Eg(t,e,n){let r=`/v1/inventory/loot-tables/${h(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Tg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/currencies/${h(r)}`;return t.client.get(i,o?.signal)}async function Ig(t,e,n,r,o){let i=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Cg(t,e,n,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${h(e)}/${h(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Mg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/items/${h(r)}`;return t.client.get(i,o?.signal)}async function Og(t,e,n,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let a=i.toString(),s=`/v1/leaderboards/${h(e)}/${h(n)}/${h(r)}`+(a?`?${a}`:"");return t.client.get(s,o?.signal)}async function Lg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders/${h(r)}`;return t.client.get(i,o?.signal)}async function Gg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}`;return t.client.get(i,o?.signal)}async function Dg(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/catalogs/${h(r)}/recipes/${h(o)}/availability`;return t.client.get(a,i?.signal)}async function $g(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${h(e)}/${h(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Fg(t,e,n,r,o){let i=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function jg(t,e,n){let r=`/v1/events/${h(e)}`;return t.client.get(r,n?.signal)}async function qg(t,e,n){let r=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Ng(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${h(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Ug(t,e,n){let r=`/v1/profiles/players/${h(e)}`;return t.client.get(r,n?.signal)}async function Bg(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Hg(t,e,n){let r=`/v1/game-room-templates/${h(e)}`;return t.client.get(r,n?.signal)}async function Vg(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/room-args`;return t.client.get(r,n?.signal)}async function Wg(t,e,n,r){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.get(o,r?.signal)}async function Kg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}`;return t.client.get(r,n?.signal)}async function Xo(t,e,n){let r=`/v1/games/${h(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true})}async function Jg(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function zg(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function Yg(t,e,n,r){let o=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/kick/${h(n)}`;return t.client.post(o,void 0,r?.signal)}async function Xg(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),o="/v1/challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Qg(t,e,n,r){let o=`/v1/settings/${h(e)}/${h(n)}`;return t.client.get(o,r?.signal)}async function Zg(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${h(e)}/${h(n)}/orders`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function ey(t,e,n,r){let o=`/v1/inventory/${h(e)}/${h(n)}/progressions`;return t.client.get(o,r?.signal)}async function ny(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${h(e)}/${h(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function ty(t,e){let n=new URLSearchParams;e?.include_inactive!==void 0&&n.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.offset!==void 0&&n.set("offset",String(e?.offset));let r=n.toString(),o="/v1/events"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function ry(t,e){let n=new URLSearchParams;e?.status!==void 0&&n.set("status",String(e?.status)),e?.game_channel!==void 0&&n.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&n.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&n.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&n.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o=`/v1/games/${h(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function oy(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function iy(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function sy(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/max`;return t.client.post(a,o,i?.signal)}async function ay(t,e,n,r,o,i){let a=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ly(t,e,n,r){let o=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/room-args`;return t.client.put(o,n,r?.signal)}async function dy(t,e,n,r,o){let i=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.put(i,r,o?.signal)}async function cy(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function uy(t,e,n,r,o,i){let a=`/v1/saves/${h(e)}/${h(n)}/${h(r)}/upload-url`;return t.client.post(a,o,i?.signal,{replaySafe:true})}async function my(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/reset`;return t.client.post(a,o,i?.signal)}async function py(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders/simulate`;return t.client.post(i,r,o?.signal)}async function gy(t,e,n,r){let o=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}/transfer/${h(n)}`;return t.client.post(o,void 0,r?.signal)}async function yy(t,e,n,r){let o=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.patch(o,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var fy=1e4,hy=50,by=1e3,vy=65536-4*1024,ql=t=>typeof t=="number"?t:0,_y=t=>typeof t=="string"?t:"";function Nl(){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 wy(t){return t?.retryable===true}function Sy(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:ql(i.index),code:_y(i.code)}}):[];return {accepted:ql(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Ul(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 Bl(t){let e=Math.max(1,Math.floor(t.maxQueue??by)),n={client:t.client,gameId:()=>t.gameId},r=[],o=0,i=null,a=false,s=false,l=false,d=false,m=w=>{t.log?.(w);},c=()=>{i!==null&&(t.clock.clearTimeout(i),i=null);},p=()=>{i!==null||a||s||(i=t.clock.setTimeout(()=>{i=null,y().catch(()=>{});},fy));},g=()=>{let w=Math.min(r.length,100),R=128;for(let C=0;C<w;C+=1){let M=r[C];if(M===void 0)break;if(R+=JSON.stringify(Ul(M,0)).length+1,R>vy)return Math.max(1,C)}return w};async function y(w){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};c();let R=r.splice(0,g()),C=o;o=0;let M=Math.round(t.clock.now()),_={batch_id:Nl(),sent_at_ms:M,events:R.map(S=>Ul(S,M))};s=true;try{let S=await Xo(n,_,w===void 0?void 0:{signal:w}),P=Sy(S,C);for(let x of P.rejected)m(`[gem] analytics: an event was refused (${x.code}). See the analytics_events section of your game config.`);return P}catch(S){if(wy(S))for(r=[...R,...r],o+=C;r.length>e;)r.shift(),o+=1;else m(`[gem] analytics: ${R.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(S)}`);throw S}finally{s=false,r.length>0&&p();}}return {track(w,R,C={}){if(a)return;if(typeof w!="string"||w===""){d||(d=true,m(`[gem] analytics: '${R}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(R.startsWith(Hr)){l||(l=true,m(`[gem] analytics: '${R}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let M={},_={};for(let[S,P]of Object.entries(C))typeof P=="string"?M[S]=P:typeof P=="number"&&Number.isFinite(P)&&(_[S]=P);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:Nl(),playerId:w,name:R,atMs:t.clock.now(),dimensions:M,measures:_}),r.length>=hy?y().catch(()=>{}):p();},flush:w=>y(w),get pending(){return r.length},dispose(){a=true,c(),r=[],o=0;}}}function Hl(t){return {async list(e){let{playerId:n,periodsBack:r,signal:o}=e??{};if(typeof n!="string"||n==="")throw new TypeError("gem.challenges.list needs { playerId }: a game-server token names no player, so the platform cannot tell whose period you mean. Pass the id from join() or gem.players().");cn(r);let i=await t({player_id:n,...r===void 0?{}:{periods_back:r},...o===void 0?{}:{signal:o}});return Ft(i)}}}function Ry(t){let e={};for(let[n,r]of Object.entries(Qo))if(typeof r=="function"){let o=r;e[n]=(...i)=>o(t,...i);}return e}function _n(t,e={}){let n=e.clock??le,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let o=Yo(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=dr({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),a=new Le({transport:i,clock:n}),s={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=Ry({client:a,gameId:()=>s.gameId}),d=s.gameRoomId,m=t.endMatch,c=t.log,p=Bl({client:a,clock:n,gameId:s.gameId,...typeof c=="function"?{log:y=>c.call(t,y)}:{}});return {identity:s,client:a,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(t);}},analytics:p,functions:new De(l.invokeFunction),challenges:Hl(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let w=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),R=w.modified?w.body:void 0;if(R?.room_args==null||R.room_args_template==null)throw new G("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:R.room_args,room_args_template:R.room_args_template}}}},dispose:()=>{p.dispose(),o.dispose();}}}function Ye(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function wn(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function it(t){return typeof t=="string"?t:t.slice().buffer}function mr(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 ky=5e3,Vl=3e4,Wl=2e3,xy=1e4,Kl=1;async function Jl(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let o=e.log===void 0?f=>console.info(f):e.log,i=f=>o?.(`[gem host] ${f}`),a=typeof t=="function"?t():t,s=Promise.resolve(),l=true,d=false,m=(f,E)=>{l&&(s=s.then(async()=>{if(!d)try{await E();}catch($){i(`the bundle's ${f} handler threw: ${Xe($)}. Serving continues.`);}}));},c=true,p,g,y,w=f=>{if(!c)return;c=false,m("leave",()=>a.leave?.(r,{cause:f??"left"}));let E=g;E&&queueMicrotask(()=>E(f));},R={send(f,E){if(!c)return;let $=wn(Ye(E));m("message",()=>a.message?.(r,f,typeof f=="string",{reliable:$.reliable,ordered:$.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){w("closed");}},C=(f,E)=>{if(!c)return;let $=wn(Ye(E));queueMicrotask(()=>{c&&p?.(f,$);});},M=new Map,_=f=>{let E=[];for(let $ of Me){let ne=f.channels[$];try{ne.binaryType="arraybuffer";}catch{}let J=wn($),Sn=pr=>{let en=mr(pr?.data);en!==null&&m("message",()=>a.message?.(f.playerId,en.data,en.isText,{reliable:J.reliable,ordered:J.ordered}));};ne.addEventListener("message",Sn),E.push(()=>ne.removeEventListener("message",Sn));}M.get(f.playerId)?.forEach($=>$()),M.set(f.playerId,E);},S=f=>{M.get(f)?.forEach(E=>E()),M.delete(f);},P=new Set,x=new Map,V=(f,E,$)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...E?{rejoin:true}:{},...$?{superseded:true}:{}}),N=f=>{let E=M.has(f.playerId),$=P.has(f.playerId);P.add(f.playerId),_(f),E&&m("leave",()=>a.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>a.join?.(f.playerId,V(f,$,E)));},W=new Set,k=(f,E,$)=>{if(f===r){C(E,$);return}let ne=n.peer(f);if(ne===null){let J=x.get(f);if(J!==void 0&&e.clock.now()-J<Wl)return;W.has(f)||(W.add(f),i(`send to '${f}' dropped: no such connected player`));return}ne.send(it(E),Ye($));},A={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:f=>e.tokens.subscribe(f),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(f=>f.playerId)??[],players(){let f=c?[r]:[];for(let E of n.peers)f.push(E.playerId);return f},profile(f){let E=e.room()?.members.find($=>$.playerId===f);if(!(!E||E.displayName===void 0))return {displayName:Ne.toPlain(E.displayName),...E.displayTag===void 0?{}:{displayTag:Ne.toPlain(E.displayTag)},...E.discriminator===void 0?{}:{discriminator:E.discriminator}}},playerNumber(f){return f===r?Kl:n.peer(f)?.assignedPeerId},send(f,E,$){k(f,E,$);},broadcast(f,E){let $=E?.except;c&&r!==$&&C(f,E);for(let ne of n.peers)ne.playerId!==$&&ne.send(it(f),Ye(E));},async endMatch(){let f=await Ce();return f.answer!=="ok"&&i(f.cause),f.answer},kick(f,E){if(f===r){w(E??"kicked");return}n.kick(f).catch($=>{i(`kick of '${f}' failed: ${Xe($)}`);});},log(f){i(f);},warn(f){i(`\u26A0 ${f}`);}},L=()=>{},D=new Promise(f=>{L=f;}),j=[],U=null,ee=async(f,E)=>{l=false;let $=s.then(async()=>{try{await a.shutdown(f);}catch(ne){i(`the bundle's shutdown threw: ${Xe(ne)}`);}});s=$,await $,de();for(let ne of j.splice(0))ne();for(let ne of [...M.keys()])S(ne);w(E);},ge=(f,E)=>U||(U=(async()=>{await ee(E,f),n.close(),L();})(),U),Q=()=>U||(U=(async()=>{await ee({reason:"signal"},"left"),await n.leave().catch(f=>i(`leaving the match failed: ${Xe(f)}`)),L();})(),U),Oe=()=>U||(U=(async()=>{l=false;let f=await Ce();f.answer==="ok"?(await ee({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(i(`${f.cause}; leaving instead`),await ee({reason:"signal"},"left"),await n.leave().catch(E=>i(`leaving the match failed: ${Xe(E)}`))),L();})(),U),Se=null,Ie=()=>(Se??=_n(A,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),Se),Ce=async()=>{try{return await ps({client:Ie().client,gameId:()=>A.gameId},A.matchId,{},{signal:AbortSignal.timeout(ky)}),{answer:"ok"}}catch(f){return f instanceof G&&(f.reason==="forbidden"||f.reason==="not_found")?{answer:f.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${f.reason})`}:{answer:"failed",cause:`ending the match failed: ${Xe(f)}`}}},re=null,Y=false,de=()=>{Y=true,re!==null&&(e.clock.clearTimeout(re),re=null);},q=async()=>{if(re=null,!Y){try{await Ie().client.post(`/v1/games/${encodeURIComponent(A.gameId)}/matches/${encodeURIComponent(A.matchId)}/heartbeat`,void 0,AbortSignal.timeout(xy));}catch(f){if(f instanceof G&&(f.reason==="forbidden"||f.reason==="not_found")){i(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),de();return}i(`heartbeat failed: ${Xe(f)}`);}Y||(re=e.clock.setTimeout(()=>{q();},Vl));}},dt=()=>{Y||re!==null||(re=e.clock.setTimeout(()=>{q();},Vl));};{let f=L;L=()=>{de(),Se?.dispose(),Se=null,f();};}let Ze=Promise.resolve().then(()=>a.init(A));s=Ze.then(()=>{},()=>{}),m("join",()=>a.join?.(r,{playerNumber:Kl,transport:"loopback"})),j.push(n.on("peerJoined",N)),j.push(n.on("peerLeft",(f,E)=>{S(f);let $=e.clock.now();for(let[ne,J]of x)$-J>=Wl&&x.delete(ne);x.set(f,$),W.delete(f),m("leave",()=>a.leave?.(f,{cause:E}));})),j.push(n.on("error",f=>{i(`\u26A0 session error: ${f.message}`);})),j.push(n.on("matchEnded",f=>{U||Zo(y,f),ge("match ended",{reason:"match_ended",platform_reason:f});})),j.push(n.on("hostChanged",f=>{f!==r&&ge("host migrated",{reason:"host_migrated"});}));for(let f of n.peers)N(f);try{await Ze,dt();}catch(f){l=false,de(),d=true;for(let E of j.splice(0))E();for(let E of [...M.keys()])S(E);throw n.leave().catch(()=>{}),L(),f}return {matchId:n.matchId,localLink:R,onMatchEnded(f){y=f;},end:Oe,leave:Q,stop:f=>ge(f,{reason:"stopped"}),done:D}}function Zo(t,e){try{t?.(e);}catch{}}function Xe(t){return t instanceof Error?t.message:String(t)}function ei(t,e){let n=async()=>{throw new b("misconfigured",`this seat is \`${t}\`, not the match's authority: `+(t==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:t,matchId:e,end:n,leave:n,stop:async()=>{}}}function zl(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,o=new Map,i=async s=>{r.isHost&&!zo(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...s.signal===void 0?{}:{signal:s.signal}});let l={...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},a=s=>({...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0?{}:{clusterTargetId:s.clusterTargetId}});return {async serve(s,l={}){let d=await i(l);if(d.protocol!==Je)return ei("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return ei("peer",d.matchId);let c=t.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(a(l)),g=await Jl(s,{session:p,clock:t.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return o.set(d.matchId,g),g.done.then(()=>{o.get(d.matchId)===g&&o.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(s={}){let l=await i(s),d=s.onMatchEnded;if(l.protocol===Je){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),Ty(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let y=await Qn(),w=async()=>t.p2p.connect({...a(s),certificate:y}),R=await w(),C=Cy(R,w,d,M=>{r.notifyMatchDisconnected(M).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(R.matchId,{redial:C.redial,abandon:C.abandon}),C.onClosed(()=>{e.get(R.matchId)?.abandon===C.abandon&&e.delete(R.matchId);})),C}let m=async(g=null)=>await t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:s.transports??[]}),c=await m(),p=Iy(c,m,r,n);return n&&(e.set(c.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(c.matchId)?.abandon===p.abandon&&e.delete(c.matchId);})),p},async redialMatch(s,l){let d=e.get(s);return d===void 0?"closed":d.redial(l)},abandonMatch(s,l){e.get(s)?.abandon(l);}}}var Yl="link_closed",Ay="host_unreachable",Py=new Set(["failed","closed"]);function Ey(t){return Py.has(t)?Yl:Ay}function Ty(t,e,n){let r=e.localLink;e.onMatchEnded(n);let o="connected";r.onClose(()=>{o="closed";});let i;return {matchId:t,protocol:"loopback",get state(){return o},send:(a,s)=>r.send(a,s),onMessage:a=>r.onMessage(a),onClose:a=>{i=a,r.onClose(s=>{o="closed",i?.(s);});},close:()=>r.close()}}function Iy(t,e,n,r){let o=t.matchId,i=t,a="connected",s,l,d=[],m=false,c=false,p=y=>{if(a!=="closed"){a="closed";for(let w of d.splice(0))w();l?.(y);}},g=y=>{y.link.onMessage((w,R)=>s?.(w,R)),y.link.onClose(w=>{if(y!==i||a==="closed")return;if(m||!r){p(w);return}let R=n.matchSession;if(R.phase==="suspended"&&R.matchId===o){a="suspended";return}p(w);});};return g(t),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return a},send(y,w){a==="connected"&&i.link.send(y,w);},onMessage(y){s=y;},onClose(y){l=y;},close(){if(a!=="closed"){if(m=true,a==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(y){if(a==="closed"||m)return "closed";if(c)return "connected";c=true;let w;try{w=await e(y===void 0?{}:{deadlineAt:y});}finally{c=false;}return m||a==="closed"?(w.close(),"closed"):(i=w,g(w),a="connected",n.notifyMatchConnected(o),"connected")},abandon(y){a!=="closed"&&(a==="connected"&&i.close(),p(y));},onClosed(y){a==="closed"?y():d.push(y);}}}function Cy(t,e,n,r,o,i=false){let a=t.matchId,s=t,l,d,m=[],c=[],p=[],g=false,y=false,w=false,R=false,C="connected",M=k=>{if(g)return;g=true,C="closed";for(let L of m.splice(0))L();for(let L of c.splice(0))L();for(let L of p.splice(0))L();let A=d;A&&queueMicrotask(()=>A(k));},_=k=>{for(let A of m.splice(0))A();for(let A of Me){let L=k.channels[A];try{L.binaryType="arraybuffer";}catch{}let D=wn(A),j=U=>{let ee=mr(U?.data);ee!==null&&l?.(ee.data,D);};L.addEventListener("message",j),m.push(()=>L.removeEventListener("message",j));}},S=()=>s.peer(s.hostPlayerId),P=k=>{if(!(g||s.isHost)&&C!=="suspended"){if(r?.(k),i){C="suspended";return}M(k);}},x=k=>{for(let A of Me){let L=k.channels[A];if(typeof L.addEventListener!="function")continue;let D=()=>{S()===k&&P(Yl);};L.addEventListener("close",D),m.push(()=>L.removeEventListener?.("close",D));}},V=k=>{_(k),x(k),!g&&(C="connected",o?.());},N=k=>{for(let A of c.splice(0))A();c.push(k.on("migrating",()=>{R=true;})),c.push(k.on("hostChanged",A=>{if(R=false,A===k.playerId){M("host_migrated_here");return}let L=S();L!==null&&V(L);})),c.push(k.on("peerJoined",A=>{A.playerId===k.hostPlayerId&&V(A);})),c.push(k.on("matchEnded",A=>{g||Zo(n,A),M(A);})),c.push(k.on("peerLeft",(A,L)=>{A===k.hostPlayerId&&P(Ey(L));}));};N(s);let W=S();return W!==null&&V(W),{matchId:a,protocol:"p2p",get state(){return C},send(k,A){C==="connected"&&S()?.send(it(k),Ye(A));},onMessage(k){l=k;},onClose(k){d=k;},close(){y=true,M("closed"),s.leave().catch(()=>{});},async redial(){if(C==="closed")return "closed";if(C==="connected"||w)return "connected";if(R)throw new O("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");w=true;let k;try{for(let L of m.splice(0))L();for(let L of c.splice(0))L();s.close(),k=await e();}finally{w=false;}if(g)return y?k.leave().catch(()=>{}):k.close(),"closed";s=k,N(s);let A=S();if(A===null)throw s.close(),new O("connection_failed","this peer rejoined the match but the host never answered with a link");return V(A),"connected"},abandon(k){M(k);},onClosed(k){g?k():p.push(k);}}}function ni(t){let e=0,n=new Map;return {resolve(){if(!t.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(o=>{let i={},a=l=>{n.delete(r)&&(t.clock.clearTimeout(i.timer),o(l));};n.set(r,a),i.timer=t.clock.setTimeout(()=>a(void 0),t.timeoutMs??2e3);let s=false;try{s=t.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,o){n.get(r)?.(o);}}}var My=12e4;function Qe(t,e){return {outcome:t,reason:e}}function Xl(t){let e=false,n=new Map;return {api:{request(r){if(!t.bridge.parentSupports("purchases"))return Promise.resolve(Qe("unavailable","error"));if(e)return Promise.resolve(Qe("declined","busy"));let o=`purchase-${Ae()}`;return new Promise(i=>{let a={},s=d=>{n.delete(o)&&(e=false,t.clock.clearTimeout(a.timer),i(d));};e=true,n.set(o,s),a.timer=t.clock.setTimeout(()=>s(Qe("unavailable","error")),t.timeoutMs??My);let l=false;try{l=t.bridge.requestPurchase(o,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||s(Qe("unavailable","error"));})}},settle(r){let o=r.outcome==="ok"||r.outcome==="declined"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}if(o!=="ok"){i(Qe(o,Ms(r.reason)));return}let a=r.purchaseId;if(a===void 0){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),i(Qe("unavailable","error"));return}(async()=>{let s;try{s=await t.confirm(a);}catch{s="unknown";}if(s==="granted"){i({outcome:"ok",purchaseId:a});return}s==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for purchase "+JSON.stringify(a)),i(Qe("unavailable","error"));})();}}}async function Ql(t,e){try{return (await Qi(t,e)).granted?"granted":"absent"}catch(n){return n instanceof G&&n.reason==="not_found"?"absent":"unknown"}}var Oy=6e5;function Zl(t){let e=null,n=new Map;return {api:{requestSignIn(){if(!t.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${Ae()}`;return e=new Promise(o=>{let i={},a=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(i.timer),o(l));};n.set(r,a),i.timer=t.clock.setTimeout(()=>{a({outcome:"unavailable"});},t.timeoutMs??Oy);let s=false;try{s=t.bridge.requestSignIn(r);}catch{}s||a({outcome:"unavailable"});}),e}},settle(r){let o=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.signInResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var Ly=new Set(["play","channel","purchase","devtools","devLocale","playOverlay","social","embedder","_s","fbclid","ttclid","gclid","msclkid"]),Gy=["utm_"];function ed(t){return Ly.has(t)||Gy.some(e=>t.startsWith(e))}var nd=16,td=512,Dy=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,$y=/[\p{Cc}\p{Cf}]/u,Fy=/\p{Cs}/u,Te="[gem] gem.share.request:";function rd(t){let{frame:e,log:n}=t,r=false,o=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,i=a=>{n!==null&&(n===void 0?console.warn(a):n(a));};return {get available(){return o()!==null},request(a){let s=o();if(s===null)throw new Error(`${Te} the arcade does not handle share here \u2014 check gem.share.available first`);if(a!==void 0&&(typeof a!="object"||a===null))throw new TypeError(`${Te} pass { params }, or nothing`);let l=a?.params===void 0?{}:a.params;if(!jy(l))throw new TypeError(`${Te} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>nd)throw new TypeError(`${Te} at most ${nd} params; got ${d.length}`);let m=[];for(let[c,p]of d){let g=JSON.stringify(c);if(!Dy.test(c))throw new TypeError(`${Te} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(ed(c))throw new TypeError(`${Te} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Te} param ${g}: values must be strings`);if(p.length>td)throw new TypeError(`${Te} param ${g}: a value is at most ${td} characters`);if($y.test(p))throw new TypeError(`${Te} param ${g}: control and format characters are not allowed`);if(Fy.test(p))throw new TypeError(`${Te} param ${g}: a value must be well-formed text`);m.push({key:c,value:p});}!s.requestShare(m)&&!r&&(r=true,i("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function jy(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var qy=18e4,od=32,Ny=/^[a-z0-9_-]+$/;function Uy(t){return t==="interstitial"||t==="rewarded"}function id(t){let e=false,n=new Map;return {api:{requestAd(r){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});if(typeof r.placement!="string"||r.placement===""||r.placement.length>od||!Ny.test(r.placement)||!Uy(r.format))return t.onDropped?.(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${JSON.stringify(r.placement)}, format ${JSON.stringify(r.format)}. A placement is 1..${String(od)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});let o=`ad-${Ae()}`,i=r.format,a=r.placement;return new Promise(s=>{let l={},d=c=>{n.delete(o)&&(e=false,t.clock.clearTimeout(l.timer),s(c));};e=true,n.set(o,d),l.timer=t.clock.setTimeout(()=>{d({outcome:"unavailable"});},t.timeoutMs??qy);let m=false;try{m=t.bridge.requestAd(o,a,i);}catch{}m||d({outcome:"no_ad"});})}},settle(r){let o=r.outcome==="shown"||r.outcome==="no_ad"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.adResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var ti=16384;function sd(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:By(e)}function By(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let o=t.charCodeAt(n+1);o>=56320&&o<=57343?(e+=4,n+=1):e+=3;}else e+=3;}return e}var Hy=1e4,Vy=5e3;function ad(t){let e=null,n=false,r=[],o=new Map,i=()=>{for(let a of r.splice(0))a();};return {api:{get current(){return e},wait(a=Vy){return n?Promise.resolve(e):new Promise(s=>{let l=()=>{let c=r.indexOf(d);c>=0&&r.splice(c,1);},d=()=>{t.clock.clearTimeout(m),l(),s(e);},m=t.clock.setTimeout(()=>{l(),s(e);},a);r.push(d);})},put(a){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let s=sd(a);if(s===null)return t.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(s>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(a)),d=`device-settings-${Ae()}`;return new Promise(m=>{let c={},p=y=>{o.delete(d)&&(t.clock.clearTimeout(c.timer),y==="stored"&&(e=l,n=true,i()),m(y));};o.set(d,p),c.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??Hy);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(a){let s=a.settings;e=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:null,n=true,i();},settle(a){let s=a.outcome==="stored"||a.outcome==="too_large"?a.outcome:"unavailable",l=o.get(a.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${s}) for an unknown requestId: `+JSON.stringify(a.requestId));return}l(s);}}}var st=class extends Error{constructor(){super("createGem: this game is not framed (window.parent === window), so nothing can hand it a player, saves, config or rooms. Play it in the Gem Arcade or the Gem Editor, or through the Gem dev host on this machine: `npm run dev` (`gemctl serve start . --dev`) while editing, `gemctl serve start .` for a build, signed in to gemctl. Do not open the dev server's own address."),this.name="GemUnframedError";}};function ld(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function ri(t,e){if(t!==true)return {visible:false};let n=[],r=false;for(let o of Array.isArray(e)?e:[])o==="score"?r=true:typeof o=="string"&&o.length>0&&o.length<=64&&!n.includes(o)&&n.push(o);return !r&&n.length===0?{visible:true}:{visible:true,currencies:n.slice(0,8),score:r}}function dd(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Wy(t){let e=t.untrusted,n=ye(e.displayName),r=e.displayTag||e.displayHandle,o=r?ye(r):void 0,i=t.discriminator||t.displayTag,a=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,s=t.avatarIconUrl||t.avatarUrl,l={displayName:n,displayHandle:o??n,badges:(t.badges??[]).map(p=>({itemId:p.itemId,iconUrl:p.iconUrl}))};t.playerId&&(l.playerId=t.playerId),a&&(l.discriminator=a),o&&(l.displayTag=o),s&&(l.avatarIconUrl=l.avatarUrl=s);let d=t.boost,m=(d?.multipliers??[]).map(p=>({currencyId:p.currencyId,currencySlug:p.currencySlug,multiplier:p.multiplierBp/1e4})),c=m.some(p=>p.multiplier>1);return l.boost=c&&d?.expiresInDays?{active:c,multipliers:m,expiresInDays:d.expiresInDays}:{active:c,multipliers:m},l}var Ky=1e4,at=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??le,this.inbound=new xn(this.clock),this.outbound=new xn(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(s=>Ar(s,e.origin))||Es(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=vt["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!Ar(o.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${o.embedder}' but arrived from '${e.origin}'`),false;let i=e.ports?.[0];if(!i)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=Ts(ht,o.versions);return a===null?(i.onmessage=null,i.postMessage({gem:K,type:"gem.error",code:"version_mismatch",message:`frame supports v${ht.min}..v${ht.max}`}),i.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=i,this.version=a,i.onmessage=s=>this.receive(s.data,s.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],this.unbidden=o.unbidden===true,i.postMessage({gem:K,type:"gem.handshake.accept",v:a,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:K,type:"gem.ready"});}settled(e=Ky){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=i=>{this.clock.clearTimeout(o),n(i);},o=this.clock.setTimeout(()=>{let i=this.settleWaiters.indexOf(r);i>=0&&this.settleWaiters.splice(i,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem:K,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:K,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:K,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:K,type:"gem.exit"}:{gem:K,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:K,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:K,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:K,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:K,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let n={gem:K,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(n.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(n.origin={x:ld(e.origin.x),y:ld(e.origin.y)}),this.send(n),true}setWalletVisible(e,n){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:K,type:"gem.walletDisplay",...ri(e,n?.only)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:K,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:K,type:"gem.frameStats",fps:dd(e.fps,1e3),frameTimeP95Ms:dd(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:K,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:K,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:K,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:K,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,o,i,a){return this.send({gem:K,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:o,...i===void 0?{}:{quantity:i},...a===void 0?{}:{catalogId:a}})}putDeviceSettings(e,n){return this.send({gem:K,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:K,type:"gem.requestAd",requestId:e,placement:n,format:r})}requestSignIn(e){return this.send({gem:K,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,o){return this.send({gem:K,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...o===void 0?{}:{params:o}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(bt)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(bt)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(bt)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:K,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let n=e.type;if(!this.outbound.allow(n))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${n}`),false;let r=vt[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||cd(n);}}dispatchInbound(e,n){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let o=vt[r];if(!o)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let i=xs(r);if(i!==void 0&&!this.options.capabilities?.includes(i))return this.fail("unsupported_capability",`${r} requires the '${i}' capability, which this frame did not advertise`),false;let a=o(e);if(a)return this.fail("invalid_message",`${r}: ${a}`),false;let s=e;if(s.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(s);break;case "gem.pause":this.options.onPause?.(s);break;case "gem.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(s);break;case "gem.willTerminate":this.options.onWillTerminate?.(s);break;case "gem.devtools":this.options.onDevtools?.(s.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=n[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:s.maxWidth,maxHeight:s.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return cd(n.slice(1)),this.options.onScreenshot(d,l,(m,c)=>this.screenshotDenied(m,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(Wy(s));break}case "gem.roomEvent":this.options.onRoomEvent?.(s);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(s);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(s);break;case "gem.socketState":this.options.onSocketState?.(s);break;case "gem.signalEvent":this.options.onSignalEvent?.(s);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(s);break;case "gem.clusterTarget":this.options.onClusterTarget?.(s);break;case "gem.partyResult":this.options.onPartyResult?.(s);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(s);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(s);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(s);break;case "gem.adResult":this.options.onAdResult?.(s);break;case "gem.signInResult":this.options.onSignInResult?.(s);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(s);break;case "gem.error":this.options.onError?.(s.code,s.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:K,type:"gem.screenshot.denied",reason:e,retryable:n});}};function cd(t){for(let e of t)try{e?.close?.();}catch{}}var ud="https://api.gemarcade.com";function oi(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 Jy=new Set(["localhost","127.0.0.1","[::1]"]);function md(t){let e=oi(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!Jy.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 zy=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),Yy=ud,pd=8e3,ii=15e3,Xy=9e4,Qy=1/0,Zy=8e3,ef=5e3,nf=5e3;async function tf(t,e,n,r){if(t.isInRoom)try{await t.leave();}catch{}r?.endSession("session_ended"),e!==null&&e.currentState==="connected"&&e.exit(n);}function lt(t){let e=null,n=false,r=[];return {get current(){return e},set(o){e=o;for(let i of r.splice(0))i(o);},release(){n=true;for(let o of r.splice(0))o(e);},wait(o){return e!==null||n?Promise.resolve(e):new Promise(i=>{let a=()=>{let d=r.indexOf(s);d>=0&&r.splice(d,1);},s=d=>{t.clearTimeout(l),a(),i(d);},l=t.setTimeout(()=>{a(),i(e);},o);r.push(s);})}}}function MS(t={}){let e=t.clock??le,n=t.log===void 0?u=>console.info(u):t.log,r=t.baseUrl??void 0;if(r!=null){let u=oi(r);if(u!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${u}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let o=jo();o.mark("sdk created");let i=()=>Vt(J.gameVersion,t.clientVersion?.gameVersion),a=new Fn({client:()=>tn,clock:e,gameId:()=>J.identity?.gameId??null,playerId:()=>J.identity?.playerId??null,environment:()=>{let u=i();return {sdk_version:hi(),...u===null?{}:{game_version:u}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),s=nl(()=>{o.mark("engaged"),a.release(),q.reportEngaged();},typeof window>"u"?{}:window),l=u=>{if(u===false)return null;let T=u?.attempts??Qy,F=u?.budgetMs??Xy;return !(T>0)||!(F>0)?null:{attempts:T,budgetMs:F,maxDelayMs:u?.maxDelayMs??Zy}},d=u=>{u.on("created",()=>{o.mark("room created");}),u.on("joined",()=>{o.mark("room joined");}),u.on("matchAllocationStarted",()=>{o.mark("allocation started");}),u.on("matchReady",()=>{o.mark("match ready");}),u.on("matchFailed",()=>{o.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new st;let m=t.allowedEmbedders;if(m!=null&&!Array.isArray(m))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let c=Array.from(m??[]),p=c.filter(u=>typeof u!="string"||!xr(u));if(p.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${p.length===1?"an entry":"entries"} that ${p.length===1?"is":"are"} not an origin: ${p.map(u=>typeof u=="string"?JSON.stringify(u):String(u)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let g=Object.freeze([...new Set([...zy,...c])]),y=lt(e),w=lt(e),R=lt(e),C=ra(n),M=lt(e),_=t.manageAudio===false?null:dl(),S=null,P=()=>{S!==null&&(w.current!==null&&w.current.muted===S||q.reportMuted(S));},x=null,V=null,N=()=>{if(x===null)return false;let u=JSON.stringify(ri(x.visible,x.only));return u===V?q.parentSupports("walletDisplay"):q.setWalletVisible(x.visible,x)?(V=u,true):false},W=cl({report:u=>q.reportFrameStats(u)}),k=false,A=hl(()=>fi,()=>k),L=u=>{let T=k&&!u,F=k!==u;if(k=u,T&&A.close(),!!F)try{t.onDevToolsPermissionChange?.(u);}catch(te){n?.(`[gem] onDevToolsPermissionChange threw: ${te instanceof Error?te.message:String(te)}`),queueMicrotask(()=>{throw te});}},D=r??Yy,j=r!==void 0,U,ee=u=>(n?.(`[gem] token refused: ${u}`),t.onError?.("internal",u),false),ge=(u,T)=>{if(u===void 0)return T!==void 0?ee("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let F=md(u);return F!==null?ee(`the embedder named an API root that cannot be used: ${F}. Its value is withheld here rather than written to logs.`):U!==void 0&&U!==u?ee("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(U=u,j||(D=u),true)},Q=window.location?.origin,Oe=null,Se=-1/0,Ie=2e3,Ce=new Set,re=u=>Oe!==false?Promise.resolve(true):new Promise(T=>{let F=e.setTimeout(()=>{Ce.delete(te),T(false);},u),te=()=>{e.clearTimeout(F),Ce.delete(te),T(true);};Ce.add(te);}),Y=()=>{},de=null,q=new at({allowedEmbedders:g,...typeof Q=="string"&&Q!==""?{selfOrigin:Q}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","earnAllowance","share","frameStats","walletDisplay","engagement","reservedAreas","viewport","purchases","deviceSettings","ads","signIn","friendChallenges",...t.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:u=>{de=u,t.onRefused?.(u);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:u=>{J.onBridgeState(u),u!=="connected"&&W.setRequested(false),V=null,u==="refused"&&(console.error("[gem] this game refused the page that framed it"+(de===null?"":` (${de})`)+", so it has no player, saves, config or rooms. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders."),Y()),u==="connected"&&(o.mark("bridge connected"),pr(),P(),N(),q.unbiddenLaunch&&!s.engaged&&a.hold(),a.startSession(),s.engaged&&q.reportEngaged()),t.onStateChange?.(u);},onPlayer:u=>{y.set(u),t.onPlayer?.(u);},onPrefs:u=>{let T={reducedMotion:u.reducedMotion,muted:u.muted,locale:u.locale,showFrameStats:u.showFrameStats===true};w.set(T),_?.setMuted(T.muted),W.setRequested(T.showFrameStats&&q.parentSupports("frameStats")),t.onPrefs?.(T);},onCohorts:u=>{let T=Object.freeze(u.cohorts.map(F=>Object.freeze({experimentId:F.experimentId,variantKey:F.variantKey})));R.set(T),t.onCohorts?.(T);},onEarnAllowanceChanged:()=>C.emit(),onViewport:u=>{let T=Object.freeze({insets:Object.freeze({top:u.insets.top,right:u.insets.right,bottom:u.insets.bottom,left:u.insets.left}),reserved:Object.freeze((u.reserved??[]).map(te=>Object.freeze({x:te.x,y:te.y,width:te.width,height:te.height})))});M.set(T);let F=ml();pl(F,T.insets),yl(F,T.reserved,gl()),t.onViewport?.(T);},onPause:u=>{a.setPaused(u.paused),W.setPaused(u.paused),t.onPause?.(u.paused);},onWillTerminate:u=>{a.endSession(u.reason),t.onWillTerminate?.({reason:u.reason,graceMs:u.graceMs});},onToken:u=>{let T=u.garden;if(L(u.allowDevTools===true),!ge(u.apiBaseUrl,T))return;let F=u;J.onToken(F);let te=J.identity;te&&(Ze.set(te),f||(f=true,ue.reconcileSeats().catch(()=>{}))),ne.push({token:F.token,expiresAt:F.expiresAt});},onTokenDenied:u=>{L(false),J.onDenied(u);},onScreenshot:(u,T,F)=>{sl(u,T,F,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{al(q,t.onFeedbackContext);},onDevtools:u=>{u==="close"?A.close():u==="open"?A.openFrom("platform").catch(()=>{}):A.isOpen?A.close():A.openFrom("platform").catch(()=>{});},onRoomEvent:u=>ue.handleRoomEvent({event:u.event,roomId:u.roomId,...u.matchId===void 0?{}:{matchId:u.matchId},...u.version===void 0?{}:{version:u.version},...u.reason===void 0?{}:{reason:u.reason},...u.platform===void 0?{}:{platform:u.platform}}),onSeatedEvent:u=>ue.handleSeated(u.roomId),onAutoStartFailedEvent:u=>ue.handleAutoStartFailed(u.roomId,u.code),onSocketState:u=>{let T=Oe;if(Oe=u.connected,u.connected)for(let te of [...Ce])te();if(!u.connected||T===true)return;let F=e.now();F-Se<Ie||(Se=F,ue.reconcile().catch(()=>{}));},onSignalEvent:u=>{let T=typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:{};rn.handleSignalEvent(u.matchId,u.event,T),u.event==="matchEnded"&&ue.reconcile({matchId:u.matchId,...typeof T.reason=="string"?{reason:T.reason}:{}}).catch(()=>{});},onDedicatedEvent:u=>{u.event==="matchEnded"&&(Rn.handleMatchEnded(u.matchId,u.reason),ue.reconcile({matchId:u.matchId,...u.reason===void 0?{}:{reason:u.reason}}).catch(()=>{})),dt.handleEvent(u);},onClusterTarget:u=>ut.accept(u.clusterTargetId,u.clusterTargetIds),onLocalServer:u=>gr.accept(u),onLocalServerDenied:u=>gr.refuse(u),onPartyResult:u=>en.settle(u.requestId,u.partyId),onPurchaseResult:u=>li.settle(u),onDeviceSettings:u=>{ct.receive(u),t.onDeviceSettings?.(ct.api.current);},onDeviceSettingsResult:u=>ct.settle(u),onAdResult:u=>di.settle(u),onSignInResult:u=>ci.settle(u),onFriendChallengeResult:u=>ui.settle(u)}),dt=new ot({bridge:q}),Ze=lt(e);Y=()=>{Ze.release(),y.release(),R.release();},q.currentState==="refused"&&Y();let f=false,E=new Set,$,ne={current:()=>$,subscribe:u=>(E.add(u),$!==void 0&&u($),()=>E.delete(u)),push:u=>{$=u;for(let T of [...E])try{T(u);}catch(F){n?.(`[gem] a server-token listener threw: ${F instanceof Error?F.message:String(F)}`);}}},J=vl({bridge:q,clock:e,onStateChange:(u,T)=>{if(u==="ready"){if(o.mark("token ready")){let F=o.marks.find(te=>te.name==="token ready")?.at;a.trackPlatform("gem_boot_ready",F===void 0?{}:{boot_ms:Math.max(0,Math.round(F))});}}else u==="lost"&&(o.mark("token lost"),a.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(u,T);}}),Sn=()=>{let u=J.identity;return !u||J.source.currentState==="lost"?null:`${u.playerId}\0${u.gameId}\0${u.channel}`},pr=()=>{o.mark("token requested"),J.source.get().catch(()=>{});},en=ni({bridge:q,clock:e}),ai={},li=Xl({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u),confirm:async u=>ai.confirm?.(u)??"unknown"}),ct=ad({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),di=id({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),ci=Zl({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),ui=ta({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),ut=ma({bridge:q,clock:e}),gr=fl({bridge:q,clock:e}),yr=u=>{let T=q.handleWindowMessage({data:u.data,origin:u.origin,source:u.source,ports:u.ports});return T&&window.removeEventListener("message",yr),T};window.addEventListener("message",yr);let nn=tl(window,yr),hd=nn?.capture,fr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];fr?.domInteractive!==void 0&&fr.domInteractive>0&&o.mark("document parsed",fr.domInteractive),hd?.late&&n?.("[gem] the early-handshake capture installed after this document finished loading, so a handshake posted at iframe load may already have been missed. Load the capture script ahead of everything else in the document.");let hr=t.handshakeWarningMs;hr!==null&&n&&e.setTimeout(()=>{let u=nn===null?"no capture script ran":`capture: ${nn.delivered} offer(s) delivered, ${nn.stale} stale, ${nn.capture.dropped} evicted${nn.capture.late?", installed late":""}`;if(q.currentState==="connected"){n(`[gem] handshake connected. boot: ${o.timeline()} \xB7 ${u}`);return}n(`[gem] no completed handshake after ${hr??pd}ms (bridge state: ${q.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${o.timeline()} \xB7 `+u);},hr??pd);let bd=dr({get baseUrl(){return D},tokenSource:J.source,get defaultQuery(){let u=J.identity;return u?{game_id:u.gameId,channel:u.channel}:{}}}),tn=new Le({transport:bd,clock:e}),he={client:tn,gameId:()=>J.identity?.gameId??""};ai.confirm=u=>Ql(he,u);let vd=()=>J.identity?.channel??"release",mi=new $t(he,vd),pi=async u=>(await mi.load())?.currency(u)?.id??void 0,gi=Ct(he,Dr,{identity:Sn,resolveCurrencyId:pi}),br=async u=>{let T=await Ze.wait(u);if(T)return T;throw q.currentState==="refused"?new ie("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new ie("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},vr=l(t.autoReconnect),ue=ko({client:tn,clock:e,gameId:()=>J.identity?.gameId??null,playerId:()=>J.identity?.playerId??null,awaitGameId:async()=>(await br(ii)).gameId,resolveParty:en.resolve,resolveClusterTargets:ut.resolveList,refreshClusterTargets:ut.refresh,ensureLocalServer:gr.ensure,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>J.gameVersion,...t.pollRooms===void 0?{}:{poll:t.pollRooms},...t.recoverStaleMembership===void 0?{}:{recoverStaleMembership:t.recoverStaleMembership},...t.retryAutoStart===void 0?{}:{retryAutoStart:t.retryAutoStart},...t.watchSeats===void 0?{}:{watchSeats:t.watchSeats},...t.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:t.seatPollIntervalMs},...vr===null?{}:{autoReconnect:{...vr,redial:(u,T)=>_r.redialMatch(u,T),abandon:(u,T)=>_r.abandonMatch(u,T)}}});d(ue),Za({analytics:a,rooms:ue});let rn=Qa({client:tn,clock:e,rooms:ue,bridge:q,gameId:()=>J.identity?.gameId??"",baseUrl:()=>D,resolveClusterTarget:ut.resolve,boot:o,...t.log===void 0?{}:{log:t.log}}),yi=Fo(o,n),Rn=Dl({client:tn,clock:e,rooms:ue,signaling:()=>dt.channel(),signalingReady:re,log:n??(()=>{})}),_r=zl({rooms:ue,p2p:{connect:u=>yi(rn.connect(u)),session:u=>rn.session(u)},dedicated:{connect:(u=>sr(o,"welcome",Rn.connect(u),n))},clock:e,identity:()=>J.identity,apiBaseUrl:()=>D,tokens:ne,room:()=>ue.currentRoom,autoReconnect:vr!==null,...t.log===void 0?{}:{log:t.log}}),_d=async()=>(await br(ii)).playerId,fi={client:tn,boot:o,get identity(){return J.identity},awaitIdentity:(u=ii)=>br(u),awaitBridge:u=>q.settled(u),get player(){return y.current},awaitPlayer:(u=ef)=>y.wait(u),me:gi,characters:new Ot(he,void 0,Sn,pi),transfers:new Gt(he,Dr,gi.inventory),gameConfig:mi,purchases:li.api,deviceSettings:ct.api,ads:di.api,account:ci.api,share:rd({frame:q,log:t.log}),analytics:a,leaderboards:new Cn(he),challenges:new En(he),showcase:new Mn(he,_d),friends:new On(he,{challenge:ui.challenge}),platform:new Gn(he,C,n),profiles:new Dn(he),functions:new De((u,T)=>is(he,u,T)),get prefs(){return w.current},get cohorts(){return R.current},get viewport(){return M.current},awaitCohorts:(u=nf)=>R.wait(u),reportMuted:u=>{S=!!u,P();},cueReward:u=>q.cueReward(u),setWalletVisible:(u,T)=>{let F=Array.isArray(T?.only)?[...T.only]:void 0;return x=F===void 0?{visible:u===true}:{visible:u===true,only:F},N()},exit:u=>tf(ue,q,u,a),frame:q,devtools:A,rooms:ue,dedicatedServer:{listClusterTargets:u=>Rn.listClusterTargets(u),connect:(u=>sr(o,"welcome",Rn.connect(u),n)),handleMatchEnded:(u,T)=>Rn.handleMatchEnded(u,T)},p2p:{handleSignalEvent:(u,T,F)=>rn.handleSignalEvent(u,T,F),session:u=>rn.session(u),connect:u=>yi(rn.connect(u))},match:_r};return fi}var gd="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 si(t,e={}){let n=e.clock??le,r=()=>{let s=t();if(s===null)throw new Error(gd);return s},o=null,i=()=>{if(o===null)throw new Error(gd);return o};return {server:{get identity(){return i().identity},get client(){return i().client},get api(){return i().api},get match(){return i().match},get analytics(){return i().analytics},get functions(){return i().functions},get challenges(){return i().challenges},get room(){return i().room},dispose(){o?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(s){let d=r().profile?.(s);if(!d)return null;let m=d.displayName;return typeof m!="string"||m===""?null:{displayName:ye(m),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:ye(d.displayTag)}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(s){return r().playerNumber?.(s)},send(s,l,d){d===void 0?r().send(s,l):r().send(s,l,d);},broadcast(s,l){l===void 0?r().broadcast(s):r().broadcast(s,l);},kick(s,l){l===void 0?r().kick(s):r().kick(s,l);},log(s){r().log(s);},warn(s){r().warn(s);}},attach:()=>{o=_n(r(),{...e,clock:n});}}}function yd(t,e={}){let{server:n,attach:r}=si(()=>t,e);return r(),n}function rf(t){if(t===void 0||typeof t.reason!="string"||t.reason==="")return;let e=t.platform_reason??t.endedReason;return {reason:t.reason,...e===void 0?{}:{endedReason:$e(e)}}}function fd(t,e={}){return ()=>{let n=null,{server:r,attach:o}=si(()=>n,e),i=t(r),a={async init(s){n=s,o(),await i.init?.();},async shutdown(s){let l=rf(s);try{await i.shutdown?.(l);}finally{r.dispose();}}};return i.join&&(a.join=(s,l)=>i.join?.(s,l)),i.leave&&(a.leave=(s,l)=>i.leave?.(s,l)),i.message&&(a.message=(s,l,d,m)=>i.message?.(s,l,d,m)),a}}
|
|
2
|
-
export{
|
|
1
|
+
var Rd=Object.defineProperty;var kd=(t,e)=>{for(var n in e)Rd(t,n,{get:e[n],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:7.8.0]";function bi(){let t=globalThis.__gemWebSdkVersion;if(typeof t!="string")return "";let e=t.lastIndexOf(":"),n=t.lastIndexOf("]");return e<0||n<=e+1?"":t.slice(e+1,n)}function xd(t,e){return e!==void 0?!e:t==="chain_exhausted"}var on=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new ie(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.grant&&e>=this.grant.chainEndsAt)throw this.enter("lost","chain_exhausted"),new ie("chain_exhausted","the token chain reached its ceiling");return this.refresh(this.nextReason())}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}refresh(e){if(this.inFlight)return this.inFlight;let n=this.generation;this.enter("pending");let r=this.options.request(e).then(o=>{if(n!==this.generation)throw new ie("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=Ad(o),a=o?.retryable;throw n===this.generation&&this.enter(xd(i,typeof a=="boolean"?a:void 0)?"lost":"degraded",i),o instanceof ie?o:new ie(i,String(o))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){this.failure=n??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,n));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},ie=class t extends Error{constructor(n,r){super(`auth ${n}: ${r}`);this.reason=n;this.name="AuthError";}reason;static isAuthError(n){if(n instanceof t)return true;let r=n;return r?.name==="AuthError"&&typeof r.reason=="string"}};function Ad(t){if(t instanceof ie)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var oe=class t extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof t)return true;let n=e;return n?.name==="TransportRefusal"&&n.retryable===false}},pt=["if-match","if-none-match"],vi=4096;function Pd(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();if(!pt.includes(o)||r===void 0)continue;let i=typeof r=="string"?Ed(r):r;if(typeof i!="string"||i.length>vi||!Td(i))throw new oe(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${vi} characters, or contains a character outside the range an HTTP header value may carry. This is a malformed request, not a server failure; the value is withheld here rather than written to logs.`);i!==""&&(e[o]=i);}return Object.freeze(e)}function Ed(t){let e=o=>o===32||o===9||o===10||o===13,n=0,r=t.length;for(;n<r&&e(t.charCodeAt(n));)n++;for(;r>n&&e(t.charCodeAt(r-1));)r--;return t.slice(n,r)}function Td(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 Id(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new oe("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new oe("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function _i(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=Pd(o.headers),a=Id(o),s=Object.freeze({...o,headers:i,...a===void 0?{}:{bytes:a}}),l=await e.tokenSource.get(),d=await t(s,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),c=await t(s,m);if(c.status===401)throw e.tokenSource.close("unavailable"),new ie("unavailable","the server refused a freshly minted token");return c}}}function gt(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Cd(e))}function yt(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function wr(t){return new TextDecoder().decode(yt(t))}function Cd(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var G=class extends Error{constructor(n,r,o,i,a){super(`${n} (${r}): ${o}`);this.reason=n;this.status=r;this.detail=o;this.retryAfterSeconds=i;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},Si=new WeakMap;function Ri(t){return Si.get(t)??{}}var Md=new Set([408,429,500,502,503,504]),Od=6e4;function Ld(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new oe(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(t)}. This is a configuration fault, not a server failure.`);return t}var Le=class{constructor(e){this.options=e;}options;async get(e,n){return this.send({method:"GET",path:e,signal:n},true)}async getWithEtag(e,n={}){let r=await this.sendRaw({method:"GET",path:e,...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{headers:{"if-none-match":n.ifNoneMatch}}},true),o=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...o}:{modified:true,body:r.body,...o}}async put(e,n,r,o={}){return this.send({method:"PUT",path:e,body:n,signal:r,...kn(o)},o.replaySafe===true)}async post(e,n,r,o={}){return this.send({method:"POST",path:e,body:n,signal:r,...kn(o)},o.replaySafe===true)}async postBytes(e,n,r,o={}){let i=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...kn(o)},o.replaySafe===true);return {bytes:Gd(i.body),...i.invocationId===void 0?{}:{invocationId:i.invocationId}}}async patch(e,n,r,o={}){return this.send({method:"PATCH",path:e,body:n,signal:r,...kn(o)},o.replaySafe===true)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...kn(r)},r.replaySafe===true)}async send(e,n){return (await this.sendRaw(e,n)).body}async sendRaw(e,n){let r=n?Ld(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw wi(e.signal);for(let i=0;i<r;i++){if(i>0&&await this.backoff(i,o,e.signal),e.signal?.aborted)throw wi(e.signal);let a;try{a=await this.options.transport.request(e);}catch(l){if(ie.isAuthError(l)||oe.isRefusal(l)||e.signal?.aborted||Dd(l))throw l;o=new G("unavailable",0,String(l));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let s=$d(a);if(!Md.has(a.status))throw s;o=s;}throw o??new G("unavailable",0,"no attempt was made")}backoff(e,n,r){if(r?.aborted)return Promise.resolve();let o=n?.retryAfterSeconds,i=o!==void 0?o*1e3:2**(e-1)*250,a=2**(e-1)*250,s=Math.min(Math.max(i,a),Od);return new Promise(l=>{let d=this.options.clock,m=false,c=false,p,g=()=>{m||(m=true,c&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,s),c=true,m&&d.clearTimeout(p);})}};function Gd(t){if(t instanceof Uint8Array)return t;if(t==null)return new Uint8Array(0);let e=typeof t=="string"?t:JSON.stringify(t);return new TextEncoder().encode(e)}function kn(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function wi(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Dd(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function $d(t){let e=jd(t),n=Nd(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&Si.set(e,r),e}var Fd=new Map([["insufficient_funds","insufficient_funds"]]);function jd(t){let{status:e,body:n}=t,r=qd(n),o=t.retryAfterSeconds??Bd(n),i=Ud(n),a=i===void 0?void 0:Fd.get(i);if(a!==void 0)return new G(a,e,r,void 0,i);switch(e){case 304:return new G("not_modified",e,r);case 400:case 422:return new G("invalid",e,r,void 0,i);case 403:return new G("forbidden",e,r,void 0,i);case 404:return new G("not_found",e,r,void 0,i);case 402:return new G("insufficient_funds",e,r,void 0,i);case 409:return new G("conflict",e,r,void 0,i);case 412:return new G("precondition_failed",e,r,void 0,i);case 413:return new G("too_large",e,r,void 0,i);case 429:return new G("rate_limited",e,r,o,i);default:return new G("unavailable",e,r,o,i)}}function qd(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 Nd(t){let n=t?.error?.details;return n===null?void 0:n}function Ud(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Bd(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function v(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function ki(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function xi(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/add`;return t.client.post(a,o,i?.signal)}async function Ai(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Pi(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/claim`;return t.client.post(a,o,i?.signal)}async function Ei(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function Ti(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ii(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ci(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Mi(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Oi(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(o,r?.signal)}async function Li(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Gi(t,e,n,r,o,i){let a=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/finalize`;return t.client.post(a,o,i?.signal)}async function Di(t,e,n){let r=`/v1/games/${v(t.gameId())}/config/channels/${v(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function $i(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.get(r,n?.signal)}async function Fi(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function ji(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function qi(t,e,n,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Ni(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/items/${v(r)}`;return t.client.get(i,o?.signal)}async function Ui(t,e,n,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let a=i.toString(),s=`/v1/leaderboards/${v(e)}/${v(n)}/${v(r)}`+(a?`?${a}`:"");return t.client.get(s,o?.signal)}async function Bi(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/${v(r)}`;return t.client.get(i,o?.signal)}async function Hi(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}`;return t.client.get(i,o?.signal)}async function Vi(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/catalogs/${v(r)}/recipes/${v(o)}/availability`;return t.client.get(a,i?.signal)}async function Wi(t,e,n,r){let o=new URLSearchParams;o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Sr(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Ki(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${v(e)}/friends`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Ji(t,e,n){let r=`/v1/showcase/friends/${v(e)}`;return t.client.get(r,n?.signal)}async function zi(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${v(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Yi(t,e){let n=`/v1/games/${v(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function ft(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function Xi(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function Qi(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Zi(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${v(e)}`;return t.client.get(r,n?.signal)}async function es(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function ns(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function ts(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function rs(t,e,n){let r=`/v1/games/${v(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{...n?.keepalive===void 0?{}:{keepalive:n.keepalive},replaySafe:true})}async function os(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function is(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/platform-funded-game-inventory-purchases`;return t.client.post(i,r,o?.signal)}async function ss(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function as(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),o="/v1/challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function ls(t,e){return t.client.get("/v1/characters",e?.signal)}async function ds(t,e,n,r){let o=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function cs(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(n)}/orders`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function us(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${v(e)}/${v(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function ms(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o="/v1/friends"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function ps(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function gs(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/matches/${v(e)}/end`;return t.client.post(o,n,r?.signal)}async function ys(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/max`;return t.client.post(a,o,i?.signal)}async function fs(t,e,n,r,o,i){let a=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function hs(t,e,n,r,o){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(i,r,o?.signal)}async function bs(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function vs(t,e,n,r){let o=`/v1/characters/${v(e)}`;return t.client.patch(o,n,r?.signal)}async function _s(t,e,n,r,o,i){let a=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/upload-url`;return t.client.post(a,o,i?.signal,{replaySafe:true})}async function ws(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/reset`;return t.client.post(a,o,i?.signal)}async function Ss(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.delete(r,n?.signal)}var K="gem-web-bridge",bt={min:1,max:1},sn=65536,Rs=8,ht=5e3,ks=1024;function kr(t){return Object.freeze(Object.assign(Object.create(null),t))}var xs=kr({"gem.handshake":30,"gem.handshake.accept":5,"gem.token":30,"gem.token.denied":30,"gem.player":12,"gem.pause":120,"gem.prefs":60,"gem.cohorts":12,"gem.earnAllowanceChanged":30,"gem.viewport":60,"gem.deviceSettings":12,"gem.willTerminate":10,"gem.roomEvent":120,"gem.socketState":12,"gem.seatedEvent":60,"gem.autoStartFailedEvent":30,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.engaged":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.walletDisplay":60,"gem.requestShare":6,"gem.frameStats":120,"gem.error":60,"gem.requestPurchase":12,"gem.purchaseResult":30,"gem.deviceSettings.put":30,"gem.deviceSettings.result":30,"gem.requestAd":6,"gem.adResult":12,"gem.requestSignIn":6,"gem.signInResult":12,"gem.requestFriendChallenge":12,"gem.friendChallengeResult":30,__malformed:60}),vt="__malformed";var Hd=kr({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.requestFriendChallenge":"friendChallenges","gem.friendChallengeResult":"friendChallenges","gem.devtools":"devtools","gem.screenshot":"screenshot","gem.screenshot.denied":"screenshot","gem.requestContext":"feedbackContext","gem.gameContext":"feedbackContext","gem.roomEvent":"rooms","gem.signal":"p2p","gem.signalEvent":"p2p","gem.dedicatedOffer":"dedicated","gem.dedicatedEvent":"dedicated","gem.clusterTarget":"clusterTarget","gem.partyRequest":"parties","gem.partyResult":"parties","gem.autoStartFailedEvent":"autoStartFailure","gem.seatedEvent":"partySeating","gem.socketState":"socketState","gem.audioState":"audioState","gem.rewardCue":"rewardCue","gem.frameStats":"frameStats","gem.engaged":"engagement","gem.viewport":"viewport","gem.walletDisplay":"walletDisplay","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.earnAllowanceChanged":"earnAllowance","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings","gem.requestShare":"share"}),Vd=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.viewport.","reservedAreas"]]);function As(t){let e=Hd[t];if(e!==void 0)return e;for(let[n,r]of Vd)if(t.startsWith(n))return r}function xr(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 Wd(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 Kd(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function Jd(t){return /^[a-z_]+$/.test(t)}function Rr(t,e,n){if(e>Rs)return `nesting deeper than ${Rs}`;if(++n.nodes>ht)return `more than ${ht} values`;if(n.bytes>sn)return `over the ${sn} byte limit`;if(t==null)return n.bytes+=4,null;let r=typeof t;if(r==="boolean")return n.bytes+=5,null;if(r==="number")return n.bytes+=8,null;if(r==="string")return n.bytes+=t.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let o=t;if(n.seen.has(o))return "a repeated or cyclic object reference";if(n.seen.add(o),Array.isArray(t)){if(t.length>ks)return `an array of ${t.length} entries, over the ${ks} limit`;n.bytes+=2;for(let s of t){let l=Rr(s,e+1,n);if(l)return l}return null}let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)return "a value that is not a plain object";n.bytes+=2;let a=t;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++n.nodes>ht)return `more than ${ht} values`;if(n.bytes+=s.length*3+4,n.bytes>sn)return `over the ${sn} byte limit`;let l=Rr(a[s],e+1,n);if(l)return l}return null}function zd(t){let e={nodes:0,bytes:0,seen:new Set},n=Rr(t,0,e);return n?`message contains ${n}`:e.bytes>sn?`message is over the ${sn} byte limit`:null}var Yd={origin:[xr,"not a well-formed origin"],url:[Wd,"not a safe absolute http(s) URL"],bcp47:[Kd,"not a well-formed BCP 47 tag"],code:[Jd,"not a code of lower-case letters and underscores"]};function Ps(t,e,n){for(let r of e){let o=n===""?r.n:`${n}.${r.n}`,i=t[r.n];if(i==null){if(r.o)continue;return `${o}: required`}let a=Es(i,r,o);if(a)return a}return null}function Es(t,e,n){switch(e.k){case "string":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e.max)return `${n}: exceeds ${e.max} characters`;if(e.f){let[r,o]=Yd[e.f];if(!r(t))return `${n}: ${o}`}return null}case "int":return typeof t!="number"||!Number.isInteger(t)?`${n}: expected integer`:t<e.lo||t>e.hi?`${n}: out of range ${e.lo}..${e.hi}`:null;case "boolean":return typeof t=="boolean"?null:`${n}: expected boolean`;case "enum":{let r=e.v;return r.includes(t)?null:`${n}: not one of ${r.join("|")}`}case "object":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:Ps(t,e.fs,n);case "json":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "array":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e.max)return `${n}: exceeds ${e.max} items`;let r=e.it,o=`${n}[]`;for(let i of t){if(i==null){if(r.o)continue;return `${o}: required`}let a=Es(i,r,o);if(a)return a}return null}default:{let r=e.k;return `${n}: unknown kind ${String(r)}`}}}function I(t,e){return n=>{let r=zd(n);if(r)return r;if(typeof n!="object"||n===null||Array.isArray(n))return "message: expected object";let o=n;return o.gem!==K?"gem: wrong protocol marker":o.type!==t?`type: expected ${t}`:Ps(o,e,"")}}var Xd=I("gem.handshake",[{n:"versions",k:"object",fs:[{n:"min",k:"int",lo:1,hi:1e3},{n:"max",k:"int",lo:1,hi:1e3}]},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}},{n:"embedder",k:"string",max:2048,f:"origin"},{n:"unbidden",k:"boolean",o:1}]),Qd=I("gem.handshake.accept",[{n:"v",k:"int",lo:1,hi:1e3},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}}]),Zd=I("gem.token",[{n:"token",k:"string",max:4096},{n:"requestId",k:"string",o:1,max:64},{n:"generation",k:"int",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"string",o:1,max:512,f:"url"},{n:"playerId",k:"string",max:64},{n:"gameId",k:"string",max:64},{n:"channel",k:"enum",v:["dev","test","release"]},{n:"gameVersion",k:"string",o:1,max:64},{n:"expiresAt",k:"int",lo:0,hi:4102444800},{n:"chainEndsAt",k:"int",lo:0,hi:4102444800},{n:"allowDevTools",k:"boolean",o:1}]),ec=I("gem.token.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:36e5},{n:"reason",k:"enum",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"string",max:64}]),nc=I("gem.player",[{n:"untrusted",k:"object",fs:[{n:"displayName",k:"string",max:64},{n:"displayTag",k:"string",o:1,max:80},{n:"displayHandle",k:"string",max:80}]},{n:"playerId",k:"string",o:1,max:64},{n:"discriminator",k:"string",o:1,max:8},{n:"avatarIconUrl",k:"string",o:1,max:2048,f:"url"},{n:"badges",k:"array",o:1,max:2,it:{n:"",k:"object",fs:[{n:"itemId",k:"string",max:64},{n:"iconUrl",k:"string",max:2048,f:"url"}]}},{n:"displayTag",k:"string",max:8},{n:"avatarUrl",k:"string",o:1,max:2048,f:"url"},{n:"boost",k:"object",o:1,fs:[{n:"multipliers",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"currencyId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"multiplierBp",k:"int",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"int",o:1,lo:1,hi:7}]}]),tc=I("gem.pause",[{n:"paused",k:"boolean"}]),rc=I("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),oc=I("gem.cohorts",[{n:"cohorts",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"experimentId",k:"string",max:36},{n:"variantKey",k:"string",max:32}]}}]),ic=I("gem.earnAllowanceChanged",[]),sc=I("gem.viewport",[{n:"insets",k:"object",fs:[{n:"top",k:"int",lo:0,hi:4096},{n:"right",k:"int",lo:0,hi:4096},{n:"bottom",k:"int",lo:0,hi:4096},{n:"left",k:"int",lo:0,hi:4096}]},{n:"reserved",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384},{n:"width",k:"int",lo:0,hi:16384},{n:"height",k:"int",lo:0,hi:16384}]}}]),ac=I("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),lc=I("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),dc=I("gem.roomEvent",[{n:"event",k:"enum",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"string",max:64},{n:"matchId",k:"string",o:1,max:64},{n:"version",k:"int",o:1,lo:0,hi:2147483647},{n:"reason",k:"string",o:1,max:64},{n:"platform",k:"enum",o:1,v:["universal","mobile"]}]),cc=I("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),uc=I("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),mc=I("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),pc=I("gem.signalEvent",[{n:"event",k:"enum",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),gc=I("gem.dedicatedEvent",[{n:"event",k:"enum",v:["answer","error","matchEnded"]},{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",o:1,max:10240},{n:"sessionId",k:"string",o:1,max:64},{n:"code",k:"string",o:1,max:64},{n:"message",k:"string",o:1,max:256},{n:"reason",k:"string",o:1,max:64}]),yc=I("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),fc=I("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),hc=I("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),bc=I("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),vc=I("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),_c=I("gem.requestContext",[]),wc=I("gem.gameContext",[{n:"context",k:"json"}]),Sc=I("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Rc=I("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),kc=I("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),xc=I("gem.ready",[]),Ac=I("gem.engaged",[]),Pc=I("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Ec=I("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),Tc=I("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),Ic=I("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),Cc=I("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),Mc=I("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),Oc=I("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),Lc=I("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),Gc=I("gem.audioState",[{n:"muted",k:"boolean"}]),Dc=I("gem.rewardCue",[{n:"currencySlug",k:"string",max:32},{n:"expected",k:"int",o:1,lo:1,hi:1e9},{n:"origin",k:"object",o:1,fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384}]}]),$c=I("gem.walletDisplay",[{n:"visible",k:"boolean"},{n:"currencies",k:"array",o:1,max:8,it:{n:"",k:"string",max:64}},{n:"score",k:"boolean",o:1}]),Fc=I("gem.requestShare",[{n:"params",k:"array",max:16,it:{n:"",k:"object",fs:[{n:"key",k:"string",max:64},{n:"value",k:"string",max:512}]}}]),jc=I("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),qc=I("gem.error",[{n:"code",k:"enum",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"string",o:1,max:256}]),Nc=I("gem.requestPurchase",[{n:"requestId",k:"string",max:64},{n:"purchaseKind",k:"enum",v:["item","recipe"]},{n:"targetId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"quantity",k:"int",o:1,lo:1,hi:10},{n:"catalogId",k:"string",o:1,max:64}]),Uc=I("gem.purchaseResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["ok","declined","unavailable"]},{n:"reason",k:"string",o:1,max:64,f:"code"},{n:"purchaseId",k:"string",o:1,max:64}]),Bc=I("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),Hc=I("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),Vc=I("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),Wc=I("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),Kc=I("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),Jc=I("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),zc=I("gem.requestFriendChallenge",[{n:"requestId",k:"string",max:64},{n:"playerId",k:"string",max:64},{n:"template",k:"string",max:64},{n:"params",k:"json",o:1}]),Yc=I("gem.friendChallengeResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"string",o:1,max:64},{n:"param",k:"string",o:1,max:64},{n:"channel",k:"string",o:1,max:16},{n:"configVersion",k:"int",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:864e5},{n:"detail",k:"string",o:1,max:300}]),_t=kr({"gem.handshake":Xd,"gem.handshake.accept":Qd,"gem.token":Zd,"gem.token.denied":ec,"gem.player":nc,"gem.pause":tc,"gem.prefs":rc,"gem.cohorts":oc,"gem.earnAllowanceChanged":ic,"gem.viewport":sc,"gem.deviceSettings":ac,"gem.willTerminate":lc,"gem.roomEvent":dc,"gem.socketState":cc,"gem.seatedEvent":uc,"gem.autoStartFailedEvent":mc,"gem.signalEvent":pc,"gem.dedicatedEvent":gc,"gem.partyResult":yc,"gem.clusterTarget":fc,"gem.devtools":hc,"gem.screenshot":bc,"gem.screenshot.denied":vc,"gem.requestContext":_c,"gem.gameContext":wc,"gem.signal":Sc,"gem.dedicatedOffer":Rc,"gem.partyRequest":kc,"gem.ready":xc,"gem.engaged":Ac,"gem.progress":Pc,"gem.requestToken":Ec,"gem.requestLocalServer":Tc,"gem.localServer":Ic,"gem.localServer.denied":Cc,"gem.exit":Mc,"gem.openExternal":Oc,"gem.requestFullscreen":Lc,"gem.audioState":Gc,"gem.rewardCue":Dc,"gem.walletDisplay":$c,"gem.requestShare":Fc,"gem.frameStats":jc,"gem.error":qc,"gem.requestPurchase":Nc,"gem.purchaseResult":Uc,"gem.deviceSettings.put":Bc,"gem.deviceSettings.result":Hc,"gem.requestAd":Vc,"gem.adResult":Wc,"gem.requestSignIn":Kc,"gem.signInResult":Jc,"gem.requestFriendChallenge":zc,"gem.friendChallengeResult":Yc});var le={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},xn=class{constructor(e=le){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=xs[e];if(n===void 0)return false;let r=this.clock.now(),o=this.lastRefill.get(e)??r,i=this.tokens.get(e)??n,a=Math.max(0,r-o),s=Math.min(n,i+a*n/6e4);return s<1?(this.tokens.set(e,s),this.lastRefill.set(e,r),false):(this.tokens.set(e,s-1),this.lastRefill.set(e,r),true)}};function Ar(t,e){return t.toLowerCase()===e.toLowerCase()}function wt(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Ts(t,e){if(typeof e!="string"||e==="")return false;let n,r;try{n=new URL(t),r=new URL(e);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||n.username!==""||n.password!==""||n.pathname!=="/"||n.search!==""||n.hash!==""||n.port===""?false:wt(n.hostname)&&wt(r.hostname)}function Is(t,e){if(e.min>e.max)return null;let n=Math.min(t.max,e.max),r=Math.max(t.min,e.min);return n>=r?n:null}var St=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,n={}){let o=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,i=o.find(s=>s.currencyId===e),a;return !i&&this.resolveCurrencyId&&(a=await this.resolveCurrencyId(e).catch(()=>{}),a!==void 0&&(i=o.find(s=>s.currencyId===a))),{currencyId:i?i.currencyId:a??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function Er(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let o=r??{};typeof o.id!="string"||o.id===""||typeof o.threshold!="number"||!Number.isFinite(o.threshold)||n.push({id:o.id,threshold:o.threshold,points:typeof o.points=="number"?o.points:0,hidden:o.hidden===true,...typeof o.unlocked_at=="number"&&Number.isFinite(o.unlocked_at)?{unlockedAt:o.unlocked_at}:{},...o.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var Cs="inventory",an=t=>typeof t=="number"?t:0,An=t=>typeof t=="string"?t:"";function Pr(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 Ms(t){let e=t??{};return {itemDefinitionId:An(e.item_definition_id),instanceId:An(e.instance_id),quantity:an(e.quantity),acquiredAt:an(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function Xc(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Pr(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(a=>{let s=a??{};return {bucket:An(s.bucket),balance:an(s.balance)}}):void 0;return {currencyId:An(o.currency_id),total:an(o.total),...i===void 0?{}:{buckets:i}}}),items:Pr(e.items,Ms),progressions:Pr(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:An(o.progression_definition_id),currentValue:an(o.current_value),completionCount:an(o.completion_count),isCompleted:o.is_completed===true,...Er(o)}}),...n===void 0?{}:{etag:n}}}var Rt=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Cs}#buckets`:Cs;return this.cache.read(n,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,n){let r=await this.snapshot();if(r.items.nextCursor===void 0){let i=r.items.data.filter(a=>a.itemDefinitionId===e);if(i.length>0)return i}let o=await Ni(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(o)?o.map(Ms):[]}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 qi(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 Xc(n)}};var Qc={unknown_currency:1,currency_not_in_game_payable:1,not_purchasable:1,no_price_in_currency:1,busy:1,cancelled:1,insufficient_funds:1,price_mismatch:1,config_version_stale:1,platform_currency_unavailable:1,not_available:1,recipe_locked:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},Zc=new Set(Object.keys(Qc));function Os(t){return typeof t=="string"&&Zc.has(t)?t:"error"}var Ge=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var Z=t=>typeof t=="string"?t:"",eu=t=>typeof t=="string"?t:Z(t&&typeof t=="object"?t.type:void 0),Re=t=>typeof t=="number"?t:0;function nu(t){let e=t??{};return {prerequisiteType:Z(e.prerequisite_type),referenceId:Z(e.reference_id),required:Re(e.required),current:Re(e.current)}}function Pn(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:Z(e.order_id),status:Z(e.status),...n===void 0?{}:{etag:n}}}function kt(){return crypto.randomUUID()}var tu="recipe-usage",Ls=100;function xt(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:Z(e.currency_id),bucket:Z(e.bucket),delta:Re(e.delta),balanceAfter:Re(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:Z(e.item_definition_id),instanceId:Z(e.instance_id),delta:Re(e.delta),quantityAfter:Re(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:Z(e.progression_definition_id),delta:Re(e.delta),valueAfter:Re(e.value_after),completed:e.completed===true};default:return {kind:"other",type:Z(e.type)}}}function ru(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:Z(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Re(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(xt):[]}}function ou(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(ru):void 0;return {orderId:Z(e.order_id),status:Z(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(xt):[],consumed:Array.isArray(e.consumed)?e.consumed.map(xt):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(xt):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function iu(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:Z(e.target_order_id)||Z(e.source_order_id),status:Z(e.status),purchaseId:Z(e.purchase_id),sourceOrderId:Z(e.source_order_id),price:{currencyId:Z(n.platform_currency_id),amount:Re(n.price)}}}function su(t){let e=t??{},n=typeof e.last_used_at=="string"?e.last_used_at:void 0,r=typeof e.cooldown_expires_at=="string"?e.cooldown_expires_at:void 0;return {recipeId:Z(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...n===void 0?{}:{lastUsedAt:n},...r===void 0?{}:{cooldownExpiresAt:r}}}function Gs(t){switch(t.type){case "currency_grant":case "currency_consume":return {type:t.type,currency_id:t.currencyId,amount:t.amount};default:return {type:t.type,item_definition_id:t.itemDefinitionId,quantity:t.quantity}}}var At=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;async create(e,n={}){let r=await this.write(()=>Ii(this.api,this.entity.type,this.entity.id,{operations:e.map(Gs),source:n.source??"play",nonce:kt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Pn(r)}async createMany(e,n={}){return this.write(()=>Ti(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Gs),nonce:kt()})),source:n.source??"play"},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}))}async recipeAvailability(e,n,r){let i=await Vi(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},a=typeof i.uses_remaining=="number"?i.uses_remaining:void 0,s=typeof i.cooldown_expires_at=="string"?i.cooldown_expires_at:void 0,l=Array.isArray(i.lock_reasons)?i.lock_reasons.map(nu):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>eu(d)):[],...a===void 0?{}:{usesRemaining:a},...s===void 0?{}:{cooldownExpiresAt:s}}}async recipeUsageAll(){return this.cache.read(tu,[],async()=>{let n=await Wi(this.api,this.entity.type,this.entity.id,{limit:Ls})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(su),truncated:r.length>=Ls}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let c=e,p=await this.write(()=>Li(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:kt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...ou(p)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,o]=await Promise.all([Qi(this.api,n.signal===void 0?{}:{signal:n.signal}),ft(this.api,n.signal===void 0?{}:{signal:n.signal})]),i=e.payment.currencySlug.toLowerCase(),a=o.currencies.find(c=>c.currency_id.toLowerCase()===i||c.slug.toLowerCase()===i);if(a===void 0){let c=o.currencies.map(p=>p.slug);throw new Ge("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${c.length===0?"none":c.join(", ")}`)}let s=e.kind==="item"?r.items.find(c=>c.item_id===e.targetId):r.recipes.find(c=>c.recipe_id===e.targetId&&c.catalog_id===e.catalogId);if(s===void 0)throw new Ge("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=s.platform_prices.find(c=>c.platform_currency_id===a.currency_id);if(l===void 0){let c=g=>o.currencies.find(y=>y.currency_id===g)?.slug??g,p=s.platform_prices.map(g=>`${c(g.platform_currency_id)} ${g.price}`);throw new Ge("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${a.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Ge("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>is(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:a.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:kt(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return iu(m)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let o=await this.write(()=>xi(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Pn(o)}async maxProgression(e,n,r){let o=await this.write(()=>ys(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Pn(o)}async claimProgression(e,n){let r=await this.write(()=>Pi(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Pn(r)}async resetProgression(e,n){let r=await this.write(()=>ws(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Pn(r)}async write(e){return this.cache.invalidate(),e()}};var Tr=t=>typeof t=="string"?t:"",au=t=>typeof t=="number"?t:0;function Ds(t){let e=t??{};return {orderId:Tr(e.order_id),status:Tr(e.status),source:Tr(e.source),createdAt:au(e.created_at)}}var Pt=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await cs(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(Ds):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Bi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Ds(r)}};var $s=t=>typeof t=="number"?t:0,lu=t=>typeof t=="string"?t:"";function du(t){let e=t??{};return {progressionDefinitionId:lu(e.progression_definition_id),currentValue:$s(e.current_value),completionCount:$s(e.completion_count),isCompleted:e.is_completed===true,...Er(e)}}var Et=class{constructor(e,n,r){this.api=e;this.entity=n;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,n){let o=(await this.inventory.snapshot()).progressions.data.find(i=>i.progressionDefinitionId===e);if(o&&o.achievementsUnavailable!==true)return o;try{let i=await Hi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return du(i)}catch{return o??null}}};var Tt=class{constructor(e,n){this.clock=e;this.identity=n;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,n,r,o){this.rebind();let i=n.length===0,a=i?e:e+"\0"+n.join("\0"),s=this.slots.get(a);if(s){let c=s.filledAt;if(c!==void 0&&(o===void 0||this.clock.now()-c<=o))return Promise.resolve(s.value);if(s.inFlight)return s.inFlight}let l=s??{};this.slots.set(a,l);let d=this.generation,m=r().then(c=>(i&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(a)===l&&this.slots.delete(a));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function Ir(t){let e=o=>new RegExp(`<${o}>([^<]{0,300})</${o}>`).exec(t)?.[1]?.trim()||void 0,n=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(n.length>0)return n.join(" \u2014 ");let r=t.trim();return r?r.slice(0,300):""}async function Cr(t){try{let e=Ir(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var se=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},cu=3e4,Fs="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",uu=/^[A-Za-z0-9_]{1,64}$/;function ke(t){let e=t.length===0?"a save key cannot be empty":t.length>64?`it is ${t.length} characters; a save key is at most 64`:t.startsWith("_")||t.startsWith("$")?`it begins with ${JSON.stringify(t[0])}, and \`_\` and \`$\` are reserved prefixes`:"a save key is ASCII letters, digits and underscores only \u2014 no hyphens, spaces or other punctuation, unlike a template slug";if(!uu.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function js(t,e){let n=new AbortController,r=AbortSignal.timeout(e),o=()=>n.abort(r.reason),i=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(r.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",i,{once:true})),{signal:n.signal,release:()=>{r.removeEventListener("abort",o),t?.removeEventListener("abort",i);}}}function Mr(t,e){return t.aborted&&e?.aborted!==true}var mu=new Set(["x-ms-blob-type"]),pu=/^[ -~]+$/;function gu(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(t)?"a list":typeof t}, which is not a set of headers.`);let n={};for(let[r,o]of Object.entries(t)){let i=r.toLowerCase();if(!mu.has(i))throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof o!="string"||!pu.test(o))throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(i in n)throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);n[i]=o;}return n}function Or(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 Lr(t){return t?.reason==="not_found"}var It=class{constructor(e,n,r={}){this.api=e;this.entity=n;this.options=r;}api;entity;options;async put(e,n,r={}){let o;try{o=JSON.stringify(n);}catch(i){throw new se("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}. Retrying stores the same unserialisable value.`)}if(o===void 0)throw new se("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(o),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){let o=r.contentType??"application/octet-stream",i=this.budget(r.timeoutMs),a=js(r.signal,i);try{let s=await _s(this.api,this.entity.type,this.entity.id,ke(e),{size_bytes:n.byteLength,content_type:o,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:a.signal});if(typeof s.upload_url!="string"||typeof s.session_id!="string")throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=gu(s.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(s.upload_url,{method:"PUT",headers:{"content-type":o,...l},body:n,credentials:"omit",signal:a.signal});}catch(c){throw Mr(a.signal,r.signal)?this.timeout("upload",i):new se("upload_failed",`${Fs} for PUT. Underlying error: ${c}`)}if(!d.ok){let c=await Cr(d);throw new se("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+c:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+c)}return Or(await Gi(this.api,this.entity.type,this.entity.id,ke(e),{session_id:s.session_id},{signal:a.signal}))}catch(s){throw this.rethrow(s,r.signal,a.signal,"save",i)}finally{a.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(o){throw new se("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${o}`)}}async getBytes(e,n={}){let r=this.budget(n.timeoutMs),o=js(n.signal,r);try{let i;try{let l=await Sr(this.api,this.entity.type,this.entity.id,ke(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(Lr(l))return null;throw l}if(typeof i.download_url!="string")throw new se("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),s;try{s=await a(i.download_url,{credentials:"omit",signal:o.signal});}catch(l){throw Mr(o.signal,n.signal)?this.timeout("download",r):new se("download_failed",`${Fs} for GET. Underlying error: ${l}`)}if(!s.ok){let l=await Cr(s);throw new se("download_failed",`the save download answered ${s.status}. `+(s.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await s.arrayBuffer())}catch(i){throw this.rethrow(i,n.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,n={}){try{let r=await Sr(this.api,this.entity.type,this.entity.id,ke(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Or(r.body):null}catch(r){if(Lr(r))return null;throw r}}async list(e={}){let n=await us(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(Or),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await Mi(this.api,this.entity.type,this.entity.id,ke(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Lr(r))throw r}}budget(e){return e??this.options.timeoutMs??cu}timeout(e,n){return new se("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,o,i){return e instanceof se?e:Mr(r,n)?this.timeout(o,i):e}};function yu(t){try{return wr(t)}catch{return t}}function Gr(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"?yu(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var Ct=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await ds(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>Gr(o)):[]}async get(e,n={}){try{let r=await ji(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?Gr(r.body,r.etag):null}catch(r){if(qs(r))return null;throw r}}async put(e,n,r={}){let o=await fs(this.api,this.entity.type,this.entity.id,e,{value:gt(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Gr(o)}async delete(e,n){try{await Ci(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!qs(r))throw r}}};function qs(t){return t?.reason==="not_found"}function Mt(t,e,n={}){let r=new Tt(le,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let o=new Rt(t,e,r);return {settings:new Ct(t,e),inventory:o,saves:new It(t,e,n.saves??{}),currencies:new St(o,n.resolveCurrencyId),mutations:new At(t,e,r),orders:new Pt(t,e),progressions:new Et(t,e,o)}}var Dr={type:"players",id:"me"};var qe=t=>typeof t=="string"?t:"",ln=t=>typeof t=="number"?t:0;function Ot(t,e){let n=e??{},r=qe(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:qe(n.player_id),gameId:qe(n.game_id),channel:qe(n.channel)||"release",name:qe(n.name),slotIndex:ln(n.slot_index),isActive:n.is_active!==false,createdAt:qe(n.created_at),updatedAt:qe(n.updated_at)}}var Lt=class{constructor(e,n,r,o){this.api=e;this.saves=n;this.identity=r;this.resolveCurrencyId=o;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let n=this.scopes.get(e);return n||(n=Mt(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,n)),n};async list(e){let r=(await ls(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>Ot(this.scope,o)):[]}async get(e,n){let r=await $i(this.api,e,n===void 0?{}:{signal:n});return Ot(this.scope,r)}async create(e){let n=await Ei(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Ot(this.scope,n)}async update(e,n,r){let o=await vs(this.api,e,{name:n},r===void 0?{}:{signal:r});return Ot(this.scope,o)}async delete(e,n){await Ss(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await ns(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:ln(r?.total_slots),availableSlots:ln(r?.available_slots),activeCharacterCount:ln(r?.active_character_count),defaultMaxSlots:ln(r?.default_max_slots),purchasedExtraSlots:ln(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var pe=class{#e;constructor(e){this.#e=e,Object.freeze(this);}toString(){return "[gem: use gem.text.toPlain()]"}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function ye(t){return new pe(t)}var Ne={toPlain(t){return pe.unwrap(t)},compare(t,e,n){let r=t instanceof pe?pe.unwrap(t):t,o=e instanceof pe?pe.unwrap(e):e,i;try{i=new Intl.Collator(n);}catch{i=new Intl.Collator;}return i.compare(r,o)},equals(t,e){let n=t instanceof pe?pe.unwrap(t):t,r=e instanceof pe?pe.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var dn=t=>typeof t=="string"?t:"";function Gt(t){let e=t??{},n=typeof e.message=="string"&&e.message.length>0?e.message:void 0,r=typeof e.resolved_at=="string"?e.resolved_at:void 0;return {id:dn(e.transfer_id),status:dn(e.status),sourceEntityId:dn(e.source_entity_id),targetEntityId:dn(e.target_entity_id),...n===void 0?{}:{message:ye(n)},createdAt:dn(e.created_at),expiresAt:dn(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function fu(){return crypto.randomUUID()}var Dt=class{constructor(e,n,r){this.api=e;this.self=n;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let n=await os(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:fu()},e.signal===void 0?{}:{signal:e.signal});return Gt(n)}async list(e={}){let r=await ps(this.api,{entity_type:this.self.type,entity_id:this.self.id,...e.direction===void 0?{}:{direction:e.direction},...e.status===void 0?{}:{status:e.status},...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(Gt):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await ts(this.api,e,n===void 0?{}:{signal:n});return Gt(r)}async accept(e,n){return this.resolve(()=>ki(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>bs(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>Ai(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Gt(await e())}};var hu=t=>typeof t=="string"?t:"",bu=t=>typeof t=="string"&&t?t:void 0,vu=t=>typeof t=="number"?t:void 0;function Ns(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 _u(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new ce("config_malformed",`the config document is ${t===null?"null":typeof t}, expected a JSON object`);let e=t,n=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new ce("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=vu(e.version);if(r===void 0)throw new ce("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let c=hu(l.id);if(!c)throw new ce("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return c},i=n("items");i.forEach((l,d)=>o(l??{},"items",d));let a=n("currencies");a.forEach((l,d)=>o(l??{},"currencies",d));let s=t;return {...s,version:r,hash:typeof s.hash=="string"?s.hash:"",items:i,currencies:a,catalogs:n("catalogs"),loot_tables:n("loot_tables"),affix_pools:n("affix_pools"),progressions:n("progressions"),game_room_templates:n("game_room_templates"),kv:typeof s.kv=="object"&&s.kv!==null&&!Array.isArray(s.kv)?s.kv:{},item:Ns(i),currency:Ns(a)}}var ce=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},Us=10*1024*1024,Bs=15e3,Hs=new Set(["dev","test","release"]);function wu(t){if(!Hs.has(t))throw new ce("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Hs].join(", ")}. gem-api would reject the assignment read.`);return t}var $t=t=>typeof t=="number"?t:0,$r=t=>typeof t=="string"?t:"";function Su(t){let e=t??{},n=Array.isArray(e.entries)?e.entries.map(r=>{let o=r??{},i=typeof o.rarity_tier=="string"?o.rarity_tier:void 0;return {entryId:$r(o.entry_id),weight:$t(o.weight),dropRate:$t(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:$r(e.loot_table_id),name:$r(e.name),rollCount:$t(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:$t(e.total_weight),entries:n}}var Ft=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=null;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,n=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===n&&(this.inFlight=null);});return this.inFlight=n,n}refresh(){this.loaded=null,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new ce("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let o=this.dropRatesByConfig.get(r);o===void 0&&(o=new Map,this.dropRatesByConfig.set(r,o));let i=o.get(e);if(i!==void 0)return i;let a=(async()=>{let s=await Fi(this.api,e,n===void 0?{}:{signal:n});return Su(s)})().catch(s=>{throw o?.get(e)===a&&o.delete(e),s});return o.set(e,a),a}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??Bs),n;try{let l=await Di(this.api,wu(this.channel()),{signal:e});if(!l.modified)throw new ce("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof ce)throw l;if(l?.reason==="not_found")return null;throw l}let r=bu(n.config_url);if(r===void 0)return null;let o=this.options.fetch??globalThis.fetch.bind(globalThis),i;try{i=await o(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new ce("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??Bs}ms`):new ce("config_unreachable",`could not fetch the game config document. From a browser this is almost always the storage CORS rule: the storage account must allow this game origin for GET. It is NOT a CSP problem \u2014 game origins carry no fetch directives by design. Underlying error: ${String(l)}`)}if(!i.ok){let l=await i.text().then(d=>Ir(d)).catch(()=>"");throw new ce("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let a=await i.text();if(a.length>Us)throw new ce("config_too_large",`the config document is ${a.length} bytes, over the ${Us} cap`);let s;try{s=JSON.parse(a);}catch(l){throw new ce("config_malformed",`config document is not JSON: ${String(l)}`)}return _u(s)}};var Vs=400,xe=t=>typeof t=="string"?t:"",Ru=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Ue(t){let e=xe(t);if(!Ru.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var ku=/^[0-9a-f]{1,64}$/,xu=/^[0-9a-f]{16}$/,Au=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Pu=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Fr(t){let e=xe(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,o,i]=[Number(n[1]),Number(n[2]),Number(n[3])],a=new Date(Date.UTC(r,o-1,i));return a.getUTCFullYear()===r&&a.getUTCMonth()===o-1&&a.getUTCDate()===i?e:void 0}var Eu=4096,Tu=new TextEncoder;function Iu(t){let e=xe(t.challenge_data),n=xe(t.challenge_data_hash);return e===""||!xu.test(n)?{}:Tu.encode(e).length>Eu?{}:{data:e,dataHash:n}}function Cu(t){let e=t??{},n=Ue(e.period_start_at),r=Ue(e.period_ends_at);if(n===0||r===0)return;let o=xe(e.slug),i=xe(e.seed),a=Fr(e.period_local_date),s=xe(e.boundary),l=xe(e.reset_time);return {id:xe(e.progression_definition_id),...o===""?{}:{slug:o},window:xe(e.window),periodStartAt:n,periodEndsAt:r,...a===void 0?{}:{periodLocalDate:a},boundary:Au.test(s)?s:"",resetTime:Pu.test(l)?l:"",seed:ku.test(i)?i:"",...Iu(e)}}function cn(t){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(t)}`)}function jt(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Cu).filter(n=>n!==void 0):[]}var En=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;cn(n);let r=await as(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return jt(r)}};function Be(t){return typeof t=="string"&&t!==""?t:void 0}var Ws=new Set(["localhost","127.0.0.1","[::1]"]);function jr(t){let e=Be(t);if(e===void 0)return;let n;try{n=new URL(e);}catch{return}if(!(n.username!==""||n.password!=="")&&(n.protocol==="https:"||n.protocol==="http:"&&Ws.has(n.hostname)))return e}function Mu(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},o=Be(r.item_id),i=jr(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function ve(t){let e=t??{},n=Be(e.player_id),r=Be(e.display_name),o=Be(e.discriminator),i=Be(e.display_tag),a=Be(e.avatar_icon_id),s=jr(e.avatar_icon_url);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:ye(r)},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:ye(i)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:Mu(e.badges)}}var Ou=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Lu(t){if(t===void 0)return;let e=jr(t);if(e===void 0)return;let n=new URL(e);return Ws.has(n.hostname)||Ou.has(n.origin)?e:void 0}var Ks=100,Ys=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function qr(t){let{periodsBack:e,period:n,playerId:r}=t;if(cn(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!Ys.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 Xs(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!Ys.test(e))return;let n=Fr(t.period_local_date),r=Ue(t.period_start_at),o=Ue(t.period_ends_at),i=r>0&&o>0;return {id:e,...n===void 0?{}:{localDate:n},...i?{startAt:r,endsAt:o}:{},opensAt:Ue(t.opens_at),closesAt:Ue(t.closes_at),final:t.final===true}}var Tn=t=>typeof t=="string"?t:"",un=t=>typeof t=="number"?t:0,In=t=>typeof t=="string"?t:void 0,Gu=t=>typeof t=="number"?t:void 0,Qs={player:"players",character:"characters"};function Du(t,e){let n=t??{},r=In(n.entity_id),o=typeof n.entity_type=="string"&&Object.hasOwn(Qs,n.entity_type)?n.entity_type:void 0,i=Zs(n.stats),a=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,s=e?n.is_viewer===true:void 0;return {...ve(n),rank:un(n.rank),occurredAt:un(n.occurred_at),...s===void 0?{}:{isViewer:s},...r===void 0?{}:{entityId:r},...o===void 0?{}:{entityType:o},...i===void 0?{}:{stats:i},...a===void 0?{}:{properties:a}}}function Js(t,e){let n=t??{},r=In(n.bucket_1),o=In(n.bucket_2),i=Gu(n.update_frequency_seconds),a=Xs(n);return {leaderboardType:Tn(n.leaderboard_type),runType:Tn(n.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(n.entries)?n.entries.map(s=>Du(s,e)):[],generatedAt:un(n.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...a===void 0?{}:{period:a}}}function zs(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=Zs(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:un(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function Zs(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 $u(t,e,n){let r=t??{},o=In(r.bucket_1),i=In(r.bucket_2),a=Xs(r);return {leaderboardType:Tn(r.leaderboard_type),runType:Tn(r.run_type),entityType:e,entityId:n,...o===void 0?{}:{bucket1:o},...i===void 0?{}:{bucket2:i},entries:Array.isArray(r.entries)?r.entries.map(zs).filter(s=>s!==void 0):[],personalBest:zs(r.personal_best)??null,totalRuns:un(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:un(r.generated_at),...a===void 0?{}:{period:a}}}var Cn=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=qr(n),o=await zi(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Js(o,false)}async friends(e,n={}){let r=qr(n),o=await Ki(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 Js(o,true)}async mine(e,n={}){return this.#t(e,"player","me",n)}async character(e,n,r={}){return this.#t(e,"character",n,r)}async#t(e,n,r,o){if(o.limit!==void 0){let{limit:l}=o;if(!Number.isInteger(l)||l<1||l>Ks)throw new TypeError(`limit must be an integer between 1 and ${Ks}, got ${String(l)}`)}let i=qr(o),a=await Ui(this.#e,e,Qs[n],r,{...i,...o.bucket1===void 0?{}:{bucket_1:o.bucket1},...o.bucket2===void 0?{}:{bucket_2:o.bucket2},...o.limit===void 0?{}:{limit:o.limit},...o.signal===void 0?{}:{signal:o.signal}}),s=n==="player"&&r==="me"&&Tn((a??{}).entity_id)||r;return $u(a,n,s)}};var qt=t=>typeof t=="string"?t:"",Nr=t=>typeof t=="number"?t:0;function ea(t){let e=t??{};return {playerId:qt(e.player_id),key:qt(e.key),value:e.value,updatedAt:Nr(e.updated_at)}}function Fu(t){let e=t??{};return {...ve(e),playerId:qt(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Nr(e.updated_at)}}function ju(t){return t?.reason==="not_found"}var Mn=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let o=await Ji(this.api,ke(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:qt(o.key),entries:Array.isArray(o.entries)?o.entries.map(Fu):[],generatedAt:Nr(o.generated_at)}}async of(e,n,r={}){try{return ea(await es(this.api,e,ke(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(ju(o))return null;throw o}}async set(e,n,r={}){if(ke(e),n===void 0)throw new TypeError(`showcase value for ${JSON.stringify(e)} is undefined, which is not JSON. Use clear() to remove one.`);try{JSON.stringify(n);}catch(i){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}.`,{cause:i})}let o=await this.selfPlayerId();return ea(await hs(this.api,o,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await Oi(this.api,r,ke(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var He=class extends G{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,o]of Object.entries(n))o!==void 0&&Object.assign(this,{[r]:o});}},na=t=>typeof t=="string"?t:void 0;function qu(t){let e=t??{};return {...ve(e),playerId:na(e.player_id)??""}}function Nu(t){let e=t??{},n=e.has_more===true?na(e.next_cursor):void 0;return {friends:Array.isArray(e.data)?e.data.map(qu):[],...n===void 0?{}:{nextCursor:n}}}var On=class{#e;#t;constructor(e,n={}){this.#e=e,this.#t=n.challenge;}async list(e={}){let n=await ms(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Nu(n)}challenge(e){return this.#t===void 0?Promise.resolve({outcome:"unavailable"}):this.#t(e)}};var Uu=0;function Ae(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++Uu)}-${String(Date.now())}-${t}`}}var Bu=12e4,ta=8,Hu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Vu=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Ln(t,e,n={}){return new He(new G("invalid",400,e,void 0,t),n)}function Wu(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Ku(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!Hu.test(e))return {error:Ln("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!Vu.test(n))return {error:Ln("unknown_template","template must be a friend_challenge_templates key from this game's config")};if(r===void 0)return {playerId:e,template:n,params:void 0};if(!Wu(r))return {error:Ln("param_invalid","params must be a plain object of strings and integers")};let o={},i=Object.keys(r);for(let a of i){let s=r[a];if(typeof s=="string"||typeof s=="number"&&Number.isSafeInteger(s)){Object.defineProperty(o,a,{value:s,enumerable:true,writable:true,configurable:true});continue}return {error:Ln("param_invalid",`params.${a} must be a string or a safe integer`,{param:a})}}return i.length>ta?{error:Ln("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(ta)}`)}:{playerId:e,template:n,params:o}}function Ju(t){switch(t.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:t.outcome}};case "rate_limited":{let e=t.retryAfterMs,n=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new He(new G("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new He(new G("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function zu(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function ra(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=Ku(n);if("error"in r)return Promise.reject(r.error);let o=`challenge-${Ae()}`;return new Promise((i,a)=>{let s={},l=m=>{e.delete(o)&&(t.clock.clearTimeout(s.timer),"error"in m?a(m.error):i(m.outcome));};e.set(o,l),s.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??Bu);let d=false;try{d=t.bridge.requestFriendChallenge(o,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(n){let r=e.get(n.requestId);if(r===void 0){t.onDropped?.(`gem.friendChallengeResult (${zu(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(Ju(n));}}}var Nt=t=>typeof t=="string"?t:void 0;function Yu(t){let e=t??{},n=Nt(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Nt(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Ut=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await ft(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=Yu(i);a!==void 0&&o.push(a);}return o}},Ur=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function Xu(t){let e=t??{},n=Nt(e.currency_id);if(n===void 0||n==="")return;let r=Ur(e.limit),o=Math.min(Ur(e.earned),r),i=Math.min(Ur(e.remaining),r-o),a=e.period_days,s=typeof a=="number"&&Number.isInteger(a)&&a>=1?a:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Nt(e.currency_slug)??"",currencyId:n,limit:r,earned:o,remaining:i,period:e.period==="day"?"day":"window",periodDays:s,...d===void 0?{}:{resetsAt:d}}}function oa(t){let e=new Set,n=r=>{t?.(`[gem] an earnAllowance 'changed' listener threw: ${r instanceof Error?r.message:String(r)}`);};return {on(r){return e.add(r),()=>{e.delete(r);}},emit(){for(let r of [...e])try{let o=r();typeof o?.then=="function"&&o.then(void 0,n);}catch(o){n(o);}}}}var Bt=class{#e;#t;#l;constructor(e,n,r){this.#e=e,this.#t=n,this.#l=r;}async get(e={}){let r=(await Yi(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=Xu(i);a!==void 0&&o.push(a);}return o}on(e,n){return e!=="changed"?(this.#l?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#t?.on(n)??(()=>{})}},Gn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Ut(e),this.earnAllowance=new Bt(e,n,r);}};var Br=t=>typeof t=="string"?t:"",ia=t=>typeof t=="number"?t:0;function Qu(t){let e=t??{};return {key:Br(e.key),visibility:Br(e.visibility),value:e.value,updatedAt:ia(e.updated_at)}}function Zu(t){let e=t??{};return {...ve(e),playerId:Br(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Qu):[],generatedAt:ia(e.generated_at)}}function em(t){return t?.reason==="not_found"}var Dn=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return Zu(await Xi(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(em(r))return null;throw r}}};var nm=new Map([["function_error",false],["function_failed",false],["function_timeout",false],["function_not_published",false],["function_input_too_large",false],["functions_not_configured",false],["forbidden",false],["function_capacity_unavailable",true],["function_host_unreachable",true],["function_host_error",true],["rate_limited",true],["service_unavailable",true]]),$n=class extends G{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:nm.get(this.code))??super.retryable}},De=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=tm(e),o;try{o=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(i){throw i instanceof G?om(i):i}return rm(o)}};function tm(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let e;try{e=JSON.stringify(t);}catch(n){throw new oe(`the function input could not be serialised to JSON: ${String(n)}. Pass bytes, or a value JSON can carry. This is a bug in the call, not a server failure.`)}if(e===void 0)throw new oe(`the function input is ${typeof t}, which JSON cannot carry. Pass bytes \u2014 an empty Uint8Array for no input \u2014 or a JSON value. This is a bug in the call, not a server failure.`);return new TextEncoder().encode(e)}function rm(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 om(t){let{details:e,invocationId:n}=Ri(t),o=e?.untrusted?.message,i=e?.reason;return new $n(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof o=="string"?{functionMessage:o}:{},...t.code==="function_failed"&&typeof i=="string"?{failure:i}:{}})}var im=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Hr="gem_";function sa(t){return t.startsWith(Hr)}var aa=1e4,la=50,sm=500,am=65536-4*1024,lm=24*1024;function da(t){let e={},n={};for(let[r,o]of Object.entries(t))typeof o=="string"?e[r]=o:typeof o=="number"&&Number.isFinite(o)&&(n[r]=o);return {dimensions:e,measures:n}}var ca=t=>typeof t=="number"?t:0,dm=t=>typeof t=="string"?t:"";function Vr(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function cm(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:ca(i.index),code:dm(i.code)}}):[];return {accepted:ca(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Wr(){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 um(t){return t?.retryable===true}var Fn=class{#e;#t;#l;#y;#n=[];#f={};#i=0;#s=null;#h=false;#b=false;#v=false;#r=false;#_=null;#a=null;#d=false;#o=false;#m=false;#w=false;#S=false;constructor(e){this.#e=e,this.#t=e.options?.enabled!==false,this.#l=Math.max(aa,e.options?.flushIntervalMs??aa),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??sm));}track(e,n={}){if(!(!this.#t||this.#r)){if(sa(e)){this.#S||(this.#S=true,this.#g(`[gem] analytics: '${e}' was not recorded \u2014 the gem_ prefix is reserved for the platform's own events, which the SDK emits for you. Name your event something else.`));return}this.#R(e,da({...this.#f,...n}));}}setContext(e){this.#f={...this.#f,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#o)return Vr();let n=this.#E();if(n===null||n==="")return this.#n.length>0&&!this.#w&&(this.#w=true,this.#g("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),Vr();if(this.#k(),this.#n.length===0)return Vr();let r=e.keepalive===true;this.#u();let o=this.#n.splice(0,this.#A(r)),i=this.#i;this.#i=0;let a=Math.round(this.#e.clock.now()),s={batch_id:Wr(),sent_at_ms:a,events:o.map(d=>ua(d,a))},l={client:this.#e.client(),gameId:()=>n};this.#v=true;try{let d=await rs(l,s,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=cm(d,i);return this.#P(m),m}catch(d){throw um(d)?this.#x(o,i):this.#g(`[gem] analytics: ${o.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#v=false,this.#n.length>0&&this.#c();}}trackPlatform(e,n={}){this.#r||this.#o&&(e==="gem_pause"||e==="gem_resume")||this.#R(e,da(n));}hold(){this.#r||this.#a!==null||(this.#o=true,this.#u());}release(){if(!this.#o||this.#r)return;this.#o=false;let e=this.#e.clock.now(),n=this.#n.map(r=>({...r,atMs:e}));this.#n=n,this.#m&&(this.#m=false,this.#a=e,this.#d=false,this.#n.unshift({uid:Wr(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#n.length>=la?this.#p():this.#n.length>0&&this.#c();}get held(){return this.#o}startSession(){if(!(this.#r||this.#a!==null)){if(this.#o){this.#m=true;return}this.#a=this.#e.clock.now(),this.#d=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#d)return;if(this.#d=true,this.#o){this.#m=false,this.#n=[],this.#i=0;return}let n=this.#a;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#p({keepalive:true});}setPaused(e){this.#r||e===this.#h||(this.#h=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#n.length>0&&this.#c());}setHidden(e){this.#r||e===this.#b||(this.#b=e,e?this.#u():this.#n.length>0&&this.#c());}dispose(){this.#r=true,this.#u(),this.#n=[],this.#i=0;}get pending(){return this.#n.length}#R(e,n){let{dimensions:r,measures:o}=n;for(this.#k();this.#n.length>=this.#y;)this.#n.shift(),this.#i+=1;this.#n.push({uid:Wr(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#n.length>=la?this.#p():this.#c();}#p(e={}){this.flush(e).catch(()=>{});}#x(e,n){for(this.#n=[...e,...this.#n],this.#i+=n;this.#n.length>this.#y;)this.#n.shift(),this.#i+=1;}#A(e){let n=e?lm:am,r=Math.min(this.#n.length,100),o=128;for(let i=0;i<r;i+=1){let a=this.#n[i];if(a===void 0)break;if(o+=JSON.stringify(ua(a,0)).length+1,o>n)return Math.max(1,i)}return r}#c(){this.#s!==null||this.#h||this.#b||this.#o||this.#r||this.#v||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#p();},this.#l));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#k(){let e=this.#T();e===null||e===""||(this.#_!==null&&this.#_!==e&&(this.#n=[],this.#i=0,this.#a=null,this.#d=false),this.#_=e);}#P(e){for(let n of e.rejected)this.#g(`[gem] analytics: an event was refused (${n.code}). `+mm(n.code));}#g(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#E(){try{return this.#e.gameId()}catch{return null}}#T(){try{return this.#e.playerId()}catch{return null}}};function ua(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function mm(t){switch(t){case "analytics_not_declared":return "This channel has no analytics_events section at all \u2014 promote a game config that declares one. The gem_* events in the same batch were still recorded.";case "unknown_event":return "This channel declares a set of events and this name is not in it \u2014 check the spelling, or declare it in analytics_events.";case "unknown_dimension":return "A string property on this event is not declared as one of its dimensions.";case "missing_dimension":return "A dimension this event declares was not supplied.";case "dimension_value_not_declared":return "A dimension value is outside the closed set the config declares for it.";case "unknown_measure":return "A numeric property on this event is not declared as one of its measures.";case "measure_wrong_type":return "A measure was the wrong shape \u2014 an int measure refuses a fractional value.";case "source_not_permitted":return "This event is declared for the server only, so a client may not emit it.";default:return "See the analytics_events section of your game config."}}function me(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function jn(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=me(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var pm=2e3,gm=5e3;function pa(t){let e=[],n=false,r=null,o=new Map,i=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let a,s=new Promise(l=>{let d=false,m=null;a=c=>{d||(d=true,r=null,t.clock.clearTimeout(m),l(c));},m=t.clock.setTimeout(()=>{n=true,a([]);},t.timeoutMs??pm);});return r={promise:s,settle:a},s};return {resolveList:i,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):i().then(a=>a[0])},refresh(a){return !ma(e,a)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{o.delete(d)&&(t.clock.clearTimeout(l),s(m));};o.set(d,a),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??gm);})},accept(a,s){let l=jn(s),d=me(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...o])ma(m,p)||c(m);}}}}function ma(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var ym=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),b=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="DedicatedServerError",this.retryable=ym.has(n),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var ga=["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"],fm=new Set(ga);function $e(t){return typeof t=="string"&&fm.has(t)?t:"unknown"}var Ht="webrtc_dedicated",Yr=["universal","mobile","web"];var hm="p2p_unavailable",bm="capacity_unavailable",vm=2,ya=3e4,fa=1e3,ha=2e4;async function Xr(t){let e=me(t.clusterTargetId),n=t.nextClusterTarget,r=0,o=t.clock??le,i=t.retry??{},a=i.budgetMs??ya,s=i.maxDelayMs??ha,l=i.initialDelayMs??fa,d=o.now(),m=d+a,c=0;for(;;){c++;try{let p=await no(t.signal,"while allocating",()=>t.client.post(`${_a(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!_m(p)||a<=0)throw p;if(p.status===503&&p.code===hm)throw new b("p2p_unavailable",`room ${t.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${p.message}`,{cause:p});if(r=p.code===bm?r+1:0,n!==void 0&&r>=vm){let C=n;n=void 0;let M=me(await C());M!==void 0&&(e=M,r=0);}let g=Math.min(s,l*2**(c-1)),y=Math.min(s,(p.retryAfterSeconds??0)*1e3),R=Math.max(g/2,y)+Math.random()*(g/2);if(o.now()+R>m)throw wm(t,p,c,o.now()-d,a);if(i.onWaiting?.({attempt:c,elapsedMs:o.now()-d,budgetMs:a,nextAttemptInMs:R,status:p.status,message:p.message}),await Vt(o,R,t.signal),t.signal?.aborted)throw zr("while waiting to allocate")}}}function _m(t){return t instanceof G?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function wm(t,e,n,r,o){let i=`${n} attempt${n===1?"":"s"} over ${r}ms of a ${o}ms budget`;return e.status===429?new b("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${i}: ${e.message}`,{cause:e}):new b("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${i}: ${e.message}`,{cause:e})}var Sm=12e4,Rm=1e3;async function Qr(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??Rm,o=t.timeoutMs??Sm,i=e.now()+o,a=ba(t),s={seen:t.knownToExist===true};for(;;){let l=await va(t,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>i)throw new b("timeout",`match ${n} was still ${l.status} after ${o}ms`);await Vt(e,r,t.signal);}}async function Zr(t){return (await va(t,ba(t),{seen:t.knownToExist===true})).outcome}function ba(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${_a(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function va(t,e,n){let{matchId:r}=t,o=t.clock.now(),i;try{i=await no(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(a){if(a instanceof G&&a.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(n.seen=true,i.status==="ready")return {status:"ready",outcome:km(r,i,o)};if(i.status==="failed"){let a=i.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:$e(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function eo(t){let e=await no(t.signal,"while listing cluster targets",()=>t.client.get("/v1/ping/targets",t.signal)),n=[];for(let r of e.targets??[]){let o=r?.cluster_target_id;typeof o!="string"||o.length===0||n.push({id:o,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return n}async function no(t,e,n){if(t?.aborted)throw zr(e);try{return await n()}catch(r){throw t?.aborted?zr(e,r):r}}function zr(t,e){return new b("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function km(t,e,n){let r=e.join_credential,o=e.expires_in_seconds,i=typeof r=="string"&&typeof o=="number";return {status:"ready",matchId:t,protocol:e.protocol??"unknown",...i?{joinCredential:r,credentialExpiresAt:n+o*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function _a(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Vt(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let o=()=>{t.clearTimeout(i),n?.removeEventListener("abort",o),r();},i=t.setTimeout(o,e);n?.addEventListener("abort",o);})}function wa(t){return typeof t=="string"&&t.trim()!==""}function Wt(t,e){return wa(t)?t.trim():wa(e)?e:null}var Kt="0.1.0-beta",Sa="0-beta",mn="web",xm=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;function Am(t){let e=xm.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Ra(t,e){let n=Pm(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:Kt};let o=Am(r);if(o===null)throw new b("misconfigured",`${e} refused: engineVersion '${r}' is not semver, so no engine line can be derived from it and gem-api answers 400. Omit it \u2014 a browser game has no engine version of its own, and the SDK reports '${Kt}' for it.`);if(o!==Sa)throw new b("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${Sa}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${o}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${Kt}' for it.`);return {...t,platform:n,engineVersion:r}}function Pm(t,e){if(t===void 0||t===mn)return mn;if(!Yr.includes(t))throw new b("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${Yr.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${mn}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${mn}' and is deprecated \u2014 remove the field. A browser game publishes its bundle in the web package dimension, so a client reporting anything else is version-checked against a dimension it has nothing in, and every blacklist, release and expiry check passes without looking at this build.`),mn}var Em="join",Tm="welcome",Im="rejected",ka=25e3,Cm=1e3,to=1;function ro(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var Mm={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 oo(t){let e=typeof t=="string"?t:"unknown";return new b(Mm[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function qn(t){let{channel:e,clock:n}=t;return new Promise((r,o)=>{let i=false,a=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??ka),s=n.setTimeout(()=>w(new b("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(a,Cm)),l=R=>{let C=R.data;if(typeof C!="string"){c(C);return}let M;try{M=JSON.parse(C);}catch{c(C);return}if(i){c(C);return}if(M.t===Tm){let _=ro(M.heartbeat_interval);y({...typeof M.player_id=="string"?{playerId:M.player_id}:{},...typeof M.match_id=="string"?{matchId:M.match_id}:{},..._===void 0?{}:{heartbeatIntervalMs:_}});return}if(M.t===Im){w(oo(M.reason));return}c(C);},d=()=>{w(new b("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{w(new b("aborted","the caller aborted during the join exchange"));},c=R=>{i&&t.onMessage?.(R);},p=()=>{n.clearTimeout(s),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=R=>{i=true,p(),t.onMessage===void 0&&g(),r({welcome:R,detach:g});},w=R=>{i||(i=true,p(),g(),o(R));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){m();return}t.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:Em,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:to}:{}}));}catch(R){w(new b("connection_failed",`the join frame could not be sent on the open channel: ${String(R)}`,{cause:R}));}})}var Ve=1,Nn=2,io=4,lo=8,Om=2,Lm=1e3,co="heartbeat timeout",Un="gem-uu",Jt=2,Aa="gem_transports";function pn(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!Gm(r)||e.includes(r)||e.push(r);}return e}function Gm(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function Bn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Aa];if(typeof n!="object"||n===null)return null;let r=n;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function zt(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Pa=new TextEncoder,Ea=new TextDecoder;function uo(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function mo(t){let e=0;return t?.reliable===false&&(e|=Ve),t?.ordered===false&&(e|=Nn),e}function po(t){return {reliable:(t&Ve)===0,ordered:(t&Nn)===0}}var go={reliable:true,ordered:true};function Ta(t){return JSON.stringify({t:"join",credential:t,wire:Jt,heartbeat:to})}function Ia(t){let e;try{e=JSON.parse(t);}catch{throw new b("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=ro(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"?oo(e.reason):new b("join_refused","the server answered the join out of protocol")}function Yt(){return typeof globalThis.WebTransport=="function"&&yo===null}function Xt(){return yo}var yo=null;var xa="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Dm(t){let e=yt(t);if(e.byteLength!==32)throw new b("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var so=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let i=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(i===0||i>1<<20)throw new b("connection_failed",`a control-stream record claims ${i} bytes`);if(this.buffered.byteLength<4+i)break;let a=this.buffered.slice(4,4+i);this.buffered=this.buffered.slice(4+i),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function ao(t,e){let n=new Uint8Array(5+e.byteLength);return new DataView(n.buffer).setUint32(0,e.byteLength+1,true),n[4]=t,n.set(e,5),n}async function Hn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let s=globalThis.WebTransport;if(s===void 0)throw new b("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new s(t.url):new s(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Dm(t.certHashBase64)}]});}let r=n,o=s=>{try{r.close();}catch{}throw s},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(yo=xa,o(new b("connection_failed",`${xa}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new b("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,a]);let s=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([s.read(),a]);if(s.releaseLock(),l.done||l.value===void 0)return o(new b("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(ao(io,Pa.encode(Ta(t.credential))));let c=new so,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),a]);if(y.done||y.value===void 0)return o(new b("connection_failed","the control stream closed before the join was answered"));for(let w of c.push(y.value)){g=Ia(Ea.decode(w.payload));break}}return {link:$m(r,m,p,c,t.log??(y=>console.warn(y)),Ma(g,t.clock)),welcome:g}}catch(s){return o(s)}}function $m(t,e,n,r,o,i){let a,s,l=false,d=y=>{if(!l){l=true,m.stop();try{t.close();}catch{}s?.(y);}},m=ho(i,()=>d(co)),c=(y,w)=>{m.heard(),(y&lo)===0&&a!==void 0&&((y&io)!==0?a(Ea.decode(w),go):a(w,po(y)));};(async()=>{try{for(;;){let y=await n.read();if(y.done||y.value===void 0)break;for(let w of r.push(y.value))c(w.flags,w.payload);}}catch{}d("stream closed");})();let p,g;try{let y=t.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let w=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let R=await w.read();if(R.done||R.value===void 0)break;let C=R.value;C.byteLength!==0&&c((C[0]??0)|Ve|Nn,C.slice(1));}}catch{}})();}else o("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,g=void 0,o(`[gem] webtransport datagram lane unusable (${zt(y)}); unreliable sends ride the stream`);}return t.closed.then(y=>d(Ca(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,w){if(l)return;if(typeof y=="string"){e.write(ao(io,Pa.encode(y))).catch(()=>d("write failed"));return}let R=mo(w);if((R&Ve)!==0&&g!==void 0){let C=uo(R,y),M=p?.maxDatagramSize;if(M===void 0||C.byteLength<=M){g.write(C).catch(()=>{});return}}e.write(ao(R,y)).catch(()=>d("write failed"));},onMessage(y){a=y;},onClose(y){s=y;},close(){d("closed");}}}function fo(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let o=globalThis.WebSocket;if(o===void 0)return Promise.reject(new b("connection_failed","this environment has no WebSocket"));n=new o(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((o,i)=>{let a=false,s=setTimeout(()=>{a||(a=true,r.close(),i(new b("timeout","websocket did not come up in time")));},e),l=g=>{a||(a=true,clearTimeout(s),r.close(),i(g));},d=()=>{r.send(Ta(t.credential));},m=g=>{if(a)return;if(typeof g.data!="string"){l(new b("join_refused","the server sent binary before answering the join"));return}let y;try{y=Ia(g.data);}catch(w){l(w);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),o({link:Fm(r,Ma(y,t.clock)),welcome:y});},c=()=>{l(new b("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new b("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",c),r.addEventListener("error",p),r.readyState===1&&d();})}function Ca(t){return typeof t=="string"&&t.length>0?t:void 0}function Ma(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function ho(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,Lm)*Om,o=n.now(),i=null,a=()=>{i=null;let s=n.now()-o;if(s>=r){e();return}i=n.setTimeout(a,r-s);};return i=n.setTimeout(a,r),{heard:()=>{o=n.now();},stop:()=>{i!==null&&(n.clearTimeout(i),i=null);}}}function Fm(t,e){let n,r,o=false,i=s=>{if(!o){o=true,a.stop();try{t.close();}catch{}r?.(s);}},a=ho(e,()=>i(co));return t.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){n?.(s.data,go);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&lo)===0&&n?.(l.slice(1),po(d));})),t.addEventListener("close",(s=>i(Ca(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!o){if(typeof s=="string"){t.send(s);return}t.send(uo(mo(l),s));}},onMessage(s){n=s;},onClose(s){r=s;},close(){i("closed");}}}function bo(t,e,n,r){let o,i,a=false,s=n,l=c=>{if(!a){a=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}i?.(c);}},d=ho(r,()=>l(co)),m=(c,p)=>{if(d.heard(),typeof c=="string"){o?.(c,go);return}let g=new Uint8Array(c);if(g.byteLength===0)return;let y=g[0]??0;(y&lo)===0&&o?.(g.slice(1),po(y|p));};if(t.addEventListener("message",(c=>m(c.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),s!==void 0){let c=s;c.addEventListener("message",(p=>m(p.data,Ve|Nn))),c.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(c,p){if(a)return;if(typeof c=="string"){t.send(c);return}let g=mo(p),y=uo(g,c);if((g&Ve)!==0&&s!==void 0&&s.readyState==="open"){s.send(y);return}t.send(y);},onMessage(c){o=c;},onClose(c){i=c;},close(){l("closed");}}}function wo(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let o=vo(r);o!==void 0&&(e[n]=o);}return e}function So(t){if(Array.isArray(t))return t.map(jm).filter(e=>!!e)}function vo(t){if(_o(t)||Array.isArray(t)&&t.every(_o))return t}function _o(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function jm(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=vo(e.fixed),r=vo(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...n===void 0?{}:{fixed:n},...r===void 0?{}:{default:r},...gn("description",qm(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(_o)?{allowed:e.allowed}:{},...gn("min",Vn(e.min)),...gn("max",Vn(e.max)),...gn("minItems",Vn(e.min_items)),...gn("maxItems",Vn(e.max_items)),...gn("maxLength",Vn(e.max_length))}}function qm(t){return typeof t=="string"&&t.length>0?t:void 0}function Vn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function gn(t,e){return e===void 0?{}:{[t]:e}}function Ee(t){let e=t??{},n=X(e.id)??X(e.game_room_id);if(n===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(Oa):[];return {id:n,gameId:X(e.game_id)??"",name:X(e.name)??"",status:X(e.status)??"open",hostPlayerId:X(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,..._e("joinCode",X(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},..._e("roomArgs",wo(e.room_args)),..._e("roomArgsTemplate",So(e.room_args_template)),gameChannel:X(e.game_channel)??"release",..._e("region",X(e.region)),..._e("clusterTargetId",X(e.cluster_target_id)),selfHosted:e.self_hosted===true,..._e("matchId",X(e.match_id)),version:Pe(e.version)??0,..._e("templateId",X(e.template_id)),roomType:X(e.game_room_type)??"Standard",..._e("transports",pn(e.transports)??void 0),createdAt:Pe(e.created_at)??0,updatedAt:Pe(e.updated_at)??0,..._e("startedAt",Pe(e.started_at))}}function Oa(t){let e=t??{};return {...ve(e),playerId:X(e.player_id)??"",isReady:e.is_ready===true,role:X(e.role)??"member",joinedAt:Pe(e.joined_at)??0,..._e("groupId",X(e.group_id)),..._e("platform",X(e.platform))}}function Qt(t){let e=t??{};return {id:X(e.id)??X(e.game_room_id)??"",gameId:X(e.game_id)??"",name:X(e.name)??"",status:X(e.status)??"open",hostPlayerId:X(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:X(e.game_channel)??"release",roomType:X(e.game_room_type)??"Standard",createdAt:Pe(e.created_at)??0}}function X(t){return typeof t=="string"&&t.length>0?t:void 0}function Pe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function _e(t,e){return e===void 0?{}:{[t]:e}}var Wn=class{constructor(e){this.options=e;}options;list(e){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.templateSlug&&n.set("template_slug",e.templateSlug),e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor&&n.set("cursor",e.cursor);let r=n.size>0?`?${n.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(o=>({rooms:(o.game_rooms??[]).map(Qt),...typeof o.next_cursor=="string"?{nextCursor:o.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(n=>({rooms:(n.game_rooms??[]).map(Qt)}))}create(e,n,r){return Nm(e.maxPlayers),this.options.client.post(this.baseV2(),{name:e.name,...e.isPublic===void 0?{}:{is_public:e.isPublic},...e.settings===void 0?{}:{settings:e.settings},...e.region===void 0?{}:{region:e.region},...r===void 0?{}:{cluster_target_id:r},...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...Zt(n)},e.signal).then(Ee)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Ee)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...Zt(r)},n.signal).then(Ee)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...Zt(r)},n.signal).then(Ee)}quickJoin(e,n,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...Zt(n)},e.signal).then(Ee)}leave(e,n,r,o=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:n},r,{keepalive:o}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}close(e,n){return this.options.client.delete(this.roomV1(e),n).then(()=>{})}update(e,n){return this.options.client.patch(this.roomV2(e),{...n.name===void 0?{}:{name:n.name},...n.maxPlayers===void 0?{}:{max_players:n.maxPlayers},...n.isPublic===void 0?{}:{is_public:n.isPublic},...n.settings===void 0?{}:{settings:n.settings},...n.roomArgs===void 0?{}:{room_args:n.roomArgs}},n.signal).then(Ee)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Ee)}kick(e,n,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(n)}`,{},r).then(()=>this.get(e,r))}transferHost(e,n,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(n)}`,{},r).then(Ee)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Zt(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function Nm(t){t!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${t}) is deprecated and was not sent. A room's seats come from the room template published in your game config \u2014 name one with templateSlug \u2014 and a room created without a template seats 8. To change a room that already exists, call update({ maxPlayers }) as its host.`);}var Kn=class{listeners=new Map;retainedMatch=null;on(e,n){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(n),e==="matchReady"&&this.retainedMatch!==null){let o=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===o&&n(o);});}return ()=>this.off(e,n)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...o)=>{r(),n(...o);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let o of [...r])o(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function Um(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var Bm=1e3,Hm=3e3,Vm=6e4,Wm=2,La=new Set(["game_room_closed","game_room_gone"]),Km=12e4,Jm=5e3,zm=new Set(["invalid_cluster_target","capacity_unavailable"]),Ym=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function ko(t){return new Ro(t)}var Ro=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Wn({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Kn;api;room=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create");let n=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("create",async()=>{let i=await n;return this.api.create(r,this.version("create"),i[0]).catch(async a=>{let s=await this.afterRefusedClusters(a,i);if(s[0]===void 0||s[0]===i[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(o,"created"),this.askForLocalServer(o),o}async join(e,n={}){this.assertNotInRoom("join");let r=await this.attachParty(n),o=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(o,"joined"),this.askForLocalServer(o),o}async joinByCode(e,n={}){this.assertNotInRoom("joinByCode");let r=await this.attachParty(n),o=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(o,"joined"),this.askForLocalServer(o),o}async quickJoin(e){this.assertNotInRoom("quickJoin");let n=this.clusterTargets(),r=await this.attachParty(e),o=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),i=await this.run("quickJoin",async()=>{let a=await n;return o(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||Qm(l,a))throw s;return o(l)})});return this.enter(i,"joined"),this.askForLocalServer(i),i}async list(e={}){let n=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",n),n}async myRooms(e){let n=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",n.rooms),n.rooms}async leave(e={}){let n=this.requireRoom("leave"),r=e.keepalive===true,o=()=>this.run("leave",()=>this.api.leave(n.id,e.asGroup!==false,e.signal,r));if(r){let i=o();this.track(this.notifyLeavingMatch({keepalive:true})),await i;}else await this.notifyLeavingMatch(),await o();this.exit(),this.emitter.emit("left");}async leaveAll(e){let n=await this.myRooms(e),r=[];for(let o of n)try{await this.run("leaveAll",()=>this.api.leave(o.id,!0,e)),r.push(o.id),this.room?.id===o.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let n=this.requireRoom("close");await this.run("close",()=>this.api.close(n.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let n=this.room;if(!n)return null;let r;try{r=await this.track(this.api.get(n.id,e));}catch(o){if(o instanceof G&&o.reason==="not_found"){let i=this.heldMatchId;if(i!==null){let a=await this.askWhyEnded(i,e);this.endMatch(i,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",o),o}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let n=this.room,r=this.heldMatchId;if(!(n===null||r===null)&&!(n.status==="in_game"&&n.matchId===r)&&!(n.matchId!==void 0&&n.matchId!==r)&&this.settling!==r){this.settling=r;try{let o=await this.askWhyEnded(r,e);o!==null&&this.endMatch(r,o,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let o=this.takeHint(e),i;try{i=await this.track(this.onceGameIdKnown(()=>Zr({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...n===void 0?{}:{signal:n}})));}catch(a){return a instanceof G&&a.reason==="not_found"?o??null:(this.reportError("reconcile",a),null)}return i===null?null:i.status==="ready"?(this.seenMatches.add(e),null):i.status==="failed"?(this.settleFailed(i.matchId,i.reason),null):i.reason==="unknown"&&o!==null?o:i.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=$e(n.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),o=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(o),o}async kick(e,n){let r=this.requireRoom("kick"),o=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(o),o}async transferHost(e,n){let r=this.requireRoom("transferHost"),o=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(o),o}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){let r=this.requireRoom("startMatch");if(!this.isHost)throw new b("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let o=me(n.clusterTargetId),i=o??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,c)=>Xr({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...o===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>s(i,[a]).catch(async m=>{if(o!==void 0||!Da(m))throw m;let c=await this.nextCluster([a],true);if(c===void 0)throw m;return s(c,[a,c])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new b("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let n=this.emitter.retained;return n!==null&&this.session.phase==="ready"?n:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let n=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),o=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(o)}chase(e,n,r){return Qr({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:n,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(n),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new b("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!La.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new b("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,n){this.heldMatchId===e&&(this.abandonReconnect(e,n),this.emitter.emit("matchFailed",e,n),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,n,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:n,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:n,roomReopened:r}),this.abandonReconnect(e,n));}armReconnect(e,n){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),n==="kicked"){r.abandon(e,n);return}let o={matchId:e,cause:n,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=o,this.track(this.reconnectStep(o));}park(e,n){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),n());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,n){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,n));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!We()){this.park(e,()=>this.reconnectStep(e));return}let n=this.options.autoReconnect;if(n===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=n.attempts||r<Bm){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(Um(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!We()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let o=null;try{o=await this.track(this.onceGameIdKnown(()=>Zr({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e.matchId,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e.matchId)})));}catch(i){this.reportError("reconcile",i);}if(this.reconnecting(e)){if(o?.status==="ended"){this.endMatch(o.matchId,o.reason,!La.has(o.reason)),this.track(this.reconcile().catch(()=>{}));return}if(o?.status==="failed"){this.abandonReconnect(e.matchId,o.reason),this.settleFailed(o.matchId,o.reason);return}if(o?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(o);let i;try{i=await n.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),i="failed";}if(e.done||this.reconnect!==e)return;if(i==="closed"){this.finishReconnect();return}if(i==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let n=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):n&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new b("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let n=this.session.matchId;this.session={phase:"suspended",matchId:n,reason:e},this.emitter.emit("matchSuspended",{matchId:n,cause:e}),this.armReconnect(n,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new b("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let n=this.heldMatchId;if(n===null)throw new b("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:n},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let n=this.heldMatchId;if(n!==null)try{await this.api.leaveMatch(n,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,n){let r=this.emitter.on(e,n);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}handleRoomEvent(e){if(this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let n=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(n).catch(()=>{}));}handleAutoStartFailed(e,n){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(n);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:n,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let o=new AbortController;this.autoStartRetry=o,this.track(this.requestStart({signal:o.signal},false).then(()=>{},i=>{o.signal.aborted||this.reportError("startMatch",i);}).finally(()=>{this.autoStartRetry===o&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!zm.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){this.disposed||!this.watchingSeats||this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}async reconcileSeats(){if(this.disposed||!this.watchingSeats)return;let e;try{e=await this.myRooms();}catch{return}let n=new Set;for(let r of e)r.status!=="closed"&&(n.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])n.has(r)||this.reported.delete(r);}async reportSeat(e){let n=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||n===null||!r.members.some(o=>o.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.seatPollMs>0&&We())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let n=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(n,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!We())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of er)e.addEventListener(r,this.visibilityListener);let n=globalThis.document;typeof n?.addEventListener=="function"&&n.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let n=this.inFlight;this.inFlight=[],await Promise.allSettled(n);}}dispose(){if(this.disposed=true,this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of er)e.removeEventListener?.(r,this.visibilityListener);globalThis.document?.removeEventListener?.("resume",this.visibilityListener),this.visibilityListener=null;}}get watchingSeats(){return this.options.watchSeats!==false&&this.emitter.hasListeners("seated")}get seatPollMs(){return this.options.seatPollIntervalMs??Jm}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new b("misconfigured","the game id is not known yet. It comes from the play token, and this manager was given no way to wait for one \u2014 pass gameId, or awaitGameId so a call made before the first token waits for it the way createGem wires it.")}playerId(){return typeof this.options.playerId=="function"?this.options.playerId():this.options.playerId}version(e){let n=this.options.clientVersion,r=Wt(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new b("misconfigured",`${e} has no game version to report \u2014 gem-api requires platform, game_version and engine_version together on every room route, and refuses a request carrying two of the three. The arcade normally supplies it with the play token; an embedder that does not, or a build running outside the arcade, leaves nobody to ask. Pass \`clientVersion: { gameVersion }\` to createGem (or to createRoomManager) as the fallback. It has to name a build you actually published, and a wrong one pins the room to the wrong build \u2014 which is why the platform answers it wherever it can.`);return Ra({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return jn(await this.options.resolveClusterTargets());let e=me(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Da(e)||n.length===0?[]:jn(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=a=>a.find(s=>!e.includes(s)),o=await this.clusterTargets(),i=r(o);return i!==void 0||!n?i:r(jn(await this.options.refreshClusterTargets?.(o)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let n=this.options.resolveParty;if(n===void 0)return e;let r=await n();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,n,r){if(!(e instanceof G)||e.reason!=="conflict"||!Ym.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new G(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let o;try{o=await this.leaveAll(n.signal);}catch{throw new G(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(o.length===0)throw new G(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.api.quickJoin(n,this.version("quickJoin"),r)}assertNotInRoom(e){if(this.room!==null)throw new b("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}requireRoom(e){if(this.room===null)throw new b("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,n){try{return await this.track(this.onceGameIdKnown(n))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,n){let r=n instanceof G?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof b?n.reason:"unavailable",message:n instanceof Error?n.message:String(n),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let n=this.options.ensureLocalServer;n===void 0||!e.selfHosted||e.status!=="open"||n(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,n){this.room=e,this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(n,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let n=this.room;if(n===null||n.id!==e.id)return;let r=new Map(n.members.map(s=>[s.playerId,s])),o=new Map(e.members.map(s=>[s.playerId,s])),i=this.playerId();for(let s of o.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!o.has(s)){if(s===i){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of o){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=Xm(n,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),a&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let n=this.heldMatchId;n!==null&&n!==e&&this.endMatch(n,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,n=this.heldMatchId;if(e===null||n===null||this.followAbort!==null&&this.followingMatchId===n)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=n,this.track(this.onceGameIdKnown(()=>this.chase(e.id,n,{signal:r.signal})).then(o=>{if(!r.signal.aborted)try{this.settleOutcome(o);}catch{}}).catch(o=>{r.signal.aborted||this.reportError("pollMatchStatus",o);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??Km;return new Promise((o,i)=>{let a=c=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},s=this.emitter.on("matchAllocationStarted",c=>a(()=>o(c))),l=this.emitter.on("matchFailed",(c,p)=>a(()=>i(new b("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>a(()=>i(new b("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>i(new b("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??Hm}pushedInterval(){return this.options.pushedPollIntervalMs??Vm}pushed(){return this.options.clock.now()-this.lastPushAt<Wm*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=n=>{n?.persisted!==true&&this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{}));},e.addEventListener("pagehide",this.unloadListener));}};function We(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var er=["visibilitychange","focus","pageshow","online"];function Xm(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||Ga(t)!==Ga(e)}function Ga(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Da(t){return t instanceof G&&t.code==="invalid_cluster_target"}function Qm(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Zm=["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 yn=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let o=ep(e,this.options.transport,(this.options.now??Date.now)());o.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:o},n);}report(e){this.post(e).catch(()=>{});}};function ep(t,e,n){let r=Math.floor(n/1e3);return t.filter(o=>xo.includes(o.type)).slice(0,100).map(o=>{let i=np(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function np(t){if(t!==void 0)return Zm.includes(t)?t:"unknown"}var Jn=class{constructor(e){this.options=e;this.reporter=new yn({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let o=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:nr(o.credential)??"",hostFingerprint:nr(o.host_fingerprint)??"",hostEpoch:tr(o.host_epoch)??0,expiresAt:(tr(o.expires_at)??0)*1e3}}async turnLease(e,n,r){let o=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),i=[];for(let l of Array.isArray(o.ice_servers)?o.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&i.push({urls:m,username:nr(d.username)??"",credential:nr(d.credential)??""});}let a=tr(o.expires_at),s=tr(o.ttl_seconds);return {iceServers:i,expiresAt:a!==void 0?a*1e3:Date.now()+(s??0)*1e3}}async kick(e,n,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:n},r);}async leave(e,n=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:n});}async telemetry(e,n){await this.reporter.post(e,n);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function nr(t){return typeof t=="string"&&t.length>0?t:void 0}function tr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var tp=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),O=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="P2pError",this.retryable=tp.has(n);}reason;retryable};var $a=10240,Fa=2048,rp=new TextEncoder;function ja(t){return rp.encode(t).length}function Fe(t,e){let n=o=>{throw new b("invalid_sdp",`the ${e} ${o}`)},r=ja(t);r>=$a&&n(`is ${r} bytes, over the ${$a} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),t.startsWith("v=")||n("does not start with 'v=', so it is not SDP"),t.includes("\0")&&n("contains a null byte"),/\r(?!\n)/.test(t)&&n("contains a bare carriage return");for(let o of t.split(/\r\n|\n/)){let i=ja(o);i>Fa&&n(`has a ${i}-byte line, over the ${Fa} limit`);}}function rr(t){for(let e of t.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[n,r="0"]=e.slice(2).trim().split(/\s+/);if(!(n!=="audio"&&n!=="video")&&r.split("/")[0]!=="0")return true}return false}var or=class{listeners=new Map;on(e,n){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(n),()=>this.off(e,n)}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...o)=>{r(),n(...o);}));return r}emit(e,...n){let r=this.listeners.get(e);if(r)for(let o of [...r])o(...n);}clear(){this.listeners.clear();}};var op=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function fn(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=ir(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function ir(t){let[e,...n]=t.trim().split(/\s+/);if(e===void 0||n.length===0)return null;let r=`${e.toLowerCase()} ${n.join("").toUpperCase()}`;return op.test(r)?r:null}function zn(t,e){if(t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}var Ao=5e3,ip=12e4+Ao,sp=1024,ap=6e4,lp=1e4,qa=64*1024,Na=5;function Po(t){let e=new Map,n=-1/0,r=null,o=(()=>{let s;try{s=new URL(`${t.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return s.username!==""||s.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:s.href,shown:`${s.protocol}//${s.host}`}})(),i=()=>{let s=t.subtle??globalThis.crypto?.subtle;if(!s)throw new O("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return s},a=async()=>{if(!o.ok)throw new O("keys_unavailable",o.reason);let s=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await s(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(lp)});}catch{throw new O("keys_unavailable",`the JWKS endpoint at ${o.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new O("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>qa)throw new O("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${qa} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof O?p:new O("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>Na)throw new O("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Na} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=i();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let y=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,y);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!o.ok)throw new O("keys_unavailable",o.reason);if(r)return await r,e.get(s)??null;let d=t.now();if(!Number.isFinite(d))throw new O("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<n&&(n=-1/0),d-n<ap?null:(n=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var Yn=class{seen=new Map;admit(e,n){for(let[r,o]of this.seen)o<=n&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=sp){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+ip),true}};function Ba(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function Ua(t){try{let e=new TextDecoder().decode(Ba(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Eo(t,e,n,r,o){let i=D=>{throw new O("peer_unauthenticated",`the peer's join credential is not usable: ${D}`)},a=t.split(".");a.length!==3&&i("it is not a three-part JWT");let[s,l,d]=a,m=Ua(s);m===null&&i("its header does not decode"),m.alg!=="RS256"&&i(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&i("it names no key");let p=await n.key(c);p===null&&i("it was signed by a key this build cannot resolve");let g=o.subtle??globalThis.crypto?.subtle;g||i("this environment has no WebCrypto");let y=new TextEncoder().encode(`${s}.${l}`),w;try{w=Ba(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,w,y)||i("its signature does not verify");let C=Ua(l);C===null&&i("its payload does not decode");let M=C,_=D=>typeof M[D]=="string"?M[D]:"",S=D=>typeof M[D]=="number"&&Number.isFinite(M[D])?M[D]:NaN;_("iss")!==o.issuer&&i("it was issued by someone else"),_("aud")!==`${o.issuer}/p2p-match`&&i("its audience is not this platform"),_("match_id")!==e.matchId&&i("it is for another match"),_("game_id")!==e.gameId&&i("it is for another game");let P=S("exp")*1e3,x=S("nbf")*1e3;(!Number.isFinite(P)||e.now>P+Ao)&&i("it has expired"),Number.isFinite(x)&&e.now<x-Ao&&i("it is not valid yet");let V=_("role");V!=="host"&&V!=="client"&&i("it names no usable role");let N=S("host_epoch");N!==e.hostEpoch&&i("it names a different host epoch");let W=ir(_("fingerprint"));W===null&&i("its fingerprint claim is malformed"),zn(W,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let k=ir(_("host_fingerprint"));k===null&&i("its host fingerprint claim is malformed"),zn(k,e.hostFingerprint)||i("it was issued against a different host certificate");let A=_("jti");A.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(A,e.now)||i("it has already been used");let L=_("sub");return L.length===0&&i("it names no player"),{playerId:L.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:N,role:V,fingerprint:W,hostFingerprint:k,jti:A,expiresAt:P}}function To(t){let e=new TextEncoder().encode(t.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let n=new ArrayBuffer(3+e.length+4+4),r=new DataView(n);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(n,3,e.length).set(e),r.setUint32(3+e.length,t.protocolVersion,true),r.setUint32(7+e.length,t.assignedPeerId,true),n}function Io(t){let e=new ArrayBuffer(9),n=new DataView(e);return n.setUint8(0,2),n.setUint32(1,t.protocolVersion,true),n.setUint32(5,t.assignedPeerId,true),e}function Co(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function Mo(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 Ha(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 Va(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Xn=class{constructor(e,n,r){this.localPlayerId=e;this.hostPlayerId=n,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,n){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=n,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var Oo={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},Me=["reliable","ordered","unreliable"];function Lo(t){let e=globalThis.RTCPeerConnection;if(!e)throw new Error("[gem] this environment has no RTCPeerConnection. Pass `peerConnectionFactory` to connect against a stand-in, which is how this flow is tested outside a browser.");return new e({iceServers:t.iceServers,...t.certificates===void 0?{}:{certificates:t.certificates}})}async function Qn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Ka=1,pp=3e4,Ja=2e3,gp=5e3,za=6e4,yp=8,Do=class{constructor(e=yp){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;}},fp=new Do,hp=8,bp=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),et=class{constructor(e){this.options=e;this.keys=e.keys??Po({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new or;links=new Map;replays=new Yn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Ka+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let n of this.links.values())n.admitted&&e.push(this.expose(n));return e}peer(e){let n=this.links.get(e);return n&&n.admitted?this.expose(n):null}on(e,n){return this.emitter.on(e,n)}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}async start(e){let n=this.options.connectTimeoutMs??pp;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),o=me(this.options.clusterTargetId);if(o!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,o,e);this.iceServers=s.iceServers,this.mark("turn leased");}catch(s){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Go(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let i=this.options.clock.setTimeout(()=>{this.fail(new O("timeout",`no usable P2P connection after ${n}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},n),a=()=>this.fail(new O("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",a),this.ready=null;}}async kick(e){if(!this.isHost)throw new O("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,n){this.closed||this.route(e,n).catch(r=>this.report_(r));}async route(e,n){switch(e){case "hello":return this.onHello(n);case "offer":return this.onOffer(n);case "answer":return this.onAnswer(n);case "ice":return this.onIce(n);case "peerLeft":return this.onPeerLeft(n);case "migration":return this.onMigration(n);case "matchEnded":return this.onMatchEnded(n);case "error":return this.onSignalingError(n);default:return}}async onHello(e){let n=ae(e.playerId),r=ae(e.hostPlayerId),o=sr(e.hostEpoch);if(!(n===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new Xn(n,r,o)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let n of e)try{await this.onOffer(n);}catch(r){this.report_(r);}}async offerToHost(e){let n=this.hostPlayerId,r=this.openLink(n,Ka),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new O("invalid_sdp","the browser produced an offer with no SDP");Fe(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,e),this.mark("offer sent"),this.fetchCredential().catch(a=>this.report_(a));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,o=r===void 0?null:fn(r);if(o===null)throw new O("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let i=this.options.credentialPacing??fp,a=()=>this.closed||e!==this.credentialGeneration,s=gp;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,c;if(m===409)c=Ja;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?c=p*1e3:(c=s,s=Math.min(s*2,za)),c=Math.min(Math.max(c,Ja),za);}else throw d;if(!await this.waitForCredential(c,a))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=ae(e.fromPlayerId),r=ae(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=hp){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let o=ae(e.sessionId);if(o!==null&&this.answeredSessions.get(n)===o)return;Fe(r,"offer"),this.refuseMedia(r,"offer");let i=fn(r);if(i===null)throw new O("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);this.mark("offer received"),o!==null&&this.answeredSessions.set(n,o);let a=this.links.get(n);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(n,this.nextPeerId++);s.remoteFingerprint=i,await s.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(s);let l=await s.connection.createAnswer();await s.connection.setLocalDescription(l);let d=s.connection.localDescription?.sdp??l.sdp;if(!d)throw new O("invalid_sdp","the browser produced an answer with no SDP");Fe(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(n,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let n=ae(e.fromPlayerId),r=ae(e.sdp);if(n===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||n!==this.hostPlayerId)return;Fe(r,"answer"),this.refuseMedia(r,"answer");let i=fn(r);if(i===null)throw new O("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),o.remoteFingerprint=i,o.pendingAnswer=r,this.hostVerified(o)&&await this.applyAnswer(o,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:zn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new O("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let n=e.pendingAnswer;n!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,n).catch(r=>this.report_(r));}async applyAnswer(e,n){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:n}),this.flushCandidates(e);}async onIce(e){let n=ae(e.fromPlayerId),r=ae(e.candidate);if(n===null||r===null)return;let o=this.links.get(n);if(!o)return;let i=ae(e.sdpMid),a=sr(e.sdpMLineIndex)??sr(e.sdpMLineIndexAlt),s={candidate:r,...i===null?{}:{sdpMid:i},...a===null?{}:{sdpMLineIndex:a}};if(o.connection.remoteDescription===null){o.pendingCandidates.length<64&&o.pendingCandidates.push(s);return}await o.connection.addIceCandidate(s);}onPeerLeft(e){let n=ae(e.playerId);if(n===null)return;let r=ae(e.reason)??"left";if(n===this.localPlayerId){this.fail(new O("kicked",`this player was removed from the match (${r})`)),this.close();return}let o=this.links.get(n);o&&this.dropLink(o,r,true);}async onMigration(e){let n=ae(e.hostPlayerId),r=sr(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:n,hostEpoch:r,...ae(e.reason)===null?{}:{reason:ae(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(i=>typeof i=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(o.kind!=="duplicate"){if(o.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(o.kind==="refused"){this.report_(new O("migration_failed",o.why));return}for(let i of [...this.links.values()])this.dropLink(i,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),o.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new O("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let n=ae(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new O("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=ae(e.code)??"unknown",r=ae(e.message)??"the platform refused a signaling message";this.report_(new O("signaling_failed",`${n}: ${r}`));}openLink(e,n){let o=(this.options.peerConnectionFactory??Lo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of Me){let g=o.createDataChannel(p,Oo[p]);g.binaryType="arraybuffer",i[p]=g;}let a={playerId:e,assignedPeerId:n,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(g=>this.report_(g));},c=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",s),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",c),i.reliable.addEventListener("message",m),a.detachHandshake=()=>{i.reliable.removeEventListener("open",c),i.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),o.removeEventListener("icecandidate",s),o.removeEventListener("iceconnectionstatechange",l),o.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}flushCandidates(e){let n=e.pendingCandidates;e.pendingCandidates=[];for(let r of n)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let n=this.credential;if(n===null)throw new O("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=n.expiresAt)throw new O("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(To({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=Mo(n);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new O(Va(r.reason),Ha(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,n,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let o=fn(e.connection.localDescription?.sdp??"");if(o===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let i;try{i=await Eo(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:o,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof O&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Go(a)),s&&this.fail(a);return}if(i.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${i.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(i.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Io({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,o){this.warn(`refused to admit ${e.playerId}: ${o}`);try{e.channels.reliable.send(Co(n));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let o of Me)Ya(e.channels[o]);Ya(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,n);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let n=this.ready;this.ready=null,n.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof O?e:new O("connection_failed",Go(e),{cause:e}));}count(e){this.counted||!bp.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(rr(e))throw new O("media_refused",`the ${n} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(n=>this.options.clock.setTimeout(n,e))}warn(e){let n=this.options.log;n!==null&&(n??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function ae(t){return typeof t=="string"&&t.length>0?t:null}function sr(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function Go(t){return t instanceof Error?t.message:String(t)}function Ya(t){try{t.close();}catch{}}var vp=100,_p=50,nt=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,n){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:n});}answer(e,n,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:n,assignedPeerId:r});}candidate(e,n,r,o){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??vp)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...r===void 0?{}:{sdpMid:r},...o===void 0?{}:{sdpMLineIndex:o}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,n){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:n,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new O("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new O("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:n,candidate:r,sdpMid:o,sdpMLineIndex:i}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...o===void 0?{}:{sdpMid:o},...i===void 0?{}:{sdpMLineIndex:i}});}if(this.dropped>0&&this.queue.length===0){let n=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(n),this.dropListener?.(n);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??_p));}};function B(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function je(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function hn(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function Xa(t){return typeof t=="boolean"?t:void 0}var fe=B(64),tt=je(0,2147483647);function $o(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=fe(n);typeof r=="string"&&e.push(r);}return e}function z(t,e,n){return {to:t,from:e,read:n,required:true}}function H(t,e,n){return {to:t,from:e,read:n,required:false}}var Rp=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=hn("disconnected","failed","closed")(e.iceState),r=je(0,4102444800)(e.lastSeenAt);if(!(n===void 0&&r===void 0))return {...n===void 0?{}:{ice_state:n},...r===void 0?{}:{last_seen_timestamp:r}}};Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[z("sdp","sdp",B(10240)),z("signaling_intent","intent",hn("initial","ice_restart","full_reconnect")),H("sdp_hash","sdpHash",B(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[z("peer_id","peerId",fe),z("sdp","sdp",B(10240)),z("assigned_peer_id","assignedPeerId",je(0,4294967295)),H("sdp_hash","sdpHash",B(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[z("peer_id","peerId",fe),z("candidate","candidate",B(512)),H("sdp_mid","sdpMid",B(64)),H("sdp_mline_index","sdpMLineIndex",je(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[z("host_epoch","hostEpoch",tt)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[z("host_epoch","hostEpoch",tt),H("evidence","evidence",Rp)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"}));Object.freeze(Object.assign(Object.create(null),{hello:[z("playerId","player_id",fe),z("hostPlayerId","host_player_id",fe),z("hostEpoch","host_epoch",tt),H("members","members",$o)],offer:[z("fromPlayerId","from_player_id",fe),z("sdp","sdp",B(10240)),H("sessionId","signaling_session_id",B(128)),H("sdpHash","sdp_hash",B(128)),H("iceUfrag","ice_ufrag",B(64)),H("intent","signaling_intent",hn("initial","ice_restart","full_reconnect"))],answer:[z("fromPlayerId","from_player_id",fe),z("sdp","sdp",B(10240)),H("sessionId","signaling_session_id",B(128)),H("sdpHash","sdp_hash",B(128)),H("iceUfrag","ice_ufrag",B(64)),H("assignedPeerId","assigned_peer_id",je(0,4294967295))],ice:[z("fromPlayerId","from_player_id",fe),z("candidate","candidate",B(512)),H("sdpMid","sdp_mid",B(64)),H("sdpMLineIndex","sdp_m_line_index",je(0,255)),H("sdpMLineIndexAlt","sdp_mline_index",je(0,255))],peerJoined:[z("playerId","player_id",fe)],peerLeft:[z("playerId","player_id",fe),H("reason","reason",B(64))],migration:[z("hostPlayerId","new_host_player_id",fe),z("hostEpoch","host_epoch",tt),H("reason","reason",B(64)),H("kickedPlayerIds","kicked_player_ids",$o),H("migrationComplete","migration_complete",Xa)],matchEnded:[H("reason","reason",B(64))],error:[H("code","code",B(64)),H("message","message",B(256))]}));Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));var Je="webrtc_p2p";function Za(t){let e=new Jn({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,o,i){n.get(r)?.handleSignal(o,i);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new O("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let o=me(r.clusterTargetId),i=o??me(await t.resolveClusterTarget?.());t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...o===void 0?{}:{clusterTargetId:o},...r.signal===void 0?{}:{signal:r.signal}});let a=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==Je)throw new O("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${Je}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new nt({bridge:t.bridge,matchId:a.matchId,clock:t.clock}),l=new et({api:e,clock:t.clock,matchId:a.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:s,...i===void 0?{}:{clusterTargetId:i},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Qn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(a.matchId,l),l.on("matchEnded",()=>n.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(a.matchId),l.close(),d}return l}}}function el(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,o=t.document??globalThis.document,i=[];if(typeof r.addEventListener=="function"){let s=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",s),i.push(()=>r.removeEventListener?.("pagehide",s));let l=()=>e.setHidden(!We());for(let d of er)r.addEventListener(d,l),i.push(()=>r.removeEventListener?.(d,l));typeof o?.addEventListener=="function"&&(o.addEventListener("resume",l),i.push(()=>o.removeEventListener?.("resume",l))),e.setHidden(!We());}let a=new Map;return i.push(n.on("matchReady",s=>{let l=s.protocol===Je?"p2p":"dedicated";a.set(s.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),i.push(n.on("matchEnded",s=>{let l=a.get(s.matchId);l!==void 0&&(a.delete(s.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let s of i.splice(0))try{s();}catch{}a.clear();}}var nl=["pointerdown","keydown"];function tl(t,e=globalThis){let n=false,r=false,o=null,i=()=>{if(o!==null){try{e.cancelAnimationFrame?.(o);}catch{}o=null;}},a=()=>{if(!r){r=true,i();for(let g of nl)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},s=()=>{if(!(n||r)){n=true,a();try{t();}catch{}}};function l(g){g?.isTrusted===true&&s();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(y=>y?.buttons.some(w=>w.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},c=()=>{if(o=null,!(n||r)){if(d()){s();return}m()&&(o=e.requestAnimationFrame?.(c)??null);}};function p(){o===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let g of nl)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(o=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:a}}async function ar(t,e,n,r){let o=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),o}function Fo(t,e){let n=false;return async r=>{let o=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),o}}function jo(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(o,i){return r.has(o)?false:(r.add(o),n.push({name:o,at:i??e()}),true)},timeline(){let o=[...n].sort((i,a)=>i.at-a.at);return o.map((i,a)=>{let s=o[a-1],l=s===void 0?"":` (+${Math.round(i.at-s.at)}ms)`;return `${i.name}@${Math.round(i.at)}ms${l}`}).join(" \u2192 ")}}}var kp="GemWebSdkHandshake";var xp=()=>Date.now();function rl(t,e,n={}){let r=t[kp];if(r===void 0)return null;let o=n.ttlMs??9500,i=n.now??xp,a=r.events.splice(0),s=r.times?.splice(0),l=0,d=0,m=false,c=i()-o;for(let p=a.length-1;p>=0;p--){let g=s?.[p];if(g!==void 0&&g<c){d+=1;continue}if(l+=1,e(a[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var qo=false;async function al(t,e,n,r){if(qo){e.close(),n("busy",true);return}qo=true;let o=null;try{let i=await Pp(t,r);if(typeof i=="string"){e.close(),n(i,Ap(i));return}o=i;let s=await(r.encodeRef??(l=>Cp(l,r)))(o);if(o.close(),o=null,s===null){e.close(),n("failed",!0);return}if(s.size>Ip){e.close(),n("too_large",!1);return}e.postMessage(s);}catch(i){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",i);}finally{qo=false,o?.close();}}function Ap(t){switch(t){case "no_source":case "busy":case "failed":return true;case "not_wired":case "unsupported":case "unreadable":case "tainted":case "too_large":case "declined":return false}}async function Pp(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":ol(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=Tp(n);if(!r)return "no_source";let o=Ep(r);if(o!==null)return o;try{return ol(await createImageBitmap(r),t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}function Ep(t){let e;try{e=t.getContext("webgl2")??t.getContext("webgl");}catch{return "unreadable"}if(e){let n=e.getContextAttributes();return !n||n.preserveDrawingBuffer!==true?"unsupported":null}try{if(t.getContext("2d"))return null}catch{return "unreadable"}return "unreadable"}function Tp(t){let e=null,n=0;for(let r of Array.from(t.querySelectorAll("canvas"))){let o=r.width*r.height;o<=0||r.clientWidth<=0||r.clientHeight<=0||o>n&&(e=r,n=o);}return e}async function ol(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let o=Math.min(n/t.width,r/t.height),i=Math.max(1,Math.floor(t.width*o)),a=Math.max(1,Math.floor(t.height*o));try{let s=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:"high"});return t.close(),s}catch{return t.close(),"too_large"}}var Ip=8*1024*1024,il="image/webp",sl=.92;async function Cp(t,e){try{if(typeof OffscreenCanvas=="function"){let i=new OffscreenCanvas(t.width,t.height),a=i.getContext("2d");if(a){a.drawImage(t,0,0);let s=await i.convertToBlob({type:il,quality:sl});if(s&&s.size>0)return s}}}catch{}let n=e.documentRef??globalThis.document;if(!n)return null;let r=n.createElement("canvas");r.width=t.width,r.height=t.height;let o=r.getContext("2d");return !o||(o.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(i=>{r.toBlob(a=>i(a),il,sl);})}async function ll(t,e){if(!e)return;let n;try{n=await Mp(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 Mp(t){return new Promise((e,n)=>{let r=false,o=setTimeout(()=>{r||(r=true,console.warn("[gem] onFeedbackContext did not answer within 1000ms; sending the report without context. Gather cheaply, or keep a snapshot."),e(null));},1e3);(async()=>t())().then(i=>{r||(r=true,clearTimeout(o),e(i??null));},i=>{r||(r=true,clearTimeout(o),n(i instanceof Error?i:new Error(String(i))));});})}var dl=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function cl(t=globalThis){let n=t[dl];if(n!==void 0)return n;let r=false,o=()=>r,i=[],a=Op(t,o);a!==null&&i.push(a);let s=Lp(t,o);s!==null&&i.push(s);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let c of i)c();}}};return Object.defineProperty(t,dl,{value:l,configurable:true}),l}function Op(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let o=t.OfflineAudioContext,i=n.connect,a=n.disconnect,s=new Map,l=m=>{let c=m.gain,p=m.context.currentTime;c.cancelScheduledValues(p),e()?c.setValueAtTime(0,p):c.setTargetAtTime(1,p,.01);},d=m=>{let c=m.context;if(o!==void 0&&c instanceof o)return null;let p=s.get(c);return p===void 0&&(p=c.createGain(),p.gain.value=e()?0:1,i.call(p,m),s.set(c,p)),p};return n.connect=function(...c){let[p,...g]=c;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return i.call(this,y,...g),p}return i.apply(this,c)},n.disconnect=function(...c){let[p,...g]=c;if(p instanceof r){let y=s.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...g)}catch{}}return a.apply(this,c)},()=>{for(let[m,c]of s){if(m.state==="closed"){s.delete(m);continue}try{l(c);}catch{}}}}function Lp(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,o=Object.getOwnPropertyDescriptor(r,"muted"),i=o?.get,a=o?.set;if(i===void 0||a===void 0)return null;let s=r.play,l=new WeakMap,d=new WeakSet,m=new Set,c=p=>{l.has(p)||l.set(p,!!i.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),a.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!i.call(this):p},set(p){l.set(this,!!p),c(this);}}),r.play=function(){try{c(this);}catch{}return s.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{c(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{a.call(g,(l.get(g)??!1)||e());}catch{}}}}var Gp=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Dp=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',$p=`${Gp}${Dp}`,No=new WeakSet;function ul(t=globalThis.document){if(t==null||No.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($p),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],No.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"),No.add(t),"inline")}catch{return null}}function ml(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=false,o=false,i=false,a=null,s=null,l=null,d=[],m=()=>r&&!o&&!i,c=()=>{s=null,l=null,d=[];},p=w=>{if(a=null,!m()){c();return}if(l!==null&&d.push(w-l),l=w,s===null)s=w;else {let R=w-s;R>=e&&d.length>0&&(t.report(Fp(d,R)),s=w,d=[]);}g();},g=()=>{let w=n.requestAnimationFrame;typeof w=="function"&&(a=w.call(n,p));},y=()=>{if(m()){a===null&&(c(),g());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),c();};return {setRequested(w){r=w,y();},setPaused(w){o=w,y();},get running(){return a!==null},dispose(){i=true,y();}}}function Fp(t,e){let n=[...t].sort((o,i)=>o-i),r=Math.max(1,Math.ceil(n.length*.95));return {fps:t.length*1e3/e,frameTimeP95Ms:n[r-1]}}var lr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function gl(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function yl(t,e){t!==null&&(t.style.setProperty(lr.top,`${e.top}px`),t.style.setProperty(lr.right,`${e.right}px`),t.style.setProperty(lr.bottom,`${e.bottom}px`),t.style.setProperty(lr.left,`${e.left}px`));}var pl=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height"}});function fl(){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 jp(t,e){let n={tl:{width:0,height:0},tr:{width:0,height:0},bl:{width:0,height:0},br:{width:0,height:0}};for(let r of t){let o=e?r.x+r.width/2<=e.width/2:r.x===0,i=e?r.y+r.height/2<=e.height/2:r.y===0,a=o?r.x+r.width:e?e.width-r.x:r.width,s=i?r.y+r.height:e?e.height-r.y:r.height,l=n[`${i?"t":"b"}${o?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(a)),l.height=Math.max(l.height,Math.ceil(s));}return n}function hl(t,e,n){if(t===null)return;let r=jp(e,n);for(let o of ["tl","tr","bl","br"])t.style.setProperty(pl[o].width,`${r[o].width}px`),t.style.setProperty(pl[o].height,`${r[o].height}px`);}var qp=3e4,dr=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function bl(t){let e=t.clock??le,n=t.timeoutMs??qp,r=new Map,o=new Map,i=0,a=s=>{let l=r.get(s);return l?(r.delete(s),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(s){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(s);if(l)return l;let d=new Promise((m,c)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(s),c(new dr("timeout",true,`the embedder did not answer a local-server request for room ${s} within ${String(n)}ms`));},n);r.set(p,{room:s,resolve:m,reject:c,timer:g}),t.bridge.requestLocalServer(p,s)||(a(p),m());});return o.set(s,d),d.catch(()=>{}),d},accept(s){a(s.requestId)?.resolve();},refuse(s){let l=a(s.requestId);l&&l.reject(new dr(s.reason,s.retryable,s.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var rt={url:"https://downloads.indiegems.games/sdk/v7.8.0/gem-web-sdk.devtools.min.js",integrity:"sha384-a8+SJvOz79OBtl9cfr23Da+zG5mIOPa3yEq1/mtMIJpkeTSUkgW7DgPIiM/6JkGx"};var vn=null;function Np(){return vn!==null||(vn=new Promise((t,e)=>{let n=document.createElement("script");n.src=rt.url,n.integrity=rt.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){vn=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${rt.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{vn=null,e(new Error(`gem devtools: could not load ${rt.url}. Either the network refused it or its Subresource Integrity check failed, or the CDN did not answer the CORS preflight this request needs \u2014 SRI is only checkable on bytes the page may read. A locally rebuilt SDK is the commonest cause: it produces panel bytes that do not match the hash compiled into this build.`));},document.head.append(n);})),vn}function vl(t,e){let n=null,r=0;async function o(i){if(n!==null)return true;let a=++r;if(!e())return false;let s=await Np();return !e()||a!==r?false:(n!==null||(n=s.mount(t(),{openedBy:i,text:Ne,onDismiss:()=>{n?.unmount(),n=null;}})),true)}return {get isOpen(){return n!==null},close(){r+=1,n?.unmount(),n=null;},open:()=>o("game"),openFrom:o}}var Up=1e4,_l={reason:"unavailable",retryable:false};function wl(t){let e=new Map,n=null,r=null,o=0,i=(d,m)=>{m.timer=t.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},t.timeoutMs??Up);},a=(d,m)=>{let c=s(d);c&&m(c);},s=d=>{let m=e.get(d);return m?(e.delete(d),t.clock.clearTimeout(m.timer),m):null},l=new on({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,c)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){c(_l);return}let g=`t${++o}`,y={resolve:m,reject:c,reason:d,timer:null,held:p!=="connected"};e.set(g,y),i(g,y),y.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){a(d.requestId,c=>c.resolve(m));return}l.accept(m);},onDenied(d){a(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),i(m,c),t.bridge.requestToken(m,c.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])a(m,c=>c.reject(_l));},get identity(){return n},get gameVersion(){return r}}}function Bp(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var Hp=new Set(pt);function Vp(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))Hp.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function cr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return _i(async(n,r)=>{let o;try{o=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new oe("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let i;try{i=new URL(o.href.replace(/\/+$/,"")+n.path);}catch{throw new oe(`${JSON.stringify(typeof n.path=="string"?Bp(n.path):"(a non-string path)")} does not form a valid URL against ${o.protocol}//${o.host}. This is a malformed request, not a server failure.`)}if(i.protocol!==o.protocol||i.host!==o.host)throw new oe(`${JSON.stringify(i.pathname)} resolves to ${i.protocol}//${i.host}, not ${o.protocol}//${o.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(i.username!==""||i.password!==""){let g=o.username!==""||o.password!=="",y=i.username!==o.username||i.password!==o.password,w=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new oe(`the ${w} puts credentials in the URL, which cannot be fetched (${n.method} ${i.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,y]of Object.entries(t.defaultQuery??{}))i.searchParams.has(g)||i.searchParams.set(g,y);let a=n.bytes,s=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(a=JSON.stringify(n.body),s="application/json");}catch(g){throw new oe(`the body of ${n.method} ${JSON.stringify(i.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(i.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...s===void 0?{}:{"content-type":s},...Vp(n.headers)},body:a,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),c=Wp(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...c===void 0?{}:{retryAfterSeconds:c},...p===null||p===""?{}:{invocationId:p}}},t)}function Wp(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}var Kp=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Bo="embedder_relay_unavailable",Jp="embedder_no_relay",zp=new Set([Bo]),Ho=new Set([Jp]),ot=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Uo(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new b("match_ended",`the match ended while the offer was in flight (${e.reason??"no reason given"}), so no server is left to answer it`));return}if(e.event==="answer"){if(typeof e.sdp!="string"||e.sdp.length===0){n.refuse(new b("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(Yp(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new b("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,n);}release(e,n){this.pending.get(e)===n&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new b("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new b("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function Yp(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new b(Xp(t),r,{platformCode:t})}function Xp(t){return t===void 0||zp.has(t)?"signaling_failed":Ho.has(t)?"offer_refused":Kp.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Uo=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new b("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(o){return Promise.reject(o)}return n?.aborted?Promise.reject(new b("aborted","the caller aborted before the offer was sent")):new Promise((o,i)=>{let a=()=>{s(),i(new b("aborted","the caller aborted the signaling exchange"));},s=()=>{n?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),o(d);},refuse:d=>{s(),i(d);}};this.teardown=s,n?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof b?d:new b("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var Sl="match_ended:",Rl="server_shutdown:",kl="kicked:",Qp=123;function Zp(t){if(typeof t!="string"||t.length===0||t.length>Qp)return {kind:"other"};if(t.startsWith(Sl)){let e=$e(t.slice(Sl.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Rl)?{kind:"server_shutdown",cause:t.slice(Rl.length)}:t.startsWith(kl)?{kind:"kicked",detail:t.slice(kl.length)}:{kind:"other"}}function Vo(t,e,n){let r=Zp(n),o=r.kind==="kicked"?"kicked":"link_closed";t.notifyMatchDisconnected(o).catch(()=>{}),r.kind==="match_ended"&&t.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function Wo(){return {exchange(){return Promise.reject(new b("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See docs/dedicated-server-flow.md \xA72."))},close(){}}}var eg=3e3,ng=1e4,tg=15e3;async function ur(t){let e=t.peerConnection;try{Al(t,"before the handshake started"),Ko(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let a of t.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});t.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await ig(e,t),Ko(t);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new b("invalid_sdp","the offer carried no SDP");Fe(o,"offer"),xl(o,"offer");let i=await og(t,o);if(Ko(t),typeof i?.sdp!="string")throw new b("invalid_sdp","the signaling channel answered without an SDP");return Fe(i.sdp,"answer"),xl(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await sg(n,t),Al(t,"before the channel opened"),n}catch(n){throw e.close(),rg(n)}}function rg(t){return t instanceof b?t:Tl(t)?ze():new b("connection_failed",Il(t),{cause:t})}function xl(t,e){if(rr(t))throw new b("media_refused",`the ${e} carries an active audio or video section. This path carries a data channel only; voice belongs to the platform voice service.`)}async function og(t,e){let n=t.exchangeTimeoutMs??ng,r=El(t,n),o=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(i=>{throw i instanceof b?i:Tl(i)?ze():new b("signaling_failed",Il(i),{cause:i})});return ag(o,t,r,()=>r.exhausted?Jo("while the offer was in flight"):new b("timeout",`no answer arrived within ${n}ms`))}function ig(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let o=()=>{n.clearTimeout(a),t.removeEventListener("icegatheringstatechange",i),e.signal?.removeEventListener("abort",o),r();},i=()=>{t.iceGatheringState==="complete"&&o();},a=n.setTimeout(o,e.gatherTimeoutMs??eg);t.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function sg(t,e){if(e.signal?.aborted)return Promise.reject(ze());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new b("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??tg,o=El(e,r);return new Promise((i,a)=>{let s=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),i();},d=g=>{s(),a(new b("connection_failed","the data channel failed before it opened",Pl(g)===void 0?void 0:{cause:Pl(g)}));},m=()=>{s(),a(ze());},c=()=>{s(),a(o.exhausted?Jo("while the channel was still opening"):new b("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(c,o.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function El(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 ag(t,e,n,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(ze()):new Promise((a,s)=>{let l=c=>{o.clearTimeout(m),i?.removeEventListener("abort",d),c();},d=()=>l(()=>s(ze())),m=o.setTimeout(()=>l(()=>s(r())),n.ms);i?.addEventListener("abort",d),t.then(c=>l(()=>a(c)),c=>l(()=>s(c)));})}function Al(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw Jo(`already ${e}`)}function Jo(t){return new b("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function Ko(t){if(t.signal?.aborted)throw ze()}function ze(){return new b("aborted","the caller aborted the connection attempt")}function Tl(t){return t?.name==="AbortError"}function Pl(t){return t?.error}function Il(t){return t instanceof Error?t.message:String(t)}Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"}));Object.freeze(Object.assign(Object.create(null),{answer:[z("sdp","sdp",B(10240)),H("sessionId","session_id",B(64))],error:[H("code","code",B(64)),H("message","message",B(256))],matchEnded:[H("reason","reason",B(64))]}));function Fl(t){let{client:e,clock:n,rooms:r}=t,o=t.signaling??Wo,i=t.log??(_=>console.warn(_)),a=new yn({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(_,S)=>{let P=s.get(_)??new Set;P.add(S),s.set(_,P);},d=(_,S)=>{let P=s.get(_);P!==void 0&&(P.delete(S),P.size===0&&s.delete(_));},m=async _=>{if(r.isHost&&!Yo(r)&&r.currentRoom?.matchId===void 0){let S=me(_.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},..._.retry===void 0?{}:{retry:_.retry},..._.signal===void 0?{}:{signal:_.signal}});}return Dl(r.matchConnectionState==="suspended"?await r.reconnectToMatch(zo(_)):await r.awaitMatch(zo(_)))},c=async _=>Dl(await r.pollMatchStatus(zo(_))),p=async(_,S)=>{let P=false;try{let x=await m(_),V=r.currentRoom?.transports;if(V!==void 0&&!V.includes("webrtc"))throw new b("misconfigured",`the room template offers (${V.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let N=_.peerConnection??$l();P=!0;let W=await ur({peerConnection:N,signaling:S,clock:n,matchId:x.matchId,credentialExpiresAt:x.credentialExpiresAt,...mr(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),k=null;if(_.presentCredential!==!1)try{k=await qn({channel:W,clock:n,credential:x.joinCredential,credentialExpiresAt:x.credentialExpiresAt,...mr(_,"onMessage","signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(A){throw we(W),we(N),A}return fg(r,x,W,N,S,_.reportDisconnect!==!1,_.reportConnected!==!1,k,{remember:l,forget:d},_.onMatchEnded)}catch(x){throw P&&Gl(a,x),we(S),x}},g=async(_,S,P,x,V,N)=>{if(_==="webtransport"){let j=x?.webtransport;if(j===void 0)throw new b("misconfigured","webtransport is not advertised");let U={credential:P.joinCredential,credentialExpiresAt:P.credentialExpiresAt,clock:n};if(typeof j.named_url=="string"&&j.named_url!==""){let ee=Math.max(Math.floor(N/2),1e3);try{return await Hn({url:j.named_url,timeoutMs:ee,log:i,...U})}catch(ge){if(Xt()!==null)throw ge;return i(`[gem] webtransport named dial failed (${zt(ge)}); retrying the pinned dial`),Hn({url:j.url,certHashBase64:j.cert_sha256_b64,timeoutMs:ee,log:i,...U})}}return Hn({url:j.url,certHashBase64:j.cert_sha256_b64,timeoutMs:N,...U})}if(_==="websocket"){let j=x?.websocket;if(j===void 0)throw new b("misconfigured","websocket is not advertised");return fo({url:j.url,credential:P.joinCredential,credentialExpiresAt:P.credentialExpiresAt,clock:n,timeoutMs:N})}let W=S.peerConnection??$l(),k,A=await ur({peerConnection:W,signaling:V,clock:n,matchId:P.matchId,credentialExpiresAt:P.credentialExpiresAt,extraChannels:[{label:Un,ordered:false,maxRetransmits:0}],onExtraChannel:(j,U)=>{j===Un&&(k=U);},...mr(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:cg}:{}}),L;try{L=await qn({channel:A,clock:n,credential:P.joinCredential,credentialExpiresAt:P.credentialExpiresAt,wire:Jt,heartbeat:!0,...mr(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(j){throw we(A),we(W),j}let D=L.welcome.heartbeatIntervalMs;return {link:bo(A,W,k,D===void 0?void 0:{clock:n,intervalMs:D}),welcome:L.welcome,channel:A,peerConnection:W}},y=(_,S,P,x,V)=>{let N=false,W;x.link.onClose(D=>{!N&&_.reportDisconnect!==false&&Vo(r,S.matchId,D),W?.(D);}),_.reportDisconnect!==false&&_.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let k={transport:x.link.transport,send:(D,j)=>x.link.send(D,j),onMessage:D=>x.link.onMessage(D),onClose:D=>{W=D;},close:()=>x.link.close()},A=()=>{N||(N=true,we(x.link),we(V));},L=D=>{if(!N){try{_.onMatchEnded?.(D);}catch{}A();}};return l(S.matchId,L),{matchId:S.matchId,transport:P,link:k,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:x.welcome,...x.channel===void 0?{}:{channel:x.channel},...x.peerConnection===void 0?{}:{peerConnection:x.peerConnection},close(){d(S.matchId,L),A();}}},w=async(_,S)=>{let P=r.currentRoom?.id,x=r.gameId,V=()=>({advert:Bn(r.currentRoom?.settings,_),template:r.currentRoom?.transports??null});if(P===void 0||x===null)return V();try{let N=await e.get(`/v2/games/${encodeURIComponent(x)}/game-rooms/${encodeURIComponent(P)}`,S);return {advert:Bn(N.settings,_),template:pn(N.transports)??r.currentRoom?.transports??null}}catch{return V()}},R=(_,S)=>{let P=_??Cl;return S.length===0?P:P.filter(x=>S.includes(x))},C=async(_,S,P)=>{try{let x=await m(_),{advert:V,template:N}=await w(x.matchId,_.signal),W=R(N,S),k=W.filter(Q=>pg(Q,V)),A=Xt();if(A!==null&&W.includes("webtransport")&&V?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${A} (learned on an earlier dial in this page)`),k.length===0){let Q=N===null?`the default order (${Cl.join(", ")})`:`the room template's transports (${N.join(", ")||"none"})`;throw new b("misconfigured",`none of ${Q}`+(S.length>0?`, narrowed to (${S.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let L=_.transportAttemptTimeoutMs??dg,D=()=>_.deadlineAt===void 0?1/0:_.deadlineAt-n.now(),j=Q=>t.signalingReady===void 0||Q<=0?Promise.resolve(!0):t.signalingReady(Q),U=[],ee=[];for(let Q of k){if(D()<Ol){i(`[gem] ${Q} rung not tried: the reconnect budget is spent`);break}ee.length>0&&x.credentialExpiresAt-n.now()<Ll&&(x=await c(_)),ee.push(Q);let Oe=!1,Se=!1,Ie={attempts:0,waitedMs:0};for(;;){if(Q==="webrtc"&&_.redial===!0){let re=Math.min(Ml,D());await j(re)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(re)}ms; offering anyway`);}let Ce=Math.max(Math.min(L,D()),Ol);try{return y(_,x,Q,await g(Q,_,x,V,P,Ce),P)}catch(re){let Y=re instanceof b?re:new b("connection_failed",re instanceof Error?re.message:String(re),{cause:re});if(Q==="webrtc"&&Gl(a,Y),(Y.reason==="credential_expired"||Y.reason==="credential_reused")&&!Oe){Oe=!0,x=await c(_);continue}if(Q==="webrtc"&&Y.reason==="signaling_failed"&&Y.platformCode===Bo&&!Se){Se=!0;let de=Math.min(Ml,D());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(de)}ms for the socket before offering again`),await j(de))continue}if(Y.reason==="join_rate_limited"){let de=mg(Ie,Math.random,D());if(de!==null){if(Ie.attempts+=1,Ie.waitedMs+=de,i(`[gem] ${Q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(de)}ms before presenting again (retry ${Ie.attempts} of ${ql.maxAttempts})`),await Vt(n,de,_.signal),_.signal?.aborted)throw new b("aborted","the caller aborted while waiting out a join rate limit");x.credentialExpiresAt-n.now()<Ll&&(x=await c(_));continue}}if(ug.has(Y.reason)||Y.reason==="credential_expired"||Q==="webrtc"&&jl(Y)){i(`[gem] ${Q} rung failed (${Y.reason}): ${zt(Y.cause??Y)} \u2014 `+(ee.length<k.length?`falling through to ${k[ee.length]}`:"no rungs left")),U.push(Y);break}throw i(`[gem] ${Q} rung refused the session (${Y.reason}): ${Y.message}`),Y}}}let ge=U[U.length-1];throw ge===void 0?new b("timeout",`the reconnect budget ran out before any transport (${k.join(", ")}) could be tried`):new b(ge.reason,`every transport tried (${ee.join(", ")}) failed; the last said: ${ge.message}`,{cause:U,platformCode:ge.platformCode})}catch(x){throw we(P),x}};return {listClusterTargets:async(_={})=>eo({client:e,..._}),handleMatchEnded(_,S){let P=s.get(_);if(P!==void 0){s.delete(_);for(let x of P)x(S);}},connect:(async(_={})=>{let S=_.signaling??o();return _.transports===void 0?p(_,S):C(_,_.transports,S)})}}var Cl=["webtransport","webrtc","websocket"],dg=1e4,cg=5e3,Ml=3e3,Ol=1e3,Ll=1e4,ug=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function jl(t){return t.platformCode!==void 0&&Ho.has(t.platformCode)}var ql={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function mg(t,e=Math.random,n=1/0){let r=ql;if(t.attempts>=r.maxAttempts)return null;let o=Math.min(r.budgetMs-t.waitedMs,n);if(o<r.initialDelayMs)return null;let i=r.initialDelayMs*r.factor**t.attempts;return Math.min(i+e()*r.jitterMs,o)}function pg(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Yt():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||gg(e.websocket.url)}function gg(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return wt(e)}function zo(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var yg=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Gl(t,e){e instanceof b&&(!yg.has(e.reason)&&!jl(e)||t.report([{type:"connection_failures_total",value:1}]));}function fg(t,e,n,r,o,i,a,s,l,d){let m=false,c=()=>{m||Vo(t,e.matchId,void 0);};i&&(n.addEventListener("close",c),a&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",c),s?.detach(),we(n),we(r),we(o));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function Yo(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Dl(t){if(t.status==="failed")throw new b("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new b("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==Ht)throw new b("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Ht}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:n}=t;if(e===void 0||n===void 0)throw new b("connection_failed",`match ${t.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...t,joinCredential:e,credentialExpiresAt:n}}function $l(){let t=globalThis.RTCPeerConnection;if(!t)throw new b("misconfigured","this environment has no RTCPeerConnection. Pass `peerConnection` to connect against a stand-in, which is how the flow is tested outside a browser.");return new t({iceServers:[]})}function we(t){try{t.close();}catch{}}function mr(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var hg=1e4;function Nl(t,e){return Xo(t,e)}function Xo(t,e){if(typeof t.serverToken!="function"||typeof t.onServerToken!="function")throw new Error("this runtime delivers no game-server token: host.serverToken/onServerToken are missing. The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let n=a=>({token:a.token,expiresAt:a.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,o=new on({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((a,s)=>{let l=e.clock.setTimeout(()=>{r=null,s({reason:"unavailable",retryable:true});},e.timeoutMs??hg);r={resolve:d=>{e.clock.clearTimeout(l),a(d);},reject:s,timer:l};})}),i=t.onServerToken(a=>{let s=n(a),l=r;if(l){r=null,l.resolve(s);return}o.accept(s);});return {source:o,dispose(){i(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var Zo={};kd(Zo,{acceptTransfer:()=>bg,addEntityProgression:()=>vg,adminAction:()=>_g,cancelInventoryTransfer:()=>wg,claimEntityProgressionRewards:()=>Sg,closeGameRoom:()=>Rg,createEntityBatchOrder:()=>kg,createEntityOrder:()=>xg,createSession:()=>Ag,deleteEntityGameSetting:()=>Pg,deleteEntitySave:()=>Eg,deleteSession:()=>Tg,deleteShowcaseValue:()=>Ig,executeEntityRecipe:()=>Cg,finalizeSaveUpload:()=>Mg,getChannelAssignment:()=>Og,getDropRates:()=>Lg,getEntityCurrency:()=>Gg,getEntityGameSetting:()=>Dg,getEntityInventory:()=>$g,getEntityInventoryItem:()=>Fg,getEntityLeaderboard:()=>jg,getEntityOrder:()=>qg,getEntityProgression:()=>Ng,getEntityRecipeAvailability:()=>Ug,getEntityRecipeUsage:()=>Bg,getEntitySave:()=>Hg,getEvent:()=>Vg,getGameRoomV2:()=>Wg,getLeaderboard:()=>Kg,getPlayerGameProfile:()=>Jg,getPurchaseCatalog:()=>zg,getResolvedTemplate:()=>Yg,getRoomArgs:()=>Xg,getShowcaseValue:()=>Qg,getTransferDetails:()=>Zg,ingestAnalyticsEvents:()=>Qo,initiateInventoryTransfer:()=>ey,invokeFunction:()=>ny,kickPlayer:()=>ty,listChallenges:()=>ry,listEntityGameSettings:()=>oy,listEntityOrders:()=>iy,listEntityProgressions:()=>sy,listEntitySaves:()=>ay,listEvents:()=>ly,listGameRooms:()=>dy,listResolvedTemplates:()=>cy,listTransfers:()=>uy,maxEntityProgression:()=>my,putEntityGameSetting:()=>py,putRoomArgs:()=>gy,putShowcaseValue:()=>yy,rejectTransfer:()=>fy,requestSaveUploadUrl:()=>hy,resetEntityProgression:()=>by,simulateEntityOrder:()=>vy,transferHostV2:()=>_y,updateGameRoomV2:()=>wy});function h(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function bg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function vg(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/add`;return t.client.post(a,o,i?.signal)}async function _g(t,e,n,r){let o=`/v1/voice/sessions/${h(e)}/admin`;return t.client.post(o,n,r?.signal)}async function wg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Sg(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/claim`;return t.client.post(a,o,i?.signal)}async function Rg(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.delete(r,n?.signal)}async function kg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function xg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ag(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Pg(t,e,n,r,o){let i=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(i,o?.signal)}async function Eg(t,e,n,r,o){let i=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(i,o?.signal)}async function Tg(t,e,n){let r=`/v1/voice/sessions/${h(e)}`;return t.client.delete(r,n?.signal)}async function Ig(t,e,n,r){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.delete(o,r?.signal)}async function Cg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Mg(t,e,n,r,o,i){let a=`/v1/saves/${h(e)}/${h(n)}/${h(r)}/finalize`;return t.client.post(a,o,i?.signal)}async function Og(t,e,n){let r=`/v1/games/${h(t.gameId())}/config/channels/${h(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Lg(t,e,n){let r=`/v1/inventory/loot-tables/${h(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Gg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/currencies/${h(r)}`;return t.client.get(i,o?.signal)}async function Dg(t,e,n,r,o){let i=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function $g(t,e,n,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${h(e)}/${h(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Fg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/items/${h(r)}`;return t.client.get(i,o?.signal)}async function jg(t,e,n,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let a=i.toString(),s=`/v1/leaderboards/${h(e)}/${h(n)}/${h(r)}`+(a?`?${a}`:"");return t.client.get(s,o?.signal)}async function qg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders/${h(r)}`;return t.client.get(i,o?.signal)}async function Ng(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}`;return t.client.get(i,o?.signal)}async function Ug(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/catalogs/${h(r)}/recipes/${h(o)}/availability`;return t.client.get(a,i?.signal)}async function Bg(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${h(e)}/${h(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Hg(t,e,n,r,o){let i=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Vg(t,e,n){let r=`/v1/events/${h(e)}`;return t.client.get(r,n?.signal)}async function Wg(t,e,n){let r=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Kg(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${h(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Jg(t,e,n){let r=`/v1/profiles/players/${h(e)}`;return t.client.get(r,n?.signal)}async function zg(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Yg(t,e,n){let r=`/v1/game-room-templates/${h(e)}`;return t.client.get(r,n?.signal)}async function Xg(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/room-args`;return t.client.get(r,n?.signal)}async function Qg(t,e,n,r){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.get(o,r?.signal)}async function Zg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}`;return t.client.get(r,n?.signal)}async function Qo(t,e,n){let r=`/v1/games/${h(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true})}async function ey(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ny(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function ty(t,e,n,r){let o=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/kick/${h(n)}`;return t.client.post(o,void 0,r?.signal)}async function ry(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),o="/v1/challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function oy(t,e,n,r){let o=`/v1/settings/${h(e)}/${h(n)}`;return t.client.get(o,r?.signal)}async function iy(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${h(e)}/${h(n)}/orders`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function sy(t,e,n,r){let o=`/v1/inventory/${h(e)}/${h(n)}/progressions`;return t.client.get(o,r?.signal)}async function ay(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${h(e)}/${h(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function ly(t,e){let n=new URLSearchParams;e?.include_inactive!==void 0&&n.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.offset!==void 0&&n.set("offset",String(e?.offset));let r=n.toString(),o="/v1/events"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function dy(t,e){let n=new URLSearchParams;e?.status!==void 0&&n.set("status",String(e?.status)),e?.game_channel!==void 0&&n.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&n.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&n.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&n.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o=`/v1/games/${h(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function cy(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function uy(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function my(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/max`;return t.client.post(a,o,i?.signal)}async function py(t,e,n,r,o,i){let a=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function gy(t,e,n,r){let o=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/room-args`;return t.client.put(o,n,r?.signal)}async function yy(t,e,n,r,o){let i=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.put(i,r,o?.signal)}async function fy(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function hy(t,e,n,r,o,i){let a=`/v1/saves/${h(e)}/${h(n)}/${h(r)}/upload-url`;return t.client.post(a,o,i?.signal,{replaySafe:true})}async function by(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/reset`;return t.client.post(a,o,i?.signal)}async function vy(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders/simulate`;return t.client.post(i,r,o?.signal)}async function _y(t,e,n,r){let o=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}/transfer/${h(n)}`;return t.client.post(o,void 0,r?.signal)}async function wy(t,e,n,r){let o=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.patch(o,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Sy=1e4,Ry=50,ky=1e3,xy=65536-4*1024,Ul=t=>typeof t=="number"?t:0,Ay=t=>typeof t=="string"?t:"";function Bl(){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 Py(t){return t?.retryable===true}function Ey(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:Ul(i.index),code:Ay(i.code)}}):[];return {accepted:Ul(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Hl(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 Vl(t){let e=Math.max(1,Math.floor(t.maxQueue??ky)),n={client:t.client,gameId:()=>t.gameId},r=[],o=0,i=null,a=false,s=false,l=false,d=false,m=w=>{t.log?.(w);},c=()=>{i!==null&&(t.clock.clearTimeout(i),i=null);},p=()=>{i!==null||a||s||(i=t.clock.setTimeout(()=>{i=null,y().catch(()=>{});},Sy));},g=()=>{let w=Math.min(r.length,100),R=128;for(let C=0;C<w;C+=1){let M=r[C];if(M===void 0)break;if(R+=JSON.stringify(Hl(M,0)).length+1,R>xy)return Math.max(1,C)}return w};async function y(w){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};c();let R=r.splice(0,g()),C=o;o=0;let M=Math.round(t.clock.now()),_={batch_id:Bl(),sent_at_ms:M,events:R.map(S=>Hl(S,M))};s=true;try{let S=await Qo(n,_,w===void 0?void 0:{signal:w}),P=Ey(S,C);for(let x of P.rejected)m(`[gem] analytics: an event was refused (${x.code}). See the analytics_events section of your game config.`);return P}catch(S){if(Py(S))for(r=[...R,...r],o+=C;r.length>e;)r.shift(),o+=1;else m(`[gem] analytics: ${R.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(S)}`);throw S}finally{s=false,r.length>0&&p();}}return {track(w,R,C={}){if(a)return;if(typeof w!="string"||w===""){d||(d=true,m(`[gem] analytics: '${R}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(R.startsWith(Hr)){l||(l=true,m(`[gem] analytics: '${R}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let M={},_={};for(let[S,P]of Object.entries(C))typeof P=="string"?M[S]=P:typeof P=="number"&&Number.isFinite(P)&&(_[S]=P);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:Bl(),playerId:w,name:R,atMs:t.clock.now(),dimensions:M,measures:_}),r.length>=Ry?y().catch(()=>{}):p();},flush:w=>y(w),get pending(){return r.length},dispose(){a=true,c(),r=[],o=0;}}}function Wl(t){return {async list(e){let{playerId:n,periodsBack:r,signal:o}=e??{};if(typeof n!="string"||n==="")throw new TypeError("gem.challenges.list needs { playerId }: a game-server token names no player, so the platform cannot tell whose period you mean. Pass the id from join() or gem.players().");cn(r);let i=await t({player_id:n,...r===void 0?{}:{periods_back:r},...o===void 0?{}:{signal:o}});return jt(i)}}}function Ty(t){let e={};for(let[n,r]of Object.entries(Zo))if(typeof r=="function"){let o=r;e[n]=(...i)=>o(t,...i);}return e}function _n(t,e={}){let n=e.clock??le,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let o=Xo(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=cr({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),a=new Le({transport:i,clock:n}),s={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=Ty({client:a,gameId:()=>s.gameId}),d=s.gameRoomId,m=t.endMatch,c=t.log,p=Vl({client:a,clock:n,gameId:s.gameId,...typeof c=="function"?{log:y=>c.call(t,y)}:{}});return {identity:s,client:a,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(t);}},analytics:p,functions:new De(l.invokeFunction),challenges:Wl(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let w=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),R=w.modified?w.body:void 0;if(R?.room_args==null||R.room_args_template==null)throw new G("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:R.room_args,room_args_template:R.room_args_template}}}},dispose:()=>{p.dispose(),o.dispose();}}}function Ye(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function wn(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function it(t){return typeof t=="string"?t:t.slice().buffer}function pr(t){if(typeof t=="string")return {data:t,isText:true};if(t instanceof ArrayBuffer)return {data:new Uint8Array(t),isText:false};if(ArrayBuffer.isView(t)){let e=t;return {data:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),isText:false}}return null}var Iy=5e3,Kl=3e4,Jl=2e3,Cy=1e4,zl=1;async function Yl(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let o=e.log===void 0?f=>console.info(f):e.log,i=f=>o?.(`[gem host] ${f}`),a=typeof t=="function"?t():t,s=Promise.resolve(),l=true,d=false,m=(f,E)=>{l&&(s=s.then(async()=>{if(!d)try{await E();}catch($){i(`the bundle's ${f} handler threw: ${Xe($)}. Serving continues.`);}}));},c=true,p,g,y,w=f=>{if(!c)return;c=false,m("leave",()=>a.leave?.(r,{cause:f??"left"}));let E=g;E&&queueMicrotask(()=>E(f));},R={send(f,E){if(!c)return;let $=wn(Ye(E));m("message",()=>a.message?.(r,f,typeof f=="string",{reliable:$.reliable,ordered:$.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){w("closed");}},C=(f,E)=>{if(!c)return;let $=wn(Ye(E));queueMicrotask(()=>{c&&p?.(f,$);});},M=new Map,_=f=>{let E=[];for(let $ of Me){let ne=f.channels[$];try{ne.binaryType="arraybuffer";}catch{}let J=wn($),Sn=gr=>{let en=pr(gr?.data);en!==null&&m("message",()=>a.message?.(f.playerId,en.data,en.isText,{reliable:J.reliable,ordered:J.ordered}));};ne.addEventListener("message",Sn),E.push(()=>ne.removeEventListener("message",Sn));}M.get(f.playerId)?.forEach($=>$()),M.set(f.playerId,E);},S=f=>{M.get(f)?.forEach(E=>E()),M.delete(f);},P=new Set,x=new Map,V=(f,E,$)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...E?{rejoin:true}:{},...$?{superseded:true}:{}}),N=f=>{let E=M.has(f.playerId),$=P.has(f.playerId);P.add(f.playerId),_(f),E&&m("leave",()=>a.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>a.join?.(f.playerId,V(f,$,E)));},W=new Set,k=(f,E,$)=>{if(f===r){C(E,$);return}let ne=n.peer(f);if(ne===null){let J=x.get(f);if(J!==void 0&&e.clock.now()-J<Jl)return;W.has(f)||(W.add(f),i(`send to '${f}' dropped: no such connected player`));return}ne.send(it(E),Ye($));},A={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:f=>e.tokens.subscribe(f),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(f=>f.playerId)??[],players(){let f=c?[r]:[];for(let E of n.peers)f.push(E.playerId);return f},profile(f){let E=e.room()?.members.find($=>$.playerId===f);if(!(!E||E.displayName===void 0))return {displayName:Ne.toPlain(E.displayName),...E.displayTag===void 0?{}:{displayTag:Ne.toPlain(E.displayTag)},...E.discriminator===void 0?{}:{discriminator:E.discriminator}}},playerNumber(f){return f===r?zl:n.peer(f)?.assignedPeerId},send(f,E,$){k(f,E,$);},broadcast(f,E){let $=E?.except;c&&r!==$&&C(f,E);for(let ne of n.peers)ne.playerId!==$&&ne.send(it(f),Ye(E));},async endMatch(){let f=await Ce();return f.answer!=="ok"&&i(f.cause),f.answer},kick(f,E){if(f===r){w(E??"kicked");return}n.kick(f).catch($=>{i(`kick of '${f}' failed: ${Xe($)}`);});},log(f){i(f);},warn(f){i(`\u26A0 ${f}`);}},L=()=>{},D=new Promise(f=>{L=f;}),j=[],U=null,ee=async(f,E)=>{l=false;let $=s.then(async()=>{try{await a.shutdown(f);}catch(ne){i(`the bundle's shutdown threw: ${Xe(ne)}`);}});s=$,await $,de();for(let ne of j.splice(0))ne();for(let ne of [...M.keys()])S(ne);w(E);},ge=(f,E)=>U||(U=(async()=>{await ee(E,f),n.close(),L();})(),U),Q=()=>U||(U=(async()=>{await ee({reason:"signal"},"left"),await n.leave().catch(f=>i(`leaving the match failed: ${Xe(f)}`)),L();})(),U),Oe=()=>U||(U=(async()=>{l=false;let f=await Ce();f.answer==="ok"?(await ee({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(i(`${f.cause}; leaving instead`),await ee({reason:"signal"},"left"),await n.leave().catch(E=>i(`leaving the match failed: ${Xe(E)}`))),L();})(),U),Se=null,Ie=()=>(Se??=_n(A,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),Se),Ce=async()=>{try{return await gs({client:Ie().client,gameId:()=>A.gameId},A.matchId,{},{signal:AbortSignal.timeout(Iy)}),{answer:"ok"}}catch(f){return f instanceof G&&(f.reason==="forbidden"||f.reason==="not_found")?{answer:f.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${f.reason})`}:{answer:"failed",cause:`ending the match failed: ${Xe(f)}`}}},re=null,Y=false,de=()=>{Y=true,re!==null&&(e.clock.clearTimeout(re),re=null);},q=async()=>{if(re=null,!Y){try{await Ie().client.post(`/v1/games/${encodeURIComponent(A.gameId)}/matches/${encodeURIComponent(A.matchId)}/heartbeat`,void 0,AbortSignal.timeout(Cy));}catch(f){if(f instanceof G&&(f.reason==="forbidden"||f.reason==="not_found")){i(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),de();return}i(`heartbeat failed: ${Xe(f)}`);}Y||(re=e.clock.setTimeout(()=>{q();},Kl));}},dt=()=>{Y||re!==null||(re=e.clock.setTimeout(()=>{q();},Kl));};{let f=L;L=()=>{de(),Se?.dispose(),Se=null,f();};}let Ze=Promise.resolve().then(()=>a.init(A));s=Ze.then(()=>{},()=>{}),m("join",()=>a.join?.(r,{playerNumber:zl,transport:"loopback"})),j.push(n.on("peerJoined",N)),j.push(n.on("peerLeft",(f,E)=>{S(f);let $=e.clock.now();for(let[ne,J]of x)$-J>=Jl&&x.delete(ne);x.set(f,$),W.delete(f),m("leave",()=>a.leave?.(f,{cause:E}));})),j.push(n.on("error",f=>{i(`\u26A0 session error: ${f.message}`);})),j.push(n.on("matchEnded",f=>{U||ei(y,f),ge("match ended",{reason:"match_ended",platform_reason:f});})),j.push(n.on("hostChanged",f=>{f!==r&&ge("host migrated",{reason:"host_migrated"});}));for(let f of n.peers)N(f);try{await Ze,dt();}catch(f){l=false,de(),d=true;for(let E of j.splice(0))E();for(let E of [...M.keys()])S(E);throw n.leave().catch(()=>{}),L(),f}return {matchId:n.matchId,localLink:R,onMatchEnded(f){y=f;},end:Oe,leave:Q,stop:f=>ge(f,{reason:"stopped"}),done:D}}function ei(t,e){try{t?.(e);}catch{}}function Xe(t){return t instanceof Error?t.message:String(t)}function ni(t,e){let n=async()=>{throw new b("misconfigured",`this seat is \`${t}\`, not the match's authority: `+(t==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:t,matchId:e,end:n,leave:n,stop:async()=>{}}}function Xl(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,o=new Map,i=async s=>{r.isHost&&!Yo(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...s.signal===void 0?{}:{signal:s.signal}});let l={...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},a=s=>({...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0?{}:{clusterTargetId:s.clusterTargetId}});return {async serve(s,l={}){let d=await i(l);if(d.protocol!==Je)return ni("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return ni("peer",d.matchId);let c=t.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(a(l)),g=await Yl(s,{session:p,clock:t.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return o.set(d.matchId,g),g.done.then(()=>{o.get(d.matchId)===g&&o.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(s={}){let l=await i(s),d=s.onMatchEnded;if(l.protocol===Je){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),Gy(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let y=await Qn(),w=async()=>t.p2p.connect({...a(s),certificate:y}),R=await w(),C=$y(R,w,d,M=>{r.notifyMatchDisconnected(M).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(R.matchId,{redial:C.redial,abandon:C.abandon}),C.onClosed(()=>{e.get(R.matchId)?.abandon===C.abandon&&e.delete(R.matchId);})),C}let m=async(g=null)=>await t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:s.transports??[]}),c=await m(),p=Dy(c,m,r,n);return n&&(e.set(c.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(c.matchId)?.abandon===p.abandon&&e.delete(c.matchId);})),p},async redialMatch(s,l){let d=e.get(s);return d===void 0?"closed":d.redial(l)},abandonMatch(s,l){e.get(s)?.abandon(l);}}}var Ql="link_closed",My="host_unreachable",Oy=new Set(["failed","closed"]);function Ly(t){return Oy.has(t)?Ql:My}function Gy(t,e,n){let r=e.localLink;e.onMatchEnded(n);let o="connected";r.onClose(()=>{o="closed";});let i;return {matchId:t,protocol:"loopback",get state(){return o},send:(a,s)=>r.send(a,s),onMessage:a=>r.onMessage(a),onClose:a=>{i=a,r.onClose(s=>{o="closed",i?.(s);});},close:()=>r.close()}}function Dy(t,e,n,r){let o=t.matchId,i=t,a="connected",s,l,d=[],m=false,c=false,p=y=>{if(a!=="closed"){a="closed";for(let w of d.splice(0))w();l?.(y);}},g=y=>{y.link.onMessage((w,R)=>s?.(w,R)),y.link.onClose(w=>{if(y!==i||a==="closed")return;if(m||!r){p(w);return}let R=n.matchSession;if(R.phase==="suspended"&&R.matchId===o){a="suspended";return}p(w);});};return g(t),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return a},send(y,w){a==="connected"&&i.link.send(y,w);},onMessage(y){s=y;},onClose(y){l=y;},close(){if(a!=="closed"){if(m=true,a==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(y){if(a==="closed"||m)return "closed";if(c)return "connected";c=true;let w;try{w=await e(y===void 0?{}:{deadlineAt:y});}finally{c=false;}return m||a==="closed"?(w.close(),"closed"):(i=w,g(w),a="connected",n.notifyMatchConnected(o),"connected")},abandon(y){a!=="closed"&&(a==="connected"&&i.close(),p(y));},onClosed(y){a==="closed"?y():d.push(y);}}}function $y(t,e,n,r,o,i=false){let a=t.matchId,s=t,l,d,m=[],c=[],p=[],g=false,y=false,w=false,R=false,C="connected",M=k=>{if(g)return;g=true,C="closed";for(let L of m.splice(0))L();for(let L of c.splice(0))L();for(let L of p.splice(0))L();let A=d;A&&queueMicrotask(()=>A(k));},_=k=>{for(let A of m.splice(0))A();for(let A of Me){let L=k.channels[A];try{L.binaryType="arraybuffer";}catch{}let D=wn(A),j=U=>{let ee=pr(U?.data);ee!==null&&l?.(ee.data,D);};L.addEventListener("message",j),m.push(()=>L.removeEventListener("message",j));}},S=()=>s.peer(s.hostPlayerId),P=k=>{if(!(g||s.isHost)&&C!=="suspended"){if(r?.(k),i){C="suspended";return}M(k);}},x=k=>{for(let A of Me){let L=k.channels[A];if(typeof L.addEventListener!="function")continue;let D=()=>{S()===k&&P(Ql);};L.addEventListener("close",D),m.push(()=>L.removeEventListener?.("close",D));}},V=k=>{_(k),x(k),!g&&(C="connected",o?.());},N=k=>{for(let A of c.splice(0))A();c.push(k.on("migrating",()=>{R=true;})),c.push(k.on("hostChanged",A=>{if(R=false,A===k.playerId){M("host_migrated_here");return}let L=S();L!==null&&V(L);})),c.push(k.on("peerJoined",A=>{A.playerId===k.hostPlayerId&&V(A);})),c.push(k.on("matchEnded",A=>{g||ei(n,A),M(A);})),c.push(k.on("peerLeft",(A,L)=>{A===k.hostPlayerId&&P(Ly(L));}));};N(s);let W=S();return W!==null&&V(W),{matchId:a,protocol:"p2p",get state(){return C},send(k,A){C==="connected"&&S()?.send(it(k),Ye(A));},onMessage(k){l=k;},onClose(k){d=k;},close(){y=true,M("closed"),s.leave().catch(()=>{});},async redial(){if(C==="closed")return "closed";if(C==="connected"||w)return "connected";if(R)throw new O("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");w=true;let k;try{for(let L of m.splice(0))L();for(let L of c.splice(0))L();s.close(),k=await e();}finally{w=false;}if(g)return y?k.leave().catch(()=>{}):k.close(),"closed";s=k,N(s);let A=S();if(A===null)throw s.close(),new O("connection_failed","this peer rejoined the match but the host never answered with a link");return V(A),"connected"},abandon(k){M(k);},onClosed(k){g?k():p.push(k);}}}function ti(t){let e=0,n=new Map;return {resolve(){if(!t.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(o=>{let i={},a=l=>{n.delete(r)&&(t.clock.clearTimeout(i.timer),o(l));};n.set(r,a),i.timer=t.clock.setTimeout(()=>a(void 0),t.timeoutMs??2e3);let s=false;try{s=t.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,o){n.get(r)?.(o);}}}var Fy=12e4;function Qe(t,e){return {outcome:t,reason:e}}function Zl(t){let e=false,n=new Map;return {api:{request(r){if(!t.bridge.parentSupports("purchases"))return Promise.resolve(Qe("unavailable","error"));if(e)return Promise.resolve(Qe("declined","busy"));let o=`purchase-${Ae()}`;return new Promise(i=>{let a={},s=d=>{n.delete(o)&&(e=false,t.clock.clearTimeout(a.timer),i(d));};e=true,n.set(o,s),a.timer=t.clock.setTimeout(()=>s(Qe("unavailable","error")),t.timeoutMs??Fy);let l=false;try{l=t.bridge.requestPurchase(o,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||s(Qe("unavailable","error"));})}},settle(r){let o=r.outcome==="ok"||r.outcome==="declined"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}if(o!=="ok"){i(Qe(o,Os(r.reason)));return}let a=r.purchaseId;if(a===void 0){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),i(Qe("unavailable","error"));return}(async()=>{let s;try{s=await t.confirm(a);}catch{s="unknown";}if(s==="granted"){i({outcome:"ok",purchaseId:a});return}s==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for purchase "+JSON.stringify(a)),i(Qe("unavailable","error"));})();}}}async function ed(t,e){try{return (await Zi(t,e)).granted?"granted":"absent"}catch(n){return n instanceof G&&n.reason==="not_found"?"absent":"unknown"}}var jy=6e5;function nd(t){let e=null,n=new Map;return {api:{requestSignIn(){if(!t.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${Ae()}`;return e=new Promise(o=>{let i={},a=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(i.timer),o(l));};n.set(r,a),i.timer=t.clock.setTimeout(()=>{a({outcome:"unavailable"});},t.timeoutMs??jy);let s=false;try{s=t.bridge.requestSignIn(r);}catch{}s||a({outcome:"unavailable"});}),e}},settle(r){let o=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.signInResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var qy=new Set(["play","channel","purchase","devtools","devLocale","playOverlay","social","embedder","_s","fbclid","ttclid","gclid","msclkid"]),Ny=["utm_"];function td(t){return qy.has(t)||Ny.some(e=>t.startsWith(e))}var rd=16,od=512,Uy=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,By=/[\p{Cc}\p{Cf}]/u,Hy=/\p{Cs}/u,Te="[gem] gem.share.request:";function id(t){let{frame:e,log:n}=t,r=false,o=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,i=a=>{n!==null&&(n===void 0?console.warn(a):n(a));};return {get available(){return o()!==null},request(a){let s=o();if(s===null)throw new Error(`${Te} the arcade does not handle share here \u2014 check gem.share.available first`);if(a!==void 0&&(typeof a!="object"||a===null))throw new TypeError(`${Te} pass { params }, or nothing`);let l=a?.params===void 0?{}:a.params;if(!Vy(l))throw new TypeError(`${Te} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>rd)throw new TypeError(`${Te} at most ${rd} params; got ${d.length}`);let m=[];for(let[c,p]of d){let g=JSON.stringify(c);if(!Uy.test(c))throw new TypeError(`${Te} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(td(c))throw new TypeError(`${Te} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Te} param ${g}: values must be strings`);if(p.length>od)throw new TypeError(`${Te} param ${g}: a value is at most ${od} characters`);if(By.test(p))throw new TypeError(`${Te} param ${g}: control and format characters are not allowed`);if(Hy.test(p))throw new TypeError(`${Te} param ${g}: a value must be well-formed text`);m.push({key:c,value:p});}!s.requestShare(m)&&!r&&(r=true,i("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function Vy(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Wy=18e4,sd=32,Ky=/^[a-z0-9_-]+$/;function Jy(t){return t==="interstitial"||t==="rewarded"}function ad(t){let e=false,n=new Map;return {api:{requestAd(r){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});if(typeof r.placement!="string"||r.placement===""||r.placement.length>sd||!Ky.test(r.placement)||!Jy(r.format))return t.onDropped?.(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${JSON.stringify(r.placement)}, format ${JSON.stringify(r.format)}. A placement is 1..${String(sd)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});let o=`ad-${Ae()}`,i=r.format,a=r.placement;return new Promise(s=>{let l={},d=c=>{n.delete(o)&&(e=false,t.clock.clearTimeout(l.timer),s(c));};e=true,n.set(o,d),l.timer=t.clock.setTimeout(()=>{d({outcome:"unavailable"});},t.timeoutMs??Wy);let m=false;try{m=t.bridge.requestAd(o,a,i);}catch{}m||d({outcome:"no_ad"});})}},settle(r){let o=r.outcome==="shown"||r.outcome==="no_ad"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.adResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var ri=16384;function ld(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:zy(e)}function zy(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let o=t.charCodeAt(n+1);o>=56320&&o<=57343?(e+=4,n+=1):e+=3;}else e+=3;}return e}var Yy=1e4,Xy=5e3;function dd(t){let e=null,n=false,r=[],o=new Map,i=()=>{for(let a of r.splice(0))a();};return {api:{get current(){return e},wait(a=Xy){return n?Promise.resolve(e):new Promise(s=>{let l=()=>{let c=r.indexOf(d);c>=0&&r.splice(c,1);},d=()=>{t.clock.clearTimeout(m),l(),s(e);},m=t.clock.setTimeout(()=>{l(),s(e);},a);r.push(d);})},put(a){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let s=ld(a);if(s===null)return t.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(s>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(a)),d=`device-settings-${Ae()}`;return new Promise(m=>{let c={},p=y=>{o.delete(d)&&(t.clock.clearTimeout(c.timer),y==="stored"&&(e=l,n=true,i()),m(y));};o.set(d,p),c.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??Yy);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(a){let s=a.settings;e=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:null,n=true,i();},settle(a){let s=a.outcome==="stored"||a.outcome==="too_large"?a.outcome:"unavailable",l=o.get(a.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${s}) for an unknown requestId: `+JSON.stringify(a.requestId));return}l(s);}}}var st=class extends Error{constructor(){super("createGem: this game is not framed (window.parent === window), so nothing can hand it a player, saves, config or rooms. Play it in the Gem Arcade or the Gem Editor, or through the Gem dev host on this machine: `npm run dev` (`gemctl serve start . --dev`) while editing, `gemctl serve start .` for a build, signed in to gemctl. Do not open the dev server's own address."),this.name="GemUnframedError";}};function cd(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function oi(t,e){if(t!==true)return {visible:false};let n=[],r=false;for(let o of Array.isArray(e)?e:[])o==="score"?r=true:typeof o=="string"&&o.length>0&&o.length<=64&&!n.includes(o)&&n.push(o);return !r&&n.length===0?{visible:true}:{visible:true,currencies:n.slice(0,8),score:r}}function ud(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Qy(t){let e=t.untrusted,n=ye(e.displayName),r=e.displayTag||e.displayHandle,o=r?ye(r):void 0,i=t.discriminator||t.displayTag,a=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,s=t.avatarIconUrl||t.avatarUrl,l={displayName:n,displayHandle:o??n,badges:(t.badges??[]).map(p=>({itemId:p.itemId,iconUrl:p.iconUrl}))};t.playerId&&(l.playerId=t.playerId),a&&(l.discriminator=a),o&&(l.displayTag=o),s&&(l.avatarIconUrl=l.avatarUrl=s);let d=t.boost,m=(d?.multipliers??[]).map(p=>({currencyId:p.currencyId,currencySlug:p.currencySlug,multiplier:p.multiplierBp/1e4})),c=m.some(p=>p.multiplier>1);return l.boost=c&&d?.expiresInDays?{active:c,multipliers:m,expiresInDays:d.expiresInDays}:{active:c,multipliers:m},l}var Zy=1e4,at=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??le,this.inbound=new xn(this.clock),this.outbound=new xn(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(s=>Ar(s,e.origin))||Ts(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=_t["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!Ar(o.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${o.embedder}' but arrived from '${e.origin}'`),false;let i=e.ports?.[0];if(!i)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=Is(bt,o.versions);return a===null?(i.onmessage=null,i.postMessage({gem:K,type:"gem.error",code:"version_mismatch",message:`frame supports v${bt.min}..v${bt.max}`}),i.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=i,this.version=a,i.onmessage=s=>this.receive(s.data,s.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],this.unbidden=o.unbidden===true,i.postMessage({gem:K,type:"gem.handshake.accept",v:a,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:K,type:"gem.ready"});}settled(e=Zy){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=i=>{this.clock.clearTimeout(o),n(i);},o=this.clock.setTimeout(()=>{let i=this.settleWaiters.indexOf(r);i>=0&&this.settleWaiters.splice(i,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem:K,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:K,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:K,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:K,type:"gem.exit"}:{gem:K,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:K,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:K,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:K,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:K,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let n={gem:K,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(n.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(n.origin={x:cd(e.origin.x),y:cd(e.origin.y)}),this.send(n),true}setWalletVisible(e,n){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:K,type:"gem.walletDisplay",...oi(e,n?.only)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:K,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:K,type:"gem.frameStats",fps:ud(e.fps,1e3),frameTimeP95Ms:ud(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:K,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:K,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:K,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:K,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,o,i,a){return this.send({gem:K,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:o,...i===void 0?{}:{quantity:i},...a===void 0?{}:{catalogId:a}})}putDeviceSettings(e,n){return this.send({gem:K,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:K,type:"gem.requestAd",requestId:e,placement:n,format:r})}requestSignIn(e){return this.send({gem:K,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,o){return this.send({gem:K,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...o===void 0?{}:{params:o}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(vt)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(vt)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(vt)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:K,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let n=e.type;if(!this.outbound.allow(n))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${n}`),false;let r=_t[n]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${n}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,n=[]){let r=false;try{r=this.dispatchInbound(e,n);}finally{r||md(n);}}dispatchInbound(e,n){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let o=_t[r];if(!o)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let i=As(r);if(i!==void 0&&!this.options.capabilities?.includes(i))return this.fail("unsupported_capability",`${r} requires the '${i}' capability, which this frame did not advertise`),false;let a=o(e);if(a)return this.fail("invalid_message",`${r}: ${a}`),false;let s=e;if(s.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(s);break;case "gem.pause":this.options.onPause?.(s);break;case "gem.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(s);break;case "gem.willTerminate":this.options.onWillTerminate?.(s);break;case "gem.devtools":this.options.onDevtools?.(s.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=n[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:s.maxWidth,maxHeight:s.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return md(n.slice(1)),this.options.onScreenshot(d,l,(m,c)=>this.screenshotDenied(m,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(Qy(s));break}case "gem.roomEvent":this.options.onRoomEvent?.(s);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(s);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(s);break;case "gem.socketState":this.options.onSocketState?.(s);break;case "gem.signalEvent":this.options.onSignalEvent?.(s);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(s);break;case "gem.clusterTarget":this.options.onClusterTarget?.(s);break;case "gem.partyResult":this.options.onPartyResult?.(s);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(s);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(s);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(s);break;case "gem.adResult":this.options.onAdResult?.(s);break;case "gem.signInResult":this.options.onSignInResult?.(s);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(s);break;case "gem.error":this.options.onError?.(s.code,s.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:K,type:"gem.screenshot.denied",reason:e,retryable:n});}};function md(t){for(let e of t)try{e?.close?.();}catch{}}var pd="https://api.gemarcade.com";function ii(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 ef=new Set(["localhost","127.0.0.1","[::1]"]);function gd(t){let e=ii(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!ef.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 nf=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),tf=pd,yd=8e3,si=15e3,rf=9e4,of=1/0,sf=8e3,af=5e3,lf=5e3;async function df(t,e,n,r){if(t.isInRoom)try{await t.leave();}catch{}r?.endSession("session_ended"),e!==null&&e.currentState==="connected"&&e.exit(n);}function lt(t){let e=null,n=false,r=[];return {get current(){return e},set(o){e=o;for(let i of r.splice(0))i(o);},release(){n=true;for(let o of r.splice(0))o(e);},wait(o){return e!==null||n?Promise.resolve(e):new Promise(i=>{let a=()=>{let d=r.indexOf(s);d>=0&&r.splice(d,1);},s=d=>{t.clearTimeout(l),a(),i(d);},l=t.setTimeout(()=>{a(),i(e);},o);r.push(s);})}}}function qS(t={}){let e=t.clock??le,n=t.log===void 0?u=>console.info(u):t.log,r=t.baseUrl??void 0;if(r!=null){let u=ii(r);if(u!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${u}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let o=jo();o.mark("sdk created");let i=()=>Wt(J.gameVersion,t.clientVersion?.gameVersion),a=new Fn({client:()=>tn,clock:e,gameId:()=>J.identity?.gameId??null,playerId:()=>J.identity?.playerId??null,environment:()=>{let u=i();return {sdk_version:bi(),...u===null?{}:{game_version:u}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),s=tl(()=>{o.mark("engaged"),a.release(),q.reportEngaged();},typeof window>"u"?{}:window),l=u=>{if(u===false)return null;let T=u?.attempts??of,F=u?.budgetMs??rf;return !(T>0)||!(F>0)?null:{attempts:T,budgetMs:F,maxDelayMs:u?.maxDelayMs??sf}},d=u=>{u.on("created",()=>{o.mark("room created");}),u.on("joined",()=>{o.mark("room joined");}),u.on("matchAllocationStarted",()=>{o.mark("allocation started");}),u.on("matchReady",()=>{o.mark("match ready");}),u.on("matchFailed",()=>{o.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new st;let m=t.allowedEmbedders;if(m!=null&&!Array.isArray(m))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let c=Array.from(m??[]),p=c.filter(u=>typeof u!="string"||!xr(u));if(p.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${p.length===1?"an entry":"entries"} that ${p.length===1?"is":"are"} not an origin: ${p.map(u=>typeof u=="string"?JSON.stringify(u):String(u)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let g=Object.freeze([...new Set([...nf,...c])]),y=lt(e),w=lt(e),R=lt(e),C=oa(n),M=lt(e),_=t.manageAudio===false?null:cl();t.selectableText!==true&&ul();let S=null,P=()=>{S!==null&&(w.current!==null&&w.current.muted===S||q.reportMuted(S));},x=null,V=null,N=()=>{if(x===null)return false;let u=JSON.stringify(oi(x.visible,x.only));return u===V?q.parentSupports("walletDisplay"):q.setWalletVisible(x.visible,x)?(V=u,true):false},W=ml({report:u=>q.reportFrameStats(u)}),k=false,A=vl(()=>hi,()=>k),L=u=>{let T=k&&!u,F=k!==u;if(k=u,T&&A.close(),!!F)try{t.onDevToolsPermissionChange?.(u);}catch(te){n?.(`[gem] onDevToolsPermissionChange threw: ${te instanceof Error?te.message:String(te)}`),queueMicrotask(()=>{throw te});}},D=r??tf,j=r!==void 0,U,ee=u=>(n?.(`[gem] token refused: ${u}`),t.onError?.("internal",u),false),ge=(u,T)=>{if(u===void 0)return T!==void 0?ee("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let F=gd(u);return F!==null?ee(`the embedder named an API root that cannot be used: ${F}. Its value is withheld here rather than written to logs.`):U!==void 0&&U!==u?ee("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(U=u,j||(D=u),true)},Q=window.location?.origin,Oe=null,Se=-1/0,Ie=2e3,Ce=new Set,re=u=>Oe!==false?Promise.resolve(true):new Promise(T=>{let F=e.setTimeout(()=>{Ce.delete(te),T(false);},u),te=()=>{e.clearTimeout(F),Ce.delete(te),T(true);};Ce.add(te);}),Y=()=>{},de=null,q=new at({allowedEmbedders:g,...typeof Q=="string"&&Q!==""?{selfOrigin:Q}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","earnAllowance","share","frameStats","walletDisplay","engagement","reservedAreas","viewport","purchases","deviceSettings","ads","signIn","friendChallenges",...t.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:u=>{de=u,t.onRefused?.(u);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:u=>{J.onBridgeState(u),u!=="connected"&&W.setRequested(false),V=null,u==="refused"&&(console.error("[gem] this game refused the page that framed it"+(de===null?"":` (${de})`)+", so it has no player, saves, config or rooms. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders."),Y()),u==="connected"&&(o.mark("bridge connected"),gr(),P(),N(),q.unbiddenLaunch&&!s.engaged&&a.hold(),a.startSession(),s.engaged&&q.reportEngaged()),t.onStateChange?.(u);},onPlayer:u=>{y.set(u),t.onPlayer?.(u);},onPrefs:u=>{let T={reducedMotion:u.reducedMotion,muted:u.muted,locale:u.locale,showFrameStats:u.showFrameStats===true};w.set(T),_?.setMuted(T.muted),W.setRequested(T.showFrameStats&&q.parentSupports("frameStats")),t.onPrefs?.(T);},onCohorts:u=>{let T=Object.freeze(u.cohorts.map(F=>Object.freeze({experimentId:F.experimentId,variantKey:F.variantKey})));R.set(T),t.onCohorts?.(T);},onEarnAllowanceChanged:()=>C.emit(),onViewport:u=>{let T=Object.freeze({insets:Object.freeze({top:u.insets.top,right:u.insets.right,bottom:u.insets.bottom,left:u.insets.left}),reserved:Object.freeze((u.reserved??[]).map(te=>Object.freeze({x:te.x,y:te.y,width:te.width,height:te.height})))});M.set(T);let F=gl();yl(F,T.insets),hl(F,T.reserved,fl()),t.onViewport?.(T);},onPause:u=>{a.setPaused(u.paused),W.setPaused(u.paused),t.onPause?.(u.paused);},onWillTerminate:u=>{a.endSession(u.reason),t.onWillTerminate?.({reason:u.reason,graceMs:u.graceMs});},onToken:u=>{let T=u.garden;if(L(u.allowDevTools===true),!ge(u.apiBaseUrl,T))return;let F=u;J.onToken(F);let te=J.identity;te&&(Ze.set(te),f||(f=true,ue.reconcileSeats().catch(()=>{}))),ne.push({token:F.token,expiresAt:F.expiresAt});},onTokenDenied:u=>{L(false),J.onDenied(u);},onScreenshot:(u,T,F)=>{al(u,T,F,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{ll(q,t.onFeedbackContext);},onDevtools:u=>{u==="close"?A.close():u==="open"?A.openFrom("platform").catch(()=>{}):A.isOpen?A.close():A.openFrom("platform").catch(()=>{});},onRoomEvent:u=>ue.handleRoomEvent({event:u.event,roomId:u.roomId,...u.matchId===void 0?{}:{matchId:u.matchId},...u.version===void 0?{}:{version:u.version},...u.reason===void 0?{}:{reason:u.reason},...u.platform===void 0?{}:{platform:u.platform}}),onSeatedEvent:u=>ue.handleSeated(u.roomId),onAutoStartFailedEvent:u=>ue.handleAutoStartFailed(u.roomId,u.code),onSocketState:u=>{let T=Oe;if(Oe=u.connected,u.connected)for(let te of [...Ce])te();if(!u.connected||T===true)return;let F=e.now();F-Se<Ie||(Se=F,ue.reconcile().catch(()=>{}));},onSignalEvent:u=>{let T=typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:{};rn.handleSignalEvent(u.matchId,u.event,T),u.event==="matchEnded"&&ue.reconcile({matchId:u.matchId,...typeof T.reason=="string"?{reason:T.reason}:{}}).catch(()=>{});},onDedicatedEvent:u=>{u.event==="matchEnded"&&(Rn.handleMatchEnded(u.matchId,u.reason),ue.reconcile({matchId:u.matchId,...u.reason===void 0?{}:{reason:u.reason}}).catch(()=>{})),dt.handleEvent(u);},onClusterTarget:u=>ut.accept(u.clusterTargetId,u.clusterTargetIds),onLocalServer:u=>mt.accept(u),onLocalServerDenied:u=>mt.refuse(u),onPartyResult:u=>en.settle(u.requestId,u.partyId),onPurchaseResult:u=>di.settle(u),onDeviceSettings:u=>{ct.receive(u),t.onDeviceSettings?.(ct.api.current);},onDeviceSettingsResult:u=>ct.settle(u),onAdResult:u=>ci.settle(u),onSignInResult:u=>ui.settle(u),onFriendChallengeResult:u=>mi.settle(u)}),dt=new ot({bridge:q}),Ze=lt(e);Y=()=>{Ze.release(),y.release(),R.release();},q.currentState==="refused"&&Y();let f=false,E=new Set,$,ne={current:()=>$,subscribe:u=>(E.add(u),$!==void 0&&u($),()=>E.delete(u)),push:u=>{$=u;for(let T of [...E])try{T(u);}catch(F){n?.(`[gem] a server-token listener threw: ${F instanceof Error?F.message:String(F)}`);}}},J=wl({bridge:q,clock:e,onStateChange:(u,T)=>{if(u==="ready"){if(o.mark("token ready")){let F=o.marks.find(te=>te.name==="token ready")?.at;a.trackPlatform("gem_boot_ready",F===void 0?{}:{boot_ms:Math.max(0,Math.round(F))});}}else u==="lost"&&(o.mark("token lost"),a.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(u,T);}}),Sn=()=>{let u=J.identity;return !u||J.source.currentState==="lost"?null:`${u.playerId}\0${u.gameId}\0${u.channel}`},gr=()=>{o.mark("token requested"),J.source.get().catch(()=>{});},en=ti({bridge:q,clock:e}),li={},di=Zl({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u),confirm:async u=>li.confirm?.(u)??"unknown"}),ct=dd({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),ci=ad({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),ui=nd({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),mi=ra({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),ut=pa({bridge:q,clock:e}),mt=bl({bridge:q,clock:e}),yr=u=>{let T=q.handleWindowMessage({data:u.data,origin:u.origin,source:u.source,ports:u.ports});return T&&window.removeEventListener("message",yr),T};window.addEventListener("message",yr);let nn=rl(window,yr),vd=nn?.capture,fr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];fr?.domInteractive!==void 0&&fr.domInteractive>0&&o.mark("document parsed",fr.domInteractive),vd?.late&&n?.("[gem] the early-handshake capture installed after this document finished loading, so a handshake posted at iframe load may already have been missed. Load the capture script ahead of everything else in the document.");let hr=t.handshakeWarningMs;hr!==null&&n&&e.setTimeout(()=>{let u=nn===null?"no capture script ran":`capture: ${nn.delivered} offer(s) delivered, ${nn.stale} stale, ${nn.capture.dropped} evicted${nn.capture.late?", installed late":""}`;if(q.currentState==="connected"){n(`[gem] handshake connected. boot: ${o.timeline()} \xB7 ${u}`);return}n(`[gem] no completed handshake after ${hr??yd}ms (bridge state: ${q.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${o.timeline()} \xB7 `+u);},hr??yd);let _d=cr({get baseUrl(){return D},tokenSource:J.source,get defaultQuery(){let u=J.identity;return u?{game_id:u.gameId,channel:u.channel}:{}}}),tn=new Le({transport:_d,clock:e}),he={client:tn,gameId:()=>J.identity?.gameId??""};li.confirm=u=>ed(he,u);let wd=()=>J.identity?.channel??"release",pi=new Ft(he,wd),gi=async u=>(await pi.load())?.currency(u)?.id??void 0,yi=Mt(he,Dr,{identity:Sn,resolveCurrencyId:gi}),br=async u=>{let T=await Ze.wait(u);if(T)return T;throw q.currentState==="refused"?new ie("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new ie("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},vr=l(t.autoReconnect),ue=ko({client:tn,clock:e,gameId:()=>J.identity?.gameId??null,playerId:()=>J.identity?.playerId??null,awaitGameId:async()=>(await br(si)).gameId,resolveParty:en.resolve,resolveClusterTargets:ut.resolveList,refreshClusterTargets:ut.refresh,ensureLocalServer:mt.ensure,localHostAvailable:mt.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>J.gameVersion,...t.pollRooms===void 0?{}:{poll:t.pollRooms},...t.recoverStaleMembership===void 0?{}:{recoverStaleMembership:t.recoverStaleMembership},...t.retryAutoStart===void 0?{}:{retryAutoStart:t.retryAutoStart},...t.watchSeats===void 0?{}:{watchSeats:t.watchSeats},...t.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:t.seatPollIntervalMs},...vr===null?{}:{autoReconnect:{...vr,redial:(u,T)=>_r.redialMatch(u,T),abandon:(u,T)=>_r.abandonMatch(u,T)}}});d(ue),el({analytics:a,rooms:ue});let rn=Za({client:tn,clock:e,rooms:ue,bridge:q,gameId:()=>J.identity?.gameId??"",baseUrl:()=>D,resolveClusterTarget:ut.resolve,boot:o,...t.log===void 0?{}:{log:t.log}}),fi=Fo(o,n),Rn=Fl({client:tn,clock:e,rooms:ue,signaling:()=>dt.channel(),signalingReady:re,log:n??(()=>{})}),_r=Xl({rooms:ue,p2p:{connect:u=>fi(rn.connect(u)),session:u=>rn.session(u)},dedicated:{connect:(u=>ar(o,"welcome",Rn.connect(u),n))},clock:e,identity:()=>J.identity,apiBaseUrl:()=>D,tokens:ne,room:()=>ue.currentRoom,autoReconnect:vr!==null,...t.log===void 0?{}:{log:t.log}}),Sd=async()=>(await br(si)).playerId,hi={client:tn,boot:o,get identity(){return J.identity},awaitIdentity:(u=si)=>br(u),awaitBridge:u=>q.settled(u),get player(){return y.current},awaitPlayer:(u=af)=>y.wait(u),me:yi,characters:new Lt(he,void 0,Sn,gi),transfers:new Dt(he,Dr,yi.inventory),gameConfig:pi,purchases:di.api,deviceSettings:ct.api,ads:ci.api,account:ui.api,share:id({frame:q,log:t.log}),analytics:a,leaderboards:new Cn(he),challenges:new En(he),showcase:new Mn(he,Sd),friends:new On(he,{challenge:mi.challenge}),platform:new Gn(he,C,n),profiles:new Dn(he),functions:new De((u,T)=>ss(he,u,T)),get prefs(){return w.current},get cohorts(){return R.current},get viewport(){return M.current},awaitCohorts:(u=lf)=>R.wait(u),reportMuted:u=>{S=!!u,P();},cueReward:u=>q.cueReward(u),setWalletVisible:(u,T)=>{let F=Array.isArray(T?.only)?[...T.only]:void 0;return x=F===void 0?{visible:u===true}:{visible:u===true,only:F},N()},exit:u=>df(ue,q,u,a),frame:q,devtools:A,rooms:ue,dedicatedServer:{listClusterTargets:u=>Rn.listClusterTargets(u),connect:(u=>ar(o,"welcome",Rn.connect(u),n)),handleMatchEnded:(u,T)=>Rn.handleMatchEnded(u,T)},p2p:{handleSignalEvent:(u,T,F)=>rn.handleSignalEvent(u,T,F),session:u=>rn.session(u),connect:u=>fi(rn.connect(u))},match:_r};return hi}var fd="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 ai(t,e={}){let n=e.clock??le,r=()=>{let s=t();if(s===null)throw new Error(fd);return s},o=null,i=()=>{if(o===null)throw new Error(fd);return o};return {server:{get identity(){return i().identity},get client(){return i().client},get api(){return i().api},get match(){return i().match},get analytics(){return i().analytics},get functions(){return i().functions},get challenges(){return i().challenges},get room(){return i().room},dispose(){o?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(s){let d=r().profile?.(s);if(!d)return null;let m=d.displayName;return typeof m!="string"||m===""?null:{displayName:ye(m),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:ye(d.displayTag)}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(s){return r().playerNumber?.(s)},send(s,l,d){d===void 0?r().send(s,l):r().send(s,l,d);},broadcast(s,l){l===void 0?r().broadcast(s):r().broadcast(s,l);},kick(s,l){l===void 0?r().kick(s):r().kick(s,l);},log(s){r().log(s);},warn(s){r().warn(s);}},attach:()=>{o=_n(r(),{...e,clock:n});}}}function hd(t,e={}){let{server:n,attach:r}=ai(()=>t,e);return r(),n}function cf(t){if(t===void 0||typeof t.reason!="string"||t.reason==="")return;let e=t.platform_reason??t.endedReason;return {reason:t.reason,...e===void 0?{}:{endedReason:$e(e)}}}function bd(t,e={}){return ()=>{let n=null,{server:r,attach:o}=ai(()=>n,e),i=t(r),a={async init(s){n=s,o(),await i.init?.();},async shutdown(s){let l=cf(s);try{await i.shutdown?.(l);}finally{r.dispose();}}};return i.join&&(a.join=(s,l)=>i.join?.(s,l)),i.leave&&(a.leave=(s,l)=>i.leave?.(s,l)),i.message&&(a.message=(s,l,d,m)=>i.message?.(s,l,d,m)),a}}
|
|
2
|
+
export{nf as ARCADE_EMBEDDERS,Fn as AnalyticsApi,ie as AuthError,pt as CONDITIONAL_HEADERS,En as ChallengesApi,ri as DEVICE_SETTINGS_MAX_BYTES,b as DedicatedServerError,He as FriendChallengeError,On as FriendsApi,De as FunctionsApi,G as GemApiError,Le as GemClient,ce as GemConfigError,at as GemFrame,$n as GemFunctionError,se as GemSaveError,st as GemUnframedError,Cn as LeaderboardsApi,Vs as MAX_PERIODS_BACK,im as PLATFORM_EVENTS,Gn as PlatformApi,Ut as PlatformCurrenciesApi,Bt as PlatformEarnAllowanceApi,pe as PlayerText,Dn as ProfilesApi,Ge as PurchaseRefusal,Mn as ShowcaseApi,oe as TransportRefusal,Un as UNRELIABLE_CHANNEL_LABEL,ye as asPlayerText,jo as createBootTimeline,qS as createGem,_n as createGemServer,Nl as createHostTokenSource,hd as createMatchServer,bd as defineServer,df as leaveAndExit,ve as mapIdentity,ar as markOnResolve,Lu as platformIconUrl,qn as presentJoinCredential,pn as readTemplateTransports,Bn as readTransportAdvert,Fo as reportOnResolve,le as systemClock,Ne as text,gt as toBase64,Yt as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.sdk.js.map
|
|
3
3
|
//# sourceMappingURL=gem-web-sdk.sdk.js.map
|