@indiegems/gem-web-sdk 7.9.1 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/README.md +1 -0
- package/dist/function.d.ts +26 -1
- package/dist/game.d.ts +32 -1
- package/dist/gem-web-sdk.bridge.js +1 -1
- package/dist/gem-web-sdk.esm.js +2 -2
- package/dist/gem-web-sdk.function.js +2 -2
- 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 +12 -3
- package/dist/sdk.d.ts +32 -1
- package/docs/api/api-reference-game.md +424 -8
- package/docs/api/api-reference-server.md +1 -1
- package/docs/api/reference.json +441 -5
- package/docs/changelog.md +30 -0
- package/docs/friends.md +86 -11
- package/docs/getting-started.md +10 -6
- package/docs/manifest.json +21 -16
- package/docs/saving-player-progress.md +41 -0
- package/docs/server-bundles.md +2 -2
- package/docs/serverless-functions-js.md +3 -2
- package/docs/serverless-functions.md +53 -7
- package/docs/vibration.md +141 -0
- package/docs/what-a-game-must-do.md +12 -0
- package/package.json +1 -1
- package/schema/bridge.v1.json +60 -0
- package/schema/capabilities.public.json +9 -0
package/dist/gem-web-sdk.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var GemWebSdkGame=(function(exports){'use strict';var Cd=Object.defineProperty;var Id=(t,e)=>{for(var n in e)Cd(t,n,{get:e[n],enumerable:true});};var Sr="GemWebSdkHandshake";function Md(){return typeof document>"u"?void 0:document.readyState}var Si=()=>Date.now();function Ri(t={}){let e=t.win??window,n=e,r=n[Sr];if(r!==void 0)return r;let o=t.readyState??Md,i=t.now??Si,a=[],s=[],l=m=>{let u=m.data;!u||u.type!=="gem.handshake"||(a.length>=4&&(a.shift(),s.shift(),d.dropped+=1),a.push(m),s.push(i()));};e.addEventListener("message",l);let d={events:a,times:s,dropped:0,late:o()==="complete",uninstall(){e.removeEventListener("message",l);}};return n[Sr]=d,d}function ki(t,e,n={}){let r=t[Sr];if(r===void 0)return null;let o=n.ttlMs??9500,i=n.now??Si,a=r.events.splice(0),s=r.times?.splice(0),l=0,d=0,m=false,u=i()-o;for(let p=a.length-1;p>=0;p--){let g=s?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(a[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:7.9.1]";function xi(){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 Od(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 oe(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.grant&&e>=this.grant.chainEndsAt)throw this.enter("lost","chain_exhausted"),new oe("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 oe("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=Ld(o),a=o?.retryable;throw n===this.generation&&this.enter(Od(i,typeof a=="boolean"?a:void 0)?"lost":"degraded",i),o instanceof oe?o:new oe(i,String(o))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){this.failure=n??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,n));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},oe=class t extends Error{constructor(n,r){super(`auth ${n}: ${r}`);this.reason=n;this.name="AuthError";}reason;static isAuthError(n){if(n instanceof t)return true;let r=n;return r?.name==="AuthError"&&typeof r.reason=="string"}};function Ld(t){if(t instanceof oe)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var re=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}},gt=["if-match","if-none-match"],Ai=4096;function Gd(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();if(!gt.includes(o)||r===void 0)continue;let i=typeof r=="string"?Dd(r):r;if(typeof i!="string"||i.length>Ai||!$d(i))throw new re(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${Ai} 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 Dd(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 $d(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 Fd(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new re("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 re("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 Pi(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=Gd(o.headers),a=Fd(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(),u=await t(s,m);if(u.status===401)throw e.tokenSource.close("unavailable"),new oe("unavailable","the server refused a freshly minted token");return u}}}function yt(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(jd(e))}function ft(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 Rr(t){return new TextDecoder().decode(ft(t))}function jd(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"}},Ti=new WeakMap;function Ci(t){return Ti.get(t)??{}}var qd=new Set([408,429,500,502,503,504]),Nd=6e4;function Ud(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new re(`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:Bd(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?Ud(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw Ei(e.signal);for(let i=0;i<r;i++){if(i>0&&await this.backoff(i,o,e.signal),e.signal?.aborted)throw Ei(e.signal);let a;try{a=await this.options.transport.request(e);}catch(l){if(oe.isAuthError(l)||re.isRefusal(l)||e.signal?.aborted||Hd(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=Vd(a);if(!qd.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),Nd);return new Promise(l=>{let d=this.options.clock,m=false,u=false,p,g=()=>{m||(m=true,u&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,s),u=true,m&&d.clearTimeout(p);})}};function Bd(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 Ei(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Hd(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function Vd(t){let e=Kd(t),n=zd(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&Ti.set(e,r),e}var Wd=new Map([["insufficient_funds","insufficient_funds"]]);function Kd(t){let{status:e,body:n}=t,r=Jd(n),o=t.retryAfterSeconds??Xd(n),i=Yd(n),a=i===void 0?void 0:Wd.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 Jd(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 zd(t){let n=t?.error?.details;return n===null?void 0:n}function Yd(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Xd(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 Ii(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Mi(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 Oi(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Li(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 Gi(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function Di(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 $i(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 Fi(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function ji(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function qi(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(o,r?.signal)}async function Ni(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 Ui(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 Bi(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 Hi(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.get(r,n?.signal)}async function Vi(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Wi(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 Ki(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 Ji(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 zi(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 Yi(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 Xi(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 Qi(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 Zi(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 kr(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 es(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${v(e)}/friends`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function ns(t,e,n){let r=`/v1/showcase/friends/${v(e)}`;return t.client.get(r,n?.signal)}async function ts(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 rs(t,e){let n=`/v1/games/${v(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function ht(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function os(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function is(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 ss(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 as(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function ls(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function ds(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function cs(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 us(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ms(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 ps(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function gs(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 ys(t,e){return t.client.get("/v1/characters",e?.signal)}async function fs(t,e,n,r){let o=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function hs(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 bs(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 vs(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o="/v1/friends"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function _s(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function ws(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 Ss(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 Rs(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 ks(t,e,n,r,o){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(i,r,o?.signal)}async function xs(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function As(t,e,n,r){let o=`/v1/characters/${v(e)}`;return t.client.patch(o,n,r?.signal)}async function Ps(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 Es(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 Ts(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.delete(r,n?.signal)}var U="gem-web-bridge",vt={min:1,max:1},sn=65536,Cs=8,bt=5e3,Is=1024;function Ar(t){return Object.freeze(Object.assign(Object.create(null),t))}var Ms=Ar({"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.menu":60,"gem.menuSelect":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}),_t="__malformed";var Qd=Ar({"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","gem.menu":"gameMenu","gem.menuSelect":"gameMenu"}),Zd=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.viewport.","reservedAreas"]]);function Os(t){let e=Qd[t];if(e!==void 0)return e;for(let[n,r]of Zd)if(t.startsWith(n))return r}function Pr(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 ec(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 nc(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function tc(t){return /^[a-z_]+$/.test(t)}function xr(t,e,n){if(e>Cs)return `nesting deeper than ${Cs}`;if(++n.nodes>bt)return `more than ${bt} 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>Is)return `an array of ${t.length} entries, over the ${Is} limit`;n.bytes+=2;for(let s of t){let l=xr(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>bt)return `more than ${bt} values`;if(n.bytes+=s.length*3+4,n.bytes>sn)return `over the ${sn} byte limit`;let l=xr(a[s],e+1,n);if(l)return l}return null}function rc(t){let e={nodes:0,bytes:0,seen:new Set},n=xr(t,0,e);return n?`message contains ${n}`:e.bytes>sn?`message is over the ${sn} byte limit`:null}var oc={origin:[Pr,"not a well-formed origin"],url:[ec,"not a safe absolute http(s) URL"],bcp47:[nc,"not a well-formed BCP 47 tag"],code:[tc,"not a code of lower-case letters and underscores"]};function Ls(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=Gs(i,r,o);if(a)return a}return null}function Gs(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]=oc[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`:Ls(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=Gs(i,r,o);if(a)return a}return null}default:{let r=e.k;return `${n}: unknown kind ${String(r)}`}}}function P(t,e){return n=>{let r=rc(n);if(r)return r;if(typeof n!="object"||n===null||Array.isArray(n))return "message: expected object";let o=n;return o.gem!==U?"gem: wrong protocol marker":o.type!==t?`type: expected ${t}`:Ls(o,e,"")}}var ic=P("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}]),sc=P("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}}]),ac=P("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}]),lc=P("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}]),dc=P("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}]}]),cc=P("gem.pause",[{n:"paused",k:"boolean"}]),uc=P("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),mc=P("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}]}}]),pc=P("gem.earnAllowanceChanged",[]),gc=P("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}]}}]),yc=P("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),fc=P("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),hc=P("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"]}]),bc=P("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),vc=P("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),_c=P("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),wc=P("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"}]),Sc=P("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}]),Rc=P("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),kc=P("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),xc=P("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),Ac=P("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),Pc=P("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),Ec=P("gem.requestContext",[]),Tc=P("gem.gameContext",[{n:"context",k:"json"}]),Cc=P("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Ic=P("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),Mc=P("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),Oc=P("gem.ready",[]),Lc=P("gem.engaged",[]),Gc=P("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Dc=P("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),$c=P("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),Fc=P("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),jc=P("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),qc=P("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),Nc=P("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),Uc=P("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),Bc=P("gem.audioState",[{n:"muted",k:"boolean"}]),Hc=P("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}]}]),Vc=P("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}]),Wc=P("gem.menu",[{n:"settings",k:"boolean"},{n:"items",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"id",k:"string",max:32},{n:"label",k:"string",max:40}]}}]),Kc=P("gem.menuSelect",[{n:"entry",k:"enum",v:["settings","item"]},{n:"id",k:"string",o:1,max:32}]),Jc=P("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}]}}]),zc=P("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),Yc=P("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}]),Xc=P("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=P("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}]),Zc=P("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),eu=P("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),nu=P("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),tu=P("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),ru=P("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),ou=P("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),iu=P("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}]),su=P("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}]),wt=Ar({"gem.handshake":ic,"gem.handshake.accept":sc,"gem.token":ac,"gem.token.denied":lc,"gem.player":dc,"gem.pause":cc,"gem.prefs":uc,"gem.cohorts":mc,"gem.earnAllowanceChanged":pc,"gem.viewport":gc,"gem.deviceSettings":yc,"gem.willTerminate":fc,"gem.roomEvent":hc,"gem.socketState":bc,"gem.seatedEvent":vc,"gem.autoStartFailedEvent":_c,"gem.signalEvent":wc,"gem.dedicatedEvent":Sc,"gem.partyResult":Rc,"gem.clusterTarget":kc,"gem.devtools":xc,"gem.screenshot":Ac,"gem.screenshot.denied":Pc,"gem.requestContext":Ec,"gem.gameContext":Tc,"gem.signal":Cc,"gem.dedicatedOffer":Ic,"gem.partyRequest":Mc,"gem.ready":Oc,"gem.engaged":Lc,"gem.progress":Gc,"gem.requestToken":Dc,"gem.requestLocalServer":$c,"gem.localServer":Fc,"gem.localServer.denied":jc,"gem.exit":qc,"gem.openExternal":Nc,"gem.requestFullscreen":Uc,"gem.audioState":Bc,"gem.rewardCue":Hc,"gem.walletDisplay":Vc,"gem.menu":Wc,"gem.menuSelect":Kc,"gem.requestShare":Jc,"gem.frameStats":zc,"gem.error":Yc,"gem.requestPurchase":Xc,"gem.purchaseResult":Qc,"gem.deviceSettings.put":Zc,"gem.deviceSettings.result":eu,"gem.requestAd":nu,"gem.adResult":tu,"gem.requestSignIn":ru,"gem.signInResult":ou,"gem.requestFriendChallenge":iu,"gem.friendChallengeResult":su});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=Ms[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 Er(t,e){return t.toLowerCase()===e.toLowerCase()}function St(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Ds(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:St(n.hostname)&&St(r.hostname)}function $s(t,e){if(e.min>e.max)return null;let n=Math.min(t.max,e.max),r=Math.max(t.min,e.min);return n>=r?n:null}var Rt=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 Cr(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 Fs="inventory",an=t=>typeof t=="number"?t:0,An=t=>typeof t=="string"?t:"";function Tr(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 js(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 au(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Tr(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:Tr(e.items,js),progressions:Tr(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,...Cr(o)}}),...n===void 0?{}:{etag:n}}}var kt=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Fs}#buckets`:Fs;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 Ji(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(o)?o.map(js):[]}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 Ki(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 au(n)}};var lu={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},du=new Set(Object.keys(lu));function qs(t){return typeof t=="string"&&du.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:"",cu=t=>typeof t=="string"?t:Z(t&&typeof t=="object"?t.type:void 0),Re=t=>typeof t=="number"?t:0;function uu(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 xt(){return crypto.randomUUID()}var mu="recipe-usage",Ns=100;function At(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 pu(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(At):[]}}function gu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(pu):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(At):[],consumed:Array.isArray(e.consumed)?e.consumed.map(At):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(At):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function yu(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 fu(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 Us(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 Pt=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(()=>$i(this.api,this.entity.type,this.entity.id,{operations:e.map(Us),source:n.source??"play",nonce:xt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Pn(r)}async createMany(e,n={}){return this.write(()=>Di(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Us),nonce:xt()})),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 Qi(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(uu):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>cu(d)):[],...a===void 0?{}:{usesRemaining:a},...s===void 0?{}:{cooldownExpiresAt:s}}}async recipeUsageAll(){return this.cache.read(mu,[],async()=>{let n=await Zi(this.api,this.entity.type,this.entity.id,{limit:Ns})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(fu),truncated:r.length>=Ns}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let u=e,p=await this.write(()=>Ni(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:xt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...gu(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([is(this.api,n.signal===void 0?{}:{signal:n.signal}),ht(this.api,n.signal===void 0?{}:{signal:n.signal})]),i=e.payment.currencySlug.toLowerCase(),a=o.currencies.find(u=>u.currency_id.toLowerCase()===i||u.slug.toLowerCase()===i);if(a===void 0){let u=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: ${u.length===0?"none":u.join(", ")}`)}let s=e.kind==="item"?r.items.find(u=>u.item_id===e.targetId):r.recipes.find(u=>u.recipe_id===e.targetId&&u.catalog_id===e.catalogId);if(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(u=>u.platform_currency_id===a.currency_id);if(l===void 0){let u=g=>o.currencies.find(f=>f.currency_id===g)?.slug??g,p=s.platform_prices.map(g=>`${u(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(()=>ms(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:xt(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return yu(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(()=>Mi(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(()=>Ss(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(()=>Li(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(()=>Es(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 Ir=t=>typeof t=="string"?t:"",hu=t=>typeof t=="number"?t:0;function Bs(t){let e=t??{};return {orderId:Ir(e.order_id),status:Ir(e.status),source:Ir(e.source),createdAt:hu(e.created_at)}}var Et=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await hs(this.api,this.entity.type,this.entity.id,{...e.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(Bs):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Yi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Bs(r)}};var Hs=t=>typeof t=="number"?t:0,bu=t=>typeof t=="string"?t:"";function vu(t){let e=t??{};return {progressionDefinitionId:bu(e.progression_definition_id),currentValue:Hs(e.current_value),completionCount:Hs(e.completion_count),isCompleted:e.is_completed===true,...Cr(e)}}var Tt=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 Xi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return vu(i)}catch{return o??null}}};var Ct=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 u=s.filledAt;if(u!==void 0&&(o===void 0||this.clock.now()-u<=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(u=>(i&&this.generation===d&&(l.value=u,l.filledAt=this.clock.now()),u)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(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 Mr(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 Or(t){try{let e=Mr(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var ie=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},_u=3e4,Vs="the save payload could not reach storage. From a browser this is almost always the storage account's CORS rule, which the platform owns and your game cannot change. If every save fails this way, report it rather than working around it",wu=/^[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(!wu.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Ws(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 Lr(t,e){return t.aborted&&e?.aborted!==true}var Su=new Set(["x-ms-blob-type"]),Ru=/^[ -~]+$/;function ku(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new ie("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(!Su.has(i))throw new ie("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"||!Ru.test(o))throw new ie("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 ie("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);n[i]=o;}return n}function Gr(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 Dr(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 ie("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 ie("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=Ws(r.signal,i);try{let s=await Ps(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 ie("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=ku(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(u){throw Lr(a.signal,r.signal)?this.timeout("upload",i):new ie("upload_failed",`${Vs} for PUT. Underlying error: ${u}`)}if(!d.ok){let u=await Or(d);throw new ie("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+u:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+u)}return Gr(await Ui(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 ie("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=Ws(n.signal,r);try{let i;try{let l=await kr(this.api,this.entity.type,this.entity.id,ke(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(Dr(l))return null;throw l}if(typeof i.download_url!="string")throw new ie("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 Lr(o.signal,n.signal)?this.timeout("download",r):new ie("download_failed",`${Vs} for GET. Underlying error: ${l}`)}if(!s.ok){let l=await Or(s);throw new ie("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 kr(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?Gr(r.body):null}catch(r){if(Dr(r))return null;throw r}}async list(e={}){let n=await bs(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}}),r=n.next_cursor;return {saves:(n.data??[]).map(Gr),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await ji(this.api,this.entity.type,this.entity.id,ke(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Dr(r))throw r}}budget(e){return e??this.options.timeoutMs??_u}timeout(e,n){return new ie("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,o,i){return e instanceof ie?e:Lr(r,n)?this.timeout(o,i):e}};function xu(t){try{return Rr(t)}catch{return t}}function $r(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"?xu(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var Mt=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await fs(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>$r(o)):[]}async get(e,n={}){try{let r=await Wi(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?$r(r.body,r.etag):null}catch(r){if(Ks(r))return null;throw r}}async put(e,n,r={}){let o=await Rs(this.api,this.entity.type,this.entity.id,e,{value:yt(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return $r(o)}async delete(e,n){try{await Fi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!Ks(r))throw r}}};function Ks(t){return t?.reason==="not_found"}function Ot(t,e,n={}){let r=new Ct(le,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let o=new kt(t,e,r);return {settings:new Mt(t,e),inventory:o,saves:new It(t,e,n.saves??{}),currencies:new Rt(o,n.resolveCurrencyId),mutations:new Pt(t,e,r),orders:new Et(t,e),progressions:new Tt(t,e,o)}}var Fr={type:"players",id:"me"};var Ne=t=>typeof t=="string"?t:"",ln=t=>typeof t=="number"?t:0;function Lt(t,e){let n=e??{},r=Ne(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:Ne(n.player_id),gameId:Ne(n.game_id),channel:Ne(n.channel)||"release",name:Ne(n.name),slotIndex:ln(n.slot_index),isActive:n.is_active!==false,createdAt:Ne(n.created_at),updatedAt:Ne(n.updated_at)}}var Gt=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=Ot(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 ys(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>Lt(this.scope,o)):[]}async get(e,n){let r=await Hi(this.api,e,n===void 0?{}:{signal:n});return Lt(this.scope,r)}async create(e){let n=await Gi(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Lt(this.scope,n)}async update(e,n,r){let o=await As(this.api,e,{name:n},r===void 0?{}:{signal:r});return Lt(this.scope,o)}async delete(e,n){await Ts(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await ls(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 me=class{#e;constructor(e){this.#e=e,Object.freeze(this);}toString(){return "[gem: use gem.text.toPlain()]"}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function ge(t){return new me(t)}var Ue={toPlain(t){return me.unwrap(t)},compare(t,e,n){let r=t instanceof me?me.unwrap(t):t,o=e instanceof me?me.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 me?me.unwrap(t):t,r=e instanceof me?me.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var dn=t=>typeof t=="string"?t:"";function Dt(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:ge(n)},createdAt:dn(e.created_at),expiresAt:dn(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Au(){return crypto.randomUUID()}var $t=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 us(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:Au()},e.signal===void 0?{}:{signal:e.signal});return Dt(n)}async list(e={}){let r=await _s(this.api,{entity_type:this.self.type,entity_id:this.self.id,...e.direction===void 0?{}:{direction:e.direction},...e.status===void 0?{}:{status:e.status},...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(Dt):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await ds(this.api,e,n===void 0?{}:{signal:n});return Dt(r)}async accept(e,n){return this.resolve(()=>Ii(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>xs(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>Oi(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Dt(await e())}};var Pu=t=>typeof t=="string"?t:"",Eu=t=>typeof t=="string"&&t?t:void 0,Tu=t=>typeof t=="number"?t:void 0;function Js(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 Cu(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new de("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 de("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Tu(e.version);if(r===void 0)throw new de("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let u=Pu(l.id);if(!u)throw new de("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return u},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:Js(i),currency:Js(a)}}var de=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},zs=10*1024*1024,Ys=15e3,Xs=new Set(["dev","test","release"]);function Iu(t){if(!Xs.has(t))throw new de("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Xs].join(", ")}. gem-api would reject the assignment read.`);return t}var Ft=t=>typeof t=="number"?t:0,jr=t=>typeof t=="string"?t:"";function Mu(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:jr(o.entry_id),weight:Ft(o.weight),dropRate:Ft(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:jr(e.loot_table_id),name:jr(e.name),rollCount:Ft(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Ft(e.total_weight),entries:n}}var jt=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 de("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 Vi(this.api,e,n===void 0?{}:{signal:n});return Mu(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??Ys),n;try{let l=await Bi(this.api,Iu(this.channel()),{signal:e});if(!l.modified)throw new de("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof de)throw l;if(l?.reason==="not_found")return null;throw l}let r=Eu(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 de("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??Ys}ms`):new de("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=>Mr(d)).catch(()=>"");throw new de("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let a=await i.text();if(a.length>zs)throw new de("config_too_large",`the config document is ${a.length} bytes, over the ${zs} cap`);let s;try{s=JSON.parse(a);}catch(l){throw new de("config_malformed",`config document is not JSON: ${String(l)}`)}return Cu(s)}};var Qs=400,xe=t=>typeof t=="string"?t:"",Ou=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Be(t){let e=xe(t);if(!Ou.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Lu=/^[0-9a-f]{1,64}$/,Gu=/^[0-9a-f]{16}$/,Du=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,$u=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function qr(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 Fu=4096,ju=new TextEncoder;function qu(t){let e=xe(t.challenge_data),n=xe(t.challenge_data_hash);return e===""||!Gu.test(n)?{}:ju.encode(e).length>Fu?{}:{data:e,dataHash:n}}function Nu(t){let e=t??{},n=Be(e.period_start_at),r=Be(e.period_ends_at);if(n===0||r===0)return;let o=xe(e.slug),i=xe(e.seed),a=qr(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:Du.test(s)?s:"",resetTime:$u.test(l)?l:"",seed:Lu.test(i)?i:"",...qu(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 qt(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Nu).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 gs(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return qt(r)}};function He(t){return typeof t=="string"&&t!==""?t:void 0}var Zs=new Set(["localhost","127.0.0.1","[::1]"]);function Nr(t){let e=He(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:"&&Zs.has(n.hostname)))return e}function Uu(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},o=He(r.item_id),i=Nr(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function _e(t){let e=t??{},n=He(e.player_id),r=He(e.display_name),o=He(e.discriminator),i=He(e.display_tag),a=He(e.avatar_icon_id),s=Nr(e.avatar_icon_url);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:ge(r)},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:ge(i)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:Uu(e.badges)}}var Bu=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Hu(t){if(t===void 0)return;let e=Nr(t);if(e===void 0)return;let n=new URL(e);return Zs.has(n.hostname)||Bu.has(n.origin)?e:void 0}var ea=100,ra=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Ur(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"||!ra.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 oa(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!ra.test(e))return;let n=qr(t.period_local_date),r=Be(t.period_start_at),o=Be(t.period_ends_at),i=r>0&&o>0;return {id:e,...n===void 0?{}:{localDate:n},...i?{startAt:r,endsAt:o}:{},opensAt:Be(t.opens_at),closesAt:Be(t.closes_at),final:t.final===true}}var Tn=t=>typeof t=="string"?t:"",un=t=>typeof t=="number"?t:0,Cn=t=>typeof t=="string"?t:void 0,Vu=t=>typeof t=="number"?t:void 0,ia={player:"players",character:"characters"};function Wu(t,e){let n=t??{},r=Cn(n.entity_id),o=typeof n.entity_type=="string"&&Object.hasOwn(ia,n.entity_type)?n.entity_type:void 0,i=sa(n.stats),a=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,s=e?n.is_viewer===true:void 0;return {..._e(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 na(t,e){let n=t??{},r=Cn(n.bucket_1),o=Cn(n.bucket_2),i=Vu(n.update_frequency_seconds),a=oa(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=>Wu(s,e)):[],generatedAt:un(n.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...a===void 0?{}:{period:a}}}function ta(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=sa(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 sa(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 Ku(t,e,n){let r=t??{},o=Cn(r.bucket_1),i=Cn(r.bucket_2),a=oa(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(ta).filter(s=>s!==void 0):[],personalBest:ta(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 In=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=Ur(n),o=await ts(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 na(o,false)}async friends(e,n={}){let r=Ur(n),o=await es(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return na(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>ea)throw new TypeError(`limit must be an integer between 1 and ${ea}, got ${String(l)}`)}let i=Ur(o),a=await zi(this.#e,e,ia[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 Ku(a,n,s)}};var Nt=t=>typeof t=="string"?t:"",Br=t=>typeof t=="number"?t:0;function aa(t){let e=t??{};return {playerId:Nt(e.player_id),key:Nt(e.key),value:e.value,updatedAt:Br(e.updated_at)}}function Ju(t){let e=t??{};return {..._e(e),playerId:Nt(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Br(e.updated_at)}}function zu(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 ns(this.api,ke(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:Nt(o.key),entries:Array.isArray(o.entries)?o.entries.map(Ju):[],generatedAt:Br(o.generated_at)}}async of(e,n,r={}){try{return aa(await as(this.api,e,ke(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(zu(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 aa(await ks(this.api,o,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await qi(this.api,r,ke(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var Ve=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});}},la=t=>typeof t=="string"?t:void 0;function Yu(t){let e=t??{};return {..._e(e),playerId:la(e.player_id)??""}}function Xu(t){let e=t??{},n=e.has_more===true?la(e.next_cursor):void 0;return {friends:Array.isArray(e.data)?e.data.map(Yu):[],...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 vs(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Xu(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 Zu=12e4,da=8,em=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,nm=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Ln(t,e,n={}){return new Ve(new G("invalid",400,e,void 0,t),n)}function tm(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function rm(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!em.test(e))return {error:Ln("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!nm.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(!tm(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>da?{error:Ln("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(da)}`)}:{playerId:e,template:n,params:o}}function om(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 Ve(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 Ve(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 im(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function ca(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=rm(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??Zu);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 (${im(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(om(n));}}}var Ut=t=>typeof t=="string"?t:void 0;function sm(t){let e=t??{},n=Ut(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Ut(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Bt=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await ht(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=sm(i);a!==void 0&&o.push(a);}return o}},Hr=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function am(t){let e=t??{},n=Ut(e.currency_id);if(n===void 0||n==="")return;let r=Hr(e.limit),o=Math.min(Hr(e.earned),r),i=Math.min(Hr(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:Ut(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 ua(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 Ht=class{#e;#t;#l;constructor(e,n,r){this.#e=e,this.#t=n,this.#l=r;}async get(e={}){let r=(await rs(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=am(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 Bt(e),this.earnAllowance=new Ht(e,n,r);}};var Vr=t=>typeof t=="string"?t:"",ma=t=>typeof t=="number"?t:0;function lm(t){let e=t??{};return {key:Vr(e.key),visibility:Vr(e.visibility),value:e.value,updatedAt:ma(e.updated_at)}}function dm(t){let e=t??{};return {..._e(e),playerId:Vr(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(lm):[],generatedAt:ma(e.generated_at)}}function cm(t){return t?.reason==="not_found"}var Dn=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return dm(await os(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(cm(r))return null;throw r}}};var um=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:um.get(this.code))??super.retryable}},De=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=mm(e),o;try{o=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(i){throw i instanceof G?gm(i):i}return pm(o)}};function mm(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 re(`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 re(`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 pm(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 gm(t){let{details:e,invocationId:n}=Ci(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 ym=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Wr="gem_";function pa(t){return t.startsWith(Wr)}var ga=1e4,ya=50,fm=500,hm=65536-4*1024,bm=24*1024;function fa(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 ha=t=>typeof t=="number"?t:0,vm=t=>typeof t=="string"?t:"";function Kr(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function _m(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:ha(i.index),code:vm(i.code)}}):[];return {accepted:ha(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Jr(){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 wm(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(ga,e.options?.flushIntervalMs??ga),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??fm));}track(e,n={}){if(!(!this.#t||this.#r)){if(pa(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,fa({...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 Kr();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.")),Kr();if(this.#k(),this.#n.length===0)return Kr();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:Jr(),sent_at_ms:a,events:o.map(d=>ba(d,a))},l={client:this.#e.client(),gameId:()=>n};this.#v=true;try{let d=await cs(l,s,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=_m(d,i);return this.#P(m),m}catch(d){throw wm(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,fa(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:Jr(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#n.length>=ya?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:Jr(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#n.length>=ya?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?bm:hm,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(ba(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}). `+Sm(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 ba(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function Sm(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 ue(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=ue(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Rm=2e3,km=5e3;function _a(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=u=>{d||(d=true,r=null,t.clock.clearTimeout(m),l(u));},m=t.clock.setTimeout(()=>{n=true,a([]);},t.timeoutMs??Rm);});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 !va(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??km);})},accept(a,s){let l=jn(s),d=ue(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[u,p]of [...o])va(m,p)||u(m);}}}}function va(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var xm=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=xm.has(n),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var wa=["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"],Am=new Set(wa);function $e(t){return typeof t=="string"&&Am.has(t)?t:"unknown"}var Vt="webrtc_dedicated",Qr=["universal","mobile","web"];var Pm="p2p_unavailable",Em="capacity_unavailable",Tm=2,Sa=3e4,Ra=1e3,ka=2e4;async function Zr(t){let e=ue(t.clusterTargetId),n=t.nextClusterTarget,r=0,o=t.clock??le,i=t.retry??{},a=i.budgetMs??Sa,s=i.maxDelayMs??ka,l=i.initialDelayMs??Ra,d=o.now(),m=d+a,u=0;for(;;){u++;try{let p=await ro(t.signal,"while allocating",()=>t.client.post(`${Pa(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Cm(p)||a<=0)throw p;if(p.status===503&&p.code===Pm)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===Em?r+1:0,n!==void 0&&r>=Tm){let I=n;n=void 0;let M=ue(await I());M!==void 0&&(e=M,r=0);}let g=Math.min(s,l*2**(u-1)),f=Math.min(s,(p.retryAfterSeconds??0)*1e3),R=Math.max(g/2,f)+Math.random()*(g/2);if(o.now()+R>m)throw Im(t,p,u,o.now()-d,a);if(i.onWaiting?.({attempt:u,elapsedMs:o.now()-d,budgetMs:a,nextAttemptInMs:R,status:p.status,message:p.message}),await Wt(o,R,t.signal),t.signal?.aborted)throw Xr("while waiting to allocate")}}}function Cm(t){return t instanceof G?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function Im(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 Mm=12e4,Om=1e3;async function eo(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??Om,o=t.timeoutMs??Mm,i=e.now()+o,a=xa(t),s={seen:t.knownToExist===true};for(;;){let l=await Aa(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 Wt(e,r,t.signal);}}async function no(t){return (await Aa(t,xa(t),{seen:t.knownToExist===true})).outcome}function xa(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Pa(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function Aa(t,e,n){let{matchId:r}=t,o=t.clock.now(),i;try{i=await ro(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:Lm(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 to(t){let e=await ro(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 ro(t,e,n){if(t?.aborted)throw Xr(e);try{return await n()}catch(r){throw t?.aborted?Xr(e,r):r}}function Xr(t,e){return new b("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function Lm(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 Pa(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Wt(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 Ea(t){return typeof t=="string"&&t.trim()!==""}function Kt(t,e){return Ea(t)?t.trim():Ea(e)?e:null}var Jt="0.1.0-beta",Ta="0-beta",mn="web",Gm=/^(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 Dm(t){let e=Gm.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Ca(t,e){let n=$m(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:Jt};let o=Dm(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 '${Jt}' for it.`);if(o!==Ta)throw new b("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${Ta}' 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 '${Jt}' for it.`);return {...t,platform:n,engineVersion:r}}function $m(t,e){if(t===void 0||t===mn)return mn;if(!Qr.includes(t))throw new b("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${Qr.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 Fm="join",jm="welcome",qm="rejected",Ia=25e3,Nm=1e3,oo=1;function io(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var Um={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 so(t){let e=typeof t=="string"?t:"unknown";return new b(Um[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??Ia),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,Nm)),l=R=>{let I=R.data;if(typeof I!="string"){u(I);return}let M;try{M=JSON.parse(I);}catch{u(I);return}if(i){u(I);return}if(M.t===jm){let _=io(M.heartbeat_interval);f({...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===qm){w(so(M.reason));return}u(I);},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"));},u=R=>{i&&t.onMessage?.(R);},p=()=>{n.clearTimeout(s),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},f=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:Fm,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:oo}:{}}));}catch(R){w(new b("connection_failed",`the join frame could not be sent on the open channel: ${String(R)}`,{cause:R}));}})}var We=1,Nn=2,ao=4,uo=8,Bm=2,Hm=1e3,mo="heartbeat timeout",Un="gem-uu",zt=2,Oa="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();!Vm(r)||e.includes(r)||e.push(r);}return e}function Vm(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function Bn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Oa];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 Yt(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var La=new TextEncoder,Ga=new TextDecoder;function po(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function go(t){let e=0;return t?.reliable===false&&(e|=We),t?.ordered===false&&(e|=Nn),e}function yo(t){return {reliable:(t&We)===0,ordered:(t&Nn)===0}}var fo={reliable:true,ordered:true};function Da(t){return JSON.stringify({t:"join",credential:t,wire:zt,heartbeat:oo})}function $a(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=io(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"?so(e.reason):new b("join_refused","the server answered the join out of protocol")}function Xt(){return typeof globalThis.WebTransport=="function"&&ho===null}function Qt(){return ho}var ho=null;var Ma="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Wm(t){let e=ft(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 lo=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 co(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:Wm(t.certHashBase64)}]});}let r=n,o=s=>{try{r.close();}catch{}throw s},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(ho=Ma,o(new b("connection_failed",`${Ma}; 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(co(ao,La.encode(Da(t.credential))));let u=new lo,p=d.readable.getReader(),g;for(;g===void 0;){let f=await Promise.race([p.read(),a]);if(f.done||f.value===void 0)return o(new b("connection_failed","the control stream closed before the join was answered"));for(let w of u.push(f.value)){g=$a(Ga.decode(w.payload));break}}return {link:Km(r,m,p,u,t.log??(f=>console.warn(f)),ja(g,t.clock)),welcome:g}}catch(s){return o(s)}}function Km(t,e,n,r,o,i){let a,s,l=false,d=f=>{if(!l){l=true,m.stop();try{t.close();}catch{}s?.(f);}},m=vo(i,()=>d(mo)),u=(f,w)=>{m.heard(),(f&uo)===0&&a!==void 0&&((f&ao)!==0?a(Ga.decode(w),fo):a(w,yo(f)));};(async()=>{try{for(;;){let f=await n.read();if(f.done||f.value===void 0)break;for(let w of r.push(f.value))u(w.flags,w.payload);}}catch{}d("stream closed");})();let p,g;try{let f=t.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let w=f.readable.getReader();g=f.writable.getWriter(),p=f,(async()=>{try{for(;;){let R=await w.read();if(R.done||R.value===void 0)break;let I=R.value;I.byteLength!==0&&u((I[0]??0)|We|Nn,I.slice(1));}}catch{}})();}else o("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(f){p=void 0,g=void 0,o(`[gem] webtransport datagram lane unusable (${Yt(f)}); unreliable sends ride the stream`);}return t.closed.then(f=>d(Fa(f?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(f,w){if(l)return;if(typeof f=="string"){e.write(co(ao,La.encode(f))).catch(()=>d("write failed"));return}let R=go(w);if((R&We)!==0&&g!==void 0){let I=po(R,f),M=p?.maxDatagramSize;if(M===void 0||I.byteLength<=M){g.write(I).catch(()=>{});return}}e.write(co(R,f)).catch(()=>d("write failed"));},onMessage(f){a=f;},onClose(f){s=f;},close(){d("closed");}}}function bo(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(Da(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 f;try{f=$a(g.data);}catch(w){l(w);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",u),r.removeEventListener("error",p),o({link:Jm(r,ja(f,t.clock)),welcome:f});},u=()=>{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",u),r.addEventListener("error",p),r.readyState===1&&d();})}function Fa(t){return typeof t=="string"&&t.length>0?t:void 0}function ja(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function vo(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,Hm)*Bm,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 Jm(t,e){let n,r,o=false,i=s=>{if(!o){o=true,a.stop();try{t.close();}catch{}r?.(s);}},a=vo(e,()=>i(mo));return t.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){n?.(s.data,fo);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&uo)===0&&n?.(l.slice(1),yo(d));})),t.addEventListener("close",(s=>i(Fa(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!o){if(typeof s=="string"){t.send(s);return}t.send(po(go(l),s));}},onMessage(s){n=s;},onClose(s){r=s;},close(){i("closed");}}}function _o(t,e,n,r){let o,i,a=false,s=n,l=u=>{if(!a){a=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}i?.(u);}},d=vo(r,()=>l(mo)),m=(u,p)=>{if(d.heard(),typeof u=="string"){o?.(u,fo);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let f=g[0]??0;(f&uo)===0&&o?.(g.slice(1),yo(f|p));};if(t.addEventListener("message",(u=>m(u.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),s!==void 0){let u=s;u.addEventListener("message",(p=>m(p.data,We|Nn))),u.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(u,p){if(a)return;if(typeof u=="string"){t.send(u);return}let g=go(p),f=po(g,u);if((g&We)!==0&&s!==void 0&&s.readyState==="open"){s.send(f);return}t.send(f);},onMessage(u){o=u;},onClose(u){i=u;},close(){l("closed");}}}function Ro(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let o=wo(r);o!==void 0&&(e[n]=o);}return e}function ko(t){if(Array.isArray(t))return t.map(zm).filter(e=>!!e)}function wo(t){if(So(t)||Array.isArray(t)&&t.every(So))return t}function So(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function zm(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=wo(e.fixed),r=wo(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...n===void 0?{}:{fixed:n},...r===void 0?{}:{default:r},...gn("description",Ym(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(So)?{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 Ym(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=J(e.id)??J(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(qa):[];return {id:n,gameId:J(e.game_id)??"",name:J(e.name)??"",status:J(e.status)??"open",hostPlayerId:J(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...we("joinCode",J(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...we("roomArgs",Ro(e.room_args)),...we("roomArgsTemplate",ko(e.room_args_template)),gameChannel:J(e.game_channel)??"release",...we("region",J(e.region)),...we("clusterTargetId",J(e.cluster_target_id)),selfHosted:e.self_hosted===true,...we("matchId",J(e.match_id)),version:Pe(e.version)??0,...we("templateId",J(e.template_id)),roomType:J(e.game_room_type)??"Standard",...we("transports",pn(e.transports)??void 0),createdAt:Pe(e.created_at)??0,updatedAt:Pe(e.updated_at)??0,...we("startedAt",Pe(e.started_at))}}function qa(t){let e=t??{};return {..._e(e),playerId:J(e.player_id)??"",isReady:e.is_ready===true,role:J(e.role)??"member",joinedAt:Pe(e.joined_at)??0,...we("groupId",J(e.group_id)),...we("platform",J(e.platform))}}function Zt(t){let e=t??{};return {id:J(e.id)??J(e.game_room_id)??"",gameId:J(e.game_id)??"",name:J(e.name)??"",status:J(e.status)??"open",hostPlayerId:J(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:J(e.game_channel)??"release",roomType:J(e.game_room_type)??"Standard",createdAt:Pe(e.created_at)??0}}function J(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 we(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(Zt),...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(Zt)}))}create(e,n,r){return Xm(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},...er(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},...er(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},...er(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}:{},...er(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 er(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function Xm(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 Zm=1e3,ep=3e3,np=6e4,tp=2,Na=new Set(["game_room_closed","game_room_gone"]),rp=12e4,op=5e3,ip=new Set(["invalid_cluster_target","capacity_unavailable"]),sp=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Ao(t){return new xo(t)}var xo=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||lp(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(()=>no({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=ue(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,u)=>Zr({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(u)}:{},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||!Ba(m))throw m;let u=await this.nextCluster([a],true);if(u===void 0)throw m;return s(u,[a,u])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new 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 eo({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:n,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(n),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new b("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!Na.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(!Ke()){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<Zm){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(!Ke()){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(()=>no({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,!Na.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||!ip.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&&Ke())){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(),!!Ke())){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 nr)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 nr)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??op}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=Kt(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 Ca({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return jn(await this.options.resolveClusterTargets());let e=ue(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Ba(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"||!sp.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=ap(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??rp;return new Promise((o,i)=>{let a=u=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),u();},s=this.emitter.on("matchAllocationStarted",u=>a(()=>o(u))),l=this.emitter.on("matchFailed",(u,p)=>a(()=>i(new b("allocation_failed",`match ${u} 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??ep}pushedInterval(){return this.options.pushedPollIntervalMs??np}pushed(){return this.options.clock.now()-this.lastPushAt<tp*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 Ke(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var nr=["visibilitychange","focus","pageshow","online"];function ap(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||Ua(t)!==Ua(e)}function Ua(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Ba(t){return t instanceof G&&t.code==="invalid_cluster_target"}function lp(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var dp=["p2p","dedicated","unknown"],Po=["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=cp(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 cp(t,e,n){let r=Math.floor(n/1e3);return t.filter(o=>Po.includes(o.type)).slice(0,100).map(o=>{let i=up(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function up(t){if(t!==void 0)return dp.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:tr(o.credential)??"",hostFingerprint:tr(o.host_fingerprint)??"",hostEpoch:rr(o.host_epoch)??0,expiresAt:(rr(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(u=>typeof u=="string"&&u.length>0);m.length!==0&&i.push({urls:m,username:tr(d.username)??"",credential:tr(d.credential)??""});}let a=rr(o.expires_at),s=rr(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 tr(t){return typeof t=="string"&&t.length>0?t:void 0}function rr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var mp=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),L=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="P2pError",this.retryable=mp.has(n);}reason;retryable};var Ha=10240,Va=2048,pp=new TextEncoder;function Wa(t){return pp.encode(t).length}function Fe(t,e){let n=o=>{throw new b("invalid_sdp",`the ${e} ${o}`)},r=Wa(t);r>=Ha&&n(`is ${r} bytes, over the ${Ha} 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=Wa(o);i>Va&&n(`has a ${i}-byte line, over the ${Va} limit`);}}function or(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 ir=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 gp=/^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=sr(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function sr(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 gp.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 Eo=5e3,yp=12e4+Eo,fp=1024,hp=6e4,bp=1e4,Ka=64*1024,Ja=5;function To(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 L("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return s},a=async()=>{if(!o.ok)throw new L("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(bp)});}catch{throw new L("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 L("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>Ka)throw new L("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${Ka} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof L?p:new L("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>Ja)throw new L("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Ja} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=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 f=await u.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,f);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!o.ok)throw new L("keys_unavailable",o.reason);if(r)return await r,e.get(s)??null;let d=t.now();if(!Number.isFinite(d))throw new L("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<n&&(n=-1/0),d-n<hp?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>=fp){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+yp),true}};function Ya(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 za(t){try{let e=new TextDecoder().decode(Ya(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Co(t,e,n,r,o){let i=D=>{throw new L("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=za(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 u=m.kid;(typeof u!="string"||u.length===0)&&i("it names no key");let p=await n.key(u);p===null&&i("it was signed by a key this build cannot resolve");let g=o.subtle??globalThis.crypto?.subtle;g||i("this environment has no WebCrypto");let f=new TextEncoder().encode(`${s}.${l}`),w;try{w=Ya(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,w,f)||i("its signature does not verify");let I=za(l);I===null&&i("its payload does not decode");let M=I,_=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 E=S("exp")*1e3,A=S("nbf")*1e3;(!Number.isFinite(E)||e.now>E+Eo)&&i("it has expired"),Number.isFinite(A)&&e.now<A-Eo&&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 q=sr(_("fingerprint"));q===null&&i("its fingerprint claim is malformed"),zn(q,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let k=sr(_("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 C=_("jti");C.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(C,e.now)||i("it has already been used");let O=_("sub");return O.length===0&&i("it names no player"),{playerId:O.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:N,role:V,fingerprint:q,hostFingerprint:k,jti:C,expiresAt:E}}function Io(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 Mo(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 Oo(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function Lo(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 Xa(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 Qa(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 Go={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}},Ie=["reliable","ordered","unreliable"];function Do(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 el=1,Rp=3e4,nl=2e3,kp=5e3,tl=6e4,xp=8,Fo=class{constructor(e=xp){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;}},Ap=new Fo,Pp=8,Ep=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??To({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new ir;links=new Map;replays=new Yn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=el+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??Rp;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),o=ue(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: ${$o(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 L("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 L("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 L("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,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=se(e.playerId),r=se(e.hostPlayerId),o=ar(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,el),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new L("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 L("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??Ap,a=()=>this.closed||e!==this.credentialGeneration,s=kp;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,u;if(m===409)u=nl;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=s,s=Math.min(s*2,tl)),u=Math.min(Math.max(u,nl),tl);}else throw d;if(!await this.waitForCredential(u,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=se(e.fromPlayerId),r=se(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=Pp){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=se(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 L("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 L("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=se(e.fromPlayerId),r=se(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 L("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 L("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let 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=se(e.fromPlayerId),r=se(e.candidate);if(n===null||r===null)return;let o=this.links.get(n);if(!o)return;let i=se(e.sdpMid),a=ar(e.sdpMLineIndex)??ar(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=se(e.playerId);if(n===null)return;let r=se(e.reason)??"left";if(n===this.localPlayerId){this.fail(new L("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=se(e.hostPlayerId),r=ar(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:n,hostEpoch:r,...se(e.reason)===null?{}:{reason:se(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 L("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 L("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let n=se(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new L("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=se(e.code)??"unknown",r=se(e.message)??"the platform refused a signaling message";this.report_(new L("signaling_failed",`${n}: ${r}`));}openLink(e,n){let o=(this.options.peerConnectionFactory??Do)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of Ie){let g=o.createDataChannel(p,Go[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));},u=()=>{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",u),i.reliable.addEventListener("message",m),a.detachHandshake=()=>{i.reliable.removeEventListener("open",u),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 L("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 L("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(Io({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=Lo(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 L(Qa(r.reason),Xa(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 Co(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 L&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",$o(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(Mo({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(Oo(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 Ie)rl(e.channels[o]);rl(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 L?e:new L("connection_failed",$o(e),{cause:e}));}count(e){this.counted||!Ep.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(or(e))throw new L("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 se(t){return typeof t=="string"&&t.length>0?t:null}function ar(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function $o(t){return t instanceof Error?t.message:String(t)}function rl(t){try{t.close();}catch{}}var Tp=100,Cp=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??Tp)){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 L("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new L("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId: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??Cp));}};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 ol(t){return typeof t=="boolean"?t:void 0}var ye=B(64),tt=je(0,2147483647);function jo(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=ye(n);typeof r=="string"&&e.push(r);}return e}function K(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 Op=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:[K("sdp","sdp",B(10240)),K("signaling_intent","intent",hn("initial","ice_restart","full_reconnect")),H("sdp_hash","sdpHash",B(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[K("peer_id","peerId",ye),K("sdp","sdp",B(10240)),K("assigned_peer_id","assignedPeerId",je(0,4294967295)),H("sdp_hash","sdpHash",B(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[K("peer_id","peerId",ye),K("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:[K("host_epoch","hostEpoch",tt)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[K("host_epoch","hostEpoch",tt),H("evidence","evidence",Op)]}}));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:[K("playerId","player_id",ye),K("hostPlayerId","host_player_id",ye),K("hostEpoch","host_epoch",tt),H("members","members",jo)],offer:[K("fromPlayerId","from_player_id",ye),K("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:[K("fromPlayerId","from_player_id",ye),K("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:[K("fromPlayerId","from_player_id",ye),K("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:[K("playerId","player_id",ye)],peerLeft:[K("playerId","player_id",ye),H("reason","reason",B(64))],migration:[K("hostPlayerId","new_host_player_id",ye),K("hostEpoch","host_epoch",tt),H("reason","reason",B(64)),H("kickedPlayerIds","kicked_player_ids",jo),H("migrationComplete","migration_complete",ol)],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 ze="webrtc_p2p";function sl(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 L("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let o=ue(r.clusterTargetId),i=o??ue(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!==ze)throw new L("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${ze}'. 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 al(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(!Ke());for(let d of nr)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(!Ke());}let a=new Map;return i.push(n.on("matchReady",s=>{let l=s.protocol===ze?"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 ll=["pointerdown","keydown"];function dl(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 ll)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(f=>f?.buttons.some(w=>w.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},u=()=>{if(o=null,!(n||r)){if(d()){s();return}m()&&(o=e.requestAnimationFrame?.(u)??null);}};function p(){o===null&&!n&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of ll)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(o=e.requestAnimationFrame?.(u)??null);}return {get engaged(){return n},stop:a}}async function lr(t,e,n,r){let o=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),o}function qo(t,e){let n=false;return async r=>{let o=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),o}}function No(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 Uo=false;async function pl(t,e,n,r){if(Uo){e.close(),n("busy",true);return}Uo=true;let o=null;try{let i=await Gp(t,r);if(typeof i=="string"){e.close(),n(i,Lp(i));return}o=i;let s=await(r.encodeRef??(l=>jp(l,r)))(o);if(o.close(),o=null,s===null){e.close(),n("failed",!0);return}if(s.size>Fp){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{Uo=false,o?.close();}}function Lp(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 Gp(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":cl(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=$p(n);if(!r)return "no_source";let o=Dp(r);if(o!==null)return o;try{return cl(await createImageBitmap(r),t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}function Dp(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 $p(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 cl(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 Fp=8*1024*1024,ul="image/webp",ml=.92;async function jp(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:ul,quality:ml});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),ul,ml);})}async function gl(t,e){if(!e)return;let n;try{n=await qp(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 qp(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 yl=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function fl(t=globalThis){let n=t[yl];if(n!==void 0)return n;let r=false,o=()=>r,i=[],a=Np(t,o);a!==null&&i.push(a);let s=Up(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 u of i)u();}}};return Object.defineProperty(t,yl,{value:l,configurable:true}),l}function Np(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 u=m.gain,p=m.context.currentTime;u.cancelScheduledValues(p),e()?u.setValueAtTime(0,p):u.setTargetAtTime(1,p,.01);},d=m=>{let u=m.context;if(o!==void 0&&u instanceof o)return null;let p=s.get(u);return p===void 0&&(p=u.createGain(),p.gain.value=e()?0:1,i.call(p,m),s.set(u,p)),p};return n.connect=function(...u){let[p,...g]=u;if(p instanceof r){let f;try{f=d(p);}catch{f=null;}if(f!==null)return i.call(this,f,...g),p}return i.apply(this,u)},n.disconnect=function(...u){let[p,...g]=u;if(p instanceof r){let f=s.get(p.context);if(f!==void 0&&f!==this)try{return a.call(this,f,...g)}catch{}}return a.apply(this,u)},()=>{for(let[m,u]of s){if(m.state==="closed"){s.delete(m);continue}try{l(u);}catch{}}}}function Up(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,u=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),u(this);}}),r.play=function(){try{u(this);}catch{}return s.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{u(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 Bp=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Hp=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Vp=`${Bp}${Hp}`,Bo=new WeakSet;function hl(t=globalThis.document){if(t==null||Bo.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(Vp),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],Bo.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"),Bo.add(t),"inline")}catch{return null}}function bl(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,u=()=>{s=null,l=null,d=[];},p=w=>{if(a=null,!m()){u();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(Wp(d,R)),s=w,d=[]);}g();},g=()=>{let w=n.requestAnimationFrame;typeof w=="function"&&(a=w.call(n,p));},f=()=>{if(m()){a===null&&(u(),g());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),u();};return {setRequested(w){r=w,f();},setPaused(w){o=w,f();},get running(){return a!==null},dispose(){i=true,f();}}}function Wp(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 dr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function _l(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function wl(t,e){t!==null&&(t.style.setProperty(dr.top,`${e.top}px`),t.style.setProperty(dr.right,`${e.right}px`),t.style.setProperty(dr.bottom,`${e.bottom}px`),t.style.setProperty(dr.left,`${e.left}px`));}var vl=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 Sl(){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 Kp(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 Rl(t,e,n){if(t===null)return;let r=Kp(e,n);for(let o of ["tl","tr","bl","br"])t.style.setProperty(vl[o].width,`${r[o].width}px`),t.style.setProperty(vl[o].height,`${r[o].height}px`);}var Jp=3e4,cr=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function kl(t){let e=t.clock??le,n=t.timeoutMs??Jp,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,u)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(s),u(new cr("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:u,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 cr(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.9.1/gem-web-sdk.devtools.min.js",integrity:"sha384-jZUCZvoobGUVHiuFD3kx35yN9IR+luuU0L0xAaPl4iY5t2LocNUhDV0vfGvZ0TMZ"};var vn=null;function zp(){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 xl(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 zp();return !e()||a!==r?false:(n!==null||(n=s.mount(t(),{openedBy:i,text:Ue,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 Yp=1e4,Al={reason:"unavailable",retryable:false};function Pl(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??Yp);},a=(d,m)=>{let u=s(d);u&&m(u);},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,u)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){u(Al);return}let g=`t${++o}`,f={resolve:m,reject:u,reason:d,timer:null,held:p!=="connected"};e.set(g,f),i(g,f),f.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let 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,u=>u.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,u]of e)u.held&&(u.held=false,t.clock.clearTimeout(u.timer),i(m,u),t.bridge.requestToken(m,u.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])a(m,u=>u.reject(Al));},get identity(){return n},get gameVersion(){return r}}}function Xp(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var Qp=new Set(gt);function Zp(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))Qp.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function ur(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return Pi(async(n,r)=>{let o;try{o=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new re("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 re(`${JSON.stringify(typeof n.path=="string"?Xp(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 re(`${JSON.stringify(i.pathname)} resolves to ${i.protocol}//${i.host}, not ${o.protocol}//${o.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(i.username!==""||i.password!==""){let g=o.username!==""||o.password!=="",f=i.username!==o.username||i.password!==o.password,w=g?f?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new re(`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,f]of Object.entries(t.defaultQuery??{}))i.searchParams.has(g)||i.searchParams.set(g,f);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 re(`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},...Zp(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"),u=eg(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...u===void 0?{}:{retryAfterSeconds:u},...p===null||p===""?{}:{invocationId:p}}},t)}function eg(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 ng=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Vo="embedder_relay_unavailable",tg="embedder_no_relay",rg=new Set([Vo]),Wo=new Set([tg]),ot=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Ho(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(og(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 og(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new b(ig(t),r,{platformCode:t})}function ig(t){return t===void 0||rg.has(t)?"signaling_failed":Wo.has(t)?"offer_refused":ng.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Ho=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 El="match_ended:",Tl="server_shutdown:",Cl="kicked:",sg=123;function ag(t){if(typeof t!="string"||t.length===0||t.length>sg)return {kind:"other"};if(t.startsWith(El)){let e=$e(t.slice(El.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Tl)?{kind:"server_shutdown",cause:t.slice(Tl.length)}:t.startsWith(Cl)?{kind:"kicked",detail:t.slice(Cl.length)}:{kind:"other"}}function Ko(t,e,n){let r=ag(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 Jo(){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 lg=3e3,dg=1e4,cg=15e3;async function mr(t){let e=t.peerConnection;try{Ml(t,"before the handshake started"),zo(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 pg(e,t),zo(t);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new b("invalid_sdp","the offer carried no SDP");Fe(o,"offer"),Il(o,"offer");let i=await mg(t,o);if(zo(t),typeof i?.sdp!="string")throw new b("invalid_sdp","the signaling channel answered without an SDP");return Fe(i.sdp,"answer"),Il(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await gg(n,t),Ml(t,"before the channel opened"),n}catch(n){throw e.close(),ug(n)}}function ug(t){return t instanceof b?t:Gl(t)?Ye():new b("connection_failed",Dl(t),{cause:t})}function Il(t,e){if(or(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 mg(t,e){let n=t.exchangeTimeoutMs??dg,r=Ll(t,n),o=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(i=>{throw i instanceof b?i:Gl(i)?Ye():new b("signaling_failed",Dl(i),{cause:i})});return yg(o,t,r,()=>r.exhausted?Yo("while the offer was in flight"):new b("timeout",`no answer arrived within ${n}ms`))}function pg(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??lg);t.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function gg(t,e){if(e.signal?.aborted)return Promise.reject(Ye());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??cg,o=Ll(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",Ol(g)===void 0?void 0:{cause:Ol(g)}));},m=()=>{s(),a(Ye());},u=()=>{s(),a(o.exhausted?Yo("while the channel was still opening"):new b("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(u,o.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Ll(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 yg(t,e,n,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(Ye()):new Promise((a,s)=>{let l=u=>{o.clearTimeout(m),i?.removeEventListener("abort",d),u();},d=()=>l(()=>s(Ye())),m=o.setTimeout(()=>l(()=>s(r())),n.ms);i?.addEventListener("abort",d),t.then(u=>l(()=>a(u)),u=>l(()=>s(u)));})}function Ml(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw Yo(`already ${e}`)}function Yo(t){return new b("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function zo(t){if(t.signal?.aborted)throw Ye()}function Ye(){return new b("aborted","the caller aborted the connection attempt")}function Gl(t){return t?.name==="AbortError"}function Ol(t){return t?.error}function Dl(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:[K("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 Hl(t){let{client:e,clock:n,rooms:r}=t,o=t.signaling??Jo,i=t.log??(_=>console.warn(_)),a=new yn({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(_,S)=>{let E=s.get(_)??new Set;E.add(S),s.set(_,E);},d=(_,S)=>{let E=s.get(_);E!==void 0&&(E.delete(S),E.size===0&&s.delete(_));},m=async _=>{if(r.isHost&&!Qo(r)&&r.currentRoom?.matchId===void 0){let S=ue(_.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},..._.retry===void 0?{}:{retry:_.retry},..._.signal===void 0?{}:{signal:_.signal}});}return Ul(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Xo(_)):await r.awaitMatch(Xo(_)))},u=async _=>Ul(await r.pollMatchStatus(Xo(_))),p=async(_,S)=>{let E=false;try{let A=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??Bl();E=!0;let q=await mr({peerConnection:N,signaling:S,clock:n,matchId:A.matchId,credentialExpiresAt:A.credentialExpiresAt,...pr(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),k=null;if(_.presentCredential!==!1)try{k=await qn({channel:q,clock:n,credential:A.joinCredential,credentialExpiresAt:A.credentialExpiresAt,...pr(_,"onMessage","signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(C){throw Se(q),Se(N),C}return kg(r,A,q,N,S,_.reportDisconnect!==!1,_.reportConnected!==!1,k,{remember:l,forget:d},_.onMatchEnded)}catch(A){throw E&&Nl(a,A),Se(S),A}},g=async(_,S,E,A,V,N)=>{if(_==="webtransport"){let F=A?.webtransport;if(F===void 0)throw new b("misconfigured","webtransport is not advertised");let W={credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n};if(typeof F.named_url=="string"&&F.named_url!==""){let Q=Math.max(Math.floor(N/2),1e3);try{return await Hn({url:F.named_url,timeoutMs:Q,log:i,...W})}catch(pe){if(Qt()!==null)throw pe;return i(`[gem] webtransport named dial failed (${Yt(pe)}); retrying the pinned dial`),Hn({url:F.url,certHashBase64:F.cert_sha256_b64,timeoutMs:Q,log:i,...W})}}return Hn({url:F.url,certHashBase64:F.cert_sha256_b64,timeoutMs:N,...W})}if(_==="websocket"){let F=A?.websocket;if(F===void 0)throw new b("misconfigured","websocket is not advertised");return bo({url:F.url,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n,timeoutMs:N})}let q=S.peerConnection??Bl(),k,C=await mr({peerConnection:q,signaling:V,clock:n,matchId:E.matchId,credentialExpiresAt:E.credentialExpiresAt,extraChannels:[{label:Un,ordered:false,maxRetransmits:0}],onExtraChannel:(F,W)=>{F===Un&&(k=W);},...pr(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:bg}:{}}),O;try{O=await qn({channel:C,clock:n,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,wire:zt,heartbeat:!0,...pr(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(F){throw Se(C),Se(q),F}let D=O.welcome.heartbeatIntervalMs;return {link:_o(C,q,k,D===void 0?void 0:{clock:n,intervalMs:D}),welcome:O.welcome,channel:C,peerConnection:q}},f=(_,S,E,A,V)=>{let N=false,q;A.link.onClose(D=>{!N&&_.reportDisconnect!==false&&Ko(r,S.matchId,D),q?.(D);}),_.reportDisconnect!==false&&_.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let k={transport:A.link.transport,send:(D,F)=>A.link.send(D,F),onMessage:D=>A.link.onMessage(D),onClose:D=>{q=D;},close:()=>A.link.close()},C=()=>{N||(N=true,Se(A.link),Se(V));},O=D=>{if(!N){try{_.onMatchEnded?.(D);}catch{}C();}};return l(S.matchId,O),{matchId:S.matchId,transport:E,link:k,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:A.welcome,...A.channel===void 0?{}:{channel:A.channel},...A.peerConnection===void 0?{}:{peerConnection:A.peerConnection},close(){d(S.matchId,O),C();}}},w=async(_,S)=>{let E=r.currentRoom?.id,A=r.gameId,V=()=>({advert:Bn(r.currentRoom?.settings,_),template:r.currentRoom?.transports??null});if(E===void 0||A===null)return V();try{let N=await e.get(`/v2/games/${encodeURIComponent(A)}/game-rooms/${encodeURIComponent(E)}`,S);return {advert:Bn(N.settings,_),template:pn(N.transports)??r.currentRoom?.transports??null}}catch{return V()}},R=(_,S)=>{let E=_??$l;return S.length===0?E:E.filter(A=>S.includes(A))},I=async(_,S,E)=>{try{let A=await m(_),{advert:V,template:N}=await w(A.matchId,_.signal),q=R(N,S),k=q.filter(z=>wg(z,V)),C=Qt();if(C!==null&&q.includes("webtransport")&&V?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${C} (learned on an earlier dial in this page)`),k.length===0){let z=N===null?`the default order (${$l.join(", ")})`:`the room template's transports (${N.join(", ")||"none"})`;throw new b("misconfigured",`none of ${z}`+(S.length>0?`, narrowed to (${S.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let O=_.transportAttemptTimeoutMs??hg,D=()=>_.deadlineAt===void 0?1/0:_.deadlineAt-n.now(),F=z=>t.signalingReady===void 0||z<=0?Promise.resolve(!0):t.signalingReady(z),W=[],Q=[];for(let z of k){if(D()<jl){i(`[gem] ${z} rung not tried: the reconnect budget is spent`);break}Q.length>0&&A.credentialExpiresAt-n.now()<ql&&(A=await u(_)),Q.push(z);let Me=!1,Ce=!1,be={attempts:0,waitedMs:0};for(;;){if(z==="webrtc"&&_.redial===!0){let ee=Math.min(Fl,D());await F(ee)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(ee)}ms; offering anyway`);}let Oe=Math.max(Math.min(O,D()),jl);try{return f(_,A,z,await g(z,_,A,V,E,Oe),E)}catch(ee){let X=ee instanceof b?ee:new b("connection_failed",ee instanceof Error?ee.message:String(ee),{cause:ee});if(z==="webrtc"&&Nl(a,X),(X.reason==="credential_expired"||X.reason==="credential_reused")&&!Me){Me=!0,A=await u(_);continue}if(z==="webrtc"&&X.reason==="signaling_failed"&&X.platformCode===Vo&&!Ce){Ce=!0;let ae=Math.min(Fl,D());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ae)}ms for the socket before offering again`),await F(ae))continue}if(X.reason==="join_rate_limited"){let ae=_g(be,Math.random,D());if(ae!==null){if(be.attempts+=1,be.waitedMs+=ae,i(`[gem] ${z} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ae)}ms before presenting again (retry ${be.attempts} of ${Wl.maxAttempts})`),await Wt(n,ae,_.signal),_.signal?.aborted)throw new b("aborted","the caller aborted while waiting out a join rate limit");A.credentialExpiresAt-n.now()<ql&&(A=await u(_));continue}}if(vg.has(X.reason)||X.reason==="credential_expired"||z==="webrtc"&&Vl(X)){i(`[gem] ${z} rung failed (${X.reason}): ${Yt(X.cause??X)} \u2014 `+(Q.length<k.length?`falling through to ${k[Q.length]}`:"no rungs left")),W.push(X);break}throw i(`[gem] ${z} rung refused the session (${X.reason}): ${X.message}`),X}}}let pe=W[W.length-1];throw pe===void 0?new b("timeout",`the reconnect budget ran out before any transport (${k.join(", ")}) could be tried`):new b(pe.reason,`every transport tried (${Q.join(", ")}) failed; the last said: ${pe.message}`,{cause:W,platformCode:pe.platformCode})}catch(A){throw Se(E),A}};return {listClusterTargets:async(_={})=>to({client:e,..._}),handleMatchEnded(_,S){let E=s.get(_);if(E!==void 0){s.delete(_);for(let A of E)A(S);}},connect:(async(_={})=>{let S=_.signaling??o();return _.transports===void 0?p(_,S):I(_,_.transports,S)})}}var $l=["webtransport","webrtc","websocket"],hg=1e4,bg=5e3,Fl=3e3,jl=1e3,ql=1e4,vg=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Vl(t){return t.platformCode!==void 0&&Wo.has(t.platformCode)}var Wl={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function _g(t,e=Math.random,n=1/0){let r=Wl;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 wg(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Xt():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||Sg(e.websocket.url)}function Sg(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return St(e)}function Xo(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var Rg=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Nl(t,e){e instanceof b&&(!Rg.has(e.reason)&&!Vl(e)||t.report([{type:"connection_failures_total",value:1}]));}function kg(t,e,n,r,o,i,a,s,l,d){let m=false,u=()=>{m||Ko(t,e.matchId,void 0);};i&&(n.addEventListener("close",u),a&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",u),s?.detach(),Se(n),Se(r),Se(o));},g=f=>{if(!m){try{d?.(f);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function Qo(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Ul(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!==Vt)throw new b("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Vt}' 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 Bl(){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 Se(t){try{t.close();}catch{}}function pr(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var xg=1e4;function Kl(t,e){return Zo(t,e)}function Zo(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??xg);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 ni={};Id(ni,{acceptTransfer:()=>Ag,addEntityProgression:()=>Pg,adminAction:()=>Eg,cancelInventoryTransfer:()=>Tg,claimEntityProgressionRewards:()=>Cg,closeGameRoom:()=>Ig,createEntityBatchOrder:()=>Mg,createEntityOrder:()=>Og,createSession:()=>Lg,deleteEntityGameSetting:()=>Gg,deleteEntitySave:()=>Dg,deleteSession:()=>$g,deleteShowcaseValue:()=>Fg,executeEntityRecipe:()=>jg,finalizeSaveUpload:()=>qg,getChannelAssignment:()=>Ng,getDropRates:()=>Ug,getEntityCurrency:()=>Bg,getEntityGameSetting:()=>Hg,getEntityInventory:()=>Vg,getEntityInventoryItem:()=>Wg,getEntityLeaderboard:()=>Kg,getEntityOrder:()=>Jg,getEntityProgression:()=>zg,getEntityRecipeAvailability:()=>Yg,getEntityRecipeUsage:()=>Xg,getEntitySave:()=>Qg,getEvent:()=>Zg,getGameRoomV2:()=>ey,getLeaderboard:()=>ny,getPlayerGameProfile:()=>ty,getPurchaseCatalog:()=>ry,getResolvedTemplate:()=>oy,getRoomArgs:()=>iy,getShowcaseValue:()=>sy,getTransferDetails:()=>ay,ingestAnalyticsEvents:()=>ei,initiateInventoryTransfer:()=>ly,invokeFunction:()=>dy,kickPlayer:()=>cy,listChallenges:()=>uy,listEntityGameSettings:()=>my,listEntityOrders:()=>py,listEntityProgressions:()=>gy,listEntitySaves:()=>yy,listEvents:()=>fy,listGameRooms:()=>hy,listResolvedTemplates:()=>by,listTransfers:()=>vy,maxEntityProgression:()=>_y,putEntityGameSetting:()=>wy,putRoomArgs:()=>Sy,putShowcaseValue:()=>Ry,rejectTransfer:()=>ky,requestSaveUploadUrl:()=>xy,resetEntityProgression:()=>Ay,simulateEntityOrder:()=>Py,transferHostV2:()=>Ey,updateGameRoomV2:()=>Ty});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 Ag(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 Eg(t,e,n,r){let o=`/v1/voice/sessions/${h(e)}/admin`;return t.client.post(o,n,r?.signal)}async function Tg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Cg(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 Ig(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.delete(r,n?.signal)}async function Mg(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 Og(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 Lg(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Gg(t,e,n,r,o){let i=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(i,o?.signal)}async function Dg(t,e,n,r,o){let i=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(i,o?.signal)}async function $g(t,e,n){let r=`/v1/voice/sessions/${h(e)}`;return t.client.delete(r,n?.signal)}async function Fg(t,e,n,r){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.delete(o,r?.signal)}async function jg(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 qg(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 Ng(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 Ug(t,e,n){let r=`/v1/inventory/loot-tables/${h(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Bg(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 Hg(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 Vg(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 Wg(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 Kg(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 Jg(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 zg(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 Yg(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 Xg(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 Qg(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 Zg(t,e,n){let r=`/v1/events/${h(e)}`;return t.client.get(r,n?.signal)}async function ey(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 ny(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 ty(t,e,n){let r=`/v1/profiles/players/${h(e)}`;return t.client.get(r,n?.signal)}async function ry(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 oy(t,e,n){let r=`/v1/game-room-templates/${h(e)}`;return t.client.get(r,n?.signal)}async function iy(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 sy(t,e,n,r){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.get(o,r?.signal)}async function ay(t,e,n){let r=`/v1/inventory/transfers/${h(e)}`;return t.client.get(r,n?.signal)}async function ei(t,e,n){let r=`/v1/games/${h(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true})}async function ly(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function dy(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function cy(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 uy(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 my(t,e,n,r){let o=`/v1/settings/${h(e)}/${h(n)}`;return t.client.get(o,r?.signal)}async function py(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 gy(t,e,n,r){let o=`/v1/inventory/${h(e)}/${h(n)}/progressions`;return t.client.get(o,r?.signal)}async function yy(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 fy(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 hy(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 by(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function vy(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 _y(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 wy(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 Sy(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 Ry(t,e,n,r,o){let i=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.put(i,r,o?.signal)}async function ky(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function xy(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 Ay(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 Ey(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 Ty(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 Cy=1e4,Iy=50,My=1e3,Oy=65536-4*1024,Jl=t=>typeof t=="number"?t:0,Ly=t=>typeof t=="string"?t:"";function zl(){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 Gy(t){return t?.retryable===true}function Dy(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:Jl(i.index),code:Ly(i.code)}}):[];return {accepted:Jl(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Yl(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 Xl(t){let e=Math.max(1,Math.floor(t.maxQueue??My)),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);},u=()=>{i!==null&&(t.clock.clearTimeout(i),i=null);},p=()=>{i!==null||a||s||(i=t.clock.setTimeout(()=>{i=null,f().catch(()=>{});},Cy));},g=()=>{let w=Math.min(r.length,100),R=128;for(let I=0;I<w;I+=1){let M=r[I];if(M===void 0)break;if(R+=JSON.stringify(Yl(M,0)).length+1,R>Oy)return Math.max(1,I)}return w};async function f(w){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};u();let R=r.splice(0,g()),I=o;o=0;let M=Math.round(t.clock.now()),_={batch_id:zl(),sent_at_ms:M,events:R.map(S=>Yl(S,M))};s=true;try{let S=await ei(n,_,w===void 0?void 0:{signal:w}),E=Dy(S,I);for(let A of E.rejected)m(`[gem] analytics: an event was refused (${A.code}). See the analytics_events section of your game config.`);return E}catch(S){if(Gy(S))for(r=[...R,...r],o+=I;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,I={}){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(Wr)){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,E]of Object.entries(I))typeof E=="string"?M[S]=E:typeof E=="number"&&Number.isFinite(E)&&(_[S]=E);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:zl(),playerId:w,name:R,atMs:t.clock.now(),dimensions:M,measures:_}),r.length>=Iy?f().catch(()=>{}):p();},flush:w=>f(w),get pending(){return r.length},dispose(){a=true,u(),r=[],o=0;}}}function Ql(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 qt(i)}}}function $y(t){let e={};for(let[n,r]of Object.entries(ni))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=Zo(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=ur({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=$y({client:a,gameId:()=>s.gameId}),d=s.gameRoomId,m=t.endMatch,u=t.log,p=Xl({client:a,clock:n,gameId:s.gameId,...typeof u=="function"?{log:f=>u.call(t,f)}:{}});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:Ql(l.listChallenges),...d===void 0?{}:{room:{get:f=>l.getGameRoomV2(d,f),args:async f=>{let w=await l.getGameRoomV2(d,f?.signal===void 0?{}:{signal:f.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 Xe(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 gr(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 Fy=5e3,Zl=3e4,ed=2e3,jy=1e4,nd=1;async function td(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?y=>console.info(y):e.log,i=y=>o?.(`[gem host] ${y}`),a=typeof t=="function"?t():t,s=Promise.resolve(),l=true,d=false,m=(y,T)=>{l&&(s=s.then(async()=>{if(!d)try{await T();}catch(j){i(`the bundle's ${y} handler threw: ${Qe(j)}. Serving continues.`);}}));},u=true,p,g,f,w=y=>{if(!u)return;u=false,m("leave",()=>a.leave?.(r,{cause:y??"left"}));let T=g;T&&queueMicrotask(()=>T(y));},R={send(y,T){if(!u)return;let j=wn(Xe(T));m("message",()=>a.message?.(r,y,typeof y=="string",{reliable:j.reliable,ordered:j.ordered}));},onMessage(y){p=y;},onClose(y){g=y;},close(){w("closed");}},I=(y,T)=>{if(!u)return;let j=wn(Xe(T));queueMicrotask(()=>{u&&p?.(y,j);});},M=new Map,_=y=>{let T=[];for(let j of Ie){let ne=y.channels[j];try{ne.binaryType="arraybuffer";}catch{}let ve=wn(j),qe=ct=>{let Y=gr(ct?.data);Y!==null&&m("message",()=>a.message?.(y.playerId,Y.data,Y.isText,{reliable:ve.reliable,ordered:ve.ordered}));};ne.addEventListener("message",qe),T.push(()=>ne.removeEventListener("message",qe));}M.get(y.playerId)?.forEach(j=>j()),M.set(y.playerId,T);},S=y=>{M.get(y)?.forEach(T=>T()),M.delete(y);},E=new Set,A=new Map,V=(y,T,j)=>({playerNumber:y.assignedPeerId,transport:"webrtc_p2p",...T?{rejoin:true}:{},...j?{superseded:true}:{}}),N=y=>{let T=M.has(y.playerId),j=E.has(y.playerId);E.add(y.playerId),_(y),T&&m("leave",()=>a.leave?.(y.playerId,{cause:"superseded"})),m("join",()=>a.join?.(y.playerId,V(y,j,T)));},q=new Set,k=(y,T,j)=>{if(y===r){I(T,j);return}let ne=n.peer(y);if(ne===null){let ve=A.get(y);if(ve!==void 0&&e.clock.now()-ve<ed)return;q.has(y)||(q.add(y),i(`send to '${y}' dropped: no such connected player`));return}ne.send(it(T),Xe(j));},C={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:y=>e.tokens.subscribe(y),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(y=>y.playerId)??[],players(){let y=u?[r]:[];for(let T of n.peers)y.push(T.playerId);return y},profile(y){let T=e.room()?.members.find(j=>j.playerId===y);if(!(!T||T.displayName===void 0))return {displayName:Ue.toPlain(T.displayName),...T.displayTag===void 0?{}:{displayTag:Ue.toPlain(T.displayTag)},...T.discriminator===void 0?{}:{discriminator:T.discriminator}}},playerNumber(y){return y===r?nd:n.peer(y)?.assignedPeerId},send(y,T,j){k(y,T,j);},broadcast(y,T){let j=T?.except;u&&r!==j&&I(y,T);for(let ne of n.peers)ne.playerId!==j&&ne.send(it(y),Xe(T));},async endMatch(){let y=await Oe();return y.answer!=="ok"&&i(y.cause),y.answer},kick(y,T){if(y===r){w(T??"kicked");return}n.kick(y).catch(j=>{i(`kick of '${y}' failed: ${Qe(j)}`);});},log(y){i(y);},warn(y){i(`\u26A0 ${y}`);}},O=()=>{},D=new Promise(y=>{O=y;}),F=[],W=null,Q=async(y,T)=>{l=false;let j=s.then(async()=>{try{await a.shutdown(y);}catch(ne){i(`the bundle's shutdown threw: ${Qe(ne)}`);}});s=j,await j,ae();for(let ne of F.splice(0))ne();for(let ne of [...M.keys()])S(ne);w(T);},pe=(y,T)=>W||(W=(async()=>{await Q(T,y),n.close(),O();})(),W),z=()=>W||(W=(async()=>{await Q({reason:"signal"},"left"),await n.leave().catch(y=>i(`leaving the match failed: ${Qe(y)}`)),O();})(),W),Me=()=>W||(W=(async()=>{l=false;let y=await Oe();y.answer==="ok"?(await Q({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(i(`${y.cause}; leaving instead`),await Q({reason:"signal"},"left"),await n.leave().catch(T=>i(`leaving the match failed: ${Qe(T)}`))),O();})(),W),Ce=null,be=()=>(Ce??=_n(C,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),Ce),Oe=async()=>{try{return await ws({client:be().client,gameId:()=>C.gameId},C.matchId,{},{signal:AbortSignal.timeout(Fy)}),{answer:"ok"}}catch(y){return y instanceof G&&(y.reason==="forbidden"||y.reason==="not_found")?{answer:y.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${y.reason})`}:{answer:"failed",cause:`ending the match failed: ${Qe(y)}`}}},ee=null,X=false,ae=()=>{X=true,ee!==null&&(e.clock.clearTimeout(ee),ee=null);},dt=async()=>{if(ee=null,!X){try{await be().client.post(`/v1/games/${encodeURIComponent(C.gameId)}/matches/${encodeURIComponent(C.matchId)}/heartbeat`,void 0,AbortSignal.timeout(jy));}catch(y){if(y instanceof G&&(y.reason==="forbidden"||y.reason==="not_found")){i(`the platform no longer holds this match under this host (${y.reason}); heartbeats stop`),ae();return}i(`heartbeat failed: ${Qe(y)}`);}X||(ee=e.clock.setTimeout(()=>{dt();},Zl));}},Sn=()=>{X||ee!==null||(ee=e.clock.setTimeout(()=>{dt();},Zl));};{let y=O;O=()=>{ae(),Ce?.dispose(),Ce=null,y();};}let en=Promise.resolve().then(()=>a.init(C));s=en.then(()=>{},()=>{}),m("join",()=>a.join?.(r,{playerNumber:nd,transport:"loopback"})),F.push(n.on("peerJoined",N)),F.push(n.on("peerLeft",(y,T)=>{S(y);let j=e.clock.now();for(let[ne,ve]of A)j-ve>=ed&&A.delete(ne);A.set(y,j),q.delete(y),m("leave",()=>a.leave?.(y,{cause:T}));})),F.push(n.on("error",y=>{i(`\u26A0 session error: ${y.message}`);})),F.push(n.on("matchEnded",y=>{W||ti(f,y),pe("match ended",{reason:"match_ended",platform_reason:y});})),F.push(n.on("hostChanged",y=>{y!==r&&pe("host migrated",{reason:"host_migrated"});}));for(let y of n.peers)N(y);try{await en,Sn();}catch(y){l=false,ae(),d=true;for(let T of F.splice(0))T();for(let T of [...M.keys()])S(T);throw n.leave().catch(()=>{}),O(),y}return {matchId:n.matchId,localLink:R,onMatchEnded(y){f=y;},end:Me,leave:z,stop:y=>pe(y,{reason:"stopped"}),done:D}}function ti(t,e){try{t?.(e);}catch{}}function Qe(t){return t instanceof Error?t.message:String(t)}function ri(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 rd(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,o=new Map,i=async s=>{r.isHost&&!Qo(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!==ze)return ri("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return ri("peer",d.matchId);let u=t.identity();if(u===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(a(l)),g=await td(s,{session:p,clock:t.clock,gameId:u.gameId,channel:u.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:u.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return o.set(d.matchId,g),g.done.then(()=>{o.get(d.matchId)===g&&o.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(s={}){let l=await i(s),d=s.onMatchEnded;if(l.protocol===ze){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),By(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let f=await Qn(),w=async()=>t.p2p.connect({...a(s),certificate:f}),R=await w(),I=Vy(R,w,d,M=>{r.notifyMatchDisconnected(M).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(R.matchId,{redial:I.redial,abandon:I.abandon}),I.onClosed(()=>{e.get(R.matchId)?.abandon===I.abandon&&e.delete(R.matchId);})),I}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??[]}),u=await m(),p=Hy(u,m,r,n);return n&&(e.set(u.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(u.matchId)?.abandon===p.abandon&&e.delete(u.matchId);})),p},async redialMatch(s,l){let d=e.get(s);return d===void 0?"closed":d.redial(l)},abandonMatch(s,l){e.get(s)?.abandon(l);}}}var od="link_closed",qy="host_unreachable",Ny=new Set(["failed","closed"]);function Uy(t){return Ny.has(t)?od:qy}function By(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 Hy(t,e,n,r){let o=t.matchId,i=t,a="connected",s,l,d=[],m=false,u=false,p=f=>{if(a!=="closed"){a="closed";for(let w of d.splice(0))w();l?.(f);}},g=f=>{f.link.onMessage((w,R)=>s?.(w,R)),f.link.onClose(w=>{if(f!==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(f,w){a==="connected"&&i.link.send(f,w);},onMessage(f){s=f;},onClose(f){l=f;},close(){if(a!=="closed"){if(m=true,a==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(f){if(a==="closed"||m)return "closed";if(u)return "connected";u=true;let w;try{w=await e(f===void 0?{}:{deadlineAt:f});}finally{u=false;}return m||a==="closed"?(w.close(),"closed"):(i=w,g(w),a="connected",n.notifyMatchConnected(o),"connected")},abandon(f){a!=="closed"&&(a==="connected"&&i.close(),p(f));},onClosed(f){a==="closed"?f():d.push(f);}}}function Vy(t,e,n,r,o,i=false){let a=t.matchId,s=t,l,d,m=[],u=[],p=[],g=false,f=false,w=false,R=false,I="connected",M=k=>{if(g)return;g=true,I="closed";for(let O of m.splice(0))O();for(let O of u.splice(0))O();for(let O of p.splice(0))O();let C=d;C&&queueMicrotask(()=>C(k));},_=k=>{for(let C of m.splice(0))C();for(let C of Ie){let O=k.channels[C];try{O.binaryType="arraybuffer";}catch{}let D=wn(C),F=W=>{let Q=gr(W?.data);Q!==null&&l?.(Q.data,D);};O.addEventListener("message",F),m.push(()=>O.removeEventListener("message",F));}},S=()=>s.peer(s.hostPlayerId),E=k=>{if(!(g||s.isHost)&&I!=="suspended"){if(r?.(k),i){I="suspended";return}M(k);}},A=k=>{for(let C of Ie){let O=k.channels[C];if(typeof O.addEventListener!="function")continue;let D=()=>{S()===k&&E(od);};O.addEventListener("close",D),m.push(()=>O.removeEventListener?.("close",D));}},V=k=>{_(k),A(k),!g&&(I="connected",o?.());},N=k=>{for(let C of u.splice(0))C();u.push(k.on("migrating",()=>{R=true;})),u.push(k.on("hostChanged",C=>{if(R=false,C===k.playerId){M("host_migrated_here");return}let O=S();O!==null&&V(O);})),u.push(k.on("peerJoined",C=>{C.playerId===k.hostPlayerId&&V(C);})),u.push(k.on("matchEnded",C=>{g||ti(n,C),M(C);})),u.push(k.on("peerLeft",(C,O)=>{C===k.hostPlayerId&&E(Uy(O));}));};N(s);let q=S();return q!==null&&V(q),{matchId:a,protocol:"p2p",get state(){return I},send(k,C){I==="connected"&&S()?.send(it(k),Xe(C));},onMessage(k){l=k;},onClose(k){d=k;},close(){f=true,M("closed"),s.leave().catch(()=>{});},async redial(){if(I==="closed")return "closed";if(I==="connected"||w)return "connected";if(R)throw new L("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");w=true;let k;try{for(let O of m.splice(0))O();for(let O of u.splice(0))O();s.close(),k=await e();}finally{w=false;}if(g)return f?k.leave().catch(()=>{}):k.close(),"closed";s=k,N(s);let C=S();if(C===null)throw s.close(),new L("connection_failed","this peer rejoined the match but the host never answered with a link");return V(C),"connected"},abandon(k){M(k);},onClosed(k){g?k():p.push(k);}}}function oi(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 Wy=12e4;function Ze(t,e){return {outcome:t,reason:e}}function id(t){let e=false,n=new Map;return {api:{request(r){if(!t.bridge.parentSupports("purchases"))return Promise.resolve(Ze("unavailable","error"));if(e)return Promise.resolve(Ze("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(Ze("unavailable","error")),t.timeoutMs??Wy);let l=false;try{l=t.bridge.requestPurchase(o,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||s(Ze("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(Ze(o,qs(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(Ze("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(Ze("unavailable","error"));})();}}}async function sd(t,e){try{return (await ss(t,e)).granted?"granted":"absent"}catch(n){return n instanceof G&&n.reason==="not_found"?"absent":"unknown"}}var Ky=6e5;function ad(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??Ky);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 Jy=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid"]),zy=["utm_"];function ld(t){return Jy.has(t)||zy.some(e=>t.startsWith(e))}var dd=16,cd=512,Yy=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Xy=/[\p{Cc}\p{Cf}]/u,Qy=/\p{Cs}/u,Te="[gem] gem.share.request:";function ud(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(!Zy(l))throw new TypeError(`${Te} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>dd)throw new TypeError(`${Te} at most ${dd} params; got ${d.length}`);let m=[];for(let[u,p]of d){let g=JSON.stringify(u);if(!Yy.test(u))throw new TypeError(`${Te} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(ld(u))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>cd)throw new TypeError(`${Te} param ${g}: a value is at most ${cd} characters`);if(Xy.test(p))throw new TypeError(`${Te} param ${g}: control and format characters are not allowed`);if(Qy.test(p))throw new TypeError(`${Te} param ${g}: a value must be well-formed text`);m.push({key:u,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 Zy(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var ef=18e4,md=32,nf=/^[a-z0-9_-]+$/;function tf(t){return t==="interstitial"||t==="rewarded"}function pd(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>md||!nf.test(r.placement)||!tf(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(md)} 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=u=>{n.delete(o)&&(e=false,t.clock.clearTimeout(l.timer),s(u));};e=true,n.set(o,d),l.timer=t.clock.setTimeout(()=>{d({outcome:"unavailable"});},t.timeoutMs??ef);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 ii=16384;function gd(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:rf(e)}function rf(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 of=1e4,sf=5e3;function yd(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=sf){return n?Promise.resolve(e):new Promise(s=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,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=gd(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 u={},p=f=>{o.delete(d)&&(t.clock.clearTimeout(u.timer),f==="stored"&&(e=l,n=true,i()),m(f));};o.set(d,p),u.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??of);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 fd(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function si(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 yr(t,e){let n=[];for(let r of Array.isArray(e)?e:[]){if(n.length===4)break;if(typeof r!="object"||r===null)continue;let{id:o,label:i}=r;typeof o!="string"||o.length===0||o.length>32||typeof i!="string"||i.trim().length===0||n.some(a=>a.id===o)||n.push({id:o,label:i.trim().slice(0,40)});}return n.length===0?{settings:t===true}:{settings:t===true,items:n}}function hd(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function af(t){let e=t.untrusted,n=ge(e.displayName),r=e.displayTag||e.displayHandle,o=r?ge(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})),u=m.some(p=>p.multiplier>1);return l.boost=u&&d?.expiresInDays?{active:u,multipliers:m,expiresInDays:d.expiresInDays}:{active:u,multipliers:m},l}var lf=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=>Er(s,e.origin))||Ds(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=wt["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!Er(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=$s(vt,o.versions);return a===null?(i.onmessage=null,i.postMessage({gem:U,type:"gem.error",code:"version_mismatch",message:`frame supports v${vt.min}..v${vt.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:U,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:U,type:"gem.ready"});}settled(e=lf){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:U,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:U,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:U,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:U,type:"gem.exit"}:{gem:U,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:U,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:U,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:U,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:U,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let n={gem:U,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(n.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(n.origin={x:fd(e.origin.x),y:fd(e.origin.y)}),this.send(n),true}setWalletVisible(e,n){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:U,type:"gem.walletDisplay",...si(e,n?.only)})}setMenu(e,n){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:U,type:"gem.menu",...yr(e,n)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:U,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:U,type:"gem.frameStats",fps:hd(e.fps,1e3),frameTimeP95Ms:hd(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:U,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:U,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:U,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:U,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,o,i,a){return this.send({gem:U,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:U,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:U,type:"gem.requestAd",requestId:e,placement:n,format:r})}requestSignIn(e){return this.send({gem:U,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,o){return this.send({gem:U,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(_t)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(_t)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(_t)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:U,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}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=wt[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||bd(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=wt[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=Os(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.menuSelect":this.options.onMenuSelect?.(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 bd(n.slice(1)),this.options.onScreenshot(d,l,(m,u)=>this.screenshotDenied(m,u)),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?.(af(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:U,type:"gem.screenshot.denied",reason:e,retryable:n});}};function bd(t){for(let e of t)try{e?.close?.();}catch{}}var vd="https://api.gemarcade.com";function ai(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 df=new Set(["localhost","127.0.0.1","[::1]"]);function _d(t){let e=ai(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!df.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 cf=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),uf=vd,wd=8e3,li=15e3,mf=9e4,pf=1/0,gf=8e3,yf=5e3,ff=5e3;async function hf(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 JS(t={}){let e=t.clock??le,n=t.log===void 0?c=>console.info(c):t.log,r=t.baseUrl??void 0;if(r!=null){let c=ai(r);if(c!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${c}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let o=No();o.mark("sdk created");let i=()=>Kt(Y.gameVersion,t.clientVersion?.gameVersion),a=new Fn({client:()=>tn,clock:e,gameId:()=>Y.identity?.gameId??null,playerId:()=>Y.identity?.playerId??null,environment:()=>{let c=i();return {sdk_version:xi(),...c===null?{}:{game_version:c}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),s=dl(()=>{o.mark("engaged"),a.release(),y.reportEngaged();},typeof window>"u"?{}:window),l=c=>{if(c===false)return null;let x=c?.attempts??pf,$=c?.budgetMs??mf;return !(x>0)||!($>0)?null:{attempts:x,budgetMs:$,maxDelayMs:c?.maxDelayMs??gf}},d=c=>{c.on("created",()=>{o.mark("room created");}),c.on("joined",()=>{o.mark("room joined");}),c.on("matchAllocationStarted",()=>{o.mark("allocation started");}),c.on("matchReady",()=>{o.mark("match ready");}),c.on("matchFailed",()=>{o.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new 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 u=Array.from(m??[]),p=u.filter(c=>typeof c!="string"||!Pr(c));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(c=>typeof c=="string"?JSON.stringify(c):String(c)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let g=Object.freeze([...new Set([...cf,...u])]),f=lt(e),w=lt(e),R=lt(e),I=ua(n),M=lt(e),_=t.manageAudio===false?null:fl();t.selectableText!==true&&hl();let S=null,E=()=>{S!==null&&(w.current!==null&&w.current.muted===S||y.reportMuted(S));},A=null,V=null,N=()=>{if(A===null)return false;let c=JSON.stringify(si(A.visible,A.only));return c===V?y.parentSupports("walletDisplay"):y.setWalletVisible(A.visible,A)?(V=c,true):false},q=null,k=null,C=()=>{if(q===null)return false;let c=typeof q.onSettings=="function",x=JSON.stringify(yr(c,q.items));return x===k?y.parentSupports("gameMenu"):y.setMenu(c,q.items)?(k=x,true):false},O=bl({report:c=>y.reportFrameStats(c)}),D=false,F=xl(()=>wi,()=>D),W=c=>{let x=D&&!c,$=D!==c;if(D=c,x&&F.close(),!!$)try{t.onDevToolsPermissionChange?.(c);}catch(te){n?.(`[gem] onDevToolsPermissionChange threw: ${te instanceof Error?te.message:String(te)}`),queueMicrotask(()=>{throw te});}},Q=r??uf,pe=r!==void 0,z,Me=c=>(n?.(`[gem] token refused: ${c}`),t.onError?.("internal",c),false),Ce=(c,x)=>{if(c===void 0)return x!==void 0?Me("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 $=_d(c);return $!==null?Me(`the embedder named an API root that cannot be used: ${$}. Its value is withheld here rather than written to logs.`):z!==void 0&&z!==c?Me("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(z=c,pe||(Q=c),true)},be=window.location?.origin,Oe=null,ee=-1/0,X=2e3,ae=new Set,dt=c=>Oe!==false?Promise.resolve(true):new Promise(x=>{let $=e.setTimeout(()=>{ae.delete(te),x(false);},c),te=()=>{e.clearTimeout($),ae.delete(te),x(true);};ae.add(te);}),Sn=()=>{},en=null,y=new at({allowedEmbedders:g,...typeof be=="string"&&be!==""?{selfOrigin:be}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","earnAllowance","share","frameStats","walletDisplay","gameMenu","engagement","reservedAreas","viewport","purchases","deviceSettings","ads","signIn","friendChallenges",...t.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:c=>{en=c,t.onRefused?.(c);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:c=>{Y.onBridgeState(c),c!=="connected"&&O.setRequested(false),V=null,k=null,c==="refused"&&(console.error("[gem] this game refused the page that framed it"+(en===null?"":` (${en})`)+", 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."),Sn()),c==="connected"&&(o.mark("bridge connected"),xd(),E(),N(),C(),y.unbiddenLaunch&&!s.engaged&&a.hold(),a.startSession(),s.engaged&&y.reportEngaged()),t.onStateChange?.(c);},onPlayer:c=>{f.set(c),t.onPlayer?.(c);},onPrefs:c=>{let x={reducedMotion:c.reducedMotion,muted:c.muted,locale:c.locale,showFrameStats:c.showFrameStats===true};w.set(x),_?.setMuted(x.muted),O.setRequested(x.showFrameStats&&y.parentSupports("frameStats")),t.onPrefs?.(x);},onCohorts:c=>{let x=Object.freeze(c.cohorts.map($=>Object.freeze({experimentId:$.experimentId,variantKey:$.variantKey})));R.set(x),t.onCohorts?.(x);},onEarnAllowanceChanged:()=>I.emit(),onViewport:c=>{let x=Object.freeze({insets:Object.freeze({top:c.insets.top,right:c.insets.right,bottom:c.insets.bottom,left:c.insets.left}),reserved:Object.freeze((c.reserved??[]).map(te=>Object.freeze({x:te.x,y:te.y,width:te.width,height:te.height})))});M.set(x);let $=_l();wl($,x.insets),Rl($,x.reserved,Sl()),t.onViewport?.(x);},onPause:c=>{a.setPaused(c.paused),O.setPaused(c.paused),t.onPause?.(c.paused);},onMenuSelect:c=>{if(q===null)return;if(c.entry==="settings"){q.onSettings?.();return}(yr(false,q.items).items??[]).some($=>$.id===c.id)&&q.items?.find($=>$.id===c.id)?.onSelect?.();},onWillTerminate:c=>{a.endSession(c.reason),t.onWillTerminate?.({reason:c.reason,graceMs:c.graceMs});},onToken:c=>{let x=c.garden;if(W(c.allowDevTools===true),!Ce(c.apiBaseUrl,x))return;let $=c;Y.onToken($);let te=Y.identity;te&&(j.set(te),ne||(ne=true,ce.reconcileSeats().catch(()=>{}))),ct.push({token:$.token,expiresAt:$.expiresAt});},onTokenDenied:c=>{W(false),Y.onDenied(c);},onScreenshot:(c,x,$)=>{pl(c,x,$,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{gl(y,t.onFeedbackContext);},onDevtools:c=>{c==="close"?F.close():c==="open"?F.openFrom("platform").catch(()=>{}):F.isOpen?F.close():F.openFrom("platform").catch(()=>{});},onRoomEvent:c=>ce.handleRoomEvent({event:c.event,roomId:c.roomId,...c.matchId===void 0?{}:{matchId:c.matchId},...c.version===void 0?{}:{version:c.version},...c.reason===void 0?{}:{reason:c.reason},...c.platform===void 0?{}:{platform:c.platform}}),onSeatedEvent:c=>ce.handleSeated(c.roomId),onAutoStartFailedEvent:c=>ce.handleAutoStartFailed(c.roomId,c.code),onSocketState:c=>{let x=Oe;if(Oe=c.connected,c.connected)for(let te of [...ae])te();if(!c.connected||x===true)return;let $=e.now();$-ee<X||(ee=$,ce.reconcile().catch(()=>{}));},onSignalEvent:c=>{let x=typeof c.data=="object"&&c.data!==null&&!Array.isArray(c.data)?c.data:{};rn.handleSignalEvent(c.matchId,c.event,x),c.event==="matchEnded"&&ce.reconcile({matchId:c.matchId,...typeof x.reason=="string"?{reason:x.reason}:{}}).catch(()=>{});},onDedicatedEvent:c=>{c.event==="matchEnded"&&(Rn.handleMatchEnded(c.matchId,c.reason),ce.reconcile({matchId:c.matchId,...c.reason===void 0?{}:{reason:c.reason}}).catch(()=>{})),T.handleEvent(c);},onClusterTarget:c=>mt.accept(c.clusterTargetId,c.clusterTargetIds),onLocalServer:c=>pt.accept(c),onLocalServerDenied:c=>pt.refuse(c),onPartyResult:c=>ui.settle(c.requestId,c.partyId),onPurchaseResult:c=>pi.settle(c),onDeviceSettings:c=>{ut.receive(c),t.onDeviceSettings?.(ut.api.current);},onDeviceSettingsResult:c=>ut.settle(c),onAdResult:c=>gi.settle(c),onSignInResult:c=>yi.settle(c),onFriendChallengeResult:c=>fi.settle(c)}),T=new ot({bridge:y}),j=lt(e);Sn=()=>{j.release(),f.release(),R.release();},y.currentState==="refused"&&Sn();let ne=false,ve=new Set,qe,ct={current:()=>qe,subscribe:c=>(ve.add(c),qe!==void 0&&c(qe),()=>ve.delete(c)),push:c=>{qe=c;for(let x of [...ve])try{x(c);}catch($){n?.(`[gem] a server-token listener threw: ${$ instanceof Error?$.message:String($)}`);}}},Y=Pl({bridge:y,clock:e,onStateChange:(c,x)=>{if(c==="ready"){if(o.mark("token ready")){let $=o.marks.find(te=>te.name==="token ready")?.at;a.trackPlatform("gem_boot_ready",$===void 0?{}:{boot_ms:Math.max(0,Math.round($))});}}else c==="lost"&&(o.mark("token lost"),a.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(c,x);}}),ci=()=>{let c=Y.identity;return !c||Y.source.currentState==="lost"?null:`${c.playerId}\0${c.gameId}\0${c.channel}`},xd=()=>{o.mark("token requested"),Y.source.get().catch(()=>{});},ui=oi({bridge:y,clock:e}),mi={},pi=id({bridge:y,clock:e,onDropped:c=>t.onError?.("internal",c),confirm:async c=>mi.confirm?.(c)??"unknown"}),ut=yd({bridge:y,clock:e,onDropped:c=>t.onError?.("internal",c)}),gi=pd({bridge:y,clock:e,onDropped:c=>t.onError?.("internal",c)}),yi=ad({bridge:y,clock:e,onDropped:c=>t.onError?.("internal",c)}),fi=ca({bridge:y,clock:e,onDropped:c=>t.onError?.("internal",c)}),mt=_a({bridge:y,clock:e}),pt=kl({bridge:y,clock:e}),fr=c=>{let x=y.handleWindowMessage({data:c.data,origin:c.origin,source:c.source,ports:c.ports});return x&&window.removeEventListener("message",fr),x};window.addEventListener("message",fr);let nn=ki(window,fr),Ad=nn?.capture,hr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];hr?.domInteractive!==void 0&&hr.domInteractive>0&&o.mark("document parsed",hr.domInteractive),Ad?.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 br=t.handshakeWarningMs;br!==null&&n&&e.setTimeout(()=>{let c=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(y.currentState==="connected"){n(`[gem] handshake connected. boot: ${o.timeline()} \xB7 ${c}`);return}n(`[gem] no completed handshake after ${br??wd}ms (bridge state: ${y.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${o.timeline()} \xB7 `+c);},br??wd);let Pd=ur({get baseUrl(){return Q},tokenSource:Y.source,get defaultQuery(){let c=Y.identity;return c?{game_id:c.gameId,channel:c.channel}:{}}}),tn=new Le({transport:Pd,clock:e}),fe={client:tn,gameId:()=>Y.identity?.gameId??""};mi.confirm=c=>sd(fe,c);let Ed=()=>Y.identity?.channel??"release",hi=new jt(fe,Ed),bi=async c=>(await hi.load())?.currency(c)?.id??void 0,vi=Ot(fe,Fr,{identity:ci,resolveCurrencyId:bi}),vr=async c=>{let x=await j.wait(c);if(x)return x;throw y.currentState==="refused"?new oe("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new oe("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},_r=l(t.autoReconnect),ce=Ao({client:tn,clock:e,gameId:()=>Y.identity?.gameId??null,playerId:()=>Y.identity?.playerId??null,awaitGameId:async()=>(await vr(li)).gameId,resolveParty:ui.resolve,resolveClusterTargets:mt.resolveList,refreshClusterTargets:mt.refresh,ensureLocalServer:pt.ensure,localHostAvailable:pt.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>Y.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},..._r===null?{}:{autoReconnect:{..._r,redial:(c,x)=>wr.redialMatch(c,x),abandon:(c,x)=>wr.abandonMatch(c,x)}}});d(ce),al({analytics:a,rooms:ce});let rn=sl({client:tn,clock:e,rooms:ce,bridge:y,gameId:()=>Y.identity?.gameId??"",baseUrl:()=>Q,resolveClusterTarget:mt.resolve,boot:o,...t.log===void 0?{}:{log:t.log}}),_i=qo(o,n),Rn=Hl({client:tn,clock:e,rooms:ce,signaling:()=>T.channel(),signalingReady:dt,log:n??(()=>{})}),wr=rd({rooms:ce,p2p:{connect:c=>_i(rn.connect(c)),session:c=>rn.session(c)},dedicated:{connect:(c=>lr(o,"welcome",Rn.connect(c),n))},clock:e,identity:()=>Y.identity,apiBaseUrl:()=>Q,tokens:ct,room:()=>ce.currentRoom,autoReconnect:_r!==null,...t.log===void 0?{}:{log:t.log}}),Td=async()=>(await vr(li)).playerId,wi={client:tn,boot:o,get identity(){return Y.identity},awaitIdentity:(c=li)=>vr(c),awaitBridge:c=>y.settled(c),get player(){return f.current},awaitPlayer:(c=yf)=>f.wait(c),me:vi,characters:new Gt(fe,void 0,ci,bi),transfers:new $t(fe,Fr,vi.inventory),gameConfig:hi,purchases:pi.api,deviceSettings:ut.api,ads:gi.api,account:yi.api,share:ud({frame:y,log:t.log}),analytics:a,leaderboards:new In(fe),challenges:new En(fe),showcase:new Mn(fe,Td),friends:new On(fe,{challenge:fi.challenge}),platform:new Gn(fe,I,n),profiles:new Dn(fe),functions:new De((c,x)=>ps(fe,c,x)),get prefs(){return w.current},get cohorts(){return R.current},get viewport(){return M.current},awaitCohorts:(c=ff)=>R.wait(c),reportMuted:c=>{S=!!c,E();},cueReward:c=>y.cueReward(c),setWalletVisible:(c,x)=>{let $=Array.isArray(x?.only)?[...x.only]:void 0;return A=$===void 0?{visible:c===true}:{visible:c===true,only:$},N()},setMenu:c=>(q={...typeof c?.onSettings=="function"?{onSettings:c.onSettings}:{},...Array.isArray(c?.items)?{items:c.items.map(x=>({...x}))}:{}},C()),exit:c=>hf(ce,y,c,a),frame:y,devtools:F,rooms:ce,dedicatedServer:{listClusterTargets:c=>Rn.listClusterTargets(c),connect:(c=>lr(o,"welcome",Rn.connect(c),n)),handleMatchEnded:(c,x)=>Rn.handleMatchEnded(c,x)},p2p:{handleSignalEvent:(c,x,$)=>rn.handleSignalEvent(c,x,$),session:c=>rn.session(c),connect:c=>_i(rn.connect(c))},match:wr};return wi}var Sd="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 di(t,e={}){let n=e.clock??le,r=()=>{let s=t();if(s===null)throw new Error(Sd);return s},o=null,i=()=>{if(o===null)throw new Error(Sd);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:ge(m),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:ge(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 Rd(t,e={}){let{server:n,attach:r}=di(()=>t,e);return r(),n}function bf(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 kd(t,e={}){return ()=>{let n=null,{server:r,attach:o}=di(()=>n,e),i=t(r),a={async init(s){n=s,o(),await i.init?.();},async shutdown(s){let l=bf(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}}Ri();
|
|
2
|
-
exports.ARCADE_EMBEDDERS=
|
|
1
|
+
var GemWebSdkGame=(function(exports){'use strict';var Nd=Object.defineProperty;var Ud=(t,e)=>{for(var n in e)Nd(t,n,{get:e[n],enumerable:true});};var kr="GemWebSdkHandshake";function Bd(){return typeof document>"u"?void 0:document.readyState}var xi=()=>Date.now();function Ai(t={}){let e=t.win??window,n=e,r=n[kr];if(r!==void 0)return r;let o=t.readyState??Bd,i=t.now??xi,a=[],s=[],l=m=>{let c=m.data;!c||c.type!=="gem.handshake"||(a.length>=4&&(a.shift(),s.shift(),d.dropped+=1),a.push(m),s.push(i()));};e.addEventListener("message",l);let d={events:a,times:s,dropped:0,late:o()==="complete",uninstall(){e.removeEventListener("message",l);}};return n[kr]=d,d}function Pi(t,e,n={}){let r=t[kr];if(r===void 0)return null;let o=n.ttlMs??9500,i=n.now??xi,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}}globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:8.0.0]";function Ei(){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 Hd(t,e){return e!==void 0?!e:t==="chain_exhausted"}var ln=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 oe(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.grant&&e>=this.grant.chainEndsAt)throw this.enter("lost","chain_exhausted"),new oe("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 oe("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=Vd(o),a=o?.retryable;throw n===this.generation&&this.enter(Hd(i,typeof a=="boolean"?a:void 0)?"lost":"degraded",i),o instanceof oe?o:new oe(i,String(o))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){this.failure=n??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,n));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},oe=class t extends Error{constructor(n,r){super(`auth ${n}: ${r}`);this.reason=n;this.name="AuthError";}reason;static isAuthError(n){if(n instanceof t)return true;let r=n;return r?.name==="AuthError"&&typeof r.reason=="string"}};function Vd(t){if(t instanceof oe)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var re=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}},gt=["if-match","if-none-match"],Ti=4096;function Wd(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();if(!gt.includes(o)||r===void 0)continue;let i=typeof r=="string"?Kd(r):r;if(typeof i!="string"||i.length>Ti||!Jd(i))throw new re(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${Ti} 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 Kd(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 Jd(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 zd(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new re("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 re("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 Ci(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=Wd(o.headers),a=zd(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 oe("unavailable","the server refused a freshly minted token");return c}}}function yt(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Yd(e))}function ft(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 xr(t){return new TextDecoder().decode(ft(t))}function Yd(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var O=class extends Error{constructor(n,r,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"}},Mi=new WeakMap;function Oi(t){return Mi.get(t)??{}}var Xd=new Set([408,429,500,502,503,504]),Qd=6e4;function Zd(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new re(`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,...An(o)},o.replaySafe===true)}async post(e,n,r,o={}){return this.send({method:"POST",path:e,body:n,signal:r,...An(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,...An(o)},o.replaySafe===true);return {bytes:ec(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,...An(o)},o.replaySafe===true)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...An(r)},r.replaySafe===true)}async send(e,n){return (await this.sendRaw(e,n)).body}async sendRaw(e,n){let r=n?Zd(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw Ii(e.signal);for(let i=0;i<r;i++){if(i>0&&await this.backoff(i,o,e.signal),e.signal?.aborted)throw Ii(e.signal);let a;try{a=await this.options.transport.request(e);}catch(l){if(oe.isAuthError(l)||re.isRefusal(l)||e.signal?.aborted||nc(l))throw l;o=new O("unavailable",0,String(l));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let s=tc(a);if(!Xd.has(a.status))throw s;o=s;}throw o??new O("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),Qd);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 ec(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 An(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function Ii(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function nc(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function tc(t){let e=oc(t),n=sc(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&Mi.set(e,r),e}var rc=new Map([["insufficient_funds","insufficient_funds"]]);function oc(t){let{status:e,body:n}=t,r=ic(n),o=t.retryAfterSeconds??lc(n),i=ac(n),a=i===void 0?void 0:rc.get(i);if(a!==void 0)return new O(a,e,r,void 0,i);switch(e){case 304:return new O("not_modified",e,r);case 400:case 422:return new O("invalid",e,r,void 0,i);case 403:return new O("forbidden",e,r,void 0,i);case 404:return new O("not_found",e,r,void 0,i);case 402:return new O("insufficient_funds",e,r,void 0,i);case 409:return new O("conflict",e,r,void 0,i);case 412:return new O("precondition_failed",e,r,void 0,i);case 413:return new O("too_large",e,r,void 0,i);case 429:return new O("rate_limited",e,r,o,i);default:return new O("unavailable",e,r,o,i)}}function ic(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 sc(t){let n=t?.error?.details;return n===null?void 0:n}function ac(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function lc(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 Li(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Gi(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 Di(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Fi(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 $i(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function ji(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 qi(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 Ni(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Ui(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Bi(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(o,r?.signal)}async function Hi(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 Vi(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 Wi(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 Ki(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.get(r,n?.signal)}async function Ji(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function zi(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 Yi(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 Xi(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 Qi(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 Zi(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 es(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 ns(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 ts(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 Ar(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 rs(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 os(t,e,n){let r=`/v1/showcase/friends/${v(e)}`;return t.client.get(r,n?.signal)}async function is(t,e,n){let r=`/v1/inbox/friend-challenges/${v(e)}`;return t.client.get(r,n?.signal)}async function ss(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 as(t,e){let n=`/v1/games/${v(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function ht(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function ls(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function ds(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 cs(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 us(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function ms(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function ps(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function gs(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 ys(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function fs(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 hs(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function bs(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 vs(t,e){return t.client.get("/v1/characters",e?.signal)}async function _s(t,e,n,r){let o=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function ws(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 Ss(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 Rs(t,e){let n=new URLSearchParams;e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inbox/friend-challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function ks(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 xs(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 As(t,e,n){let r=`/v1/inbox/friend-challenges/${v(e)}/answered`;return t.client.post(r,void 0,n?.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 Es(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 Ts(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 Cs(t,e,n,r,o){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(i,r,o?.signal)}async function Is(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Ms(t,e,n,r){let o=`/v1/characters/${v(e)}`;return t.client.patch(o,n,r?.signal)}async function Os(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 Ls(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 Gs(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.delete(r,n?.signal)}var B="gem-web-bridge",vt={min:1,max:1},dn=65536,Ds=8,bt=5e3,Fs=1024;function Er(t){return Object.freeze(Object.assign(Object.create(null),t))}var $s=Er({"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.menu":60,"gem.menuSelect":60,"gem.requestShare":6,"gem.vibrate":600,"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}),_t="__malformed";var dc=Er({"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","gem.vibrate":"vibration","gem.menu":"gameMenu","gem.menuSelect":"gameMenu"}),cc=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function js(t){let e=dc[t];if(e!==void 0)return e;for(let[n,r]of cc)if(t.startsWith(n))return r}function Tr(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 uc(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 mc(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function pc(t){return /^[a-z_]+$/.test(t)}function Pr(t,e,n){if(e>Ds)return `nesting deeper than ${Ds}`;if(++n.nodes>bt)return `more than ${bt} values`;if(n.bytes>dn)return `over the ${dn} 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>Fs)return `an array of ${t.length} entries, over the ${Fs} limit`;n.bytes+=2;for(let s of t){let l=Pr(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>bt)return `more than ${bt} values`;if(n.bytes+=s.length*3+4,n.bytes>dn)return `over the ${dn} byte limit`;let l=Pr(a[s],e+1,n);if(l)return l}return null}function gc(t){let e={nodes:0,bytes:0,seen:new Set},n=Pr(t,0,e);return n?`message contains ${n}`:e.bytes>dn?`message is over the ${dn} byte limit`:null}var yc={origin:[Tr,"not a well-formed origin"],url:[uc,"not a safe absolute http(s) URL"],bcp47:[mc,"not a well-formed BCP 47 tag"],code:[pc,"not a code of lower-case letters and underscores"]};function qs(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=Ns(i,r,o);if(a)return a}return null}function Ns(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]=yc[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`:qs(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=Ns(i,r,o);if(a)return a}return null}default:{let r=e.k;return `${n}: unknown kind ${String(r)}`}}}function E(t,e){return n=>{let r=gc(n);if(r)return r;if(typeof n!="object"||n===null||Array.isArray(n))return "message: expected object";let o=n;return o.gem!==B?"gem: wrong protocol marker":o.type!==t?`type: expected ${t}`:qs(o,e,"")}}var fc=E("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}]),hc=E("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}}]),bc=E("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}]),vc=E("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}]),_c=E("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}]}]),wc=E("gem.pause",[{n:"paused",k:"boolean"}]),Sc=E("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),Rc=E("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}]}}]),kc=E("gem.earnAllowanceChanged",[]),xc=E("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=E("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),Pc=E("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),Ec=E("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"]}]),Tc=E("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),Cc=E("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),Ic=E("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),Mc=E("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"}]),Oc=E("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}]),Lc=E("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),Gc=E("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),Dc=E("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),Fc=E("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),$c=E("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),jc=E("gem.requestContext",[]),qc=E("gem.gameContext",[{n:"context",k:"json"}]),Nc=E("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Uc=E("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),Bc=E("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),Hc=E("gem.ready",[]),Vc=E("gem.engaged",[]),Wc=E("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Kc=E("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),Jc=E("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),zc=E("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),Yc=E("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),Xc=E("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),Qc=E("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),Zc=E("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),eu=E("gem.audioState",[{n:"muted",k:"boolean"}]),nu=E("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}]}]),tu=E("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}]),ru=E("gem.menu",[{n:"settings",k:"boolean"},{n:"items",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"id",k:"string",max:32},{n:"label",k:"string",max:40}]}}]),ou=E("gem.menuSelect",[{n:"entry",k:"enum",v:["settings","item"]},{n:"id",k:"string",o:1,max:32}]),iu=E("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}]}}]),su=E("gem.vibrate",[{n:"pattern",k:"array",max:99,it:{n:"",k:"int",lo:0,hi:1e4}}]),au=E("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),lu=E("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}]),du=E("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}]),cu=E("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}]),uu=E("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),mu=E("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),pu=E("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),gu=E("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),yu=E("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),fu=E("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),hu=E("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}]),bu=E("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}]),wt=Er({"gem.handshake":fc,"gem.handshake.accept":hc,"gem.token":bc,"gem.token.denied":vc,"gem.player":_c,"gem.pause":wc,"gem.prefs":Sc,"gem.cohorts":Rc,"gem.earnAllowanceChanged":kc,"gem.viewport":xc,"gem.deviceSettings":Ac,"gem.willTerminate":Pc,"gem.roomEvent":Ec,"gem.socketState":Tc,"gem.seatedEvent":Cc,"gem.autoStartFailedEvent":Ic,"gem.signalEvent":Mc,"gem.dedicatedEvent":Oc,"gem.partyResult":Lc,"gem.clusterTarget":Gc,"gem.devtools":Dc,"gem.screenshot":Fc,"gem.screenshot.denied":$c,"gem.requestContext":jc,"gem.gameContext":qc,"gem.signal":Nc,"gem.dedicatedOffer":Uc,"gem.partyRequest":Bc,"gem.ready":Hc,"gem.engaged":Vc,"gem.progress":Wc,"gem.requestToken":Kc,"gem.requestLocalServer":Jc,"gem.localServer":zc,"gem.localServer.denied":Yc,"gem.exit":Xc,"gem.openExternal":Qc,"gem.requestFullscreen":Zc,"gem.audioState":eu,"gem.rewardCue":nu,"gem.walletDisplay":tu,"gem.menu":ru,"gem.menuSelect":ou,"gem.requestShare":iu,"gem.vibrate":su,"gem.frameStats":au,"gem.error":lu,"gem.requestPurchase":du,"gem.purchaseResult":cu,"gem.deviceSettings.put":uu,"gem.deviceSettings.result":mu,"gem.requestAd":pu,"gem.adResult":gu,"gem.requestSignIn":yu,"gem.signInResult":fu,"gem.requestFriendChallenge":hu,"gem.friendChallengeResult":bu});var ae={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Pn=class{constructor(e=ae){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=$s[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 Cr(t,e){return t.toLowerCase()===e.toLowerCase()}function St(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Us(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:St(n.hostname)&&St(r.hostname)}function Bs(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 Rt=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 Mr(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 Hs="inventory",cn=t=>typeof t=="number"?t:0,En=t=>typeof t=="string"?t:"";function Ir(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 Vs(t){let e=t??{};return {itemDefinitionId:En(e.item_definition_id),instanceId:En(e.instance_id),quantity:cn(e.quantity),acquiredAt:cn(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function vu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Ir(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(a=>{let s=a??{};return {bucket:En(s.bucket),balance:cn(s.balance)}}):void 0;return {currencyId:En(o.currency_id),total:cn(o.total),...i===void 0?{}:{buckets:i}}}),items:Ir(e.items,Vs),progressions:Ir(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:En(o.progression_definition_id),currentValue:cn(o.current_value),completionCount:cn(o.completion_count),isCompleted:o.is_completed===true,...Mr(o)}}),...n===void 0?{}:{etag:n}}}var kt=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Hs}#buckets`:Hs;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 Xi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(o)?o.map(Vs):[]}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 Yi(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 vu(n)}};var _u={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},wu=new Set(Object.keys(_u));function Ws(t){return typeof t=="string"&&wu.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:"",Su=t=>typeof t=="string"?t:Z(t&&typeof t=="object"?t.type:void 0),Re=t=>typeof t=="number"?t:0;function Ru(t){let e=t??{};return {prerequisiteType:Z(e.prerequisite_type),referenceId:Z(e.reference_id),required:Re(e.required),current:Re(e.current)}}function Tn(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 xt(){return crypto.randomUUID()}var ku="recipe-usage",Ks=100;function At(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 xu(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(At):[]}}function Au(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(xu):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(At):[],consumed:Array.isArray(e.consumed)?e.consumed.map(At):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(At):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function Pu(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 Eu(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 Js(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 Pt=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(()=>qi(this.api,this.entity.type,this.entity.id,{operations:e.map(Js),source:n.source??"play",nonce:xt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Tn(r)}async createMany(e,n={}){return this.write(()=>ji(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Js),nonce:xt()})),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 ns(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(Ru):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>Su(d)):[],...a===void 0?{}:{usesRemaining:a},...s===void 0?{}:{cooldownExpiresAt:s}}}async recipeUsageAll(){return this.cache.read(ku,[],async()=>{let n=await ts(this.api,this.entity.type,this.entity.id,{limit:Ks})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(Eu),truncated:r.length>=Ks}})}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(()=>Hi(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:xt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...Au(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([ds(this.api,n.signal===void 0?{}:{signal:n.signal}),ht(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(()=>fs(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:xt(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return Pu(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(()=>Gi(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Tn(o)}async maxProgression(e,n,r){let o=await this.write(()=>Es(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Tn(o)}async claimProgression(e,n){let r=await this.write(()=>Fi(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Tn(r)}async resetProgression(e,n){let r=await this.write(()=>Ls(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Tn(r)}async write(e){return this.cache.invalidate(),e()}};var Or=t=>typeof t=="string"?t:"",Tu=t=>typeof t=="number"?t:0;function zs(t){let e=t??{};return {orderId:Or(e.order_id),status:Or(e.status),source:Or(e.source),createdAt:Tu(e.created_at)}}var Et=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await ws(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(zs):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Zi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return zs(r)}};var Ys=t=>typeof t=="number"?t:0,Cu=t=>typeof t=="string"?t:"";function Iu(t){let e=t??{};return {progressionDefinitionId:Cu(e.progression_definition_id),currentValue:Ys(e.current_value),completionCount:Ys(e.completion_count),isCompleted:e.is_completed===true,...Mr(e)}}var Tt=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 es(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Iu(i)}catch{return o??null}}};var Ct=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 Lr(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 Gr(t){try{let e=Lr(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var ie=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},Mu=3e4,Xs="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",Ou=/^[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(!Ou.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Qs(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 Dr(t,e){return t.aborted&&e?.aborted!==true}var Lu=new Set(["x-ms-blob-type"]),Gu=/^[ -~]+$/;function Du(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new ie("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(!Lu.has(i))throw new ie("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"||!Gu.test(o))throw new ie("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 ie("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);n[i]=o;}return n}function Fr(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 $r(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 ie("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 ie("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=Qs(r.signal,i);try{let s=await Os(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 ie("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=Du(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 Dr(a.signal,r.signal)?this.timeout("upload",i):new ie("upload_failed",`${Xs} for PUT. Underlying error: ${c}`)}if(!d.ok){let c=await Gr(d);throw new ie("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 Fr(await Vi(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 ie("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=Qs(n.signal,r);try{let i;try{let l=await Ar(this.api,this.entity.type,this.entity.id,ke(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if($r(l))return null;throw l}if(typeof i.download_url!="string")throw new ie("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 Dr(o.signal,n.signal)?this.timeout("download",r):new ie("download_failed",`${Xs} for GET. Underlying error: ${l}`)}if(!s.ok){let l=await Gr(s);throw new ie("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 Ar(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?Fr(r.body):null}catch(r){if($r(r))return null;throw r}}async list(e={}){let n=await Ss(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(Fr),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await Ui(this.api,this.entity.type,this.entity.id,ke(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!$r(r))throw r}}budget(e){return e??this.options.timeoutMs??Mu}timeout(e,n){return new ie("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,o,i){return e instanceof ie?e:Dr(r,n)?this.timeout(o,i):e}};function Fu(t){try{return xr(t)}catch{return t}}function jr(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"?Fu(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var Mt=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await _s(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>jr(o)):[]}async get(e,n={}){try{let r=await zi(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?jr(r.body,r.etag):null}catch(r){if(Zs(r))return null;throw r}}async put(e,n,r={}){let o=await Ts(this.api,this.entity.type,this.entity.id,e,{value:yt(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return jr(o)}async delete(e,n){try{await Ni(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!Zs(r))throw r}}};function Zs(t){return t?.reason==="not_found"}function Ot(t,e,n={}){let r=new Ct(ae,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let o=new kt(t,e,r);return {settings:new Mt(t,e),inventory:o,saves:new It(t,e,n.saves??{}),currencies:new Rt(o,n.resolveCurrencyId),mutations:new Pt(t,e,r),orders:new Et(t,e),progressions:new Tt(t,e,o)}}var qr={type:"players",id:"me"};var Ne=t=>typeof t=="string"?t:"",un=t=>typeof t=="number"?t:0;function Lt(t,e){let n=e??{},r=Ne(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:Ne(n.player_id),gameId:Ne(n.game_id),channel:Ne(n.channel)||"release",name:Ne(n.name),slotIndex:un(n.slot_index),isActive:n.is_active!==false,createdAt:Ne(n.created_at),updatedAt:Ne(n.updated_at)}}var Gt=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=Ot(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 vs(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>Lt(this.scope,o)):[]}async get(e,n){let r=await Ki(this.api,e,n===void 0?{}:{signal:n});return Lt(this.scope,r)}async create(e){let n=await $i(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Lt(this.scope,n)}async update(e,n,r){let o=await Ms(this.api,e,{name:n},r===void 0?{}:{signal:r});return Lt(this.scope,o)}async delete(e,n){await Gs(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await ms(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:un(r?.total_slots),availableSlots:un(r?.available_slots),activeCharacterCount:un(r?.active_character_count),defaultMaxSlots:un(r?.default_max_slots),purchasedExtraSlots:un(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 ge(t){return new pe(t)}var Ue={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 mn=t=>typeof t=="string"?t:"";function Dt(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:mn(e.transfer_id),status:mn(e.status),sourceEntityId:mn(e.source_entity_id),targetEntityId:mn(e.target_entity_id),...n===void 0?{}:{message:ge(n)},createdAt:mn(e.created_at),expiresAt:mn(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function $u(){return crypto.randomUUID()}var Ft=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 ys(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:$u()},e.signal===void 0?{}:{signal:e.signal});return Dt(n)}async list(e={}){let r=await xs(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(Dt):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await ps(this.api,e,n===void 0?{}:{signal:n});return Dt(r)}async accept(e,n){return this.resolve(()=>Li(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>Is(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>Di(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Dt(await e())}};var ju=t=>typeof t=="string"?t:"",qu=t=>typeof t=="string"&&t?t:void 0,Nu=t=>typeof t=="number"?t:void 0;function ea(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 Uu(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new de("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 de("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Nu(e.version);if(r===void 0)throw new de("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let c=ju(l.id);if(!c)throw new de("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:ea(i),currency:ea(a)}}var de=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},na=10*1024*1024,ta=15e3,ra=new Set(["dev","test","release"]);function Bu(t){if(!ra.has(t))throw new de("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...ra].join(", ")}. gem-api would reject the assignment read.`);return t}var $t=t=>typeof t=="number"?t:0,Nr=t=>typeof t=="string"?t:"";function Hu(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:Nr(o.entry_id),weight:$t(o.weight),dropRate:$t(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:Nr(e.loot_table_id),name:Nr(e.name),rollCount:$t(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:$t(e.total_weight),entries:n}}var jt=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 de("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 Ji(this.api,e,n===void 0?{}:{signal:n});return Hu(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??ta),n;try{let l=await Wi(this.api,Bu(this.channel()),{signal:e});if(!l.modified)throw new de("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof de)throw l;if(l?.reason==="not_found")return null;throw l}let r=qu(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 de("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??ta}ms`):new de("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=>Lr(d)).catch(()=>"");throw new de("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let a=await i.text();if(a.length>na)throw new de("config_too_large",`the config document is ${a.length} bytes, over the ${na} cap`);let s;try{s=JSON.parse(a);}catch(l){throw new de("config_malformed",`config document is not JSON: ${String(l)}`)}return Uu(s)}};var oa=400,xe=t=>typeof t=="string"?t:"",Vu=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Be(t){let e=xe(t);if(!Vu.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Wu=/^[0-9a-f]{1,64}$/,Ku=/^[0-9a-f]{16}$/,Ju=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,zu=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Ur(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 Yu=4096,Xu=new TextEncoder;function Qu(t){let e=xe(t.challenge_data),n=xe(t.challenge_data_hash);return e===""||!Ku.test(n)?{}:Xu.encode(e).length>Yu?{}:{data:e,dataHash:n}}function Zu(t){let e=t??{},n=Be(e.period_start_at),r=Be(e.period_ends_at);if(n===0||r===0)return;let o=xe(e.slug),i=xe(e.seed),a=Ur(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:Ju.test(s)?s:"",resetTime:zu.test(l)?l:"",seed:Wu.test(i)?i:"",...Qu(e)}}function pn(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 qt(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Zu).filter(n=>n!==void 0):[]}var Cn=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;pn(n);let r=await bs(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return qt(r)}};function He(t){return typeof t=="string"&&t!==""?t:void 0}var ia=new Set(["localhost","127.0.0.1","[::1]"]);function Br(t){let e=He(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:"&&ia.has(n.hostname)))return e}function em(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},o=He(r.item_id),i=Br(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function ve(t){let e=t??{},n=He(e.player_id),r=He(e.display_name),o=He(e.discriminator),i=He(e.display_tag),a=He(e.avatar_icon_id),s=Br(e.avatar_icon_url);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:ge(r)},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:ge(i)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:em(e.badges)}}var nm=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function tm(t){if(t===void 0)return;let e=Br(t);if(e===void 0)return;let n=new URL(e);return ia.has(n.hostname)||nm.has(n.origin)?e:void 0}var sa=100,da=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Hr(t){let{periodsBack:e,period:n,playerId:r}=t;if(pn(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!da.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 ca(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!da.test(e))return;let n=Ur(t.period_local_date),r=Be(t.period_start_at),o=Be(t.period_ends_at),i=r>0&&o>0;return {id:e,...n===void 0?{}:{localDate:n},...i?{startAt:r,endsAt:o}:{},opensAt:Be(t.opens_at),closesAt:Be(t.closes_at),final:t.final===true}}var In=t=>typeof t=="string"?t:"",gn=t=>typeof t=="number"?t:0,Mn=t=>typeof t=="string"?t:void 0,rm=t=>typeof t=="number"?t:void 0,ua={player:"players",character:"characters"};function om(t,e){let n=t??{},r=Mn(n.entity_id),o=typeof n.entity_type=="string"&&Object.hasOwn(ua,n.entity_type)?n.entity_type:void 0,i=ma(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:gn(n.rank),occurredAt:gn(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 aa(t,e){let n=t??{},r=Mn(n.bucket_1),o=Mn(n.bucket_2),i=rm(n.update_frequency_seconds),a=ca(n);return {leaderboardType:In(n.leaderboard_type),runType:In(n.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(n.entries)?n.entries.map(s=>om(s,e)):[],generatedAt:gn(n.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...a===void 0?{}:{period:a}}}function la(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=ma(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:gn(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function ma(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 im(t,e,n){let r=t??{},o=Mn(r.bucket_1),i=Mn(r.bucket_2),a=ca(r);return {leaderboardType:In(r.leaderboard_type),runType:In(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(la).filter(s=>s!==void 0):[],personalBest:la(r.personal_best)??null,totalRuns:gn(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:gn(r.generated_at),...a===void 0?{}:{period:a}}}var On=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=Hr(n),o=await ss(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 aa(o,false)}async friends(e,n={}){let r=Hr(n),o=await rs(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 aa(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>sa)throw new TypeError(`limit must be an integer between 1 and ${sa}, got ${String(l)}`)}let i=Hr(o),a=await Qi(this.#e,e,ua[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"&&In((a??{}).entity_id)||r;return im(a,n,s)}};var Nt=t=>typeof t=="string"?t:"",Vr=t=>typeof t=="number"?t:0;function pa(t){let e=t??{};return {playerId:Nt(e.player_id),key:Nt(e.key),value:e.value,updatedAt:Vr(e.updated_at)}}function sm(t){let e=t??{};return {...ve(e),playerId:Nt(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Vr(e.updated_at)}}function am(t){return t?.reason==="not_found"}var Ln=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let o=await os(this.api,ke(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:Nt(o.key),entries:Array.isArray(o.entries)?o.entries.map(sm):[],generatedAt:Vr(o.generated_at)}}async of(e,n,r={}){try{return pa(await us(this.api,e,ke(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(am(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 pa(await Cs(this.api,o,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await Bi(this.api,r,ke(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var lm="gemChallenge",ga=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ya(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(lm)??void 0}catch{return}}var Ve=class extends O{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});}},Ut=t=>typeof t=="string"?t:void 0;function fa(t){let e=t??{};return {...ve(e),playerId:Ut(e.player_id)??""}}function ha(t){let e=t.has_more===true?Ut(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function dm(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(fa):[],...ha(e)}}var Wr=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function cm(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"||typeof e[1]=="number"&&Number.isFinite(e[1])))}function ba(t){let e=t??{},n=Wr(e.opened_at),r=Wr(e.answered_at);return {id:Ut(e.item_id)??"",from:fa(e.sender),template:Ut(e.template)??"",params:cm(e.params),createdAt:Wr(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function um(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(ba):[],...ha(e)}}function mm(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Gn=class{#e;#t;#i;constructor(e,n={}){this.#e=e,this.#t=n.challenge,this.#i=n.launchedChallengeId;}async list(e={}){let n=await ks(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return dm(n)}challenge(e){return this.#t===void 0?Promise.resolve({outcome:"unavailable"}):this.#t(e)}async inbox(e={}){let n=await Rs(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return um(n)}async launchedChallenge(e={}){let n=this.#i;if(n===void 0||!ga.test(n))return null;try{return ba(await is(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(mm(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!ga.test(e))throw new O("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await As(this.#e,e);}};var pm=0;function Ae(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++pm)}-${String(Date.now())}-${t}`}}var gm=12e4,va=8,ym=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,fm=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Dn(t,e,n={}){return new Ve(new O("invalid",400,e,void 0,t),n)}function hm(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function bm(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!ym.test(e))return {error:Dn("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!fm.test(n))return {error:Dn("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(!hm(r))return {error:Dn("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:Dn("param_invalid",`params.${a} must be a string or a safe integer`,{param:a})}}return i.length>va?{error:Dn("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(va)}`)}:{playerId:e,template:n,params:o}}function vm(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 Ve(new O("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new Ve(new O("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function _m(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function _a(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=bm(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??gm);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 (${_m(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(vm(n));}}}var Bt=t=>typeof t=="string"?t:void 0;function wm(t){let e=t??{},n=Bt(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Bt(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Ht=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await ht(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=wm(i);a!==void 0&&o.push(a);}return o}},Kr=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function Sm(t){let e=t??{},n=Bt(e.currency_id);if(n===void 0||n==="")return;let r=Kr(e.limit),o=Math.min(Kr(e.earned),r),i=Math.min(Kr(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:Bt(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 wa(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 Vt=class{#e;#t;#i;constructor(e,n,r){this.#e=e,this.#t=n,this.#i=r;}async get(e={}){let r=(await as(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=Sm(i);a!==void 0&&o.push(a);}return o}on(e,n){return e!=="changed"?(this.#i?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#t?.on(n)??(()=>{})}},Fn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Ht(e),this.earnAllowance=new Vt(e,n,r);}};var Jr=t=>typeof t=="string"?t:"",Sa=t=>typeof t=="number"?t:0;function Rm(t){let e=t??{};return {key:Jr(e.key),visibility:Jr(e.visibility),value:e.value,updatedAt:Sa(e.updated_at)}}function km(t){let e=t??{};return {...ve(e),playerId:Jr(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Rm):[],generatedAt:Sa(e.generated_at)}}function xm(t){return t?.reason==="not_found"}var $n=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return km(await ls(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(xm(r))return null;throw r}}};var Am=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]]),jn=class extends O{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:Am.get(this.code))??super.retryable}},De=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=Pm(e),o;try{o=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(i){throw i instanceof O?Tm(i):i}return Em(o)}};function Pm(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 re(`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 re(`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 Em(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}=Oi(t),o=e?.untrusted?.message,i=e?.reason;return new jn(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 Cm=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],zr="gem_";function Ra(t){return t.startsWith(zr)}var ka=1e4,xa=50,Im=500,Mm=65536-4*1024,Om=24*1024;function Aa(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 Pa=t=>typeof t=="number"?t:0,Lm=t=>typeof t=="string"?t:"";function Yr(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function Gm(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:Pa(i.index),code:Lm(i.code)}}):[];return {accepted:Pa(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Xr(){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 qn=class{#e;#t;#i;#y;#n=[];#f={};#s=0;#a=null;#h=false;#b=false;#v=false;#r=false;#_=null;#l=null;#d=false;#o=false;#m=false;#w=false;#S=false;constructor(e){this.#e=e,this.#t=e.options?.enabled!==false,this.#i=Math.max(ka,e.options?.flushIntervalMs??ka),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??Im));}track(e,n={}){if(!(!this.#t||this.#r)){if(Ra(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,Aa({...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 Yr();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.")),Yr();if(this.#k(),this.#n.length===0)return Yr();let r=e.keepalive===true;this.#u();let o=this.#n.splice(0,this.#A(r)),i=this.#s;this.#s=0;let a=Math.round(this.#e.clock.now()),s={batch_id:Xr(),sent_at_ms:a,events:o.map(d=>Ea(d,a))},l={client:this.#e.client(),gameId:()=>n};this.#v=true;try{let d=await gs(l,s,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=Gm(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,Aa(n));}hold(){this.#r||this.#l!==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.#l=e,this.#d=false,this.#n.unshift({uid:Xr(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#n.length>=xa?this.#p():this.#n.length>0&&this.#c();}get held(){return this.#o}startSession(){if(!(this.#r||this.#l!==null)){if(this.#o){this.#m=true;return}this.#l=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.#s=0;return}let n=this.#l;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#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.#s=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.#s+=1;this.#n.push({uid:Xr(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#n.length>=xa?this.#p():this.#c();}#p(e={}){this.flush(e).catch(()=>{});}#x(e,n){for(this.#n=[...e,...this.#n],this.#s+=n;this.#n.length>this.#y;)this.#n.shift(),this.#s+=1;}#A(e){let n=e?Om:Mm,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(Ea(a,0)).length+1,o>n)return Math.max(1,i)}return r}#c(){this.#a!==null||this.#h||this.#b||this.#o||this.#r||this.#v||(this.#a=this.#e.clock.setTimeout(()=>{this.#a=null,this.#p();},this.#i));}#u(){this.#a!==null&&(this.#e.clock.clearTimeout(this.#a),this.#a=null);}#k(){let e=this.#T();e===null||e===""||(this.#_!==null&&this.#_!==e&&(this.#n=[],this.#s=0,this.#l=null,this.#d=false),this.#_=e);}#P(e){for(let n of e.rejected)this.#g(`[gem] analytics: an event was refused (${n.code}). `+Fm(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 Ea(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function Fm(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 ue(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function Nn(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=ue(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var $m=2e3,jm=5e3;function Ca(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??$m);});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 !Ta(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??jm);})},accept(a,s){let l=Nn(s),d=ue(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])Ta(m,p)||c(m);}}}}function Ta(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var qm=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=qm.has(n),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var Ia=["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"],Nm=new Set(Ia);function Fe(t){return typeof t=="string"&&Nm.has(t)?t:"unknown"}var Wt="webrtc_dedicated",no=["universal","mobile","web"];var Um="p2p_unavailable",Bm="capacity_unavailable",Hm=2,Ma=3e4,Oa=1e3,La=2e4;async function to(t){let e=ue(t.clusterTargetId),n=t.nextClusterTarget,r=0,o=t.clock??ae,i=t.retry??{},a=i.budgetMs??Ma,s=i.maxDelayMs??La,l=i.initialDelayMs??Oa,d=o.now(),m=d+a,c=0;for(;;){c++;try{let p=await so(t.signal,"while allocating",()=>t.client.post(`${Fa(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Vm(p)||a<=0)throw p;if(p.status===503&&p.code===Um)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>=Hm){let I=n;n=void 0;let M=ue(await I());M!==void 0&&(e=M,r=0);}let g=Math.min(s,l*2**(c-1)),y=Math.min(s,(p.retryAfterSeconds??0)*1e3),x=Math.max(g/2,y)+Math.random()*(g/2);if(o.now()+x>m)throw Wm(t,p,c,o.now()-d,a);if(i.onWaiting?.({attempt:c,elapsedMs:o.now()-d,budgetMs:a,nextAttemptInMs:x,status:p.status,message:p.message}),await Kt(o,x,t.signal),t.signal?.aborted)throw eo("while waiting to allocate")}}}function Vm(t){return t instanceof O?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 Km=12e4,Jm=1e3;async function ro(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??Jm,o=t.timeoutMs??Km,i=e.now()+o,a=Ga(t),s={seen:t.knownToExist===true};for(;;){let l=await Da(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 Kt(e,r,t.signal);}}async function oo(t){return (await Da(t,Ga(t),{seen:t.knownToExist===true})).outcome}function Ga(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Fa(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function Da(t,e,n){let{matchId:r}=t,o=t.clock.now(),i;try{i=await so(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(a){if(a instanceof O&&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:zm(r,i,o)};if(i.status==="failed"){let a=i.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Fe(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function io(t){let e=await so(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 so(t,e,n){if(t?.aborted)throw eo(e);try{return await n()}catch(r){throw t?.aborted?eo(e,r):r}}function eo(t,e){return new b("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function zm(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 Fa(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Kt(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 Jt(t,e){return $a(t)?t.trim():$a(e)?e:null}var zt="0.1.0-beta",ja="0-beta",yn="web",Ym=/^(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 Xm(t){let e=Ym.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function qa(t,e){let n=Qm(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:zt};let o=Xm(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 '${zt}' for it.`);if(o!==ja)throw new b("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${ja}' 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 '${zt}' for it.`);return {...t,platform:n,engineVersion:r}}function Qm(t,e){if(t===void 0||t===yn)return yn;if(!no.includes(t))throw new b("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${no.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${yn}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${yn}' 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.`),yn}var Zm="join",ep="welcome",np="rejected",Na=25e3,tp=1e3,ao=1;function lo(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var rp={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 co(t){let e=typeof t=="string"?t:"unknown";return new b(rp[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Un(t){let{channel:e,clock:n}=t;return new Promise((r,o)=>{let i=false,a=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Na),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,tp)),l=x=>{let I=x.data;if(typeof I!="string"){c(I);return}let M;try{M=JSON.parse(I);}catch{c(I);return}if(i){c(I);return}if(M.t===ep){let _=lo(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===np){w(co(M.reason));return}c(I);},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=x=>{i&&t.onMessage?.(x);},p=()=>{n.clearTimeout(s),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=x=>{i=true,p(),t.onMessage===void 0&&g(),r({welcome:x,detach:g});},w=x=>{i||(i=true,p(),g(),o(x));};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:Zm,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:ao}:{}}));}catch(x){w(new b("connection_failed",`the join frame could not be sent on the open channel: ${String(x)}`,{cause:x}));}})}var We=1,Bn=2,uo=4,go=8,op=2,ip=1e3,yo="heartbeat timeout",Hn="gem-uu",Yt=2,Ba="gem_transports";function fn(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!sp(r)||e.includes(r)||e.push(r);}return e}function sp(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function Vn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Ba];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 Xt(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Ha=new TextEncoder,Va=new TextDecoder;function fo(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function ho(t){let e=0;return t?.reliable===false&&(e|=We),t?.ordered===false&&(e|=Bn),e}function bo(t){return {reliable:(t&We)===0,ordered:(t&Bn)===0}}var vo={reliable:true,ordered:true};function Wa(t){return JSON.stringify({t:"join",credential:t,wire:Yt,heartbeat:ao})}function Ka(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=lo(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"?co(e.reason):new b("join_refused","the server answered the join out of protocol")}function Qt(){return typeof globalThis.WebTransport=="function"&&_o===null}function Zt(){return _o}var _o=null;var Ua="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function ap(t){let e=ft(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 mo=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let 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 po(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 Wn(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:ap(t.certHashBase64)}]});}let r=n,o=s=>{try{r.close();}catch{}throw s},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(_o=Ua,o(new b("connection_failed",`${Ua}; 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(po(uo,Ha.encode(Wa(t.credential))));let c=new mo,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=Ka(Va.decode(w.payload));break}}return {link:lp(r,m,p,c,t.log??(y=>console.warn(y)),za(g,t.clock)),welcome:g}}catch(s){return o(s)}}function lp(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=So(i,()=>d(yo)),c=(y,w)=>{m.heard(),(y&go)===0&&a!==void 0&&((y&uo)!==0?a(Va.decode(w),vo):a(w,bo(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 x=await w.read();if(x.done||x.value===void 0)break;let I=x.value;I.byteLength!==0&&c((I[0]??0)|We|Bn,I.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 (${Xt(y)}); unreliable sends ride the stream`);}return t.closed.then(y=>d(Ja(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,w){if(l)return;if(typeof y=="string"){e.write(po(uo,Ha.encode(y))).catch(()=>d("write failed"));return}let x=ho(w);if((x&We)!==0&&g!==void 0){let I=fo(x,y),M=p?.maxDatagramSize;if(M===void 0||I.byteLength<=M){g.write(I).catch(()=>{});return}}e.write(po(x,y)).catch(()=>d("write failed"));},onMessage(y){a=y;},onClose(y){s=y;},close(){d("closed");}}}function wo(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(Wa(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=Ka(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:dp(r,za(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 Ja(t){return typeof t=="string"&&t.length>0?t:void 0}function za(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function So(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,ip)*op,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 dp(t,e){let n,r,o=false,i=s=>{if(!o){o=true,a.stop();try{t.close();}catch{}r?.(s);}},a=So(e,()=>i(yo));return t.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){n?.(s.data,vo);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&go)===0&&n?.(l.slice(1),bo(d));})),t.addEventListener("close",(s=>i(Ja(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!o){if(typeof s=="string"){t.send(s);return}t.send(fo(ho(l),s));}},onMessage(s){n=s;},onClose(s){r=s;},close(){i("closed");}}}function Ro(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=So(r,()=>l(yo)),m=(c,p)=>{if(d.heard(),typeof c=="string"){o?.(c,vo);return}let g=new Uint8Array(c);if(g.byteLength===0)return;let y=g[0]??0;(y&go)===0&&o?.(g.slice(1),bo(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,We|Bn))),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=ho(p),y=fo(g,c);if((g&We)!==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 Ao(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let o=ko(r);o!==void 0&&(e[n]=o);}return e}function Po(t){if(Array.isArray(t))return t.map(cp).filter(e=>!!e)}function ko(t){if(xo(t)||Array.isArray(t)&&t.every(xo))return t}function xo(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function cp(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=ko(e.fixed),r=ko(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},...hn("description",up(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(xo)?{allowed:e.allowed}:{},...hn("min",Kn(e.min)),...hn("max",Kn(e.max)),...hn("minItems",Kn(e.min_items)),...hn("maxItems",Kn(e.max_items)),...hn("maxLength",Kn(e.max_length))}}function up(t){return typeof t=="string"&&t.length>0?t:void 0}function Kn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function hn(t,e){return e===void 0?{}:{[t]:e}}function Ee(t){let e=t??{},n=J(e.id)??J(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(Ya):[];return {id:n,gameId:J(e.game_id)??"",name:J(e.name)??"",status:J(e.status)??"open",hostPlayerId:J(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",J(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},..._e("roomArgs",Ao(e.room_args)),..._e("roomArgsTemplate",Po(e.room_args_template)),gameChannel:J(e.game_channel)??"release",..._e("region",J(e.region)),..._e("clusterTargetId",J(e.cluster_target_id)),selfHosted:e.self_hosted===true,..._e("matchId",J(e.match_id)),version:Pe(e.version)??0,..._e("templateId",J(e.template_id)),roomType:J(e.game_room_type)??"Standard",..._e("transports",fn(e.transports)??void 0),createdAt:Pe(e.created_at)??0,updatedAt:Pe(e.updated_at)??0,..._e("startedAt",Pe(e.started_at))}}function Ya(t){let e=t??{};return {...ve(e),playerId:J(e.player_id)??"",isReady:e.is_ready===true,role:J(e.role)??"member",joinedAt:Pe(e.joined_at)??0,..._e("groupId",J(e.group_id)),..._e("platform",J(e.platform))}}function er(t){let e=t??{};return {id:J(e.id)??J(e.game_room_id)??"",gameId:J(e.game_id)??"",name:J(e.name)??"",status:J(e.status)??"open",hostPlayerId:J(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:J(e.game_channel)??"release",roomType:J(e.game_room_type)??"Standard",createdAt:Pe(e.created_at)??0}}function J(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 Jn=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(er),...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(er)}))}create(e,n,r){return mp(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},...nr(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},...nr(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},...nr(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}:{},...nr(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 nr(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function mp(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 zn=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 pp(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var gp=1e3,yp=3e3,fp=6e4,hp=2,Xa=new Set(["game_room_closed","game_room_gone"]),bp=12e4,vp=5e3,_p=new Set(["invalid_cluster_target","capacity_unavailable"]),wp=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function To(t){return new Eo(t)}var Eo=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Jn({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new zn;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||Rp(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 O&&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(()=>oo({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 O&&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=Fe(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=ue(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)=>to({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||!Za(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 ro({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,!Xa.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(!Ke()){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<gp){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(pp(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Ke()){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(()=>oo({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,!Xa.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||!_p.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&&Ke())){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(),!!Ke())){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 tr)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 tr)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??vp}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=Jt(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 qa({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return Nn(await this.options.resolveClusterTargets());let e=ue(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Za(e)||n.length===0?[]:Nn(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(Nn(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 O)||e.reason!=="conflict"||!wp.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new O(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let o;try{o=await this.leaveAll(n.signal);}catch{throw new O(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(o.length===0)throw new O(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.api.quickJoin(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 O?{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=Sp(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??bp;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??yp}pushedInterval(){return this.options.pushedPollIntervalMs??fp}pushed(){return this.options.clock.now()-this.lastPushAt<hp*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 Ke(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var tr=["visibilitychange","focus","pageshow","online"];function Sp(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||Qa(t)!==Qa(e)}function Qa(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Za(t){return t instanceof O&&t.code==="invalid_cluster_target"}function Rp(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var kp=["p2p","dedicated","unknown"],Co=["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 bn=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let o=xp(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 xp(t,e,n){let r=Math.floor(n/1e3);return t.filter(o=>Co.includes(o.type)).slice(0,100).map(o=>{let i=Ap(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function Ap(t){if(t!==void 0)return kp.includes(t)?t:"unknown"}var Yn=class{constructor(e){this.options=e;this.reporter=new bn({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:rr(o.credential)??"",hostFingerprint:rr(o.host_fingerprint)??"",hostEpoch:or(o.host_epoch)??0,expiresAt:(or(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:rr(d.username)??"",credential:rr(d.credential)??""});}let a=or(o.expires_at),s=or(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 rr(t){return typeof t=="string"&&t.length>0?t:void 0}function or(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var Pp=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),L=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="P2pError",this.retryable=Pp.has(n);}reason;retryable};var el=10240,nl=2048,Ep=new TextEncoder;function tl(t){return Ep.encode(t).length}function $e(t,e){let n=o=>{throw new b("invalid_sdp",`the ${e} ${o}`)},r=tl(t);r>=el&&n(`is ${r} bytes, over the ${el} 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=tl(o);i>nl&&n(`has a ${i}-byte line, over the ${nl} limit`);}}function ir(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 sr=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 Tp=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function vn(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=ar(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function ar(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 Tp.test(r)?r:null}function Xn(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 Io=5e3,Cp=12e4+Io,Ip=1024,Mp=6e4,Op=1e4,rl=64*1024,ol=5;function Mo(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 L("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return s},a=async()=>{if(!o.ok)throw new L("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(Op)});}catch{throw new L("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 L("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>rl)throw new L("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${rl} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof L?p:new L("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>ol)throw new L("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${ol} 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 L("keys_unavailable",o.reason);if(r)return await r,e.get(s)??null;let d=t.now();if(!Number.isFinite(d))throw new L("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<n&&(n=-1/0),d-n<Mp?null:(n=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var Qn=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>=Ip){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+Cp),true}};function sl(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 il(t){try{let e=new TextDecoder().decode(sl(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Oo(t,e,n,r,o){let i=F=>{throw new L("peer_unauthenticated",`the peer's join credential is not usable: ${F}`)},a=t.split(".");a.length!==3&&i("it is not a three-part JWT");let[s,l,d]=a,m=il(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=sl(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 I=il(l);I===null&&i("its payload does not decode");let M=I,_=F=>typeof M[F]=="string"?M[F]:"",R=F=>typeof M[F]=="number"&&Number.isFinite(M[F])?M[F]: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=R("exp")*1e3,T=R("nbf")*1e3;(!Number.isFinite(P)||e.now>P+Io)&&i("it has expired"),Number.isFinite(T)&&e.now<T-Io&&i("it is not valid yet");let N=_("role");N!=="host"&&N!=="client"&&i("it names no usable role");let U=R("host_epoch");U!==e.hostEpoch&&i("it names a different host epoch");let W=ar(_("fingerprint"));W===null&&i("its fingerprint claim is malformed"),Xn(W,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let k=ar(_("host_fingerprint"));k===null&&i("its host fingerprint claim is malformed"),Xn(k,e.hostFingerprint)||i("it was issued against a different host certificate");let C=_("jti");C.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(C,e.now)||i("it has already been used");let G=_("sub");return G.length===0&&i("it names no player"),{playerId:G.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:U,role:N,fingerprint:W,hostFingerprint:k,jti:C,expiresAt:P}}function Lo(t){let e=new TextEncoder().encode(t.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let n=new ArrayBuffer(3+e.length+4+4),r=new DataView(n);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(n,3,e.length).set(e),r.setUint32(3+e.length,t.protocolVersion,true),r.setUint32(7+e.length,t.assignedPeerId,true),n}function Go(t){let e=new ArrayBuffer(9),n=new DataView(e);return n.setUint8(0,2),n.setUint32(1,t.protocolVersion,true),n.setUint32(5,t.assignedPeerId,true),e}function Do(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function Fo(t){if(t.byteLength<1)return null;let e=new DataView(t);switch(e.getUint8(0)){case 1:{if(t.byteLength<3)return null;let n=e.getUint16(1,true);return n>8192||t.byteLength<3+n+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(t,3,n)),protocolVersion:e.getUint32(3+n,true),assignedPeerId:e.getUint32(7+n,true)}}case 2:return t.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return t.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function al(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 ll(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Zn=class{constructor(e,n,r){this.localPlayerId=e;this.hostPlayerId=n,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,n){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=n,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var $o={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},Ie=["reliable","ordered","unreliable"];function jo(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 et(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var cl=1,$p=3e4,ul=2e3,jp=5e3,ml=6e4,qp=8,No=class{constructor(e=qp){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;}},Np=new No,Up=8,Bp=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),tt=class{constructor(e){this.options=e;this.keys=e.keys??Mo({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new sr;links=new Map;replays=new Qn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=cl+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??$p;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),o=ue(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: ${qo(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 L("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 L("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 L("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,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=se(e.playerId),r=se(e.hostPlayerId),o=lr(e.hostEpoch);if(!(n===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new Zn(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,cl),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new L("invalid_sdp","the browser produced an offer with no SDP");$e(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:vn(r);if(o===null)throw new L("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let i=this.options.credentialPacing??Np,a=()=>this.closed||e!==this.credentialGeneration,s=jp;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=ul;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,ml)),c=Math.min(Math.max(c,ul),ml);}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=se(e.fromPlayerId),r=se(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=Up){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=se(e.sessionId);if(o!==null&&this.answeredSessions.get(n)===o)return;$e(r,"offer"),this.refuseMedia(r,"offer");let i=vn(r);if(i===null)throw new L("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 L("invalid_sdp","the browser produced an answer with no SDP");$e(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=se(e.fromPlayerId),r=se(e.sdp);if(n===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||n!==this.hostPlayerId)return;$e(r,"answer"),this.refuseMedia(r,"answer");let i=vn(r);if(i===null)throw new L("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:Xn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new L("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let 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=se(e.fromPlayerId),r=se(e.candidate);if(n===null||r===null)return;let o=this.links.get(n);if(!o)return;let i=se(e.sdpMid),a=lr(e.sdpMLineIndex)??lr(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=se(e.playerId);if(n===null)return;let r=se(e.reason)??"left";if(n===this.localPlayerId){this.fail(new L("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=se(e.hostPlayerId),r=lr(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:n,hostEpoch:r,...se(e.reason)===null?{}:{reason:se(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 L("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 L("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let n=se(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new L("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=se(e.code)??"unknown",r=se(e.message)??"the platform refused a signaling message";this.report_(new L("signaling_failed",`${n}: ${r}`));}openLink(e,n){let o=(this.options.peerConnectionFactory??jo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of Ie){let g=o.createDataChannel(p,$o[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 L("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 L("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(Lo({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=Fo(n);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new L(ll(r.reason),al(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=vn(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 Oo(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 L&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",qo(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(Go({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(Do(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 Ie)pl(e.channels[o]);pl(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 L?e:new L("connection_failed",qo(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(ir(e))throw new L("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 se(t){return typeof t=="string"&&t.length>0?t:null}function lr(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function qo(t){return t instanceof Error?t.message:String(t)}function pl(t){try{t.close();}catch{}}var Hp=100,Vp=50,rt=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??Hp)){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 L("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new L("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId: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??Vp));}};function H(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 _n(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function gl(t){return typeof t=="boolean"?t:void 0}var ye=H(64),ot=je(0,2147483647);function Uo(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=ye(n);typeof r=="string"&&e.push(r);}return e}function K(t,e,n){return {to:t,from:e,read:n,required:true}}function V(t,e,n){return {to:t,from:e,read:n,required:false}}var Jp=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=_n("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:[K("sdp","sdp",H(10240)),K("signaling_intent","intent",_n("initial","ice_restart","full_reconnect")),V("sdp_hash","sdpHash",H(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[K("peer_id","peerId",ye),K("sdp","sdp",H(10240)),K("assigned_peer_id","assignedPeerId",je(0,4294967295)),V("sdp_hash","sdpHash",H(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[K("peer_id","peerId",ye),K("candidate","candidate",H(512)),V("sdp_mid","sdpMid",H(64)),V("sdp_mline_index","sdpMLineIndex",je(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[K("host_epoch","hostEpoch",ot)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[K("host_epoch","hostEpoch",ot),V("evidence","evidence",Jp)]}}));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:[K("playerId","player_id",ye),K("hostPlayerId","host_player_id",ye),K("hostEpoch","host_epoch",ot),V("members","members",Uo)],offer:[K("fromPlayerId","from_player_id",ye),K("sdp","sdp",H(10240)),V("sessionId","signaling_session_id",H(128)),V("sdpHash","sdp_hash",H(128)),V("iceUfrag","ice_ufrag",H(64)),V("intent","signaling_intent",_n("initial","ice_restart","full_reconnect"))],answer:[K("fromPlayerId","from_player_id",ye),K("sdp","sdp",H(10240)),V("sessionId","signaling_session_id",H(128)),V("sdpHash","sdp_hash",H(128)),V("iceUfrag","ice_ufrag",H(64)),V("assignedPeerId","assigned_peer_id",je(0,4294967295))],ice:[K("fromPlayerId","from_player_id",ye),K("candidate","candidate",H(512)),V("sdpMid","sdp_mid",H(64)),V("sdpMLineIndex","sdp_m_line_index",je(0,255)),V("sdpMLineIndexAlt","sdp_mline_index",je(0,255))],peerJoined:[K("playerId","player_id",ye)],peerLeft:[K("playerId","player_id",ye),V("reason","reason",H(64))],migration:[K("hostPlayerId","new_host_player_id",ye),K("hostEpoch","host_epoch",ot),V("reason","reason",H(64)),V("kickedPlayerIds","kicked_player_ids",Uo),V("migrationComplete","migration_complete",gl)],matchEnded:[V("reason","reason",H(64))],error:[V("code","code",H(64)),V("message","message",H(256))]}));Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));var ze="webrtc_p2p";function fl(t){let e=new Yn({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 L("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let o=ue(r.clusterTargetId),i=o??ue(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!==ze)throw new L("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${ze}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new rt({bridge:t.bridge,matchId:a.matchId,clock:t.clock}),l=new tt({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 et(),...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 hl(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(!Ke());for(let d of tr)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(!Ke());}let a=new Map;return i.push(n.on("matchReady",s=>{let l=s.protocol===ze?"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 bl=["pointerdown","keydown"];function vl(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 bl)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 bl)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 dr(t,e,n,r){let o=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),o}function Bo(t,e){let n=false;return async r=>{let o=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),o}}function Ho(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 Vo=false;async function Rl(t,e,n,r){if(Vo){e.close(),n("busy",true);return}Vo=true;let o=null;try{let i=await Yp(t,r);if(typeof i=="string"){e.close(),n(i,zp(i));return}o=i;let s=await(r.encodeRef??(l=>eg(l,r)))(o);if(o.close(),o=null,s===null){e.close(),n("failed",!0);return}if(s.size>Zp){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{Vo=false,o?.close();}}function zp(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 Yp(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":_l(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=Qp(n);if(!r)return "no_source";let o=Xp(r);if(o!==null)return o;try{return _l(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 Qp(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 _l(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 Zp=8*1024*1024,wl="image/webp",Sl=.92;async function eg(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:wl,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),wl,Sl);})}async function kl(t,e){if(!e)return;let n;try{n=await ng(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 ng(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 xl=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Al(t=globalThis){let n=t[xl];if(n!==void 0)return n;let r=false,o=()=>r,i=[],a=tg(t,o);a!==null&&i.push(a);let s=rg(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,xl,{value:l,configurable:true}),l}function tg(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 rg(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 og=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",ig=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',sg=`${og}${ig}`,Wo=new WeakSet;function Pl(t=globalThis.document){if(t==null||Wo.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(sg),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],Wo.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"),Wo.add(t),"inline")}catch{return null}}function El(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 x=w-s;x>=e&&d.length>0&&(t.report(ag(d,x)),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 ag(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 cr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Cl(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Il(t,e){t!==null&&(t.style.setProperty(cr.top,`${e.top}px`),t.style.setProperty(cr.right,`${e.right}px`),t.style.setProperty(cr.bottom,`${e.bottom}px`),t.style.setProperty(cr.left,`${e.left}px`));}var Tl=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 Ml(){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 lg(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 Ol(t,e,n){if(t===null)return;let r=lg(e,n);for(let o of ["tl","tr","bl","br"])t.style.setProperty(Tl[o].width,`${r[o].width}px`),t.style.setProperty(Tl[o].height,`${r[o].height}px`);}var dg=3e4,ur=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function Ll(t){let e=t.clock??ae,n=t.timeoutMs??dg,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 ur("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 ur(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 it={url:"https://downloads.indiegems.games/sdk/v8.0.0/gem-web-sdk.devtools.min.js",integrity:"sha384-9JqCsteahTi7oeiy1DAoqQsI3oo5LmqWMn4BJSMVSphd3kI1KjKnUWaE+NqmKHFP"};var Sn=null;function cg(){return Sn!==null||(Sn=new Promise((t,e)=>{let n=document.createElement("script");n.src=it.url,n.integrity=it.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Sn=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${it.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{Sn=null,e(new Error(`gem devtools: could not load ${it.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);})),Sn}function Gl(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 cg();return !e()||a!==r?false:(n!==null||(n=s.mount(t(),{openedBy:i,text:Ue,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 ug=1e4,Dl={reason:"unavailable",retryable:false};function Fl(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??ug);},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 ln({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,c)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){c(Dl);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(Dl));},get identity(){return n},get gameVersion(){return r}}}function mg(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var pg=new Set(gt);function gg(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))pg.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function mr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return Ci(async(n,r)=>{let o;try{o=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new re("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 re(`${JSON.stringify(typeof n.path=="string"?mg(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 re(`${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 re(`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 re(`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},...gg(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=yg(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 yg(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 fg=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Jo="embedder_relay_unavailable",hg="embedder_no_relay",bg=new Set([Jo]),zo=new Set([hg]),st=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Ko(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(vg(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 vg(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new b(_g(t),r,{platformCode:t})}function _g(t){return t===void 0||bg.has(t)?"signaling_failed":zo.has(t)?"offer_refused":fg.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Ko=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:",jl="server_shutdown:",ql="kicked:",wg=123;function Sg(t){if(typeof t!="string"||t.length===0||t.length>wg)return {kind:"other"};if(t.startsWith($l)){let e=Fe(t.slice($l.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(jl)?{kind:"server_shutdown",cause:t.slice(jl.length)}:t.startsWith(ql)?{kind:"kicked",detail:t.slice(ql.length)}:{kind:"other"}}function Yo(t,e,n){let r=Sg(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 Xo(){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 Rg=3e3,kg=1e4,xg=15e3;async function pr(t){let e=t.peerConnection;try{Ul(t,"before the handshake started"),Qo(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 Eg(e,t),Qo(t);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new b("invalid_sdp","the offer carried no SDP");$e(o,"offer"),Nl(o,"offer");let i=await Pg(t,o);if(Qo(t),typeof i?.sdp!="string")throw new b("invalid_sdp","the signaling channel answered without an SDP");return $e(i.sdp,"answer"),Nl(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await Tg(n,t),Ul(t,"before the channel opened"),n}catch(n){throw e.close(),Ag(n)}}function Ag(t){return t instanceof b?t:Vl(t)?Ye():new b("connection_failed",Wl(t),{cause:t})}function Nl(t,e){if(ir(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 Pg(t,e){let n=t.exchangeTimeoutMs??kg,r=Hl(t,n),o=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(i=>{throw i instanceof b?i:Vl(i)?Ye():new b("signaling_failed",Wl(i),{cause:i})});return Cg(o,t,r,()=>r.exhausted?Zo("while the offer was in flight"):new b("timeout",`no answer arrived within ${n}ms`))}function Eg(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??Rg);t.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function Tg(t,e){if(e.signal?.aborted)return Promise.reject(Ye());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??xg,o=Hl(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",Bl(g)===void 0?void 0:{cause:Bl(g)}));},m=()=>{s(),a(Ye());},c=()=>{s(),a(o.exhausted?Zo("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 Hl(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 Cg(t,e,n,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(Ye()):new Promise((a,s)=>{let l=c=>{o.clearTimeout(m),i?.removeEventListener("abort",d),c();},d=()=>l(()=>s(Ye())),m=o.setTimeout(()=>l(()=>s(r())),n.ms);i?.addEventListener("abort",d),t.then(c=>l(()=>a(c)),c=>l(()=>s(c)));})}function Ul(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw Zo(`already ${e}`)}function Zo(t){return new b("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function Qo(t){if(t.signal?.aborted)throw Ye()}function Ye(){return new b("aborted","the caller aborted the connection attempt")}function Vl(t){return t?.name==="AbortError"}function Bl(t){return t?.error}function Wl(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:[K("sdp","sdp",H(10240)),V("sessionId","session_id",H(64))],error:[V("code","code",H(64)),V("message","message",H(256))],matchEnded:[V("reason","reason",H(64))]}));function ed(t){let{client:e,clock:n,rooms:r}=t,o=t.signaling??Xo,i=t.log??(_=>console.warn(_)),a=new bn({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(_,R)=>{let P=s.get(_)??new Set;P.add(R),s.set(_,P);},d=(_,R)=>{let P=s.get(_);P!==void 0&&(P.delete(R),P.size===0&&s.delete(_));},m=async _=>{if(r.isHost&&!ni(r)&&r.currentRoom?.matchId===void 0){let R=ue(_.clusterTargetId);await r.startMatch({...R===void 0?{}:{clusterTargetId:R},..._.retry===void 0?{}:{retry:_.retry},..._.signal===void 0?{}:{signal:_.signal}});}return Ql(r.matchConnectionState==="suspended"?await r.reconnectToMatch(ei(_)):await r.awaitMatch(ei(_)))},c=async _=>Ql(await r.pollMatchStatus(ei(_))),p=async(_,R)=>{let P=false;try{let T=await m(_),N=r.currentRoom?.transports;if(N!==void 0&&!N.includes("webrtc"))throw new b("misconfigured",`the room template offers (${N.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 U=_.peerConnection??Zl();P=!0;let W=await pr({peerConnection:U,signaling:R,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...gr(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),k=null;if(_.presentCredential!==!1)try{k=await Un({channel:W,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...gr(_,"onMessage","signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(C){throw we(W),we(U),C}return jg(r,T,W,U,R,_.reportDisconnect!==!1,_.reportConnected!==!1,k,{remember:l,forget:d},_.onMatchEnded)}catch(T){throw P&&Xl(a,T),we(R),T}},g=async(_,R,P,T,N,U)=>{if(_==="webtransport"){let $=T?.webtransport;if($===void 0)throw new b("misconfigured","webtransport is not advertised");let q={credential:P.joinCredential,credentialExpiresAt:P.credentialExpiresAt,clock:n};if(typeof $.named_url=="string"&&$.named_url!==""){let te=Math.max(Math.floor(U/2),1e3);try{return await Wn({url:$.named_url,timeoutMs:te,log:i,...q})}catch(le){if(Zt()!==null)throw le;return i(`[gem] webtransport named dial failed (${Xt(le)}); retrying the pinned dial`),Wn({url:$.url,certHashBase64:$.cert_sha256_b64,timeoutMs:te,log:i,...q})}}return Wn({url:$.url,certHashBase64:$.cert_sha256_b64,timeoutMs:U,...q})}if(_==="websocket"){let $=T?.websocket;if($===void 0)throw new b("misconfigured","websocket is not advertised");return wo({url:$.url,credential:P.joinCredential,credentialExpiresAt:P.credentialExpiresAt,clock:n,timeoutMs:U})}let W=R.peerConnection??Zl(),k,C=await pr({peerConnection:W,signaling:N,clock:n,matchId:P.matchId,credentialExpiresAt:P.credentialExpiresAt,extraChannels:[{label:Hn,ordered:false,maxRetransmits:0}],onExtraChannel:($,q)=>{$===Hn&&(k=q);},...gr(R,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...R.exchangeTimeoutMs===void 0&&R.redial===true?{exchangeTimeoutMs:Og}:{}}),G;try{G=await Un({channel:C,clock:n,credential:P.joinCredential,credentialExpiresAt:P.credentialExpiresAt,wire:Yt,heartbeat:!0,...gr(R,"signal"),...R.welcomeTimeoutMs===void 0?{}:{ceilingMs:R.welcomeTimeoutMs}});}catch($){throw we(C),we(W),$}let F=G.welcome.heartbeatIntervalMs;return {link:Ro(C,W,k,F===void 0?void 0:{clock:n,intervalMs:F}),welcome:G.welcome,channel:C,peerConnection:W}},y=(_,R,P,T,N)=>{let U=false,W;T.link.onClose(F=>{!U&&_.reportDisconnect!==false&&Yo(r,R.matchId,F),W?.(F);}),_.reportDisconnect!==false&&_.reportConnected!==false&&r.notifyMatchConnected(R.matchId);let k={transport:T.link.transport,send:(F,$)=>T.link.send(F,$),onMessage:F=>T.link.onMessage(F),onClose:F=>{W=F;},close:()=>T.link.close()},C=()=>{U||(U=true,we(T.link),we(N));},G=F=>{if(!U){try{_.onMatchEnded?.(F);}catch{}C();}};return l(R.matchId,G),{matchId:R.matchId,transport:P,link:k,joinCredential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(R.matchId,G),C();}}},w=async(_,R)=>{let P=r.currentRoom?.id,T=r.gameId,N=()=>({advert:Vn(r.currentRoom?.settings,_),template:r.currentRoom?.transports??null});if(P===void 0||T===null)return N();try{let U=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(P)}`,R);return {advert:Vn(U.settings,_),template:fn(U.transports)??r.currentRoom?.transports??null}}catch{return N()}},x=(_,R)=>{let P=_??Kl;return R.length===0?P:P.filter(T=>R.includes(T))},I=async(_,R,P)=>{try{let T=await m(_),{advert:N,template:U}=await w(T.matchId,_.signal),W=x(U,R),k=W.filter(Y=>Dg(Y,N)),C=Zt();if(C!==null&&W.includes("webtransport")&&N?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${C} (learned on an earlier dial in this page)`),k.length===0){let Y=U===null?`the default order (${Kl.join(", ")})`:`the room template's transports (${U.join(", ")||"none"})`;throw new b("misconfigured",`none of ${Y}`+(R.length>0?`, narrowed to (${R.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let G=_.transportAttemptTimeoutMs??Mg,F=()=>_.deadlineAt===void 0?1/0:_.deadlineAt-n.now(),$=Y=>t.signalingReady===void 0||Y<=0?Promise.resolve(!0):t.signalingReady(Y),q=[],te=[];for(let Y of k){if(F()<zl){i(`[gem] ${Y} rung not tried: the reconnect budget is spent`);break}te.length>0&&T.credentialExpiresAt-n.now()<Yl&&(T=await c(_)),te.push(Y);let Me=!1,be=!1,Ce={attempts:0,waitedMs:0};for(;;){if(Y==="webrtc"&&_.redial===!0){let X=Math.min(Jl,F());await $(X)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(X)}ms; offering anyway`);}let Oe=Math.max(Math.min(G,F()),zl);try{return y(_,T,Y,await g(Y,_,T,N,P,Oe),P)}catch(X){let z=X instanceof b?X:new b("connection_failed",X instanceof Error?X.message:String(X),{cause:X});if(Y==="webrtc"&&Xl(a,z),(z.reason==="credential_expired"||z.reason==="credential_reused")&&!Me){Me=!0,T=await c(_);continue}if(Y==="webrtc"&&z.reason==="signaling_failed"&&z.platformCode===Jo&&!be){be=!0;let me=Math.min(Jl,F());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(me)}ms for the socket before offering again`),await $(me))continue}if(z.reason==="join_rate_limited"){let me=Gg(Ce,Math.random,F());if(me!==null){if(Ce.attempts+=1,Ce.waitedMs+=me,i(`[gem] ${Y} rung: the server is rate-limiting this player's joins; waiting ${Math.round(me)}ms before presenting again (retry ${Ce.attempts} of ${td.maxAttempts})`),await Kt(n,me,_.signal),_.signal?.aborted)throw new b("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<Yl&&(T=await c(_));continue}}if(Lg.has(z.reason)||z.reason==="credential_expired"||Y==="webrtc"&&nd(z)){i(`[gem] ${Y} rung failed (${z.reason}): ${Xt(z.cause??z)} \u2014 `+(te.length<k.length?`falling through to ${k[te.length]}`:"no rungs left")),q.push(z);break}throw i(`[gem] ${Y} rung refused the session (${z.reason}): ${z.message}`),z}}}let le=q[q.length-1];throw le===void 0?new b("timeout",`the reconnect budget ran out before any transport (${k.join(", ")}) could be tried`):new b(le.reason,`every transport tried (${te.join(", ")}) failed; the last said: ${le.message}`,{cause:q,platformCode:le.platformCode})}catch(T){throw we(P),T}};return {listClusterTargets:async(_={})=>io({client:e,..._}),handleMatchEnded(_,R){let P=s.get(_);if(P!==void 0){s.delete(_);for(let T of P)T(R);}},connect:(async(_={})=>{let R=_.signaling??o();return _.transports===void 0?p(_,R):I(_,_.transports,R)})}}var Kl=["webtransport","webrtc","websocket"],Mg=1e4,Og=5e3,Jl=3e3,zl=1e3,Yl=1e4,Lg=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function nd(t){return t.platformCode!==void 0&&zo.has(t.platformCode)}var td={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Gg(t,e=Math.random,n=1/0){let r=td;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 Dg(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Qt():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||Fg(e.websocket.url)}function Fg(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return St(e)}function ei(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var $g=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Xl(t,e){e instanceof b&&(!$g.has(e.reason)&&!nd(e)||t.report([{type:"connection_failures_total",value:1}]));}function jg(t,e,n,r,o,i,a,s,l,d){let m=false,c=()=>{m||Yo(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 ni(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Ql(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!==Wt)throw new b("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Wt}' 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 Zl(){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 gr(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var qg=1e4;function rd(t,e){return ti(t,e)}function ti(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 ln({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??qg);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 oi={};Ud(oi,{acceptTransfer:()=>Ng,addEntityProgression:()=>Ug,adminAction:()=>Bg,cancelInventoryTransfer:()=>Hg,claimEntityProgressionRewards:()=>Vg,closeGameRoom:()=>Wg,createEntityBatchOrder:()=>Kg,createEntityOrder:()=>Jg,createSession:()=>zg,deleteEntityGameSetting:()=>Yg,deleteEntitySave:()=>Xg,deleteSession:()=>Qg,deleteShowcaseValue:()=>Zg,executeEntityRecipe:()=>ey,finalizeSaveUpload:()=>ny,getChannelAssignment:()=>ty,getDropRates:()=>ry,getEntityCurrency:()=>oy,getEntityGameSetting:()=>iy,getEntityInventory:()=>sy,getEntityInventoryItem:()=>ay,getEntityLeaderboard:()=>ly,getEntityOrder:()=>dy,getEntityProgression:()=>cy,getEntityRecipeAvailability:()=>uy,getEntityRecipeUsage:()=>my,getEntitySave:()=>py,getEvent:()=>gy,getGameRoomV2:()=>yy,getLeaderboard:()=>fy,getPlayerGameProfile:()=>hy,getPurchaseCatalog:()=>by,getResolvedTemplate:()=>vy,getRoomArgs:()=>_y,getShowcaseValue:()=>wy,getTransferDetails:()=>Sy,ingestAnalyticsEvents:()=>ri,initiateInventoryTransfer:()=>Ry,invokeFunction:()=>ky,kickPlayer:()=>xy,listChallenges:()=>Ay,listEntityGameSettings:()=>Py,listEntityOrders:()=>Ey,listEntityProgressions:()=>Ty,listEntitySaves:()=>Cy,listEvents:()=>Iy,listGameRooms:()=>My,listResolvedTemplates:()=>Oy,listTransfers:()=>Ly,maxEntityProgression:()=>Gy,putEntityGameSetting:()=>Dy,putRoomArgs:()=>Fy,putShowcaseValue:()=>$y,rejectTransfer:()=>jy,requestSaveUploadUrl:()=>qy,resetEntityProgression:()=>Ny,simulateEntityOrder:()=>Uy,transferHostV2:()=>By,updateGameRoomV2:()=>Hy});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 Ng(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Ug(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 Bg(t,e,n,r){let o=`/v1/voice/sessions/${h(e)}/admin`;return t.client.post(o,n,r?.signal)}async function Hg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/cancel`;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)}/claim`;return t.client.post(a,o,i?.signal)}async function Wg(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 Jg(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 zg(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Yg(t,e,n,r,o){let i=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(i,o?.signal)}async function Xg(t,e,n,r,o){let i=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(i,o?.signal)}async function Qg(t,e,n){let r=`/v1/voice/sessions/${h(e)}`;return t.client.delete(r,n?.signal)}async function Zg(t,e,n,r){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.delete(o,r?.signal)}async function ey(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 ny(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 ty(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 ry(t,e,n){let r=`/v1/inventory/loot-tables/${h(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function oy(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 iy(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 sy(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 ay(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 ly(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 dy(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 cy(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 uy(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 my(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 py(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 gy(t,e,n){let r=`/v1/events/${h(e)}`;return t.client.get(r,n?.signal)}async function yy(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 fy(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 hy(t,e,n){let r=`/v1/profiles/players/${h(e)}`;return t.client.get(r,n?.signal)}async function by(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 vy(t,e,n){let r=`/v1/game-room-templates/${h(e)}`;return t.client.get(r,n?.signal)}async function _y(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 wy(t,e,n,r){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.get(o,r?.signal)}async function Sy(t,e,n){let r=`/v1/inventory/transfers/${h(e)}`;return t.client.get(r,n?.signal)}async function ri(t,e,n){let r=`/v1/games/${h(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true})}async function Ry(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ky(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function xy(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 Ay(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 Py(t,e,n,r){let o=`/v1/settings/${h(e)}/${h(n)}`;return t.client.get(o,r?.signal)}async function Ey(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 Ty(t,e,n,r){let o=`/v1/inventory/${h(e)}/${h(n)}/progressions`;return t.client.get(o,r?.signal)}async function Cy(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 Iy(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 My(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 Ly(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 Gy(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 Dy(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 Fy(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 $y(t,e,n,r,o){let i=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.put(i,r,o?.signal)}async function jy(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function qy(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 Ny(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 Uy(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 By(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 Hy(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 Vy=1e4,Wy=50,Ky=1e3,Jy=65536-4*1024,od=t=>typeof t=="number"?t:0,zy=t=>typeof t=="string"?t:"";function id(){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 Yy(t){return t?.retryable===true}function Xy(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:od(i.index),code:zy(i.code)}}):[];return {accepted:od(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function sd(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 ad(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(()=>{});},Vy));},g=()=>{let w=Math.min(r.length,100),x=128;for(let I=0;I<w;I+=1){let M=r[I];if(M===void 0)break;if(x+=JSON.stringify(sd(M,0)).length+1,x>Jy)return Math.max(1,I)}return w};async function y(w){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};c();let x=r.splice(0,g()),I=o;o=0;let M=Math.round(t.clock.now()),_={batch_id:id(),sent_at_ms:M,events:x.map(R=>sd(R,M))};s=true;try{let R=await ri(n,_,w===void 0?void 0:{signal:w}),P=Xy(R,I);for(let T of P.rejected)m(`[gem] analytics: an event was refused (${T.code}). See the analytics_events section of your game config.`);return P}catch(R){if(Yy(R))for(r=[...x,...r],o+=I;r.length>e;)r.shift(),o+=1;else m(`[gem] analytics: ${x.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(R)}`);throw R}finally{s=false,r.length>0&&p();}}return {track(w,x,I={}){if(a)return;if(typeof w!="string"||w===""){d||(d=true,m(`[gem] analytics: '${x}' 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(x.startsWith(zr)){l||(l=true,m(`[gem] analytics: '${x}' 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[R,P]of Object.entries(I))typeof P=="string"?M[R]=P:typeof P=="number"&&Number.isFinite(P)&&(_[R]=P);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:id(),playerId:w,name:x,atMs:t.clock.now(),dimensions:M,measures:_}),r.length>=Wy?y().catch(()=>{}):p();},flush:w=>y(w),get pending(){return r.length},dispose(){a=true,c(),r=[],o=0;}}}function ld(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().");pn(r);let i=await t({player_id:n,...r===void 0?{}:{periods_back:r},...o===void 0?{}:{signal:o}});return qt(i)}}}function Qy(t){let e={};for(let[n,r]of Object.entries(oi))if(typeof r=="function"){let o=r;e[n]=(...i)=>o(t,...i);}return e}function Rn(t,e={}){let n=e.clock??ae,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=ti(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=mr({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=Qy({client:a,gameId:()=>s.gameId}),d=s.gameRoomId,m=t.endMatch,c=t.log,p=ad({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:ld(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}),x=w.modified?w.body:void 0;if(x?.room_args==null||x.room_args_template==null)throw new O("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:x.room_args,room_args_template:x.room_args_template}}}},dispose:()=>{p.dispose(),o.dispose();}}}function Xe(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function kn(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function at(t){return typeof t=="string"?t:t.slice().buffer}function yr(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 Zy=5e3,dd=3e4,cd=2e3,ef=1e4,ud=1;async function md(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,S)=>{l&&(s=s.then(async()=>{if(!d)try{await S();}catch(j){i(`the bundle's ${f} handler threw: ${Qe(j)}. Serving continues.`);}}));},c=true,p,g,y,w=f=>{if(!c)return;c=false,m("leave",()=>a.leave?.(r,{cause:f??"left"}));let S=g;S&&queueMicrotask(()=>S(f));},x={send(f,S){if(!c)return;let j=kn(Xe(S));m("message",()=>a.message?.(r,f,typeof f=="string",{reliable:j.reliable,ordered:j.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){w("closed");}},I=(f,S)=>{if(!c)return;let j=kn(Xe(S));queueMicrotask(()=>{c&&p?.(f,j);});},M=new Map,_=f=>{let S=[];for(let j of Ie){let Q=f.channels[j];try{Q.binaryType="arraybuffer";}catch{}let Se=kn(j),nn=tn=>{let rn=yr(tn?.data);rn!==null&&m("message",()=>a.message?.(f.playerId,rn.data,rn.isText,{reliable:Se.reliable,ordered:Se.ordered}));};Q.addEventListener("message",nn),S.push(()=>Q.removeEventListener("message",nn));}M.get(f.playerId)?.forEach(j=>j()),M.set(f.playerId,S);},R=f=>{M.get(f)?.forEach(S=>S()),M.delete(f);},P=new Set,T=new Map,N=(f,S,j)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...S?{rejoin:true}:{},...j?{superseded:true}:{}}),U=f=>{let S=M.has(f.playerId),j=P.has(f.playerId);P.add(f.playerId),_(f),S&&m("leave",()=>a.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>a.join?.(f.playerId,N(f,j,S)));},W=new Set,k=(f,S,j)=>{if(f===r){I(S,j);return}let Q=n.peer(f);if(Q===null){let Se=T.get(f);if(Se!==void 0&&e.clock.now()-Se<cd)return;W.has(f)||(W.add(f),i(`send to '${f}' dropped: no such connected player`));return}Q.send(at(S),Xe(j));},C={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 S of n.peers)f.push(S.playerId);return f},profile(f){let S=e.room()?.members.find(j=>j.playerId===f);if(!(!S||S.displayName===void 0))return {displayName:Ue.toPlain(S.displayName),...S.displayTag===void 0?{}:{displayTag:Ue.toPlain(S.displayTag)},...S.discriminator===void 0?{}:{discriminator:S.discriminator}}},playerNumber(f){return f===r?ud:n.peer(f)?.assignedPeerId},send(f,S,j){k(f,S,j);},broadcast(f,S){let j=S?.except;c&&r!==j&&I(f,S);for(let Q of n.peers)Q.playerId!==j&&Q.send(at(f),Xe(S));},async endMatch(){let f=await Oe();return f.answer!=="ok"&&i(f.cause),f.answer},kick(f,S){if(f===r){w(S??"kicked");return}n.kick(f).catch(j=>{i(`kick of '${f}' failed: ${Qe(j)}`);});},log(f){i(f);},warn(f){i(`\u26A0 ${f}`);}},G=()=>{},F=new Promise(f=>{G=f;}),$=[],q=null,te=async(f,S)=>{l=false;let j=s.then(async()=>{try{await a.shutdown(f);}catch(Q){i(`the bundle's shutdown threw: ${Qe(Q)}`);}});s=j,await j,me();for(let Q of $.splice(0))Q();for(let Q of [...M.keys()])R(Q);w(S);},le=(f,S)=>q||(q=(async()=>{await te(S,f),n.close(),G();})(),q),Y=()=>q||(q=(async()=>{await te({reason:"signal"},"left"),await n.leave().catch(f=>i(`leaving the match failed: ${Qe(f)}`)),G();})(),q),Me=()=>q||(q=(async()=>{l=false;let f=await Oe();f.answer==="ok"?(await te({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(i(`${f.cause}; leaving instead`),await te({reason:"signal"},"left"),await n.leave().catch(S=>i(`leaving the match failed: ${Qe(S)}`))),G();})(),q),be=null,Ce=()=>(be??=Rn(C,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),be),Oe=async()=>{try{return await Ps({client:Ce().client,gameId:()=>C.gameId},C.matchId,{},{signal:AbortSignal.timeout(Zy)}),{answer:"ok"}}catch(f){return f instanceof O&&(f.reason==="forbidden"||f.reason==="not_found")?{answer:f.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${f.reason})`}:{answer:"failed",cause:`ending the match failed: ${Qe(f)}`}}},X=null,z=false,me=()=>{z=true,X!==null&&(e.clock.clearTimeout(X),X=null);},qe=async()=>{if(X=null,!z){try{await Ce().client.post(`/v1/games/${encodeURIComponent(C.gameId)}/matches/${encodeURIComponent(C.matchId)}/heartbeat`,void 0,AbortSignal.timeout(ef));}catch(f){if(f instanceof O&&(f.reason==="forbidden"||f.reason==="not_found")){i(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),me();return}i(`heartbeat failed: ${Qe(f)}`);}z||(X=e.clock.setTimeout(()=>{qe();},dd));}},hr=()=>{z||X!==null||(X=e.clock.setTimeout(()=>{qe();},dd));};{let f=G;G=()=>{me(),be?.dispose(),be=null,f();};}let en=Promise.resolve().then(()=>a.init(C));s=en.then(()=>{},()=>{}),m("join",()=>a.join?.(r,{playerNumber:ud,transport:"loopback"})),$.push(n.on("peerJoined",U)),$.push(n.on("peerLeft",(f,S)=>{R(f);let j=e.clock.now();for(let[Q,Se]of T)j-Se>=cd&&T.delete(Q);T.set(f,j),W.delete(f),m("leave",()=>a.leave?.(f,{cause:S}));})),$.push(n.on("error",f=>{i(`\u26A0 session error: ${f.message}`);})),$.push(n.on("matchEnded",f=>{q||ii(y,f),le("match ended",{reason:"match_ended",platform_reason:f});})),$.push(n.on("hostChanged",f=>{f!==r&&le("host migrated",{reason:"host_migrated"});}));for(let f of n.peers)U(f);try{await en,hr();}catch(f){l=false,me(),d=true;for(let S of $.splice(0))S();for(let S of [...M.keys()])R(S);throw n.leave().catch(()=>{}),G(),f}return {matchId:n.matchId,localLink:x,onMatchEnded(f){y=f;},end:Me,leave:Y,stop:f=>le(f,{reason:"stopped"}),done:F}}function ii(t,e){try{t?.(e);}catch{}}function Qe(t){return t instanceof Error?t.message:String(t)}function si(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 pd(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,o=new Map,i=async s=>{r.isHost&&!ni(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!==ze)return si("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return si("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 md(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===ze){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),of(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 et(),w=async()=>t.p2p.connect({...a(s),certificate:y}),x=await w(),I=af(x,w,d,M=>{r.notifyMatchDisconnected(M).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(x.matchId,{redial:I.redial,abandon:I.abandon}),I.onClosed(()=>{e.get(x.matchId)?.abandon===I.abandon&&e.delete(x.matchId);})),I}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=sf(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 gd="link_closed",nf="host_unreachable",tf=new Set(["failed","closed"]);function rf(t){return tf.has(t)?gd:nf}function of(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 sf(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,x)=>s?.(w,x)),y.link.onClose(w=>{if(y!==i||a==="closed")return;if(m||!r){p(w);return}let x=n.matchSession;if(x.phase==="suspended"&&x.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 af(t,e,n,r,o,i=false){let a=t.matchId,s=t,l,d,m=[],c=[],p=[],g=false,y=false,w=false,x=false,I="connected",M=k=>{if(g)return;g=true,I="closed";for(let G of m.splice(0))G();for(let G of c.splice(0))G();for(let G of p.splice(0))G();let C=d;C&&queueMicrotask(()=>C(k));},_=k=>{for(let C of m.splice(0))C();for(let C of Ie){let G=k.channels[C];try{G.binaryType="arraybuffer";}catch{}let F=kn(C),$=q=>{let te=yr(q?.data);te!==null&&l?.(te.data,F);};G.addEventListener("message",$),m.push(()=>G.removeEventListener("message",$));}},R=()=>s.peer(s.hostPlayerId),P=k=>{if(!(g||s.isHost)&&I!=="suspended"){if(r?.(k),i){I="suspended";return}M(k);}},T=k=>{for(let C of Ie){let G=k.channels[C];if(typeof G.addEventListener!="function")continue;let F=()=>{R()===k&&P(gd);};G.addEventListener("close",F),m.push(()=>G.removeEventListener?.("close",F));}},N=k=>{_(k),T(k),!g&&(I="connected",o?.());},U=k=>{for(let C of c.splice(0))C();c.push(k.on("migrating",()=>{x=true;})),c.push(k.on("hostChanged",C=>{if(x=false,C===k.playerId){M("host_migrated_here");return}let G=R();G!==null&&N(G);})),c.push(k.on("peerJoined",C=>{C.playerId===k.hostPlayerId&&N(C);})),c.push(k.on("matchEnded",C=>{g||ii(n,C),M(C);})),c.push(k.on("peerLeft",(C,G)=>{C===k.hostPlayerId&&P(rf(G));}));};U(s);let W=R();return W!==null&&N(W),{matchId:a,protocol:"p2p",get state(){return I},send(k,C){I==="connected"&&R()?.send(at(k),Xe(C));},onMessage(k){l=k;},onClose(k){d=k;},close(){y=true,M("closed"),s.leave().catch(()=>{});},async redial(){if(I==="closed")return "closed";if(I==="connected"||w)return "connected";if(x)throw new L("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");w=true;let k;try{for(let G of m.splice(0))G();for(let G of c.splice(0))G();s.close(),k=await e();}finally{w=false;}if(g)return y?k.leave().catch(()=>{}):k.close(),"closed";s=k,U(s);let C=R();if(C===null)throw s.close(),new L("connection_failed","this peer rejoined the match but the host never answered with a link");return N(C),"connected"},abandon(k){M(k);},onClosed(k){g?k():p.push(k);}}}function ai(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 lf=12e4;function Ze(t,e){return {outcome:t,reason:e}}function yd(t){let e=false,n=new Map;return {api:{request(r){if(!t.bridge.parentSupports("purchases"))return Promise.resolve(Ze("unavailable","error"));if(e)return Promise.resolve(Ze("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(Ze("unavailable","error")),t.timeoutMs??lf);let l=false;try{l=t.bridge.requestPurchase(o,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||s(Ze("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(Ze(o,Ws(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(Ze("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(Ze("unavailable","error"));})();}}}async function fd(t,e){try{return (await cs(t,e)).granted?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}var df=6e5;function hd(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??df);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 cf=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid"]),uf=["utm_"];function bd(t){return cf.has(t)||uf.some(e=>t.startsWith(e))}var vd=16,_d=512,mf=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,pf=/[\p{Cc}\p{Cf}]/u,gf=/\p{Cs}/u,Te="[gem] gem.share.request:";function wd(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(!yf(l))throw new TypeError(`${Te} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>vd)throw new TypeError(`${Te} at most ${vd} params; got ${d.length}`);let m=[];for(let[c,p]of d){let g=JSON.stringify(c);if(!mf.test(c))throw new TypeError(`${Te} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(bd(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>_d)throw new TypeError(`${Te} param ${g}: a value is at most ${_d} characters`);if(pf.test(p))throw new TypeError(`${Te} param ${g}: control and format characters are not allowed`);if(gf.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 yf(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var vf="(any-pointer: coarse)";function _f(t){let e=Array.isArray(t)?t:[t],n=[],r=1e4;for(let o of e){if(typeof o!="number"||!Number.isFinite(o)||o<0)return null;if(n.length===99||r===0)continue;let i=Math.min(Math.trunc(o),1e4,r);n.push(i),r-=i;}return n.length%2===0&&n.pop(),n.every(o=>o===0)?[]:n}function Sd(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?m=>matchMedia(m):void 0},o=r.navigator,i,a=new Set,s=()=>typeof o?.vibrate!="function"||r.matchMedia===void 0?false:(i??=r.matchMedia(vf),i.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,c)=>{a.has(m)||(a.add(m),n!==null&&(n===void 0?console.warn(c):n(c)));};return {get available(){return s()||l()},vibrate(m){let c=s();if(!c&&!l())return false;let p=_f(m);if(p===null)return d("pattern","[gem] gem.vibration.vibrate did nothing: a pattern is a number of milliseconds, or an array of them, each finite and not negative."),false;if(o?.userActivation?.hasBeenActive!==true)return d("activation","[gem] gem.vibration.vibrate did nothing: the player has not tapped or pressed a key in your game yet, and browsers allow vibration only after that."),false;if(c)try{return o.vibrate(p)===!0}catch{return false}let g=e.requestVibrate(p);return g||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),g}}}var wf=18e4,Rd=32,Sf=/^[a-z0-9_-]+$/;function Rf(t){return t==="interstitial"||t==="rewarded"}function kd(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>Rd||!Sf.test(r.placement)||!Rf(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(Rd)} 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??wf);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 li=16384;function xd(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:kf(e)}function kf(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 xf=1e4,Af=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=Af){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=xd(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??xf);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 lt=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 Pd(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function di(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 fr(t,e){let n=[];for(let r of Array.isArray(e)?e:[]){if(n.length===4)break;if(typeof r!="object"||r===null)continue;let{id:o,label:i}=r;typeof o!="string"||o.length===0||o.length>32||typeof i!="string"||i.trim().length===0||n.some(a=>a.id===o)||n.push({id:o,label:i.trim().slice(0,40)});}return n.length===0?{settings:t===true}:{settings:t===true,items:n}}function Ed(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Pf(t){let e=t.untrusted,n=ge(e.displayName),r=e.displayTag||e.displayHandle,o=r?ge(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 Ef=1e4,dt=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??ae,this.inbound=new Pn(this.clock),this.outbound=new Pn(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=>Cr(s,e.origin))||Us(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=wt["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!Cr(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=Bs(vt,o.versions);return a===null?(i.onmessage=null,i.postMessage({gem:B,type:"gem.error",code:"version_mismatch",message:`frame supports v${vt.min}..v${vt.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:B,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:B,type:"gem.ready"});}settled(e=Ef){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=i=>{this.clock.clearTimeout(o),n(i);},o=this.clock.setTimeout(()=>{let i=this.settleWaiters.indexOf(r);i>=0&&this.settleWaiters.splice(i,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem:B,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:B,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:B,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:B,type:"gem.exit"}:{gem:B,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:B,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:B,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:B,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:B,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let n={gem:B,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:Pd(e.origin.x),y:Pd(e.origin.y)}),this.send(n),true}setWalletVisible(e,n){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:B,type:"gem.walletDisplay",...di(e,n?.only)})}setMenu(e,n){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:B,type:"gem.menu",...fr(e,n)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:B,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:B,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:B,type:"gem.frameStats",fps:Ed(e.fps,1e3),frameTimeP95Ms:Ed(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:B,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:B,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:B,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:B,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,o,i,a){return this.send({gem:B,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:B,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:B,type:"gem.requestAd",requestId:e,placement:n,format:r})}requestSignIn(e){return this.send({gem:B,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,o){return this.send({gem:B,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...o===void 0?{}:{params:o}})}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(_t)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(_t)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(_t)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:B,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}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=wt[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||Td(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=wt[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=js(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.menuSelect":this.options.onMenuSelect?.(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 Td(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?.(Pf(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:B,type:"gem.screenshot.denied",reason:e,retryable:n});}};function Td(t){for(let e of t)try{e?.close?.();}catch{}}var Cd="https://api.gemarcade.com";function ci(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 Tf=new Set(["localhost","127.0.0.1","[::1]"]);function Id(t){let e=ci(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!Tf.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 Cf=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),If=Cd,Md=8e3,ui=15e3,Mf=9e4,Of=1/0,Lf=8e3,Gf=5e3,Df=5e3;async function Ff(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 ct(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 bR(t={}){let e=t.clock??ae,n=t.log===void 0?u=>console.info(u):t.log,r=t.baseUrl??void 0;if(r!=null){let u=ci(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=ya(typeof window>"u"?void 0:window.location?.search),i=Ho();i.mark("sdk created");let a=()=>Jt(ee.gameVersion,t.clientVersion?.gameVersion),s=new qn({client:()=>sn,clock:e,gameId:()=>ee.identity?.gameId??null,playerId:()=>ee.identity?.playerId??null,environment:()=>{let u=a();return {sdk_version:Ei(),...u===null?{}:{game_version:u}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),l=vl(()=>{i.mark("engaged"),s.release(),S.reportEngaged();},typeof window>"u"?{}:window),d=u=>{if(u===false)return null;let A=u?.attempts??Of,D=u?.budgetMs??Mf;return !(A>0)||!(D>0)?null:{attempts:A,budgetMs:D,maxDelayMs:u?.maxDelayMs??Lf}},m=u=>{u.on("created",()=>{i.mark("room created");}),u.on("joined",()=>{i.mark("room joined");}),u.on("matchAllocationStarted",()=>{i.mark("allocation started");}),u.on("matchReady",()=>{i.mark("match ready");}),u.on("matchFailed",()=>{i.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 lt;let c=t.allowedEmbedders;if(c!=null&&!Array.isArray(c))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let p=Array.from(c??[]),g=p.filter(u=>typeof u!="string"||!Tr(u));if(g.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${g.length===1?"an entry":"entries"} that ${g.length===1?"is":"are"} not an origin: ${g.map(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 y=Object.freeze([...new Set([...Cf,...p])]),w=ct(e),x=ct(e),I=ct(e),M=wa(n),_=ct(e),R=t.manageAudio===false?null:Al();t.selectableText!==true&&Pl();let P=null,T=()=>{P!==null&&(x.current!==null&&x.current.muted===P||S.reportMuted(P));},N=null,U=null,W=()=>{if(N===null)return false;let u=JSON.stringify(di(N.visible,N.only));return u===U?S.parentSupports("walletDisplay"):S.setWalletVisible(N.visible,N)?(U=u,true):false},k=null,C=null,G=()=>{if(k===null)return false;let u=typeof k.onSettings=="function",A=JSON.stringify(fr(u,k.items));return A===C?S.parentSupports("gameMenu"):S.setMenu(u,k.items)?(C=A,true):false},F=El({report:u=>S.reportFrameStats(u)}),$=false,q=Gl(()=>ki,()=>$),te=u=>{let A=$&&!u,D=$!==u;if($=u,A&&q.close(),!!D)try{t.onDevToolsPermissionChange?.(u);}catch(ne){n?.(`[gem] onDevToolsPermissionChange threw: ${ne instanceof Error?ne.message:String(ne)}`),queueMicrotask(()=>{throw ne});}},le=r??If,Y=r!==void 0,Me,be=u=>(n?.(`[gem] token refused: ${u}`),t.onError?.("internal",u),false),Ce=(u,A)=>{if(u===void 0)return A!==void 0?be("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let D=Id(u);return D!==null?be(`the embedder named an API root that cannot be used: ${D}. Its value is withheld here rather than written to logs.`):Me!==void 0&&Me!==u?be("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(Me=u,Y||(le=u),true)},Oe=window.location?.origin,X=null,z=-1/0,me=2e3,qe=new Set,hr=u=>X!==false?Promise.resolve(true):new Promise(A=>{let D=e.setTimeout(()=>{qe.delete(ne),A(false);},u),ne=()=>{e.clearTimeout(D),qe.delete(ne),A(true);};qe.add(ne);}),en=()=>{},f=null,S=new dt({allowedEmbedders:y,...typeof Oe=="string"&&Oe!==""?{selfOrigin:Oe}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","earnAllowance","share","vibration","frameStats","walletDisplay","gameMenu","engagement","reservedAreas","viewport","purchases","deviceSettings","ads","signIn","friendChallenges",...t.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:u=>{f=u,t.onRefused?.(u);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:u=>{ee.onBridgeState(u),u!=="connected"&&F.setRequested(false),U=null,C=null,u==="refused"&&(console.error("[gem] this game refused the page that framed it"+(f===null?"":` (${f})`)+", 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."),en()),u==="connected"&&(i.mark("bridge connected"),Dd(),T(),W(),G(),S.unbiddenLaunch&&!l.engaged&&s.hold(),s.startSession(),l.engaged&&S.reportEngaged()),t.onStateChange?.(u);},onPlayer:u=>{w.set(u),t.onPlayer?.(u);},onPrefs:u=>{let A={reducedMotion:u.reducedMotion,muted:u.muted,locale:u.locale,showFrameStats:u.showFrameStats===true};x.set(A),R?.setMuted(A.muted),F.setRequested(A.showFrameStats&&S.parentSupports("frameStats")),t.onPrefs?.(A);},onCohorts:u=>{let A=Object.freeze(u.cohorts.map(D=>Object.freeze({experimentId:D.experimentId,variantKey:D.variantKey})));I.set(A),t.onCohorts?.(A);},onEarnAllowanceChanged:()=>M.emit(),onViewport:u=>{let A=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(ne=>Object.freeze({x:ne.x,y:ne.y,width:ne.width,height:ne.height})))});_.set(A);let D=Cl();Il(D,A.insets),Ol(D,A.reserved,Ml()),t.onViewport?.(A);},onPause:u=>{s.setPaused(u.paused),F.setPaused(u.paused),t.onPause?.(u.paused);},onMenuSelect:u=>{if(k===null)return;if(u.entry==="settings"){k.onSettings?.();return}(fr(false,k.items).items??[]).some(D=>D.id===u.id)&&k.items?.find(D=>D.id===u.id)?.onSelect?.();},onWillTerminate:u=>{s.endSession(u.reason),t.onWillTerminate?.({reason:u.reason,graceMs:u.graceMs});},onToken:u=>{let A=u.garden;if(te(u.allowDevTools===true),!Ce(u.apiBaseUrl,A))return;let D=u;ee.onToken(D);let ne=ee.identity;ne&&(Q.set(ne),Se||(Se=true,ce.reconcileSeats().catch(()=>{}))),rn.push({token:D.token,expiresAt:D.expiresAt});},onTokenDenied:u=>{te(false),ee.onDenied(u);},onScreenshot:(u,A,D)=>{Rl(u,A,D,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{kl(S,t.onFeedbackContext);},onDevtools:u=>{u==="close"?q.close():u==="open"?q.openFrom("platform").catch(()=>{}):q.isOpen?q.close():q.openFrom("platform").catch(()=>{});},onRoomEvent:u=>ce.handleRoomEvent({event:u.event,roomId:u.roomId,...u.matchId===void 0?{}:{matchId:u.matchId},...u.version===void 0?{}:{version:u.version},...u.reason===void 0?{}:{reason:u.reason},...u.platform===void 0?{}:{platform:u.platform}}),onSeatedEvent:u=>ce.handleSeated(u.roomId),onAutoStartFailedEvent:u=>ce.handleAutoStartFailed(u.roomId,u.code),onSocketState:u=>{let A=X;if(X=u.connected,u.connected)for(let ne of [...qe])ne();if(!u.connected||A===true)return;let D=e.now();D-z<me||(z=D,ce.reconcile().catch(()=>{}));},onSignalEvent:u=>{let A=typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:{};an.handleSignalEvent(u.matchId,u.event,A),u.event==="matchEnded"&&ce.reconcile({matchId:u.matchId,...typeof A.reason=="string"?{reason:A.reason}:{}}).catch(()=>{});},onDedicatedEvent:u=>{u.event==="matchEnded"&&(xn.handleMatchEnded(u.matchId,u.reason),ce.reconcile({matchId:u.matchId,...u.reason===void 0?{}:{reason:u.reason}}).catch(()=>{})),j.handleEvent(u);},onClusterTarget:u=>mt.accept(u.clusterTargetId,u.clusterTargetIds),onLocalServer:u=>pt.accept(u),onLocalServerDenied:u=>pt.refuse(u),onPartyResult:u=>gi.settle(u.requestId,u.partyId),onPurchaseResult:u=>fi.settle(u),onDeviceSettings:u=>{ut.receive(u),t.onDeviceSettings?.(ut.api.current);},onDeviceSettingsResult:u=>ut.settle(u),onAdResult:u=>hi.settle(u),onSignInResult:u=>bi.settle(u),onFriendChallengeResult:u=>vi.settle(u)}),j=new st({bridge:S}),Q=ct(e);en=()=>{Q.release(),w.release(),I.release();},S.currentState==="refused"&&en();let Se=false,nn=new Set,tn,rn={current:()=>tn,subscribe:u=>(nn.add(u),tn!==void 0&&u(tn),()=>nn.delete(u)),push:u=>{tn=u;for(let A of [...nn])try{A(u);}catch(D){n?.(`[gem] a server-token listener threw: ${D instanceof Error?D.message:String(D)}`);}}},ee=Fl({bridge:S,clock:e,onStateChange:(u,A)=>{if(u==="ready"){if(i.mark("token ready")){let D=i.marks.find(ne=>ne.name==="token ready")?.at;s.trackPlatform("gem_boot_ready",D===void 0?{}:{boot_ms:Math.max(0,Math.round(D))});}}else u==="lost"&&(i.mark("token lost"),s.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(u,A);}}),pi=()=>{let u=ee.identity;return !u||ee.source.currentState==="lost"?null:`${u.playerId}\0${u.gameId}\0${u.channel}`},Dd=()=>{i.mark("token requested"),ee.source.get().catch(()=>{});},gi=ai({bridge:S,clock:e}),yi={},fi=yd({bridge:S,clock:e,onDropped:u=>t.onError?.("internal",u),confirm:async u=>yi.confirm?.(u)??"unknown"}),ut=Ad({bridge:S,clock:e,onDropped:u=>t.onError?.("internal",u)}),hi=kd({bridge:S,clock:e,onDropped:u=>t.onError?.("internal",u)}),bi=hd({bridge:S,clock:e,onDropped:u=>t.onError?.("internal",u)}),vi=_a({bridge:S,clock:e,onDropped:u=>t.onError?.("internal",u)}),mt=Ca({bridge:S,clock:e}),pt=Ll({bridge:S,clock:e}),br=u=>{let A=S.handleWindowMessage({data:u.data,origin:u.origin,source:u.source,ports:u.ports});return A&&window.removeEventListener("message",br),A};window.addEventListener("message",br);let on=Pi(window,br),Fd=on?.capture,vr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];vr?.domInteractive!==void 0&&vr.domInteractive>0&&i.mark("document parsed",vr.domInteractive),Fd?.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 _r=t.handshakeWarningMs;_r!==null&&n&&e.setTimeout(()=>{let u=on===null?"no capture script ran":`capture: ${on.delivered} offer(s) delivered, ${on.stale} stale, ${on.capture.dropped} evicted${on.capture.late?", installed late":""}`;if(S.currentState==="connected"){n(`[gem] handshake connected. boot: ${i.timeline()} \xB7 ${u}`);return}n(`[gem] no completed handshake after ${_r??Md}ms (bridge state: ${S.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: ${i.timeline()} \xB7 `+u);},_r??Md);let $d=mr({get baseUrl(){return le},tokenSource:ee.source,get defaultQuery(){let u=ee.identity;return u?{game_id:u.gameId,channel:u.channel}:{}}}),sn=new Le({transport:$d,clock:e}),fe={client:sn,gameId:()=>ee.identity?.gameId??""};yi.confirm=u=>fd(fe,u);let jd=()=>ee.identity?.channel??"release",_i=new jt(fe,jd),wi=async u=>(await _i.load())?.currency(u)?.id??void 0,Si=Ot(fe,qr,{identity:pi,resolveCurrencyId:wi}),wr=async u=>{let A=await Q.wait(u);if(A)return A;throw S.currentState==="refused"?new oe("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new oe("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},Sr=d(t.autoReconnect),ce=To({client:sn,clock:e,gameId:()=>ee.identity?.gameId??null,playerId:()=>ee.identity?.playerId??null,awaitGameId:async()=>(await wr(ui)).gameId,resolveParty:gi.resolve,resolveClusterTargets:mt.resolveList,refreshClusterTargets:mt.refresh,ensureLocalServer:pt.ensure,localHostAvailable:pt.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>ee.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},...Sr===null?{}:{autoReconnect:{...Sr,redial:(u,A)=>Rr.redialMatch(u,A),abandon:(u,A)=>Rr.abandonMatch(u,A)}}});m(ce),hl({analytics:s,rooms:ce});let an=fl({client:sn,clock:e,rooms:ce,bridge:S,gameId:()=>ee.identity?.gameId??"",baseUrl:()=>le,resolveClusterTarget:mt.resolve,boot:i,...t.log===void 0?{}:{log:t.log}}),Ri=Bo(i,n),xn=ed({client:sn,clock:e,rooms:ce,signaling:()=>j.channel(),signalingReady:hr,log:n??(()=>{})}),Rr=pd({rooms:ce,p2p:{connect:u=>Ri(an.connect(u)),session:u=>an.session(u)},dedicated:{connect:(u=>dr(i,"welcome",xn.connect(u),n))},clock:e,identity:()=>ee.identity,apiBaseUrl:()=>le,tokens:rn,room:()=>ce.currentRoom,autoReconnect:Sr!==null,...t.log===void 0?{}:{log:t.log}}),qd=async()=>(await wr(ui)).playerId,ki={client:sn,boot:i,get identity(){return ee.identity},awaitIdentity:(u=ui)=>wr(u),awaitBridge:u=>S.settled(u),get player(){return w.current},awaitPlayer:(u=Gf)=>w.wait(u),me:Si,characters:new Gt(fe,void 0,pi,wi),transfers:new Ft(fe,qr,Si.inventory),gameConfig:_i,purchases:fi.api,deviceSettings:ut.api,ads:hi.api,account:bi.api,share:wd({frame:S,log:t.log}),vibration:Sd({frame:S,log:t.log}),analytics:s,leaderboards:new On(fe),challenges:new Cn(fe),showcase:new Ln(fe,qd),friends:new Gn(fe,{challenge:vi.challenge,...o===void 0?{}:{launchedChallengeId:o}}),platform:new Fn(fe,M,n),profiles:new $n(fe),functions:new De((u,A)=>hs(fe,u,A)),get prefs(){return x.current},get cohorts(){return I.current},get viewport(){return _.current},awaitCohorts:(u=Df)=>I.wait(u),reportMuted:u=>{P=!!u,T();},cueReward:u=>S.cueReward(u),setWalletVisible:(u,A)=>{let D=Array.isArray(A?.only)?[...A.only]:void 0;return N=D===void 0?{visible:u===true}:{visible:u===true,only:D},W()},setMenu:u=>(k={...typeof u?.onSettings=="function"?{onSettings:u.onSettings}:{},...Array.isArray(u?.items)?{items:u.items.map(A=>({...A}))}:{}},G()),exit:u=>Ff(ce,S,u,s),frame:S,devtools:q,rooms:ce,dedicatedServer:{listClusterTargets:u=>xn.listClusterTargets(u),connect:(u=>dr(i,"welcome",xn.connect(u),n)),handleMatchEnded:(u,A)=>xn.handleMatchEnded(u,A)},p2p:{handleSignalEvent:(u,A,D)=>an.handleSignalEvent(u,A,D),session:u=>an.session(u),connect:u=>Ri(an.connect(u))},match:Rr};return ki}var Od="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 mi(t,e={}){let n=e.clock??ae,r=()=>{let s=t();if(s===null)throw new Error(Od);return s},o=null,i=()=>{if(o===null)throw new Error(Od);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:ge(m),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:ge(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=Rn(r(),{...e,clock:n});}}}function Ld(t,e={}){let{server:n,attach:r}=mi(()=>t,e);return r(),n}function $f(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:Fe(e)}}}function Gd(t,e={}){return ()=>{let n=null,{server:r,attach:o}=mi(()=>n,e),i=t(r),a={async init(s){n=s,o(),await i.init?.();},async shutdown(s){let l=$f(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}}Ai();
|
|
2
|
+
exports.ARCADE_EMBEDDERS=Cf;exports.AnalyticsApi=qn;exports.AuthError=oe;exports.CONDITIONAL_HEADERS=gt;exports.ChallengesApi=Cn;exports.DEVICE_SETTINGS_MAX_BYTES=li;exports.DedicatedServerError=b;exports.FriendChallengeError=Ve;exports.FriendsApi=Gn;exports.FunctionsApi=De;exports.GemApiError=O;exports.GemClient=Le;exports.GemConfigError=de;exports.GemFrame=dt;exports.GemFunctionError=jn;exports.GemSaveError=ie;exports.GemUnframedError=lt;exports.LeaderboardsApi=On;exports.MAX_PERIODS_BACK=oa;exports.PLATFORM_EVENTS=Cm;exports.PlatformApi=Fn;exports.PlatformCurrenciesApi=Ht;exports.PlatformEarnAllowanceApi=Vt;exports.PlayerText=pe;exports.ProfilesApi=$n;exports.PurchaseRefusal=Ge;exports.ShowcaseApi=Ln;exports.TransportRefusal=re;exports.UNRELIABLE_CHANNEL_LABEL=Hn;exports.asPlayerText=ge;exports.createBootTimeline=Ho;exports.createGem=bR;exports.createGemServer=Rn;exports.createHostTokenSource=rd;exports.createMatchServer=Ld;exports.defineServer=Gd;exports.leaveAndExit=Ff;exports.mapIdentity=ve;exports.markOnResolve=dr;exports.platformIconUrl=tm;exports.presentJoinCredential=Un;exports.readTemplateTransports=fn;exports.readTransportAdvert=Vn;exports.reportOnResolve=Bo;exports.systemClock=ae;exports.text=Ue;exports.toBase64=yt;exports.webTransportAvailable=Qt;return exports;})({});
|