@opengamehq/cli 0.0.0-stage → 0.4.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.
Files changed (74) hide show
  1. package/AGENTS.md +235 -0
  2. package/CHANGELOG.md +9 -0
  3. package/README.md +128 -2
  4. package/dist/cli.mjs +1415 -0
  5. package/dist/opengame-global.js +3 -0
  6. package/dist/opengame-global.js.LEGAL.txt +1 -0
  7. package/dist/preflight-worker.mjs +13 -0
  8. package/dist/runtime-builder.mjs +800 -0
  9. package/dist/runtime-catalog.json +1 -0
  10. package/dist/runtime-catalog.sha256 +1 -0
  11. package/dist/runtime-shells/runtime-shell.html +4 -0
  12. package/dist/runtime-shells/runtime-shell.js +91 -0
  13. package/dist/safe-fs.py +242 -0
  14. package/dist/skills/manifest.json +512 -0
  15. package/dist/skills/opengame-accessibility/SKILL.md +90 -0
  16. package/dist/skills/opengame-api/SKILL.md +85 -0
  17. package/dist/skills/opengame-assets/SKILL.md +124 -0
  18. package/dist/skills/opengame-assets/references/pipeline.md +97 -0
  19. package/dist/skills/opengame-audio/SKILL.md +154 -0
  20. package/dist/skills/opengame-audio/helpers/audio-chain.js +325 -0
  21. package/dist/skills/opengame-audio/references/mix-notes.md +82 -0
  22. package/dist/skills/opengame-capture/SKILL.md +108 -0
  23. package/dist/skills/opengame-capture/references/pipeline.md +82 -0
  24. package/dist/skills/opengame-capture/references/threejs.md +145 -0
  25. package/dist/skills/opengame-characters/SKILL.md +129 -0
  26. package/dist/skills/opengame-characters/references/integration.md +144 -0
  27. package/dist/skills/opengame-characters/references/player-og.md +160 -0
  28. package/dist/skills/opengame-cli/SKILL.md +118 -0
  29. package/dist/skills/opengame-deploy/SKILL.md +204 -0
  30. package/dist/skills/opengame-deploy/references/json-events.md +62 -0
  31. package/dist/skills/opengame-deploy/references/manifest.md +83 -0
  32. package/dist/skills/opengame-deploy/references/packaging.md +117 -0
  33. package/dist/skills/opengame-depth/SKILL.md +130 -0
  34. package/dist/skills/opengame-enemies/SKILL.md +103 -0
  35. package/dist/skills/opengame-enemies/references/threejs.md +134 -0
  36. package/dist/skills/opengame-front-end/SKILL.md +143 -0
  37. package/dist/skills/opengame-front-end/references/launch.md +50 -0
  38. package/dist/skills/opengame-front-end/references/menus.md +47 -0
  39. package/dist/skills/opengame-game-feel/SKILL.md +137 -0
  40. package/dist/skills/opengame-game-feel/helpers/spring.js +146 -0
  41. package/dist/skills/opengame-game-feel/references/feel-numbers.md +83 -0
  42. package/dist/skills/opengame-jam/SKILL.md +103 -0
  43. package/dist/skills/opengame-lighting/SKILL.md +94 -0
  44. package/dist/skills/opengame-lighting/helpers/light-pool.js +185 -0
  45. package/dist/skills/opengame-loading/SKILL.md +99 -0
  46. package/dist/skills/opengame-loading/references/threejs.md +116 -0
  47. package/dist/skills/opengame-look/SKILL.md +114 -0
  48. package/dist/skills/opengame-look/references/post-and-lens.md +66 -0
  49. package/dist/skills/opengame-mobile/SKILL.md +90 -0
  50. package/dist/skills/opengame-performance/SKILL.md +140 -0
  51. package/dist/skills/opengame-performance/references/measuring.md +72 -0
  52. package/dist/skills/opengame-production/SKILL.md +131 -0
  53. package/dist/skills/opengame-production/references/templates.md +63 -0
  54. package/dist/skills/opengame-quality-bar/SKILL.md +122 -0
  55. package/dist/skills/opengame-quality-bar/references/cheap-tells.md +36 -0
  56. package/dist/skills/opengame-quality-bar/references/review-prompt.md +27 -0
  57. package/dist/skills/opengame-router/SKILL.md +51 -0
  58. package/dist/skills/opengame-router/references/process.md +38 -0
  59. package/dist/skills/opengame-scene-audit/SKILL.md +123 -0
  60. package/dist/skills/opengame-scene-audit/helpers/scene-audit.js +599 -0
  61. package/dist/skills/opengame-sdk/SKILL.md +254 -0
  62. package/dist/skills/opengame-sdk/references/engines.md +93 -0
  63. package/dist/skills/opengame-sdk/references/frame.md +107 -0
  64. package/dist/skills/opengame-sdk/references/identity.md +112 -0
  65. package/dist/skills/opengame-sdk/references/leaderboards.md +83 -0
  66. package/dist/skills/opengame-stability/SKILL.md +84 -0
  67. package/dist/skills/opengame-verification/SKILL.md +136 -0
  68. package/dist/skills/opengame-verification/helpers/browser-evidence.mjs +74 -0
  69. package/dist/skills/opengame-weapons/SKILL.md +109 -0
  70. package/dist/skills/opengame-weapons/references/handling-numbers.md +72 -0
  71. package/dist/skills/opengame-weapons/references/threejs.md +169 -0
  72. package/dist/skills/opengame-world-physics/SKILL.md +114 -0
  73. package/dist/skills/opengame-world-physics/references/measured-failures.md +52 -0
  74. package/package.json +38 -4
@@ -0,0 +1,3 @@
1
+ "use strict";(()=>{var m={argsBytesMax:65536};var g=["http://localhost:4590","http://localhost:4591","http://127.0.0.1:4590","http://127.0.0.1:4591"];var v={numericBounds:{fps:[0,1e3],heap_mb:[0,65536],sample_rate:[1e-6,1]},keys:["level","mode","difficulty","score","duration_ms","result","step","board","fps","heap_mb","sample_rate"],bytesMax:1024,stringCharsMax:120,digitRunMin:9};var y={keys:{label:"string",mode:"string",level:"string",character:"string",duration_ms:"number",accuracy:"number",combo:"number"},maxStringLength:24,maxBytes:384,digitRunMin:9};var _=["https://opengame.io","https://admin.opengame.io"];var k={sampleRate:.1,sampleWindowMs:5e3,sampleIntervalMs:6e4,samplesPerSessionMax:20,errorsPerSessionMax:20,errorIntervalMs:1e3};async function A(r,e,t){let n=r.body?.getReader();if(!n)throw new Error("invalid_response");let s=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",s,{once:!0});let a=new TextDecoder,i=0,l="";try{if(t.aborted)throw new Error("timeout");for(;;){let{value:o,done:d}=await n.read();if(t.aborted)throw new Error("timeout");if(d)break;if(i+=o.byteLength,i>e)throw new Error("response_too_large");l+=a.decode(o,{stream:!0})}return JSON.parse(l+a.decode())}finally{t.removeEventListener("abort",s),s(),n.releaseLock()}}function T(r){r.body?.cancel().catch(()=>{})}var U=class{constructor(e){this.session=e}session;validId(e){return typeof e=="string"&&e.length<=48&&/^[a-z0-9][a-z0-9_-]*$/.test(e)}async request(e){let t=this.session();if(t.disposed)return{ok:!1,error:"disposed"};if(t.preview)return{ok:!1,error:"unavailable_in_preview"};if(!t.token)return{ok:!1,error:"unavailable"};let n=()=>{let s=this.session();return s.disposed?{ok:!1,error:"disposed"}:s.generation!==t.generation||s.token!==t.token?{ok:!1,error:"session_changed"}:null};try{let s=AbortSignal.timeout(1e4),a=await fetch(new URL("/v1/achievements","https://api.opengame.gg"),{method:e===void 0?"GET":"POST",credentials:"omit",cache:"no-store",redirect:"error",referrerPolicy:"no-referrer",signal:s,headers:{Authorization:`Bearer ${t.token}`,...e?{"Content-Type":"application/json"}:{}},...e?{body:JSON.stringify({achievement:e})}:{}}),i=n();if(i||!a.ok||a.status===202)return T(a),i??{ok:!1,error:a.status===400?"invalid_achievement":"achievement_unavailable"};let l;try{l=await A(a,131072,s)}catch{return n()??{ok:!1,error:s.aborted?"network":"invalid_response"}}let o=l,d=e===void 0?Array.isArray(l)&&l.every(u=>u&&typeof u=="object"&&this.validId(u.achievementId)&&typeof u.title=="string"&&typeof u.description=="string"&&typeof u.unlocked=="boolean"&&(u.unlocked?typeof u.unlockedAt=="string":u.unlockedAt===null)&&u.source==="game_reported"):o&&typeof o=="object"&&o.achievementId===e&&o.unlocked===!0&&typeof o.firstUnlock=="boolean"&&typeof o.unlockedAt=="string"&&o.source==="game_reported";return n()??(d?{ok:!0,value:l}:{ok:!1,error:"invalid_response"})}catch{return n()??{ok:!1,error:"network"}}}unlock(e){return this.validId(e)?this.request(e):Promise.resolve({ok:!1,error:"invalid_achievement"})}list(){return this.request()}};function ue(r,e,t,n){let s=!1,a=0,i,l=0,o=0,d=-1/0,u=[],c=Math.random()<e.sampleRate,h=()=>{for(;u.length&&n("runtime_error",u[0]);)u.shift()},f=P=>{let F=Date.now();if(s||o>=e.errorsPerSessionMax||F-d<e.errorIntervalMs)return;o++,d=F;let K=P.type==="unhandledrejection",N;try{N=(K?P.reason:P.error)?.name}catch{}let B={TypeError:"type_error",RangeError:"range_error",ReferenceError:"reference_error",SyntaxError:"syntax_error",SecurityError:"security_error",NetworkError:"network_error",Error:"error"};u.push({result:typeof N=="string"&&Object.hasOwn(B,N)?B[N]:"unknown",step:K?"rejection":P.target&&P.target!==r?"resource":"exception"}),h()},b=()=>{if(h(),!c||s||a||l>=e.samplesPerSessionMax||!t()||!r.requestAnimationFrame)return;let P,F=0,K=N=>{if(a=0,s||!t())return;P===void 0?P=N:F++;let B=N-P;if(B<e.sampleWindowMs){a=r.requestAnimationFrame(K);return}let de={fps:F*1e3/B,sample_rate:e.sampleRate},J=r.performance.memory?.usedJSHeapSize;typeof J=="number"&&Number.isFinite(J)&&J>=0&&(de.heap_mb=J/(1024*1024)),n("runtime_performance",de)&&l++};a=r.requestAnimationFrame(K)};return r.addEventListener("error",f,!0),r.addEventListener("unhandledrejection",f),{reset(){a&&r.cancelAnimationFrame(a),a=0,u.length=0},resume(){if(h(),!t()){a&&r.cancelAnimationFrame(a),a=0,clearInterval(i),i=void 0;return}c&&!s&&(b(),i||(i=setInterval(b,e.sampleIntervalMs)))},stop(){s=!0,clearInterval(i),a&&r.cancelAnimationFrame(a),u.length=0,r.removeEventListener("error",f,!0),r.removeEventListener("unhandledrejection",f)}}}var ee=Symbol.for("opengame.sdk"),te=globalThis;function ce(){if(!Object.hasOwn(te,ee))return;let r=te[ee];if(r&&Object.hasOwn(r,"major")&&r.major===0&&Object.hasOwn(r,"capabilities"))return r.capabilities}function W(r){let e=ce();return e&&Object.hasOwn(e,r)?e[r]:void 0}function H(r,e,t=!1){return te[ee]=Object.freeze({major:0,capabilities:Object.freeze({...t?{}:ce(),[r]:e})}),e}function he(r,e,t=[]){if(typeof r!="string"||!r||r.length>e||/[\s\\\u0000-\u001f\u007f]/u.test(r)||!/^https:\/\//i.test(r))return null;let n=r.slice(8).split(/[/?#]/u)[0];if(!n||/[%@]/u.test(n)||!/^[\x21-\x7e]+$/u.test(n))return null;try{let s=new URL(r);return n.toLowerCase()!==s.host.toLowerCase()||s.protocol!=="https:"||s.username||s.password||!s.hostname||t.includes(s.origin)?null:s.href.length<=e?s.href:null}catch{return null}}var Fe=/^[a-z]{1,16}(\.[a-z]{1,16}){2}(\.[a-z]{1,16}(\.(male|female)(\.[a-z]{1,16}){0,3})?)?$/;function pe(r){return typeof r!="string"?null:Fe.exec(r)?.[0]===r?r:null}var Ke=/^c[1-9]\d*(?:\.[a-z]{1,16}(?:-[a-z]{1,16})*){5,}$/;function fe(r){return typeof r=="string"&&r.length<=256&&Ke.test(r)?r:null}function V(r,e){let t={};if(!r||typeof r!="object")return t;let n=new RegExp(`\\p{Nd}{${e.digitRunMin},}`,"u"),s=a=>a.split(/\s+/u).some(i=>i.split("@").some((l,o,d)=>{let u=l.indexOf(".",1);return o>0&&d[o-1].length>0&&u>0&&u<l.length-1}));for(let a of e.keys){if(!Object.hasOwn(r,a))continue;let i=r[a],l=e.numericBounds?.[a];if(l&&(typeof i!="number"||!Number.isFinite(i)||i<l[0]||i>l[1]))continue;if(typeof i=="number"){if(!Number.isFinite(i)||Math.abs(i)>=10**(e.digitRunMin-1))continue}else if(typeof i=="string"){if(i.length>e.bytesMax)continue;let d=i.normalize("NFKC");if(d.length>e.bytesMax||s(d)||n.test(d))continue;i=i.slice(0,e.stringCharsMax)}else if(typeof i!="boolean")continue;let o={...t,[a]:i};new TextEncoder().encode(JSON.stringify(o)).byteLength>e.bytesMax||(t[a]=i)}return t}function re(r,e){if(r==null)return{ok:!0,meta:{}};if(typeof r!="object"||Array.isArray(r))return{ok:!1,reason:"meta must be an object"};let t={};for(let[n,s]of Object.entries(r)){let a=Object.hasOwn(e.keys,n)?e.keys[n]:void 0;if(a===void 0)return{ok:!1,reason:`meta key not allowed: ${n}`};if(typeof s!==a)return{ok:!1,reason:`meta.${n} must be a ${a}`};if(a==="string"){if(s.length>e.maxStringLength)return{ok:!1,reason:`meta.${n} is longer than ${e.maxStringLength}`};let i=V({[n]:s},{keys:[n],bytesMax:e.maxBytes,stringCharsMax:e.maxStringLength,digitRunMin:e.digitRunMin});if(!Object.hasOwn(i,n))return{ok:!1,reason:`meta.${n} contains a private contact value`}}else if(a==="number"&&!Number.isFinite(s))return{ok:!1,reason:`meta.${n} must be finite`};t[n]=s}return new TextEncoder().encode(JSON.stringify(t)).byteLength>e.maxBytes?{ok:!1,reason:`meta is larger than ${e.maxBytes} bytes`}:{ok:!0,meta:t}}function me(r,e,t){if(!Number.isFinite(r))return{state:"rejected",stored:0};let n=e.plausible_max,s=e.plausible_min;return n!==null&&r>n?{state:r>n*t?"rejected":"clamped",stored:n}:s!==null&&r<s?{state:r*t<s?"rejected":"clamped",stored:s}:{state:"ok",stored:r}}var p=(r,e)=>({ok:!1,error:r,reason:e}),G=r=>!!(r&&typeof r=="object"&&!Array.isArray(r)),L=r=>typeof r=="number"&&Number.isFinite(r),Q=class{constructor(e,t){this.context=e;this.initialize=t}context;initialize;generation=0;cancellation="session_changed";suppliedManifest;rawManifest=null;manifest=null;requests=new Set;isHostedOrigin(e=this.context().win?.location.hostname){let t=new URL("https://api.opengame.gg").hostname.replace(/^api\./,"");return e===t||!!e?.endsWith(`.${t}`)}configure(e){this.suppliedManifest=e}cancel(e){this.generation++,this.cancellation=e;for(let t of this.requests)t.abort(e)}board(e){return Object.freeze({submit:(t,n)=>this.submit(e,t,n),top:t=>this.read(e,"top",t?.limit),me:async()=>{let t=await this.read(e,"me");return t.ok?{ok:!0,value:t.value.entries[0]??null}:t},around:()=>this.read(e,"around")})}validKey(e){return typeof e=="string"&&e.length<=48&&/^[a-z0-9][a-z0-9_-]*$/.test(e)}async state(e){if(!this.validKey(e))return p("invalid_board","Use a board key declared in opengame.json.");await this.initialize();let t=this.context();return t.disposed||!t.win||!t.enabled?p("unavailable",t.disposed?"disposed":"leaderboards_unavailable"):!t.local&&!t.token?p("unavailable","session_unavailable"):{ok:!0,value:{...t,generation:this.generation}}}host(e){let t=new URL("https://api.opengame.gg").hostname.replace(/^api\./,""),n=e.win.location.hostname;if(!n.endsWith(`.${t}`))return null;let s=n.slice(0,-(t.length+1));return/^[a-z0-9][a-z0-9-]*$/.test(s)?s:null}async json(e,t,n,s=this.generation){if(s!==this.generation||this.context().disposed)return p("unavailable",this.cancellation);let a=new AbortController;this.requests.add(a);let i=setTimeout(()=>a.abort("timeout"),5e3);try{let l=await fetch(e,{...t,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:a.signal});if(a.signal.aborted)throw new Error("cancelled");return l.ok?Number(l.headers.get("content-length"))>n||!l.body?(T(l),p("unavailable","invalid_response")):{ok:!0,value:await A(l,n,a.signal)}:(T(l),l.status===404?p("board_unavailable","board_not_found"):l.status===401||l.status===403?p("unavailable","session_rejected"):l.status===429?p("rate_limited","Try again after the rate-limit window."):p(l.status>=500?"unavailable":"invalid_request",`http_${l.status}`))}catch(l){return p("unavailable",a.signal.aborted?String(a.signal.reason):l?.message==="response_too_large"?"response_too_large":"network_or_invalid_response")}finally{clearTimeout(i),this.requests.delete(a)}}manifestInput(){return this.rawManifest?this.rawManifest:(this.rawManifest=(async()=>{if(this.suppliedManifest!==void 0)return{ok:!0,value:this.suppliedManifest};let e=this.context().win;if(!e)return p("unavailable","local_manifest_unavailable");let t=await this.json(new URL("./opengame.json",e.location.href),{cache:"no-store"},65536);return t.ok?t:p("unavailable","local_manifest_unavailable")})(),this.rawManifest.then(e=>{e.ok||(this.rawManifest=null)}),this.rawManifest)}async definitions(){if(this.manifest)return this.manifest;this.manifest=(async()=>{let t=await this.manifestInput();if(!t.ok)return t;let n=t.value;if(!G(n)||n.leaderboards!==void 0&&!Array.isArray(n.leaderboards))return p("invalid_manifest","Invalid leaderboard declarations.");let s=n.leaderboards??[];if(s.length>10)return p("invalid_manifest","Too many leaderboard declarations.");let a=[];for(let i of s){if(!G(i)||typeof i.key!="string"||!this.validKey(i.key)||i.order!=="asc"&&i.order!=="desc"||i.min!==void 0&&!L(i.min)||i.max!==void 0&&!L(i.max)||L(i.min)&&L(i.max)&&i.min>i.max||a.some(l=>l.key===i.key))return p("invalid_manifest","Invalid leaderboard declarations.");a.push({key:i.key,order:i.order,...L(i.min)?{min:i.min}:{},...L(i.max)?{max:i.max}:{}})}return{ok:!0,value:a}})();let e=await this.manifest;return e.ok||(this.manifest=null),e}async localBoard(e){let t=await this.definitions();if(!t.ok)return t;let n=t.value.find(s=>s.key===e);return n?{ok:!0,value:n}:p("board_unavailable","Declare this board in opengame.json.")}storageKey(e){return`og:dev:leaderboard:v1:${new URL("./opengame.json",this.context().win.location.href).pathname}:${e}`}stored(e){let t=this.context().win.localStorage.getItem(this.storageKey(e.key));if(!t)return null;if(t.length>131072)throw new Error("invalid local score");let n=JSON.parse(t);if(!G(n)||typeof n.definition!="string")throw new Error("invalid local score");if(n.definition!==JSON.stringify(e))return null;if(!G(n.entry)||n.state!=="ok"&&n.state!=="clamped"&&n.state!=="rejected")throw new Error("invalid local score");let s=this.entry(n.entry,!0);if(!s)throw new Error("invalid local score");return{entry:s,state:n.state}}entry(e,t=!1){if(!G(e)||!L(e.score)||!Number.isSafeInteger(e.rank)||Number(e.rank)<1||!(e.player_name===null||typeof e.player_name=="string")||typeof e.created_at!="string"||!Number.isFinite(Date.parse(e.created_at)))return null;let n=re(e.meta,y);return n.ok?Object.freeze({name:e.player_name,score:e.score,meta:n.meta,createdAt:e.created_at,rank:Number(e.rank),isMe:t||e.is_me===!0}):null}async read(e,t,n){if(n!==void 0&&(!Number.isSafeInteger(n)||n<1))return p("invalid_limit","Use a positive integer limit.");let s=Math.min(n??50,100),a=await this.state(e);if(!a.ok)return a;let i=a.value;if(i.generation!==this.generation||this.context().disposed)return p("unavailable",this.cancellation);if(i.local){let f=await this.localBoard(e);if(!f.ok)return f;if(this.context().disposed||!this.context().local)return p("unavailable","session_changed");try{let b=this.stored(f.value),P=b?.state==="ok"?b.entry:null;return{ok:!0,value:{entries:P?[P]:[],order:f.value.order,preview:!1,source:"game_reported"}}}catch{return p("unavailable","local_storage_unavailable")}}let l=this.host(i);if(!l)return p("unavailable","unsupported_game_origin");let o=new URL("/v1/scores","https://api.opengame.gg");o.search=new URLSearchParams(i.preview?{board:e,view:t,limit:String(s)}:{board:e,host:l,view:t,limit:String(s)}).toString();let d=await this.json(o,{headers:{Authorization:`Bearer ${i.token}`},cache:t==="top"?"default":"no-store"},131072,i.generation);if(!d.ok)return d;if(this.context().disposed||i.generation!==this.generation||!this.context().enabled)return p("unavailable","session_changed");let u=d.value,c=t==="top"?s:t==="me"?1:21;if(!G(u)||u.board!==e||u.source!=="game_reported"||u.direction!=="asc"&&u.direction!=="desc"||!!u.preview!==i.preview||!Array.isArray(u.entries)||u.entries.length>c)return p("unavailable","invalid_response");let h=[];for(let f of u.entries){let b=this.entry(f);if(!b)return p("unavailable","invalid_response");h.push(b)}return t!=="top"&&h.length&&h.filter(f=>f.isMe).length!==1?p("unavailable","invalid_response"):{ok:!0,value:{entries:h,order:u.direction,preview:i.preview,source:"game_reported"}}}async submit(e,t,n){if(!L(t))return p("invalid_score","Use a finite number.");let s=re(n,y);if(!s.ok)return p("invalid_meta",s.reason);let a=await this.state(e);if(!a.ok)return a;let i=a.value;if(i.generation!==this.generation||this.context().disposed)return p("unavailable",this.cancellation);if(i.local){let d=await this.localBoard(e);if(!d.ok)return d;let u=()=>{if(this.context().disposed||!this.context().local)return p("unavailable","session_changed");let c=me(t,{plausible_min:d.value.min??null,plausible_max:d.value.max??null},10),h=this.stored(d.value),f=h&&(d.value.order==="asc"?c.stored<h.entry.score:c.stored>h.entry.score),b=!h||c.state!=="rejected"&&(h.state==="rejected"||c.state==="ok"&&h.state!=="ok"||c.state===h.state&&!!f);return b&&this.context().win.localStorage.setItem(this.storageKey(e),JSON.stringify({definition:JSON.stringify(d.value),state:c.state,entry:{player_name:"dev",score:c.stored,meta:s.meta,created_at:new Date().toISOString(),rank:1}})),{ok:!0,value:{state:c.state,score:c.stored,best:b,preview:!1}}};try{let c=i.win.navigator?.locks;if(!c)return u();let h=new AbortController;this.requests.add(h);let f=setTimeout(()=>h.abort("timeout"),5e3);try{return await c.request(this.storageKey(e),{signal:h.signal},u)}finally{clearTimeout(f),this.requests.delete(h)}}catch{return p("unavailable","local_storage_unavailable")}}if(!this.host(i))return p("unavailable","unsupported_game_origin");let l=await this.json(new URL("/v1/scores","https://api.opengame.gg"),{method:"POST",cache:"no-store",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json"},body:JSON.stringify({board:e,value:t,meta:s.meta})},131072,i.generation);if(!l.ok)return l;if(this.context().disposed||i.generation!==this.generation||!this.context().enabled)return p("unavailable","session_changed");let o=l.value;return!G(o)||o.ok!==!0||!L(o.stored)||typeof o.best!="boolean"||o.state!=="ok"&&o.state!=="clamped"&&o.state!=="rejected"||!!o.preview!==i.preview?p("unavailable","invalid_response"):{ok:!0,value:{score:o.stored,state:o.state,best:o.best,preview:i.preview}}}};var ge=_,Be=new Set(["identity","leaderboards","analytics","external-links","avatar"]),ye=Object.freeze({id:null,handle:null,ogNumber:null,signedIn:!1}),ie=r=>r==="localhost"||r==="127.0.0.1"||r==="[::1]",ne={guest:Object.freeze({id:"dev-guest",handle:null,ogNumber:null,signedIn:!1}),"signed-in":Object.freeze({id:"dev-account",handle:"dev",ogNumber:1,signedIn:!0,avatar:Object.freeze({seed:1,palette:"sky",look:"circle.classic.white",character:"c4.classic.regular.hoodie.jeans.cape-watch.retro.avatar.avatar.avatar.avatar"})}),"no-handle":Object.freeze({id:"dev-account",handle:null,ogNumber:null,signedIn:!0})};function ze(){let r=crypto.getRandomValues(new Uint8Array(10)),e=Array.from(r,n=>n.toString(16).padStart(2,"0")).join(""),t=Date.now().toString(16).padStart(12,"0");return`${t.slice(0,8)}-${t.slice(8)}-7${e.slice(0,3)}-${(8+(r[9]&3)).toString(16)}${e.slice(3,6)}-${e.slice(6,18)}`}function $(r,e){if(ge.includes(r))return!0;try{let t=new URL(r),n=new URL(e);return(t.protocol==="http:"||t.protocol==="https:")&&ie(t.hostname)&&(n.protocol==="http:"||n.protocol==="https:")&&ie(n.hostname)&&t.origin===r}catch{return!1}}function z(r,e){for(let t of r)try{t(e)}catch{}}function X(r,e,t){r.add(e);try{e(t)}catch{}return()=>{r.delete(e)}}var $e=new Set(["paper","ink","sky","meadow","coral","iris","honey","tide"]);function qe(r,e){if(!r||typeof r!="object"||Array.isArray(r))return null;let t=r,n=pe(t.look),s=n&&fe(e),a={seed:Number(t.seed),palette:t.palette,...n?{look:n}:{}};return Object.keys(t).length!==Object.keys(a).length||!Number.isSafeInteger(t.seed)||a.seed<0||!$e.has(a.palette)?null:Object.freeze(s?{...a,character:s}:a)}function Je(r,e=!1){if(!r||typeof r!="object")return null;let t=r;if(typeof t.id!="string"||!t.id||typeof t.signedIn!="boolean"||!(t.handle===null||typeof t.handle=="string")||!(t.ogNumber===null||Number.isSafeInteger(t.ogNumber)&&Number(t.ogNumber)>0))return null;let n=e&&t.signedIn?qe(t.avatar,t.character):null;return Object.freeze({id:t.id,handle:t.handle,ogNumber:t.ogNumber,signedIn:t.signedIn,...n?{avatar:n}:{}})}var be=!1;function Ue(r,e){if(be)return;try{let{protocol:n,hostname:s}=r.location;if(n!=="file:"&&!ie(s)||/jsdom|happy-?dom/i.test(r.navigator?.userAgent??""))return}catch{return}be=!0;let t=e==="signed-in";globalThis.console?.info?.(`OpenGame SDK 0.2.0: local mock
2
+ Playing as ${t?"@dev, signed in":e==="guest"?"a guest":"an account with no handle yet"}. Add ?og-dev-player=${t?"guest":"signed-in"} to switch.
3
+ Scores stay in this browser.`)}var Y=class{win;localMode=!1;sessionToken=null;account="";devPlayer="guest";onParentMessage(e){return this.parentListeners.add(e),()=>{this.parentListeners.delete(e)}}postToParent(e){return this.send(e)}parentListeners=new Set;boards=new Q(()=>({win:this.win,local:this.localMode,token:this.sessionToken,enabled:this.capabilities.includes("leaderboards"),preview:this.env.preview,disposed:this.disposed}),()=>this.init());parentOrigin=null;initialization=null;settle=null;extendedHandshake=!1;handshakeTimer;initRetry;readyRetry;readyDeadline;batchTimer;readySent=!1;readyReported=!1;readyElapsed=0;inputReported=!1;attentionReported=!1;health;bootedAt=Date.now();sessionGeneration=0;startupOpen=!0;disposed=!1;hostPaused=!1;held=!1;playWaiters=new Set;paused=!1;muted=!1;full=!1;playerValue=ye;environment=Object.freeze({embedded:!1,connected:!1,preview:!1,sdkVersion:"0.2.0",capabilities:Object.freeze([])});playerListeners=new Set;muteListeners=new Set;pauseListeners=new Set;fullscreenListeners=new Set;cancelLink=null;achievements=new U(()=>({token:this.sessionToken,preview:this.env.preview,disposed:this.disposed,generation:this.sessionGeneration}));events=[];flushing=!1;eventsRecorded=0;eventTimes=[];get env(){return this.environment}get capabilities(){return this.environment.capabilities}player=(()=>{let e=this;return{get id(){return e.playerValue.id},get handle(){return e.playerValue.handle},get ogNumber(){return e.playerValue.ogNumber},get signedIn(){return e.playerValue.signedIn},get avatar(){return e.playerValue.avatar??null},onChange:t=>X(this.playerListeners,t,this.playerValue),requestSignIn:()=>this.capabilities.includes("identity")?this.localMode?(this.playerValue.signedIn||this.setLocalPlayer("signed-in"),{ok:!0,value:void 0}):this.send({type:"sign-in"}):{ok:!1,error:"unavailable"}}})();audio=(()=>{let e=this;return{get muted(){return e.muted},onHostMute:t=>X(this.muteListeners,t,this.muted)}})();fullscreen=(()=>{let e=this;return{get active(){return e.full},request:()=>this.send({type:"fullscreen"}),onChange:t=>X(this.fullscreenListeners,t,this.full)}})();onPause(e){return X(this.pauseListeners,e,this.paused)}openLink(e){if(this.disposed)return Promise.resolve({ok:!1,error:"disposed"});if(!this.capabilities.includes("external-links")||!this.parentOrigin)return Promise.resolve({ok:!1,error:"unavailable"});let t=he(e,2048,[this.parentOrigin,this.win?.location.origin??""]);return t?this.win?.navigator.userActivation?.isActive?this.cancelLink?Promise.resolve({ok:!1,error:"busy"}):new Promise(n=>{let{port1:s,port2:a}=new MessageChannel,i=!1,l=u=>{i||(i=!0,clearTimeout(o),s.close(),a.close(),this.cancelLink=null,n(u))},o=setTimeout(()=>l({ok:!1,error:"timeout"}),30500);this.cancelLink=u=>l({ok:!1,error:u}),s.onmessage=u=>{let c=u.data;!c||c.og!==1||c.type!=="open-link"||typeof c.ok!="boolean"||l(c.ok?{ok:!0,value:void 0}:{ok:!1,error:typeof c.error=="string"?c.error:"cancelled"})},s.onmessageerror=()=>l({ok:!1,error:"invalid_response"});let d=this.send({type:"open-link",url:t},[a]);d.ok||l(d)}):Promise.resolve({ok:!1,error:"gesture_required"}):Promise.resolve({ok:!1,error:"invalid_request"})}waitForPlay(e){return this.disposed?Promise.resolve({ok:!1,error:"disposed"}):this.held?new Promise(t=>{let n=a=>{this.playWaiters.delete(n),e?.removeEventListener("abort",s),t(a)},s=()=>n({ok:!1,error:"cancelled"});this.playWaiters.add(n),e?.aborted?s():e?.addEventListener("abort",s,{once:!0})}):Promise.resolve({ok:!0,value:void 0})}finishPlayWaiters(e){for(let t of this.playWaiters)t(e)}leaderboard(e){return this.boards.board(e)}connect(){let e=typeof window>"u"?void 0:window;this.win||this.disposed||!e||e.parent===e||!this.boards.isHostedOrigin(e.location.hostname)||(this.attach(e),this.handshake())}attach(e){let t=!!(e&&e.parent!==e);this.win=e,this.environment=Object.freeze({...this.environment,embedded:t,preview:!!(e&&/^p-[a-z2-7]{52}\./.test(e.location.hostname))}),t&&e.addEventListener("message",this.receive)}handshake(){clearTimeout(this.handshakeTimer),clearInterval(this.initRetry),this.handshakeTimer=setTimeout(()=>this.finish(),4e3);let e=()=>this.send({type:"ready",phase:"init",sdk:"0.2.0",isolated:this.win?.crossOriginIsolated===!0});this.initRetry=setInterval(e,500),e()}init(e={}){if(this.initialization)return this.initialization;if(this.disposed)return Promise.resolve(this.environment);this.boards.configure(e.manifest),e.dev?.player&&Object.hasOwn(ne,e.dev.player)&&(this.devPlayer=e.dev.player),this.win||this.attach(typeof window>"u"?void 0:window);let t=this.win,n=this.environment.embedded;return this.initialization=new Promise(s=>{this.settle=s}),t?.document.addEventListener("visibilitychange",this.visibility),t?.addEventListener("pointerdown",this.firstInput,!0),t?.addEventListener("keydown",this.firstInput,!0),t&&(this.health=ue(t,k,()=>this.readySent&&(this.localMode||!!this.sessionToken)&&this.capabilities.includes("analytics")&&!this.paused&&!this.held,(s,a)=>this.track(s,a).ok)),this.visibility(),!t||!n?(this.finish(),this.initialization):(t.addEventListener("pagehide",this.flush),this.batchTimer??=setInterval(this.flush,1e4),this.environment.connected?this.finish():this.extendedHandshake?(clearTimeout(this.handshakeTimer),this.handshakeTimer=setTimeout(()=>this.finish(),10500)):this.initRetry===void 0&&this.handshake(),this.initialization)}ready(){if(this.readySent||this.disposed||(this.init(),this.readySent=!0,this.readyElapsed=Date.now()-this.bootedAt,this.reportReady(),!this.win))return;if(this.win.parent===this.win){try{this.win.postMessage({og:1,type:"ready",phase:"playable",sdk:"0.2.0",isolated:this.win.crossOriginIsolated===!0},this.win.location.origin)}catch{}return}let e=()=>this.send({type:"ready",phase:"playable",sdk:"0.2.0",isolated:this.win?.crossOriginIsolated===!0});this.readyRetry=setInterval(e,500),this.readyDeadline=setTimeout(()=>clearInterval(this.readyRetry),4e3),e()}finish(){if(!this.disposed&&this.win&&!this.environment.connected&&!this.boards.isHostedOrigin()&&this.win.__OG_DEV__===1){this.localMode=!0;let e=null;try{e=new URL(this.win.location.href)}catch{}let t=e?.searchParams.get("og-dev-player");t&&Object.hasOwn(ne,t)&&(this.devPlayer=t),this.setLocalPlayer(this.devPlayer),Ue(this.win,this.devPlayer)}clearTimeout(this.handshakeTimer),clearInterval(this.initRetry),this.initRetry=void 0,this.settle?.(this.environment),this.settle=null}setLocalPlayer(e){let t=ne[e];this.playerValue!==t&&(this.environment=Object.freeze({...this.environment,capabilities:Object.freeze(["identity","leaderboards","analytics"].concat(t.avatar?"avatar":[]))}),this.devPlayer=e,this.playerValue=t,this.account=`local:${t.id}:${t.signedIn}`,z(this.playerListeners,t))}send(e,t){let n=this.win;if(!n||n.parent===n||this.disposed)return{ok:!1,error:"unavailable"};if(t){if(!this.parentOrigin)return{ok:!1,error:"unavailable"};try{n.parent.postMessage({...e,og:1},this.parentOrigin,t)}catch{return{ok:!1,error:"unavailable"}}return{ok:!0,value:void 0}}let s=this.parentOrigin?[this.parentOrigin]:[...ge,...g.filter(a=>$(a,n.location.origin))];try{let a=new URL(n.document.referrer||n.location.ancestorOrigins?.[0]||"").origin;!this.parentOrigin&&$(a,n.location.origin)&&(s=[a])}catch{}for(let a of s)try{n.parent.postMessage({...e,og:1},a)}catch{}return{ok:!0,value:void 0}}receive=e=>{let t=this.win;if(!t||e.source!==t.parent||!$(e.origin,t.location.origin)||this.parentOrigin&&e.origin!==this.parentOrigin)return;let n=e.data;if(!(!n||typeof n!="object"||n.og!==1)){for(let s of this.parentListeners)try{s(n)}catch{}if(n.type==="session-pending")(this.settle||!this.initialization)&&!this.extendedHandshake&&(this.extendedHandshake=!0,this.parentOrigin=e.origin,clearInterval(this.initRetry),clearTimeout(this.handshakeTimer),this.handshakeTimer=setTimeout(()=>this.finish(),10500));else if(n.type==="session-request")this.send({type:"ready",phase:"init",sdk:"0.2.0",isolated:t.crossOriginIsolated===!0});else if(n.type==="ready-ack"&&n.phase==="playable")clearInterval(this.readyRetry),clearTimeout(this.readyDeadline);else if(n.type==="session"){if(!(typeof n.token=="string"||n.token===null))return;let s=this.environment.preview||n.preview===!0,i=(Array.isArray(n.capabilities)?[...new Set(n.capabilities.filter(h=>Be.has(h)))]:["leaderboards","analytics"]).filter(h=>!(s&&(h==="identity"||h==="avatar"))),l=Je(n.player,i.includes("avatar"))??ye;l.avatar||(i=i.filter(h=>h!=="avatar"));let o=l.id!==null?JSON.stringify(["player",l.id,l.signedIn,n.token!==null,s]):JSON.stringify(["token",n.token,s]);i.includes("external-links")||this.cancelLink?.("unavailable"),(this.localMode||o!==this.account)&&(this.cancelLink?.("session_changed"),this.finishPlayWaiters({ok:!1,error:"session_changed"}),this.boards.cancel("session_changed"));let d=this.sessionToken!==n.token,u=this.account!==o,c=i.includes("analytics")!==this.capabilities.includes("analytics");if((d||u||s!==this.env.preview||c)&&this.sessionGeneration++,u&&(this.attentionReported=!1,this.inputReported=!1),this.account=o,this.sessionToken=n.token,!i.includes("analytics"))this.events=this.events.filter(h=>h.token!==null),this.startupOpen=!1;else if(n.token&&this.startupOpen)for(let h of this.events)h.token===null&&(h.token=n.token);n.token&&(this.startupOpen=!1),(d||u||c)&&this.health?.reset(),this.localMode=!1,this.held=n.held===!0,this.held||this.finishPlayWaiters({ok:!0,value:void 0}),this.parentOrigin=e.origin,i.includes("leaderboards")||this.boards.cancel("leaderboards_unavailable"),this.environment=Object.freeze({...this.environment,connected:!0,preview:s,capabilities:Object.freeze(i)}),JSON.stringify(l)!==JSON.stringify(this.playerValue)&&(this.playerValue=l,z(this.playerListeners,l)),this.finish(),this.reportReady()}else n.type==="mute"&&typeof n.muted=="boolean"&&this.muted!==n.muted?(this.muted=n.muted,z(this.muteListeners,this.muted)):n.type==="activity"&&typeof n.active=="boolean"?(this.hostPaused=!n.active,this.visibility()):n.type==="fullscreen"&&typeof n.active=="boolean"&&this.full!==n.active?(this.full=n.active,z(this.fullscreenListeners,this.full)):n.type==="play"&&(this.held=!1,this.finishPlayWaiters({ok:!0,value:void 0}),this.hostPaused=!1,this.visibility())}};reportReady=()=>{this.readySent&&!this.readyReported&&(this.localMode||this.sessionToken)&&this.capabilities.includes("analytics")&&this.track("sdk_ready",{duration_ms:this.readyElapsed}).ok&&(this.readyReported=!0),this.reportAttention(),this.health?.resume()};reportAttention=()=>!this.readySent||!this.sessionToken||this.paused||this.held||!this.capabilities.includes("analytics")?!1:(!this.attentionReported&&this.track("attention_coverage",{result:"sdk_v1"}).ok&&(this.attentionReported=!0),this.attentionReported);firstInput=e=>{!e.isTrusted||this.disposed||this.reportAttention()&&!this.inputReported&&this.track("first_input",{duration_ms:Date.now()-this.bootedAt}).ok&&(this.inputReported=!0)};visibility=()=>{let e=this.hostPaused||this.win?.document.visibilityState==="hidden";e!==this.paused&&(this.paused=e,z(this.pauseListeners,e)),this.reportAttention(),this.health?.resume()};track(e,t={}){let n=this.startupOpen&&this.initialization&&!this.sessionToken;if(this.disposed||!this.initialization||!this.localMode&&!n&&(!this.sessionToken||!this.capabilities.includes("analytics")))return{ok:!1,error:"unavailable"};if(typeof e!="string"||!/^[a-z][a-z0-9_]*$/.test(e)||e.length>48)return{ok:!1,error:"invalid_event"};let s=V(t,v);if(e==="attention_coverage"){if(s.result!=="sdk_v1")return{ok:!1,error:"invalid_event"};s={result:"sdk_v1"}}if(e==="runtime_performance"&&(typeof s.fps!="number"||typeof s.sample_rate!="number"))return{ok:!1,error:"invalid_event"};if(new TextEncoder().encode(JSON.stringify({name:e,props:s})).byteLength>1024)return{ok:!1,error:"invalid_event"};let a=Date.now();if(this.eventTimes=this.eventTimes.filter(u=>u>a-6e4),this.eventTimes.length>=60||this.eventsRecorded>=200)return{ok:!1,error:"rate_limited"};let i;try{i=ze()}catch{return{ok:!1,error:"unavailable"}}let l={name:e,props:s,token:this.sessionToken,eventId:i,occurredAt:new Date(a).toISOString()},{token:o,...d}=l;return new TextEncoder().encode(JSON.stringify({events:[d]})).byteLength>65536?{ok:!1,error:"invalid_event"}:(this.eventTimes.push(a),this.eventsRecorded++,this.events.push(l),this.batchTimer||(this.batchTimer=setInterval(this.flush,1e4)),{ok:!0,value:void 0})}flush=()=>{if(!this.events.length||this.flushing)return;if(this.localMode){let a=this.events.splice(0);typeof globalThis.console?.debug=="function"&&globalThis.console.debug("[opengame] events",a);return}let e=this.events[0]?.token;if(!e)return;let t=[];for(let{token:a,...i}of this.events){if(a!==e||t.length>=50||new TextEncoder().encode(JSON.stringify({events:[...t,i]})).byteLength>65536)break;t.push(i)}if(!t.length)return;let n=new Set(t.map(a=>a.eventId)),s=a=>{this.disposed||(this.events=this.events.filter(i=>i.token!==e||!a.has(i.eventId)))};this.flushing=!0,(async()=>{try{let a=AbortSignal.timeout(1e4),i=await fetch(new URL("/v1/events","https://api.opengame.gg"),{method:"POST",credentials:"omit",cache:"no-store",redirect:"error",referrerPolicy:"no-referrer",keepalive:!0,signal:a,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!i.ok){[400,401,403,404,410,413,422].includes(i.status)&&s(n),T(i);return}if(i.status===202){T(i);return}let l=await A(i,65536,a);if(!l||typeof l!="object"||Array.isArray(l)||l.queued===!0)return;let{accepted:o,refused:d=0,limited:u=0,acceptedIds:c}=l;if(![o,d,u].every(f=>typeof f=="number"&&Number.isSafeInteger(f)&&f>=0&&f<=t.length)||o+d+u>t.length||d>0&&l.limited===void 0||c!==void 0&&(!Array.isArray(c)||c.length!==o||new Set(c).size!==c.length||!c.every(f=>typeof f=="string"&&n.has(f))))return;let h=o+d===t.length&&u===0;(h||c!==void 0)&&s(h?n:new Set(c))}catch{}finally{this.flushing=!1}})()};dispose(){this.disposed||(this.cancelLink?.("disposed"),this.finishPlayWaiters({ok:!1,error:"disposed"}),this.flush(),this.events=[],this.disposed=!0,this.sessionGeneration++,this.sessionToken=null,this.boards.cancel("disposed"),this.finish(),clearInterval(this.batchTimer),clearInterval(this.readyRetry),clearTimeout(this.readyDeadline),this.win?.removeEventListener("message",this.receive),this.win?.removeEventListener("pagehide",this.flush),this.win?.removeEventListener("pointerdown",this.firstInput,!0),this.win?.removeEventListener("keydown",this.firstInput,!0),this.health?.stop(),this.win?.document.removeEventListener("visibilitychange",this.visibility),this.playerListeners.clear(),this.muteListeners.clear(),this.pauseListeners.clear(),this.fullscreenListeners.clear(),this.parentListeners.clear())}},E=W("core"),We=E&&Object.hasOwn(E,"og")&&Object.hasOwn(E,"OpenGameClient")&&typeof E.OpenGameClient=="function"&&E.og instanceof E.OpenGameClient?E:H("core",{OpenGameClient:Y,og:new Y},!0),{OpenGameClient:ve,og:D}=We;var _e="label, mode, level and character as strings, and duration_ms, accuracy and combo as numbers";var se=Object.freeze([{code:"unavailable",where:"both",retryable:!1,hint:"The page did not offer this capability. Check og.capabilities first; the local mock simulates account, leaderboard and analytics features."},{code:"invalid_event",where:"result",retryable:!1,hint:"Event names are lowercase letters, digits and underscores, starting with a letter, at most 48 characters, and 1 KB with properties."},{code:"rate_limited",where:"both",retryable:!0,hint:"Too many calls in the window. Events allow 60 a minute. Wait, then try again."},{code:"invalid_board",where:"result",retryable:!1,hint:"Use a board key declared in opengame.json: lowercase letters, digits, hyphens and underscores."},{code:"board_unavailable",where:"result",retryable:!1,hint:"This board is not declared in opengame.json, or the published game has no such board."},{code:"invalid_score",where:"result",retryable:!1,hint:"Scores are finite numbers."},{code:"invalid_meta",where:"result",retryable:!1,hint:`Score metadata takes only ${_e}. Keep strings short.`},{code:"invalid_limit",where:"result",retryable:!1,hint:"A read limit is a positive integer. Values above the maximum are capped."},{code:"invalid_manifest",where:"result",retryable:!1,hint:"opengame.json has an invalid leaderboards list. Each board needs a unique key and an order of asc or desc."},{code:"gesture_required",where:"result",retryable:!0,hint:"Call og.openLink directly from a click or key handler, then confirm the destination on the OpenGame page."},{code:"invalid_request",where:"result",retryable:!1,hint:"The API could not read the request. Check the arguments against the README."},{code:"invalid_achievement",where:"result",retryable:!1,hint:"Use a declared achievement ID with lowercase letters, digits, hyphens or underscores within the shared length limit."},{code:"achievement_unavailable",where:"result",retryable:!0,hint:"The achievement service refused the request. Check the published game and retry when it is available."},{code:"unavailable_in_preview",where:"result",retryable:!1,hint:"Achievements work in a published game only. A preview answers this every time; unlock and list them after publishing."},{code:"network",where:"result",retryable:!0,hint:"The request failed before any service answered. Check the connection, then try again."},{code:"cancelled",where:"result",retryable:!0,hint:"The AbortSignal passed to the call was aborted."},{code:"timeout",where:"result",retryable:!0,hint:"The page did not answer in time. Try again."},{code:"session_changed",where:"both",retryable:!0,hint:"The player signed in, out or switched account. Read the player again."},{code:"disposed",where:"both",retryable:!1,hint:"og.dispose() was called on this client."},{code:"invalid_response",where:"both",retryable:!0,hint:"A service answered with something the SDK does not accept. Try again, and report it if it repeats."},{code:"busy",where:"result",retryable:!0,hint:"Too many requests are waiting on the page. Let one finish first."}]),ke=new Map(se.map(r=>[r.code,r])),He={retryable:!1,hint:"Not in the SDK error catalogue. See packages/sdk/README.md."};function we(r){return ke.has(r)}function q(r){return ke.get(r)??He}var Ve="Multiplayer is not part of the OpenGame SDK any more.";function ae(){let{retryable:r,hint:e}=q("unavailable");return Object.assign(new Error(Ve),{name:"RoomError",code:"unavailable",retryable:r,hint:e})}var Se=Object.freeze({invite:null,host:()=>Promise.reject(ae()),join:()=>Promise.reject(ae()),joinInvite:()=>Promise.resolve(null),lobby:()=>Promise.reject(ae())}),Oe=JSON.stringify({sent:0,dropped:0,closed:!0}),xe=()=>({ok:!1,error:"unavailable",reason:q("unavailable").hint}),Re=Object.freeze({send:()=>Oe,sendTo:()=>Oe,disconnectPeer:()=>JSON.stringify(xe()),maxPacketBytes:0}),Ie=r=>r==="room.joinInvite"?{ok:!0,value:null}:xe();var Qe=(r=null)=>({ok:!0,value:r}),oe=()=>({ok:!1,error:"invalid_request"});function Ce(r){let e=r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:null;return e&&we(e)?{ok:!1,error:e,reason:q(e).hint}:oe()}function Xe(r){if(typeof r!="string"||r.length>m.argsBytesMax||new TextEncoder().encode(r).byteLength>m.argsBytesMax)throw new Error;return r}var Ye=new Set(["init","track","openLink","fullscreen","signIn","board.submit","board.top","board.me","board.around","achievements.unlock","achievements.list"]);function Ze(r){let e=JSON.parse(Xe(r));if(!e||typeof e!="object"||Array.isArray(e))throw new Error;return e}function j(r){if(typeof r!="string")throw new Error;return r}function Me(r){if(typeof r!="number"||!Number.isFinite(r))throw new Error;return r}function Pe(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error;return r}function et(r){let e=null,t=0,n=0,s=new Map,a=(o,d,u,c)=>{try{let h=e?.(o,d,u,JSON.stringify(c));h&&typeof h.then=="function"&&Promise.resolve(h).catch(()=>{})}catch{}},i=(o,d)=>{s.set(o,d),a("event",0,o,d)};r.player.onChange(o=>i("player",o)),r.onPause(o=>i("pause",o)),r.audio.onHostMute(o=>i("mute",o)),r.fullscreen.onChange(o=>i("fullscreen",o));let l=async(o,d)=>{switch(o){case"init":return Qe(await r.init(d));case"track":return r.track(j(d.name),d.props===void 0?{}:Pe(d.props));case"openLink":return r.openLink(j(d.url));case"fullscreen":return r.fullscreen.request();case"signIn":return r.player.requestSignIn();case"board.submit":return r.leaderboard(j(d.key)).submit(Me(d.score),d.meta===void 0?void 0:Pe(d.meta));case"board.top":return r.leaderboard(j(d.key)).top(d.limit===void 0?void 0:{limit:Me(d.limit)});case"board.me":return r.leaderboard(j(d.key)).me();case"board.around":return r.leaderboard(j(d.key)).around();case"achievements.unlock":return r.achievements.unlock(j(d.id));case"achievements.list":return r.achievements.list();default:return oe()}};return Object.freeze({version:r.env.sdkVersion,setHandler(o){let d=++t;e=typeof o=="function"?o:null;for(let[u,c]of s){if(d!==t)break;a("event",0,u,c)}},request(o,d){let u=++n,c=t,h,f=typeof o=="string"&&o.startsWith("room.")?Ie(o):null;try{h=Ye.has(o)?l(o,Ze(d)):Promise.resolve(f??oe())}catch(b){h=Promise.resolve(Ce(b))}return h.then(b=>{c===t&&a("result",u,o,b)},b=>{c===t&&a("result",u,o,Ce(b))}),u},env:()=>JSON.stringify(r.env),player:()=>JSON.stringify(r.player),ready:()=>r.ready(),...Re})}var Le=W("bridge")??H("bridge",et(D));var le=globalThis,Z=Object.assign(D,{og:D,bridge:Le,OpenGameClient:ve,trustedParent:$,errorCatalogue:se});"multiplayer"in Z||Object.defineProperty(Z,"multiplayer",{value:Se,configurable:!0,enumerable:!1,writable:!0});var Te=Z;Object.getOwnPropertyDescriptor(le,"OpenGame")?.configurable===!1?le.OpenGame=Z:Object.defineProperty(le,"OpenGame",{configurable:!0,enumerable:!0,get:()=>Te,set:r=>{r&&Object.hasOwn(r,"og")&&typeof r.OpenGameClient=="function"&&typeof r.trustedParent=="function"||(Te=r)}});D.connect();})();
@@ -0,0 +1 @@
1
+ This SDK build bundles no third-party runtime dependencies. Multiplayer is not part of the SDK.