@vibechain/os 0.5.2 → 0.6.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.
@@ -1 +1 @@
1
- "use strict";var VibemarketOS=(()=>{var pe=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var it=Object.prototype.hasOwnProperty;var at=(e,t)=>{for(var r in t)pe(e,r,{get:t[r],enumerable:!0})},ct=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of st(t))!it.call(e,o)&&o!==r&&pe(e,o,{get:()=>t[o],enumerable:!(a=ot(t,o))||a.enumerable});return e};var lt=e=>ct(pe({},"__esModule",{value:!0}),e);var Tt={};at(Tt,{OsError:()=>M,cardLink:()=>Je,connect:()=>Ze,createAudio:()=>et,packLink:()=>Ue,parseVmosLink:()=>ie});function re(e){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw Error("Invalid game completion.");let t=Object.getOwnPropertyDescriptor(e,"score");if(Reflect.ownKeys(e).length!==1||!t||!("value"in t)||!t.enumerable||typeof t.value!="number"||!Number.isInteger(t.value)||t.value<0||t.value>1e9)throw Error("Score must be an integer from 0 to 1,000,000,000.");return Object.freeze({score:t.value})}var xe="vibexp";var S=Object.freeze({checkpointBytes:32*1024,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34*1024,responseBytes:34*1024,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:900*1e3,requestTimeoutMs:1e4}),ue=1e6;var de=e=>typeof e=="string"&&/^[1-9]\d{0,15}$/.test(e),oe=e=>typeof e=="string"&&e.length<=ue&&/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(e);function J(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function me(e,t){let r=JSON.stringify(e);if(typeof r!="string"||r.length>t||new TextEncoder().encode(r).length>t)throw Error("App message exceeds limit.");return r}function Ee(e,t){if(typeof e!="string"||e.length>t||new TextEncoder().encode(e).length>t)throw Error("Invalid app message size or encoding.");return JSON.parse(e)}var he=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Se=(e,t)=>{let r=Object.keys(e);return r.length===t.length&&Reflect.ownKeys(e).length===r.length&&r.every(a=>t.includes(a)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,a)??{},"value"))};function Re(e){let t=0,r=0,a=(s,l)=>{if(++t>S.checkpointNodes||l>S.checkpointDepth)throw Error("App checkpoint is too complex.");if(s===null||typeof s=="boolean")return;if(typeof s=="number"){if(!Number.isFinite(s))throw Error("Checkpoint numbers must be finite.");return}if(typeof s=="string"){if(s.length>S.stringBytes)throw Error("App checkpoint string is too large.");let p=new TextEncoder().encode(s).byteLength;if(p>S.stringBytes||(r+=p)>S.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(s)){if(s.length>S.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(s).length!==s.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let p=0;p<s.length;p++){let y=Object.getOwnPropertyDescriptor(s,p);if(!y||!("value"in y))throw Error("Sparse/accessor checkpoints are unsupported.");a(y.value,l+1)}return}if(!he(s))throw Error("App checkpoint must contain only JSON values.");let c=Object.keys(s);if(Reflect.ownKeys(s).length!==c.length)throw Error("Checkpoint properties must be enumerable strings.");if(c.length>S.objectKeys)throw Error("App checkpoint has too many keys.");for(let p of c){if(["__proto__","constructor","prototype"].includes(p)||p.length>128)throw Error("Invalid app checkpoint key.");if(r+=new TextEncoder().encode(p).byteLength,r>S.checkpointBytes)throw Error("App checkpoint keys are too large.");let y=Object.getOwnPropertyDescriptor(s,p);if(!y||!("value"in y))throw Error("App checkpoint accessors are unsupported.");a(y.value,l+1)}};a(e,0);let o=JSON.stringify(e);if(new TextEncoder().encode(o).byteLength>S.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return o}var Z=Object.freeze({muted:!1,volume:1});function Pe(e){if(!he(e)||!Se(e,["muted","volume"])||typeof e.muted!="boolean"||typeof e.volume!="number"||!Number.isFinite(e.volume)||e.volume<0||e.volume>1)throw Error("Invalid app sound.");return Object.freeze({muted:e.muted,volume:e.volume})}function Oe(e){if(!he(e)||!Se(e,["active","width","height"])||typeof e.active!="boolean"||typeof e.width!="number"||!Number.isInteger(e.width)||e.width<0||e.width>4096||typeof e.height!="number"||!Number.isInteger(e.height)||e.height<0||e.height>4096)throw Error("Invalid app lifecycle.");return Object.freeze({active:e.active,width:e.width,height:e.height})}var Nt={descriptionMin:40,descriptionMax:2e3,supportMax:200,screenshotsMin:1,screenshotsMax:4,iconSize:256,iconBytes:256*1024,screenshotBytes:1024*1024};var Vt={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},Dt={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},pt={packs:3,network:8,packSlugMax:56},ut=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,I=e=>typeof e=="string"&&e.length<=pt.packSlugMax&&ut.test(e);var _e=["unsupported","not-permitted","invalid","too-large","rate-limited","needs-click","unavailable","timeout","closed"],Ie=e=>typeof e=="string"&&_e.includes(e),T=Object.freeze({idleMs:900*1e3,sessionMs:14400*1e3,requestsPerSecond:10,requestsPerMinute:120,lifetimeRequests:3e4,inFlight:8,readyMs:15e3,progressReadyMs:12e4,saveBytes:1048576,saveDepth:64,saveIntervalMs:1e4,messageBytes:1101024,frameChars:ue,captureMs:1200,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4}),dt=["common","rare","epic","legendary","mythic"],Q=/^[A-Za-z0-9_-]{1,64}$/,Y=Object.freeze({handle:/^[a-z0-9_]{3,15}$/,nameMax:64,token:/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,tokenMin:20,tokenMax:1500}),X=1024,mt=Object.freeze({"host.hello":{request:256,response:X,states:"LFB"},"ui.progress":{request:64,response:64,rate:[4,1e3],states:"LFB"},"app.frame":{request:1000256,response:64,rate:[4,1e3],states:"LFB"},"app.save.get":{request:64,response:11e5,rate:[6,6e4],states:"LFB"},"app.save.set":{request:11e5,response:256,rate:[1,1e4],states:"LFB"},"cards.list":{request:256,response:256*X,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*X,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*X,rate:[30,6e4],states:"LFB"},"cards.watch":{request:64,response:64,rate:[30,6e4],states:"LFB"},"pack.show":{request:128,response:64,rate:[1,1e4],bucket:"show",states:"F"},"card.show":{request:192,response:64,rate:[1,1e4],bucket:"show",states:"F"},"player.get":{request:64,response:2*X,rate:[10,6e4],states:"LFB"},"display.maximize":{request:64,response:64,rate:[2,1e3],states:"F"},"display.fullscreen":{request:64,response:64,rate:[1,1e3],states:"F"}}),qt=Object.freeze(Object.keys(mt).filter(e=>e!=="host.hello"&&e!=="card.show")),ht=new TextEncoder,ft=e=>ht.encode(e).byteLength,L=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),z=(e,t,r=[])=>Reflect.ownKeys(e).every(o=>typeof o=="string"&&(t.includes(o)||r.includes(o))&&"value"in Object.getOwnPropertyDescriptor(e,o))&&t.every(o=>Object.hasOwn(e,o)),M=class extends Error{code;constructor(t,r){super(r),this.name="OsError",this.code=t}},N=class extends Error{code;constructor(t,r){super(r),this.name="AppHostError",this.code=t}};function fe(e){let t=o=>new N("invalid",o),r=(o,s)=>{if(!(o===null||typeof o=="boolean"||typeof o=="string")){if(typeof o=="number"){if(!Number.isFinite(o))throw t("A save's numbers must be finite.");return}if(typeof o!="object")throw t("A save must contain only JSON values.");if(s>T.saveDepth)throw t(`A save nests at most ${T.saveDepth} levels deep.`);if(Array.isArray(o)){if(Reflect.ownKeys(o).length!==o.length+1)throw t("A save's arrays cannot have extra properties.");for(let l=0;l<o.length;l++){let c=Object.getOwnPropertyDescriptor(o,l);if(!c||!("value"in c))throw t("A save's arrays cannot be sparse or have accessors.");r(c.value,s+1)}return}if(!L(o))throw t("A save must contain only plain objects, arrays and JSON values.");for(let l of Reflect.ownKeys(o)){let c=Object.getOwnPropertyDescriptor(o,l);if(typeof l!="string"||!c||!("value"in c)||!c.enumerable)throw t("A save's properties must be plain enumerable data.");r(c.value,s+1)}}};r(e,1);let a=JSON.stringify(e);if(ft(a)>T.saveBytes)throw new N("too-large",`A save is at most ${T.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return a}function Te(e){let t;try{t=JSON.parse(e)}catch{throw new N("invalid","The saved data is not JSON.")}return fe(t),t}var j=(e,t,r=0)=>typeof e=="string"&&e.length>=r&&e.length<=t,se=(e,t,r)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=r,gt=e=>typeof e=="string"&&dt.includes(e),ge=".bin",yt=(e,t)=>`-/card/${e}/${t}${ge}`,wt=e=>`-/cover/${e}${ge}`,kt=e=>`-/player/${e}${ge}`;function Le(e,t){if(!L(e)||!z(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:r,pack:a,name:o,art:s}=e,l=typeof r=="string"?r.slice(r.indexOf("/")+1):"";if(!I(a)||r!==`${a}/${l}`||!Q.test(l)||!j(o,120)||!gt(e.rarity)||t&&!se(e.count,1,1e6)||s!==null&&s!==yt(a,l))throw Error("Invalid card.");return{id:r,pack:a,name:o,rarity:e.rarity,...t?{count:e.count}:{},art:s}}function ye(e){return Le(e,!0)}function bt(e){return Le(e,!1)}function ze(e){let{id:t,name:r,creator:a,art:o,total:s}=e;if(!I(t)||!j(r,120,1)||a!==null&&!j(a,64,1)||o!==null&&o!==wt(t)||!se(s,0,1e4))throw Error("Invalid pack.");return{id:t,name:r,creator:a,art:o,total:s}}function je(e){if(!L(e)||!z(e,["id","name","creator","art","held","total"])||!se(e.held,0,1e4))throw Error("Invalid pack.");let t=ze(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function $e(e){if(!L(e)||!z(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=ze(e),r=e.cards.map(bt);if(r.some(a=>a.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:r}}var At=/[\u0000-\u001F\u007F-\u009F]/,Ce=e=>typeof e=="string"&&Y.handle.test(e);function Ne(e){if(L(e)&&z(e,["guest"])&&e.guest===!0)return{guest:!0};if(!L(e)||!z(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:r,name:a,picture:o,token:s,expiresAt:l}=e;if(!Ce(t)||!j(a,Y.nameMax,1)||At.test(a)||r!==void 0&&(!Ce(r)||r===t)||o!==null&&o!==kt(t)||"token"in e!="expiresAt"in e||s!==void 0&&(!j(s,Y.tokenMax,Y.tokenMin)||!Y.token.test(s)||!se(l,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...r===void 0?{}:{username:r},name:a,picture:o,...s===void 0?{}:{token:s,expiresAt:l}}}var Me=e=>j(e,64,1);function Ve(e){if(L(e)&&z(e,["reset","revision"])&&e.reset===!0&&Me(e.revision))return{reset:!0,revision:e.revision};if(!L(e)||!z(e,["changed","removed","revision"])||!Array.isArray(e.changed)||!Array.isArray(e.removed)||!Me(e.revision)||e.removed.some(t=>!j(t,130,3)))throw Error("Invalid cards event.");return{changed:e.changed.map(ye),removed:e.removed,revision:e.revision}}function De(e){if(!L(e)||!z(e,["protocol","guest","features","root"])||e.protocol!==2||typeof e.guest!="boolean"||!Array.isArray(e.features)||e.features.length>64||e.features.some(t=>!j(t,40,1))||typeof e.root!="string"||!/^(?:\.\/|(?:\.\.\/){1,32})$/.test(e.root))throw Error("Invalid hello.");return{protocol:2,guest:e.guest,features:e.features,root:e.root}}var vt=1280,xt=[.85,.6,.4];function Et(e){let t=null,r=0;for(let a of Array.from(e.querySelectorAll("canvas"))){let o=a.getBoundingClientRect(),s=o.width*o.height;s>r&&a.width>0&&a.height>0&&(t=a,r=s)}return t}function St(e,t){try{let r=e.width,a=e.height;if(!(r>0&&a>0))return null;let o=Math.min(1,vt/Math.max(r,a)),s=t.createElement("canvas");s.width=Math.max(1,Math.round(r*o)),s.height=Math.max(1,Math.round(a*o));let l=s.getContext("2d");if(!l)return null;l.drawImage(e,0,0,s.width,s.height);for(let c of xt){let p=s.toDataURL("image/webp",c);if(p.startsWith("data:image/webp")||(p=s.toDataURL("image/jpeg",c)),oe(p))return p}return null}catch{return null}}function Fe(e,t){return typeof e=="string"?oe(e)?e:null:e!==null&&typeof e=="object"&&"getContext"in e&&"toDataURL"in e?St(e,t):null}function Be(e,t){let r=null,a=()=>globalThis.document,o=(s,l)=>{if(!t())try{e(s,l)}catch{}};return{on(s){return r=s,()=>{r===s&&(r=null)}},clear(){r=null},event(s){if(!(t()||!de(s)))try{let l=r;if(l){Promise.resolve().then(l).then(c=>Fe(c,a()),()=>null).then(c=>o(s,c),()=>{});return}requestAnimationFrame(()=>{let c=null;try{let p=Et(a());c=p?Fe(p,a()):null}catch{c=null}o(s,c)})}catch{}}}}var we="vibemarket.game.v1";function We(e,t={}){let r=0,a=!1,o,s=new Map,l=t.jsonBytes!==void 0,c=t.errors,p=[],y=[],f=k=>{k&&(k.done=Date.now(),x())},E=()=>c?c.closed():Error("Game session ended.");function x(){let k=t.pace;for(;y.length;){let m=Date.now();for(let h=p.length-1;h>=0;h--)p[h].done!==null&&m-p[h].done>=6e4&&p.splice(h,1);let w=p.filter(h=>h.done===null||m-h.done<1e3);if(w.length<k.perSecond&&p.length<k.perMinute){y.shift()();continue}let b=w.length>=k.perSecond?{list:w,ms:1e3}:{list:p,ms:6e4},A=b.list.filter(h=>h.done!==null).map(h=>h.done+b.ms-m);A.length&&o===void 0&&(o=window.setTimeout(()=>{o=void 0,x()},Math.max(1,Math.min(...A))));return}}return e.onmessage=k=>{let m;try{m=t.jsonBytes===void 0?k.data:Ee(k.data,t.jsonBytes)}catch{return}if(a||!m||typeof m!="object"||Array.isArray(m))return;let w=m;if(t.session!==void 0&&w.session!==t.session)return;if("event"in w){t.onEvent?.(w);return}if(typeof w.id!="string")return;let b=s.get(w.id);if(b)if(s.delete(w.id),window.clearTimeout(b.timer),f(b.record),typeof w.error=="string"){let A=l?w.error.slice(0,500):w.error;b.reject(c?c.reply(A,w.code):Error(A))}else"result"in w?b.resolve(w.result):b.reject(c?c.reply("Invalid host response.","unavailable"):Error("Invalid host response."))},e.start(),{request(k){if(a)return Promise.reject(E());if(s.size+y.length>=(t.maxPending??16))return Promise.reject(c?c.busy():Error("Too many pending requests."));let m=String(++r);return new Promise((w,b)=>{let A=()=>{let h=t.pace?{done:null}:void 0;h&&p.push(h);let O=window.setTimeout(()=>{s.delete(m),f(h),b(c?c.timeout():Error(t.jsonBytes===void 0?"Request timed out. Check your VibeMarket inventory before trying again; a submitted transaction may still complete.":"App request timed out. Restore the window and read its last accepted checkpoint before retrying."))},t.timeoutMs??18e4);s.set(m,{resolve:C=>w(C),reject:b,timer:O,record:h});try{let C={id:m,request:k,...t.session===void 0?{}:{session:t.session}};e.postMessage(t.jsonBytes===void 0?C:me(C,t.outBytes??t.jsonBytes))}catch(C){s.delete(m),window.clearTimeout(O),f(h),b(C)}};if(!t.pace){A();return}y.push(()=>{a?b(E()):A()}),x()})},destroy(){if(!a){a=!0,o!==void 0&&window.clearTimeout(o);for(let k of y.splice(0))k();s.forEach(k=>{window.clearTimeout(k.timer),k.reject(E())}),s.clear(),e.onmessage=null,e.close()}}}}function Ge(e,t){return new Promise((r,a)=>{let o,s=()=>{window.clearTimeout(p),o!==void 0&&window.clearInterval(o),window.removeEventListener("message",c),e?.removeEventListener("abort",l)},l=()=>{s(),a(Error("Game session ended."))},c=f=>{if(f.source!==window.parent||!f.data||typeof f.data!="object"||!("channel"in f.data)||f.data.channel!==we||f.ports.length!==1)return;let E;if(t!==void 0){if(!("challenge"in f.data)||f.data.challenge!==t||!("session"in f.data)||!J(f.data.session))return;E=f.data.session}let x=t!==void 0&&"protocol"in f.data&&f.data.protocol===2?2:void 0;s(),r({port:f.ports[0],...E===void 0?{}:{session:E},...x===void 0?{}:{protocol:x}})},p=window.setTimeout(()=>{s(),a(Error("VibeMarket did not connect. Reopen the game."))},15e3);if(window.addEventListener("message",c),e?.addEventListener("abort",l,{once:!0}),e?.aborted){l();return}let y=()=>{let f={channel:we,type:"connect",...t===void 0?{}:{challenge:t}};window.parent.postMessage(t===void 0?f:me(f,256),"*")};y(),t!==void 0&&(o=window.setInterval(y,250))})}var Rt=200,ke="[a-z0-9]+(?:-[a-z0-9]+)*",Pt="[A-Za-z0-9_-]{1,64}",He=new RegExp(`^vmos://pack/(${ke})$`),qe=new RegExp(`^vmos://card/(${ke})/(${Pt})$`),Ke=new RegExp(`^https://(?:www\\.)?vibechain\\.com/os/pack/(${ke})/?$`),nn=Object.freeze({pack:He,card:qe,web:Ke});function ie(e){if(typeof e!="string"||e.length>Rt)return null;let t=qe.exec(e);if(t)return I(t[1])?{kind:"card",pack:t[1],card:t[2]}:null;let r=He.exec(e)??Ke.exec(e);return r&&I(r[1])?{kind:"pack",pack:r[1]}:null}function Ue(e){if(!I(e))throw new M("invalid","That is not a pack slug.");return`vmos://pack/${e}`}function Je(e,t){if(!I(e)||typeof t!="string"||!Q.test(t))throw new M("invalid","That is not a pack slug and a card id.");return`vmos://card/${e}/${t}`}var Ot="0.5.2",Ct=Object.freeze({unsupported:"This host is older than this SDK and has no such feature.","not-permitted":"The manifest does not declare that, or the app is behind another window.",invalid:"That argument is not valid.","too-large":"That is too large.","rate-limited":"Too many requests; try again later.","needs-click":"That needs a fresh click in the app.",unavailable:"The host could not answer now; try again.",timeout:"The host did not answer in 10 seconds.",closed:"The session ended. Reopen the app."}),Mt=Ct,g=(e,t=Mt[e])=>new M(e,t),ee=(e,t)=>e instanceof M?e:e instanceof N?new M(e.code,e.message):g(t,e.message),ae=e=>{if(!I(e))throw g("invalid","That is not a pack slug.");return e};async function Ze(e={}){let t=new URLSearchParams(window.location.hash.slice(1)).get(xe);if(!J(t))throw g("unsupported","Open this app in VibeMarket OS or the SDK preview.");let r;try{r=await Ge(e.signal,t)}catch(a){throw g(e.signal?.aborted?"closed":"timeout",a.message)}return _t(r.port,r.session,r.protocol??1,window.location.href)}async function _t(e,t,r,a){if(!J(t))throw g("unavailable","Invalid app session.");let o=Object.freeze({active:!0,width:0,height:0}),s=!1,l=Z,c=new Set,p=new Set,y=new Set,f=new Set,E=new Set,x=We(e,{session:t,timeoutMs:S.requestTimeoutMs,maxPending:r===2?64:S.inFlight,jsonBytes:r===2?T.messageBytes:S.responseBytes,errors:{reply:(n,i)=>g(Ie(i)?i:"unavailable",n),timeout:()=>g("timeout"),closed:()=>g("closed"),busy:()=>g("rate-limited","Too many requests are waiting; try again later.")},...r===2?{pace:{perSecond:T.clientPerSecond,perMinute:T.clientPerMinute}}:{},onEvent(n){if(n.event==="app.cards"){V(n.state);return}if(n.event==="app.capture"){k.event(n.id);return}if(n.event==="app.sound"){w(n.state);return}if(n.event!=="app.lifecycle")return;let i;try{i=Oe(n.state)}catch{return}let u=o;if(o=Object.freeze({active:i.active,width:i.width,height:i.height}),u.active&&!i.active)for(let v of[...c])v();if(!u.active&&i.active)for(let v of[...p])v();if(u.width!==i.width||u.height!==i.height)for(let v of[...y])v(Object.freeze({width:i.width,height:i.height}))}}),k=Be((n,i)=>{m({method:"app.frame",id:n,image:i}).catch(()=>{})},()=>r!==2||!A||s),m=async n=>{if(s)throw g("closed");let i=await x.request(n);if(!i||typeof i!="object"||Array.isArray(i))throw g("unavailable","Invalid host response.");return i};function w(n){let i;try{i=Pe(n)}catch{return}if(!(i.muted===l.muted&&i.volume===l.volume)){l=i;for(let u of[...E])u(l)}}let b=n=>{if(n.completed!==!0)throw g("unavailable","Invalid host acknowledgement.")},A=null;if(r===2)try{A=De(await m({method:"host.hello",protocol:2,sdk:Ot}))}catch(n){throw x.destroy(),ee(n,"unavailable")}let h=()=>{if(!A)throw g("unsupported");return A},O=n=>n===null?null:new URL(h().root+n,a).href,C=n=>({...n,art:O(n.art)}),_=null,D=!1,F=null,B=async n=>{for(let i=0;i<4;i++){let u=[],v=null,R=null,ne=!0;do{let P=await m({method:"cards.list",...n===void 0?{}:{pack:n},...v===null?{}:{after:v}});if(!Array.isArray(P.cards)||P.after!==null&&typeof P.after!="string"||typeof P.revision!="string")throw g("unavailable","Invalid host response.");if(R!==null&&P.revision!==R){ne=!1;break}R=P.revision,v=P.after;for(let rt of P.cards)u.push(C(ye(rt)))}while(v!==null);if(ne&&R!==null)return n===void 0&&(_={revision:R,cards:new Map(u.map(P=>[P.id,P]))}),{cards:u,revision:R}}throw g("unavailable","The cards kept changing while they were read; try again.")},W=()=>{let n=[..._.cards.values()];for(let i of[...f])i(n.slice())},d=n=>F??=(async()=>{try{do D=!1,await B();while(D);n&&W()}catch{}finally{F=null}})();function V(n){if(!f.size)return;let i;try{i=Ve(n)}catch{return}if(F){D=!0;return}if("reset"in i||!_){d(!0);return}for(let u of i.removed)_.cards.delete(u);for(let u of i.changed)_.cards.set(u.id,C(u));_={revision:i.revision,cards:_.cards},W()}let $=null,ce=!1,be=-1/0,G,tt=r===2?T.saveIntervalMs:0,le=()=>{if(ce||!$||G!==void 0)return;let n=be+tt-Date.now();if(n>0){G=window.setTimeout(()=>{G=void 0,le()},n);return}let{text:i,waiters:u}=$;$=null,ce=!0;let v=JSON.parse(i);m(r===2?{method:"app.save.set",value:v}:{method:"app.checkpoint.set",value:v}).then(R=>{if(r===2?typeof R.savedAt!="string":R.completed!==!0)throw g("unavailable","Invalid host acknowledgement.")}).then(()=>{for(let R of u)R.resolve()},R=>{let ne=ee(R,"unavailable");for(let P of u)P.reject(ne)}).finally(()=>{ce=!1,be=Date.now(),le()})},H=null,te=async n=>{let i=h();if(n.method==="card.show"&&!i.features.includes("card.show"))throw g("unsupported");if((await m(n)).shown!==!0)throw g("unavailable","Invalid host acknowledgement.")},q={get active(){return o.active},get size(){return Object.freeze({width:o.width,height:o.height})},get guest(){return A?.guest??!1},get sound(){return l},async ready(){b(await m({method:"ui.ready"}))},progress(n){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>1)throw g("invalid","Progress is a number from 0 to 1.");!A||Ae||(K=n,U===void 0&&(ve(),U=window.setTimeout(()=>{U=void 0,K!==null&&ve()},1e3)))},async load(){if(A){let i=await m({method:"app.save.get"});return i.value===null?null:Te(JSON.stringify(i.value))}let n=await m({method:"app.checkpoint.get"});if(!("checkpoint"in n))throw g("unavailable","Invalid host response.");return n.checkpoint},save(n){let i;try{if(i=fe(n),!A){if(new TextEncoder().encode(i).byteLength>S.checkpointBytes)throw g("too-large","This host keeps at most 32 KiB, and only while the window is open.");try{Re(n)}catch(u){throw g("too-large",u.message)}}}catch(u){return Promise.reject(ee(u,"invalid"))}return s?Promise.reject(g("closed")):new Promise((u,v)=>{$={text:i,waiters:[...$?.waiters??[],{resolve:u,reject:v}]},le()})},async cards(n){let i=n===void 0?void 0:ae(n);return h(),(await B(i)).cards},onCards(n){return f.add(n),A&&f.size===1&&m({method:"cards.watch",on:!0}).then(()=>{_||d(!1)},()=>{}),()=>{!f.delete(n)||f.size||!A||s||m({method:"cards.watch",on:!1}).catch(()=>{})}},async packs(){h();let n=await m({method:"cards.packs"});if(!Array.isArray(n.packs))throw g("unavailable","Invalid host response.");return n.packs.map(i=>{let u=je(i);return{...u,art:O(u.art)}})},async pack(n){let i=ae(n);h();let u=$e((await m({method:"cards.pack",pack:i})).pack);return{...u,art:O(u.art),cards:u.cards.map(v=>({...v,art:O(v.art)}))}},async showPack(n){let i=ae(n);h(),await te({method:"pack.show",pack:i})},async showCard(n,i){let u=ae(n);if(typeof i!="string"||!Q.test(i))throw g("invalid","That is not a card id.");await te({method:"card.show",pack:u,card:i})},async open(n){let i=ie(n);if(!i)throw g("invalid","That is not a vmOS pack or card link.");await(i.kind==="pack"?te({method:"pack.show",pack:i.pack}):te({method:"card.show",pack:i.pack,card:i.card}))},async player(){if(h(),H&&H.expiresAt-Date.now()>T.tokenReuseMs)return{...H};let n=Ne(await m({method:"player.get"}));if(n.guest)return H=null,n;let i={...n,picture:O(n.picture)};return H=i.token?i:null,{...i}},async finish(n){let i;try{i=re(n)}catch(u){throw ee(u,"invalid")}b(await m({method:"game.finish",...i}))},async maximize(n=!0){if(typeof n!="boolean")throw g("invalid");h(),b(await m({method:"display.maximize",on:n}))},async fullscreen(n=!0){if(typeof n!="boolean")throw g("invalid");h(),b(await m({method:"display.fullscreen",on:n}))},onPause(n){return c.add(n),()=>{c.delete(n)}},onResume(n){return p.add(n),()=>{p.delete(n)}},onCapture(n){if(typeof n!="function")throw g("invalid","A capture handler is a function.");return k.on(n)},onResize(n){return y.add(n),()=>{y.delete(n)}},onSound(n){return E.add(n),()=>{E.delete(n)}},close(){s||(s=!0,G!==void 0&&window.clearTimeout(G),U!==void 0&&window.clearTimeout(U),$?.waiters.forEach(n=>n.reject(g("closed"))),$=null,k.clear(),c.clear(),p.clear(),y.clear(),E.clear(),f.clear(),x.destroy())}},K=null,U,Ae=!1,ve=()=>{let n=K;K=null,m({method:"ui.progress",value:n}).catch(()=>{})},nt=q.ready;q.ready=async()=>{Ae=!0,K=null,await nt()};for(let n of["ready","load","cards","packs","pack","showPack","showCard","open","player","finish","maximize","fullscreen"]){let i=q[n];q[n]=async(...u)=>{try{return await i(...u)}catch(v){throw ee(v,"unavailable")}}}return Object.freeze(q)}var Xe=.05,Ye=Object.freeze(["pointerdown","pointerup","keydown","touchend"]),Qe=Object.freeze({gestures:3,remakes:3});function It(e){if("lifecycle"in e){let t=e.sound;return{active:()=>e.lifecycle.current().active,sound:()=>t?.current()??Z,onActive(r){let a=e.lifecycle.current().active;return e.lifecycle.onChanged(o=>{o.active!==a&&(a=o.active,r(a))})},onSound:r=>t?t.onChanged(r):()=>{}}}return{active:()=>e.active,sound:()=>e.sound??Z,onActive(t){let r=[e.onPause(()=>t(!1)),e.onResume(()=>t(!0))];return()=>{for(let a of r)a()}},onSound:t=>typeof e.onSound=="function"?e.onSound(t):()=>{}}}function et(e,t={}){let r=It(e),a=()=>new AudioContext({latencyHint:t.latencyHint??"interactive"}),o=t.context??a(),s=o.createGain(),l=!1,c=!1,p=!1,y=r.active(),f=0,E=0,x,k=new Set,m=()=>{let d=r.sound();return d.muted||l||!y?0:d.volume},w=()=>{for(let d of[...k])d()},b=()=>{let d=o.currentTime,V=s.gain;V.cancelScheduledValues(d),V.setValueAtTime(V.value,d),V.linearRampToValueAtTime(m(),d+Xe)},A=()=>!p&&!c&&y,h=()=>{A()&&o.state!=="running"&&o.resume().catch(()=>{})},O=()=>{if(o.state==="running"&&(f=0),o.state==="closed"&&!p){_();return}w()},C=()=>{s.gain.value=m(),s.connect(o.destination),o.addEventListener("statechange",O)};function _(){if(E>=Qe.remakes)return;E++,f=0;let d=o;d.removeEventListener("statechange",O),d.state!=="closed"&&d.close().catch(()=>{});try{o=a()}catch{o=d;return}s=o.createGain(),C(),h(),w()}let D=()=>{clearTimeout(x),x=setTimeout(()=>{x=void 0,!p&&!A()&&o.state==="running"&&o.suspend().catch(()=>{})},Xe*1e3+20)},F=[r.onSound(()=>{b(),w()}),r.onActive(d=>{y=d,b(),y?(clearTimeout(x),h()):D(),w()})],B=()=>{!A()||o.state==="running"||(++f>Qe.gestures?_():h())},W=()=>{document.visibilityState==="visible"&&h()};for(let d of Ye)window.addEventListener(d,B,{capture:!0,passive:!0});return document.addEventListener("visibilitychange",W),C(),h(),{get context(){return o},get master(){return s},get desktop(){return r.sound()},get audible(){let d=r.sound();return!d.muted&&d.volume>0&&!l&&y&&o.state==="running"},get muted(){return l},set muted(d){d!==l&&(l=d,b(),w())},get paused(){return c},set paused(d){d!==c&&(c=d,c?o.suspend().catch(()=>{}):h(),w())},onChange(d){return k.add(d),()=>{k.delete(d)}},close(){if(!p){p=!0,clearTimeout(x);for(let d of F)d();for(let d of Ye)window.removeEventListener(d,B,{capture:!0});document.removeEventListener("visibilitychange",W),o.removeEventListener("statechange",O),k.clear(),o.close().catch(()=>{})}}}}return lt(Tt);})();
1
+ "use strict";var VibemarketOS=(()=>{var be=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var Bt=Object.getOwnPropertyNames;var Vt=Object.prototype.hasOwnProperty;var Wt=(e,t)=>{for(var r in t)be(e,r,{get:t[r],enumerable:!0})},Gt=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Bt(t))!Vt.call(e,s)&&s!==r&&be(e,s,{get:()=>t[s],enumerable:!(a=Ft(t,s))||a.enumerable});return e};var Ht=e=>Gt(be({},"__esModule",{value:!0}),e);var vn={};Wt(vn,{OsError:()=>z,appLink:()=>Ot,cardLink:()=>_t,connect:()=>Tt,createAudio:()=>$t,packLink:()=>It,parseVmosLink:()=>me});function le(e){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw Error("Invalid game completion.");let t=Object.getOwnPropertyDescriptor(e,"score");if(Reflect.ownKeys(e).length!==1||!t||!("value"in t)||!t.enumerable||typeof t.value!="number"||!Number.isInteger(t.value)||t.value<0||t.value>1e9)throw Error("Score must be an integer from 0 to 1,000,000,000.");return Object.freeze({score:t.value})}var Ve="vibexp";var _=Object.freeze({checkpointBytes:32*1024,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34*1024,responseBytes:34*1024,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:900*1e3,requestTimeoutMs:1e4}),ke=1e6;var Ae=e=>typeof e=="string"&&/^[1-9]\d{0,15}$/.test(e),pe=e=>typeof e=="string"&&e.length<=ke&&/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(e);function te(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function ve(e,t){let r=JSON.stringify(e);if(typeof r!="string"||r.length>t||new TextEncoder().encode(r).length>t)throw Error("App message exceeds limit.");return r}function We(e,t){if(typeof e!="string"||e.length>t||new TextEncoder().encode(e).length>t)throw Error("Invalid app message size or encoding.");return JSON.parse(e)}var xe=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Ge=(e,t)=>{let r=Object.keys(e);return r.length===t.length&&Reflect.ownKeys(e).length===r.length&&r.every(a=>t.includes(a)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,a)??{},"value"))};function He(e){let t=0,r=0,a=(i,c)=>{if(++t>_.checkpointNodes||c>_.checkpointDepth)throw Error("App checkpoint is too complex.");if(i===null||typeof i=="boolean")return;if(typeof i=="number"){if(!Number.isFinite(i))throw Error("Checkpoint numbers must be finite.");return}if(typeof i=="string"){if(i.length>_.stringBytes)throw Error("App checkpoint string is too large.");let p=new TextEncoder().encode(i).byteLength;if(p>_.stringBytes||(r+=p)>_.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(i)){if(i.length>_.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(i).length!==i.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let p=0;p<i.length;p++){let w=Object.getOwnPropertyDescriptor(i,p);if(!w||!("value"in w))throw Error("Sparse/accessor checkpoints are unsupported.");a(w.value,c+1)}return}if(!xe(i))throw Error("App checkpoint must contain only JSON values.");let l=Object.keys(i);if(Reflect.ownKeys(i).length!==l.length)throw Error("Checkpoint properties must be enumerable strings.");if(l.length>_.objectKeys)throw Error("App checkpoint has too many keys.");for(let p of l){if(["__proto__","constructor","prototype"].includes(p)||p.length>128)throw Error("Invalid app checkpoint key.");if(r+=new TextEncoder().encode(p).byteLength,r>_.checkpointBytes)throw Error("App checkpoint keys are too large.");let w=Object.getOwnPropertyDescriptor(i,p);if(!w||!("value"in w))throw Error("App checkpoint accessors are unsupported.");a(w.value,c+1)}};a(e,0);let s=JSON.stringify(e);if(new TextEncoder().encode(s).byteLength>_.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return s}var ne=Object.freeze({muted:!1,volume:1});function Ke(e){if(!xe(e)||!Ge(e,["muted","volume"])||typeof e.muted!="boolean"||typeof e.volume!="number"||!Number.isFinite(e.volume)||e.volume<0||e.volume>1)throw Error("Invalid app sound.");return Object.freeze({muted:e.muted,volume:e.volume})}function Ue(e){if(!xe(e)||!Ge(e,["active","width","height"])||typeof e.active!="boolean"||typeof e.width!="number"||!Number.isInteger(e.width)||e.width<0||e.width>4096||typeof e.height!="number"||!Number.isInteger(e.height)||e.height<0||e.height>4096)throw Error("Invalid app lifecycle.");return Object.freeze({active:e.active,width:e.width,height:e.height})}var Pn={descriptionMin:40,descriptionMax:2e3,supportMax:200,screenshotsMin:1,screenshotsMax:4,iconSize:256,iconBytes:256*1024,screenshotBytes:1024*1024};var Kt=/^[a-z][a-z0-9-]{0,31}$/,F=e=>typeof e=="string"&&Kt.test(e),On={leaderboards:5,achievements:50,products:50,nameMax:40,descriptionMax:120,achievementIconSize:128,achievementIconBytes:64*1024,priceMax:1e6},Je=["high","low"],Ze=["number","time"],Ee=["consumable","permanent"],In=Object.freeze({id:"score",name:"High scores",order:"high",format:"number"});var _n={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},Tn={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},Ut={packs:3,network:8,packSlugMax:56,manifestBytes:64*1024},Jt=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,B=e=>typeof e=="string"&&e.length<=Ut.packSlugMax&&Jt.test(e);function Xe(e){return e.length>0&&e.length<=200&&e.split("/").every(t=>/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(t)&&!t.endsWith("."))}var qe=["unsupported","not-permitted","invalid","too-large","rate-limited","needs-click","unavailable","timeout","closed","cancelled","insufficient","limit","guest"],Qe=e=>typeof e=="string"&&qe.includes(e),O=Object.freeze({idleMs:900*1e3,sessionMs:14400*1e3,requestsPerSecond:10,requestsPerMinute:120,lifetimeRequests:3e4,inFlight:8,readyMs:15e3,progressReadyMs:12e4,saveBytes:1048576,saveDepth:64,saveIntervalMs:1e4,messageBytes:1101024,frameChars:ke,captureMs:1200,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4,clickMs:5e3,buyClickMs:1e3,surfaceMs:1800*1e3}),Xt=["common","rare","epic","legendary","mythic"],oe=/^[A-Za-z0-9_-]{1,64}$/,V=Object.freeze({handle:/^[a-z0-9_]{3,15}$/,nameMax:64,token:/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,tokenMin:20,tokenMax:1500}),Yt=["everyone","friends"],et=["all","week"],qt=["playing","online","offline"],$=Object.freeze({boardRowsMax:50,boardRowsDefault:10,inviteText:80,inviteData:256,inviteRecipients:10,shareText:140,friendsMax:100,receiptsMax:100,timeScoreMax:864e5}),tt=/^[A-Za-z0-9_-]{1,64}$/,Qt=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,ue=e=>typeof e=="string"&&e.length<=60&&Qt.test(e),nt="game.finish.board";var T=1024,Se=Object.freeze({"host.hello":{request:256,response:T,states:"LFB"},"ui.progress":{request:64,response:64,rate:[4,1e3],states:"LFB"},"app.frame":{request:1000256,response:64,rate:[4,1e3],states:"LFB"},"app.save.get":{request:64,response:11e5,rate:[6,6e4],states:"LFB"},"app.save.set":{request:11e5,response:256,rate:[1,1e4],states:"LFB"},"cards.list":{request:256,response:256*T,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*T,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*T,rate:[30,6e4],states:"LFB"},"cards.watch":{request:64,response:64,rate:[30,6e4],states:"LFB"},"pack.show":{request:128,response:64,rate:[1,1e4],bucket:"show",states:"F"},"card.show":{request:192,response:64,rate:[1,1e4],bucket:"show",states:"F"},"player.get":{request:64,response:2*T,rate:[10,6e4],states:"LFB"},"display.maximize":{request:64,response:64,rate:[2,1e3],states:"F"},"display.fullscreen":{request:64,response:64,rate:[1,1e3],states:"F"},"leaderboard.get":{request:256,response:32*T,rate:[30,6e4],states:"LFB"},"leaderboard.show":{request:128,response:64,rate:[1,3e3],states:"F",click:O.clickMs,surface:!0},"achievement.unlock":{request:128,response:64,rate:[20,6e4],states:"LFB"},"achievements.list":{request:64,response:64*T,rate:[10,6e4],states:"LFB"},"friends.list":{request:64,response:64*T,rate:[10,6e4],states:"LFB"},"app.launch":{request:64,response:2*T,rate:[4,6e4],states:"LFB"},"invite.open":{request:4*T,response:64,rate:[1,1e4],states:"F",click:O.clickMs,guest:!0,surface:!0},"share.open":{request:2*T,response:64,rate:[1,1e4],states:"F",click:O.clickMs,guest:!0,surface:!0},"products.list":{request:64,response:64*T,rate:[10,6e4],states:"LFB"},"product.buy":{request:128,response:512,rate:[1,3e3],states:"F",click:O.buyClickMs,guest:!0,surface:!0},"purchases.list":{request:64,response:32*T,rate:[10,6e4],states:"LFB"},"purchase.consume":{request:192,response:64,rate:[30,6e4],states:"LFB"},"purchase.token":{request:192,response:2*T,rate:[10,6e4],states:"LFB"},"app.show":{request:192,response:64,rate:[1,1e4],bucket:"show",states:"F",click:O.clickMs}}),en=Object.freeze(["leaderboard.get","leaderboard.show","achievement.unlock","achievements.list","friends.list","app.launch","invite.open","share.open","products.list","product.buy","purchases.list","purchase.consume","purchase.token","app.show"]),Dn=Object.freeze(Object.keys(Se).filter(e=>e!=="host.hello"&&e!=="card.show"&&!en.includes(e))),tn=new TextEncoder,nn=e=>tn.encode(e).byteLength,S=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),I=(e,t,r=[])=>Reflect.ownKeys(e).every(s=>typeof s=="string"&&(t.includes(s)||r.includes(s))&&"value"in Object.getOwnPropertyDescriptor(e,s))&&t.every(s=>Object.hasOwn(e,s)),z=class extends Error{code;constructor(t,r){super(r),this.name="OsError",this.code=t}},J=class extends Error{code;constructor(t,r){super(r),this.name="AppHostError",this.code=t}};function Pe(e){let t=s=>new J("invalid",s),r=(s,i)=>{if(!(s===null||typeof s=="boolean"||typeof s=="string")){if(typeof s=="number"){if(!Number.isFinite(s))throw t("A save's numbers must be finite.");return}if(typeof s!="object")throw t("A save must contain only JSON values.");if(i>O.saveDepth)throw t(`A save nests at most ${O.saveDepth} levels deep.`);if(Array.isArray(s)){if(Reflect.ownKeys(s).length!==s.length+1)throw t("A save's arrays cannot have extra properties.");for(let c=0;c<s.length;c++){let l=Object.getOwnPropertyDescriptor(s,c);if(!l||!("value"in l))throw t("A save's arrays cannot be sparse or have accessors.");r(l.value,i+1)}return}if(!S(s))throw t("A save must contain only plain objects, arrays and JSON values.");for(let c of Reflect.ownKeys(s)){let l=Object.getOwnPropertyDescriptor(s,c);if(typeof c!="string"||!l||!("value"in l)||!l.enumerable)throw t("A save's properties must be plain enumerable data.");r(l.value,i+1)}}};r(e,1);let a=JSON.stringify(e);if(nn(a)>O.saveBytes)throw new J("too-large",`A save is at most ${O.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return a}function rt(e){let t;try{t=JSON.parse(e)}catch{throw new J("invalid","The saved data is not JSON.")}return Pe(t),t}var N=(e,t,r=0)=>typeof e=="string"&&e.length>=r&&e.length<=t,D=(e,t,r)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=r,rn=e=>typeof e=="string"&&Xt.includes(e),Oe=".bin",on=(e,t)=>`-/card/${e}/${t}${Oe}`,sn=e=>`-/cover/${e}${Oe}`,ot=e=>`-/player/${e}${Oe}`;function st(e,t){if(!S(e)||!I(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:r,pack:a,name:s,art:i}=e,c=typeof r=="string"?r.slice(r.indexOf("/")+1):"";if(!B(a)||r!==`${a}/${c}`||!oe.test(c)||!N(s,120)||!rn(e.rarity)||t&&!D(e.count,1,1e6)||i!==null&&i!==on(a,c))throw Error("Invalid card.");return{id:r,pack:a,name:s,rarity:e.rarity,...t?{count:e.count}:{},art:i}}function Ie(e){return st(e,!0)}function an(e){return st(e,!1)}function it(e){let{id:t,name:r,creator:a,art:s,total:i}=e;if(!B(t)||!N(r,120,1)||a!==null&&!N(a,64,1)||s!==null&&s!==sn(t)||!D(i,0,1e4))throw Error("Invalid pack.");return{id:t,name:r,creator:a,art:s,total:i}}function at(e){if(!S(e)||!I(e,["id","name","creator","art","held","total"])||!D(e.held,0,1e4))throw Error("Invalid pack.");let t=it(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function ct(e){if(!S(e)||!I(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=it(e),r=e.cards.map(an);if(r.some(a=>a.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:r}}var _e=/[\u0000-\u001F\u007F-\u009F]/,re=e=>typeof e=="string"&&V.handle.test(e);function dt(e){if(S(e)&&I(e,["guest"])&&e.guest===!0)return{guest:!0};if(!S(e)||!I(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:r,name:a,picture:s,token:i,expiresAt:c}=e;if(!re(t)||!N(a,V.nameMax,1)||_e.test(a)||r!==void 0&&(!re(r)||r===t)||s!==null&&s!==ot(t)||"token"in e!="expiresAt"in e||i!==void 0&&(!N(i,V.tokenMax,V.tokenMin)||!V.token.test(i)||!D(c,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...r===void 0?{}:{username:r},name:a,picture:s,...i===void 0?{}:{token:i,expiresAt:c}}}var Ye=e=>N(e,64,1);function lt(e){if(S(e)&&I(e,["reset","revision"])&&e.reset===!0&&Ye(e.revision))return{reset:!0,revision:e.revision};if(!S(e)||!I(e,["changed","removed","revision"])||!Array.isArray(e.changed)||!Array.isArray(e.removed)||!Ye(e.revision)||e.removed.some(t=>!N(t,130,3)))throw Error("Invalid cards event.");return{changed:e.changed.map(Ie),removed:e.removed,revision:e.revision}}function pt(e){if(!S(e)||!I(e,["protocol","guest","features","root"])||e.protocol!==2||typeof e.guest!="boolean"||!Array.isArray(e.features)||e.features.length>64||e.features.some(t=>!N(t,40,1))||typeof e.root!="string"||!/^(?:\.\/|(?:\.\.\/){1,32})$/.test(e.root))throw Error("Invalid hello.");return{protocol:2,guest:e.guest,features:e.features,root:e.root}}var G=(e,t)=>typeof t=="string"&&e.includes(t),cn=(e,t)=>e===null||e===ot(t),dn=e=>N(e,V.nameMax,1)&&!_e.test(e),Re=e=>D(e,0,1e9),Z=(e,t,r=1)=>typeof e=="string"&&e.length>=r&&[...e].length<=t&&!_e.test(e),ln=e=>typeof e=="string"&&Xe(e)&&/\.(?:png|webp)$/.test(e),ut=e=>re(e.handle)&&dn(e.name)&&cn(e.picture,e.handle);function mt(e,t){if(!S(e)||!I(e,["board","name","order","format","period","entries","you"]))throw Error("Invalid leaderboard.");let{board:r,name:a,order:s,format:i,period:c,entries:l,you:p}=e;if(!F(r)||!Z(a,40)||!G(Je,s)||!G(Ze,i)||!G(et,c)||!Array.isArray(l)||l.length>(t?.limit??$.boardRowsMax)||t&&(r!==t.board||c!==t.period))throw Error("Invalid leaderboard.");let w=l.map(b=>{if(!S(b)||!I(b,["rank","handle","name","picture","score","you"])||!D(b.rank,1,Number.MAX_SAFE_INTEGER)||!ut(b)||!Re(b.score)||typeof b.you!="boolean")throw Error("Invalid leaderboard entry.");return{rank:b.rank,handle:b.handle,name:b.name,picture:b.picture,score:b.score,you:b.you}}),m=null;if(p!==null){if(!S(p)||!I(p,["rank","score"])||!D(p.rank,1,Number.MAX_SAFE_INTEGER)||!Re(p.score))throw Error("Invalid leaderboard.");m={rank:p.rank,score:p.score}}return{board:r,name:a,order:s,format:i,period:c,entries:w,you:m}}function ht(e){if(!S(e)||!I(e,["id","name","description","icon","secret","unlocked","at"]))throw Error("Invalid achievement.");let{id:t,name:r,description:a,icon:s,secret:i,unlocked:c,at:l}=e;if(!F(t)||!Z(r,40)||!Z(a,120,0)||s!==null&&!ln(s)||typeof i!="boolean"||typeof c!="boolean"||(c?!D(l,0,Number.MAX_SAFE_INTEGER):l!==null)||i&&!c&&(a!==""||s!==null))throw Error("Invalid achievement.");return{id:t,name:r,description:a,icon:s,secret:i,unlocked:c,at:l}}function ft(e){if(!S(e)||!I(e,["handle","name","picture","presence"])||!ut(e)||!G(qt,e.presence))throw Error("Invalid friend.");return{handle:e.handle,name:e.name,picture:e.picture,presence:e.presence}}function Te(e){if(!S(e)||!I(e,["from","data"])||!re(e.from)||e.data!==null&&!N(e.data,$.inviteData))throw Error("Invalid invite.");return{from:e.from,data:e.data}}function gt(e){if(!S(e)||!I(e,["id","name","description","price","kind","owned"]))throw Error("Invalid product.");let{id:t,name:r,description:a,price:s,kind:i,owned:c}=e;if(!F(t)||!Z(r,40)||!Z(a,120)||!D(s,1,1e6)||!G(Ee,i)||typeof c!="boolean"||c&&i!=="permanent")throw Error("Invalid product.");return{id:t,name:r,description:a,price:s,kind:i,owned:c}}function Me(e){if(!S(e)||!I(e,["id","product","kind","price","at","consumed"]))throw Error("Invalid receipt.");let{id:t,product:r,kind:a,price:s,at:i,consumed:c}=e;if(typeof t!="string"||!tt.test(t)||!F(r)||!G(Ee,a)||!D(s,1,1e6)||!D(i,0,Number.MAX_SAFE_INTEGER)||typeof c!="boolean"||c&&a!=="consumable")throw Error("Invalid receipt.");return{id:t,product:r,kind:a,price:s,at:i,consumed:c}}function yt(e){let t=r=>r===void 0||F(r);switch(e.method){case"leaderboard.get":return t(e.board)?e.scope!==void 0&&!G(Yt,e.scope)?'scope is "everyone" or "friends".':e.period!==void 0&&!G(et,e.period)?'period is "all" or "week".':e.limit!==void 0&&!D(e.limit,1,$.boardRowsMax)?`limit is a whole number from 1 to ${$.boardRowsMax}.`:null:"That is not a board id.";case"leaderboard.show":return t(e.board)?null:"That is not a board id.";case"achievement.unlock":return F(e.id)?null:"That is not an achievement id.";case"invite.open":return e.to!==void 0&&!re(e.to)?"to is a player's handle.":e.text!==void 0&&!Z(e.text,$.inviteText,0)?`An invite's text is one line of at most ${$.inviteText} characters.`:e.data!==void 0&&!N(e.data,$.inviteData)?`An invite's data is at most ${$.inviteData} characters.`:null;case"share.open":return e.text!==void 0&&!Z(e.text,$.shareText,0)?`A share's text is one line of at most ${$.shareText} characters.`:e.score!==void 0&&!Re(e.score)?"score is a whole number from 0 to 1,000,000,000.":t(e.board)?e.board!==void 0&&e.score===void 0?"A board is shared with a score.":null:"That is not a board id.";case"product.buy":return F(e.product)?null:"That is not a product id.";case"purchase.consume":case"purchase.token":return tt.test(e.receipt)?null:"That is not a receipt id.";case"app.show":return ue(e.app)?null:"That is not an app id.";default:return null}}var pn=1280,un=[.85,.6,.4];function mn(e){let t=null,r=0;for(let a of Array.from(e.querySelectorAll("canvas"))){let s=a.getBoundingClientRect(),i=s.width*s.height;i>r&&a.width>0&&a.height>0&&(t=a,r=i)}return t}function hn(e,t){try{let r=e.width,a=e.height;if(!(r>0&&a>0))return null;let s=Math.min(1,pn/Math.max(r,a)),i=t.createElement("canvas");i.width=Math.max(1,Math.round(r*s)),i.height=Math.max(1,Math.round(a*s));let c=i.getContext("2d");if(!c)return null;c.drawImage(e,0,0,i.width,i.height);for(let l of un){let p=i.toDataURL("image/webp",l);if(p.startsWith("data:image/webp")||(p=i.toDataURL("image/jpeg",l)),pe(p))return p}return null}catch{return null}}function wt(e,t){return typeof e=="string"?pe(e)?e:null:e!==null&&typeof e=="object"&&"getContext"in e&&"toDataURL"in e?hn(e,t):null}function bt(e,t){let r=null,a=()=>globalThis.document,s=(i,c)=>{if(!t())try{e(i,c)}catch{}};return{on(i){return r=i,()=>{r===i&&(r=null)}},clear(){r=null},event(i){if(!(t()||!Ae(i)))try{let c=r;if(c){Promise.resolve().then(c).then(l=>wt(l,a()),()=>null).then(l=>s(i,l),()=>{});return}requestAnimationFrame(()=>{let l=null;try{let p=mn(a());l=p?wt(p,a()):null}catch{l=null}s(i,l)})}catch{}}}}var Le="vibemarket.game.v1";function kt(e,t={}){let r=0,a=!1,s,i=new Map,c=t.jsonBytes!==void 0,l=t.errors,p=[],w=[],m=v=>{v&&(v.done=Date.now(),P())},b=()=>l?l.closed():Error("Game session ended.");function P(){let v=t.pace;for(;w.length;){let f=Date.now();for(let g=p.length-1;g>=0;g--)p[g].done!==null&&f-p[g].done>=6e4&&p.splice(g,1);let y=p.filter(g=>g.done===null||f-g.done<1e3);if(y.length<v.perSecond&&p.length<v.perMinute){w.shift()();continue}let x=y.length>=v.perSecond?{list:y,ms:1e3}:{list:p,ms:6e4},A=x.list.filter(g=>g.done!==null).map(g=>g.done+x.ms-f);A.length&&s===void 0&&(s=window.setTimeout(()=>{s=void 0,P()},Math.max(1,Math.min(...A))));return}}return e.onmessage=v=>{let f;try{f=t.jsonBytes===void 0?v.data:We(v.data,t.jsonBytes)}catch{return}if(a||!f||typeof f!="object"||Array.isArray(f))return;let y=f;if(t.session!==void 0&&y.session!==t.session)return;if("event"in y){t.onEvent?.(y);return}if(typeof y.id!="string")return;let x=i.get(y.id);if(x)if(i.delete(y.id),window.clearTimeout(x.timer),m(x.record),typeof y.error=="string"){let A=c?y.error.slice(0,500):y.error;x.reject(l?l.reply(A,y.code):Error(A))}else"result"in y?x.resolve(y.result):x.reject(l?l.reply("Invalid host response.","unavailable"):Error("Invalid host response."))},e.start(),{request(v,f={}){if(a)return Promise.reject(b());if(i.size+w.length>=(t.maxPending??16))return Promise.reject(l?l.busy():Error("Too many pending requests."));let y=String(++r);return new Promise((x,A)=>{let g=()=>{let M=t.pace?{done:null}:void 0;M&&p.push(M);let E=window.setTimeout(()=>{i.delete(y),m(M),A(l?l.timeout():Error(t.jsonBytes===void 0?"Request timed out. Check your VibeMarket inventory before trying again; a submitted transaction may still complete.":"App request timed out. Restore the window and read its last accepted checkpoint before retrying."))},f.timeoutMs??t.timeoutMs??18e4);i.set(y,{resolve:L=>x(L),reject:A,timer:E,record:M});try{let L={id:y,request:v,...t.session===void 0?{}:{session:t.session}};e.postMessage(t.jsonBytes===void 0?L:ve(L,t.outBytes??t.jsonBytes))}catch(L){i.delete(y),window.clearTimeout(E),m(M),A(L)}};if(!t.pace){g();return}w.push(()=>{a?A(b()):g()}),P()})},destroy(){if(!a){a=!0,s!==void 0&&window.clearTimeout(s);for(let v of w.splice(0))v();i.forEach(v=>{window.clearTimeout(v.timer),v.reject(b())}),i.clear(),e.onmessage=null,e.close()}}}}function At(e,t){return new Promise((r,a)=>{let s,i=()=>{window.clearTimeout(p),s!==void 0&&window.clearInterval(s),window.removeEventListener("message",l),e?.removeEventListener("abort",c)},c=()=>{i(),a(Error("Game session ended."))},l=m=>{if(m.source!==window.parent||!m.data||typeof m.data!="object"||!("channel"in m.data)||m.data.channel!==Le||m.ports.length!==1)return;let b;if(t!==void 0){if(!("challenge"in m.data)||m.data.challenge!==t||!("session"in m.data)||!te(m.data.session))return;b=m.data.session}let P=t!==void 0&&"protocol"in m.data&&m.data.protocol===2?2:void 0;i(),r({port:m.ports[0],...b===void 0?{}:{session:b},...P===void 0?{}:{protocol:P}})},p=window.setTimeout(()=>{i(),a(Error("VibeMarket did not connect. Reopen the game."))},15e3);if(window.addEventListener("message",l),e?.addEventListener("abort",c,{once:!0}),e?.aborted){c();return}let w=()=>{let m={channel:Le,type:"connect",...t===void 0?{}:{challenge:t}};window.parent.postMessage(t===void 0?m:ve(m,256),"*")};w(),t!==void 0&&(s=window.setInterval(w,250))})}var fn=200,Ce="[a-z0-9]+(?:-[a-z0-9]+)*",gn="[A-Za-z0-9_-]{1,64}",vt=new RegExp(`^vmos://pack/(${Ce})$`),xt=new RegExp(`^vmos://card/(${Ce})/(${gn})$`),Et=new RegExp(`^https://(?:www\\.)?vibechain\\.com/os/pack/(${Ce})/?$`),Rt="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",St=new RegExp(`^vmos://app/(${Rt})$`),Pt=new RegExp(`^https://(?:www\\.)?vibechain\\.com/os/app/(${Rt})/?$`),Jn=Object.freeze({pack:vt,card:xt,web:Et,app:St,webApp:Pt});function me(e){if(typeof e!="string"||e.length>fn)return null;let t=xt.exec(e);if(t)return B(t[1])?{kind:"card",pack:t[1],card:t[2]}:null;let r=St.exec(e)??Pt.exec(e);if(r)return ue(r[1])?{kind:"app",app:r[1]}:null;let a=vt.exec(e)??Et.exec(e);return a&&B(a[1])?{kind:"pack",pack:a[1]}:null}function Ot(e){if(!ue(e))throw new z("invalid","That is not an app id.");return`vmos://app/${e}`}function It(e){if(!B(e))throw new z("invalid","That is not a pack slug.");return`vmos://pack/${e}`}function _t(e,t){if(!B(e)||typeof t!="string"||!oe.test(t))throw new z("invalid","That is not a pack slug and a card id.");return`vmos://card/${e}/${t}`}var yn="0.6.0",wn=Object.freeze({unsupported:"This host is older than this SDK and has no such feature.","not-permitted":"The manifest does not declare that, or the app is behind another window.",invalid:"That argument is not valid.","too-large":"That is too large.","rate-limited":"Too many requests; try again later.","needs-click":"That needs a fresh click in the app.",unavailable:"The host could not answer now; try again.",timeout:"The host did not answer in 10 seconds.",closed:"The session ended. Reopen the app.",cancelled:"The player closed the dialog without confirming.",insufficient:"The player does not have enough Printer Cash for that.",limit:"A limit was reached; try again another day.",guest:"Guests cannot do that; the player has to sign in."}),bn=wn,u=(e,t=bn[e])=>new z(e,t),se=(e,t)=>e instanceof z?e:e instanceof J?new z(e.code,e.message):u(t,e.message),he=e=>{if(!B(e))throw u("invalid","That is not a pack slug.");return e};async function Tt(e={}){let t=new URLSearchParams(window.location.hash.slice(1)).get(Ve);if(!te(t))throw u("unsupported","Open this app in VibeMarket OS or the SDK preview.");let r;try{r=await At(e.signal,t)}catch(a){throw u(e.signal?.aborted?"closed":"timeout",a.message)}return kn(r.port,r.session,r.protocol??1,window.location.href)}async function kn(e,t,r,a){if(!te(t))throw u("unavailable","Invalid app session.");let s=Object.freeze({active:!0,width:0,height:0}),i=!1,c=ne,l=new Set,p=new Set,w=new Set,m=new Set,b=new Set,P=kt(e,{session:t,timeoutMs:_.requestTimeoutMs,maxPending:r===2?64:_.inFlight,jsonBytes:r===2?O.messageBytes:_.responseBytes,errors:{reply:(n,o)=>u(Qe(o)?o:"unavailable",n),timeout:()=>u("timeout"),closed:()=>u("closed"),busy:()=>u("rate-limited","Too many requests are waiting; try again later.")},...r===2?{pace:{perSecond:O.clientPerSecond,perMinute:O.clientPerMinute}}:{},onEvent(n){if(n.event==="app.cards"){zt(n.state);return}if(n.event==="app.capture"){v.event(n.id);return}if(n.event==="app.sound"){y(n.state);return}if(n.event==="app.invite"){ae(n.state);return}if(n.event!=="app.lifecycle")return;let o;try{o=Ue(n.state)}catch{return}let d=s;if(s=Object.freeze({active:o.active,width:o.width,height:o.height}),d.active&&!o.active)for(let k of[...l])k();if(!d.active&&o.active)for(let k of[...p])k();if(d.width!==o.width||d.height!==o.height)for(let k of[...w])k(Object.freeze({width:o.width,height:o.height}))}}),v=bt((n,o)=>{f({method:"app.frame",id:n,image:o}).catch(()=>{})},()=>r!==2||!A||i),f=async(n,o)=>{if(i)throw u("closed");let d=await P.request(n,o===void 0?{}:{timeoutMs:o});if(!d||typeof d!="object"||Array.isArray(d))throw u("unavailable","Invalid host response.");return d};function y(n){let o;try{o=Ke(n)}catch{return}if(!(o.muted===c.muted&&o.volume===c.volume)){c=o;for(let d of[...b])d(c)}}let x=n=>{if(n.completed!==!0)throw u("unavailable","Invalid host acknowledgement.")},A=null;if(r===2)try{A=pt(await f({method:"host.hello",protocol:2,sdk:yn}))}catch(n){throw P.destroy(),se(n,"unavailable")}let g=()=>{if(!A)throw u("unsupported");return A},M=n=>A?.features.includes(n)===!0,E=async n=>{let o=yt(n);if(o)throw u("invalid",o);if(!M(n.method))throw u("unsupported");return f(n,Se[n.method].surface?O.surfaceMs:void 0)},L=(n,o)=>{if(n===void 0)return{};if(n===null||typeof n!="object"||Array.isArray(n)||Object.keys(n).some(d=>!o.includes(d)))throw u("invalid",`The options are an object with ${o.join(", ")}.`);return Object.fromEntries(Object.entries(n).filter(([,d])=>d!==void 0))},H=(n,o)=>{if(typeof n!="string")throw u("invalid",`${o} is a string.`);return n},ie=n=>({...n,picture:j(n.picture)}),K=new Set;function ae(n){let o;try{o=Te(n)}catch{return}for(let d of[...K])d({...o})}let h=Object.freeze({invite:null});if(M("app.launch"))try{let n=(await f({method:"app.launch"})).invite;h=Object.freeze({invite:n===null?null:Object.freeze(Te(n))})}catch{}let j=n=>n===null?null:new URL(g().root+n,a).href,$e=n=>({...n,art:j(n.art)}),W=null,fe=!1,ge=null,ze=async n=>{for(let o=0;o<4;o++){let d=[],k=null,R=null,de=!0;do{let C=await f({method:"cards.list",...n===void 0?{}:{pack:n},...k===null?{}:{after:k}});if(!Array.isArray(C.cards)||C.after!==null&&typeof C.after!="string"||typeof C.revision!="string")throw u("unavailable","Invalid host response.");if(R!==null&&C.revision!==R){de=!1;break}R=C.revision,k=C.after;for(let Nt of C.cards)d.push($e(Ie(Nt)))}while(k!==null);if(de&&R!==null)return n===void 0&&(W={revision:R,cards:new Map(d.map(C=>[C.id,C]))}),{cards:d,revision:R}}throw u("unavailable","The cards kept changing while they were read; try again.")},je=()=>{let n=[...W.cards.values()];for(let o of[...m])o(n.slice())},De=n=>ge??=(async()=>{try{do fe=!1,await ze();while(fe);n&&je()}catch{}finally{ge=null}})();function zt(n){if(!m.size)return;let o;try{o=lt(n)}catch{return}if(ge){fe=!0;return}if("reset"in o||!W){De(!0);return}for(let d of o.removed)W.cards.delete(d);for(let d of o.changed)W.cards.set(d.id,$e(d));W={revision:o.revision,cards:W.cards},je()}let U=null,ye=!1,Ne=-1/0,X,jt=r===2?O.saveIntervalMs:0,we=()=>{if(ye||!U||X!==void 0)return;let n=Ne+jt-Date.now();if(n>0){X=window.setTimeout(()=>{X=void 0,we()},n);return}let{text:o,waiters:d}=U;U=null,ye=!0;let k=JSON.parse(o);f(r===2?{method:"app.save.set",value:k}:{method:"app.checkpoint.set",value:k}).then(R=>{if(r===2?typeof R.savedAt!="string":R.completed!==!0)throw u("unavailable","Invalid host acknowledgement.")}).then(()=>{for(let R of d)R.resolve()},R=>{let de=se(R,"unavailable");for(let C of d)C.reject(de)}).finally(()=>{ye=!1,Ne=Date.now(),we()})},Y=null,ce=async n=>{let o=g();if(n.method==="card.show"&&!o.features.includes("card.show"))throw u("unsupported");if((await f(n)).shown!==!0)throw u("unavailable","Invalid host acknowledgement.")},q={get active(){return s.active},get size(){return Object.freeze({width:s.width,height:s.height})},get guest(){return A?.guest??!1},get sound(){return c},async ready(){x(await f({method:"ui.ready"}))},progress(n){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>1)throw u("invalid","Progress is a number from 0 to 1.");!A||Fe||(Q=n,ee===void 0&&(Be(),ee=window.setTimeout(()=>{ee=void 0,Q!==null&&Be()},1e3)))},async load(){if(A){let o=await f({method:"app.save.get"});return o.value===null?null:rt(JSON.stringify(o.value))}let n=await f({method:"app.checkpoint.get"});if(!("checkpoint"in n))throw u("unavailable","Invalid host response.");return n.checkpoint},save(n){let o;try{if(o=Pe(n),!A){if(new TextEncoder().encode(o).byteLength>_.checkpointBytes)throw u("too-large","This host keeps at most 32 KiB, and only while the window is open.");try{He(n)}catch(d){throw u("too-large",d.message)}}}catch(d){return Promise.reject(se(d,"invalid"))}return i?Promise.reject(u("closed")):new Promise((d,k)=>{U={text:o,waiters:[...U?.waiters??[],{resolve:d,reject:k}]},we()})},async cards(n){let o=n===void 0?void 0:he(n);return g(),(await ze(o)).cards},onCards(n){return m.add(n),A&&m.size===1&&f({method:"cards.watch",on:!0}).then(()=>{W||De(!1)},()=>{}),()=>{!m.delete(n)||m.size||!A||i||f({method:"cards.watch",on:!1}).catch(()=>{})}},async packs(){g();let n=await f({method:"cards.packs"});if(!Array.isArray(n.packs))throw u("unavailable","Invalid host response.");return n.packs.map(o=>{let d=at(o);return{...d,art:j(d.art)}})},async pack(n){let o=he(n);g();let d=ct((await f({method:"cards.pack",pack:o})).pack);return{...d,art:j(d.art),cards:d.cards.map(k=>({...k,art:j(k.art)}))}},async showPack(n){let o=he(n);g(),await ce({method:"pack.show",pack:o})},async showCard(n,o){let d=he(n);if(typeof o!="string"||!oe.test(o))throw u("invalid","That is not a card id.");await ce({method:"card.show",pack:d,card:o})},async open(n){let o=me(n);if(!o)throw u("invalid","That is not a vmOS pack, card or app link.");if(o.kind==="app"){if(g(),(await E({method:"app.show",app:o.app})).shown!==!0)throw u("unavailable","Invalid host acknowledgement.");return}await(o.kind==="pack"?ce({method:"pack.show",pack:o.pack}):ce({method:"card.show",pack:o.pack,card:o.card}))},async player(){if(g(),Y&&Y.expiresAt-Date.now()>O.tokenReuseMs)return{...Y};let n=dt(await f({method:"player.get"}));if(n.guest)return Y=null,n;let o={...n,picture:j(n.picture)};return Y=o.token?o:null,{...o}},async finish(n){let o,d;try{let{board:k,...R}=n&&typeof n=="object"?n:{};if(k!==void 0&&!F(k))throw u("invalid","That is not a board id.");d=k,o=le(n&&typeof n=="object"?R:n)}catch(k){throw se(k,"invalid")}x(await f({method:"game.finish",...o,...d!==void 0&&M(nt)?{board:d}:{}}))},async leaderboard(n){let o=L(n,["board","scope","period","limit"]),d={method:"leaderboard.get",...o},k=await E(d),R=mt(k.leaderboard,{board:o.board??"score",period:o.period??"all",limit:o.limit??$.boardRowsDefault});return{...R,entries:R.entries.map(ie)}},async showLeaderboard(n){if((await E({method:"leaderboard.show",...n===void 0?{}:{board:H(n,"A board id")}})).shown!==!0)throw u("unavailable","Invalid host acknowledgement.")},async unlock(n){let o=await E({method:"achievement.unlock",id:H(n,"An achievement id")});if(typeof o.unlocked!="boolean")throw u("unavailable","Invalid host response.");return{unlocked:o.unlocked}},async achievements(){let n=await E({method:"achievements.list"});if(!Array.isArray(n.achievements))throw u("unavailable","Invalid host response.");return n.achievements.map(o=>{let d=ht(o);return{...d,icon:j(d.icon)}})},async friends(){let n=await E({method:"friends.list"});if(!Array.isArray(n.friends))throw u("unavailable","Invalid host response.");return n.friends.map(o=>ie(ft(o)))},async invite(n){let o=await E({method:"invite.open",...L(n,["to","text","data"])});if(typeof o.sent!="number"||!Number.isInteger(o.sent)||o.sent<0||o.sent>$.inviteRecipients)throw u("unavailable","Invalid host response.");return{sent:o.sent}},get launch(){return h},onInvite(n){if(typeof n!="function")throw u("invalid","An invite listener is a function.");return K.add(n),()=>{K.delete(n)}},async share(n){let o=await E({method:"share.open",...L(n,["text","score","board"])});if(typeof o.shared!="boolean")throw u("unavailable","Invalid host response.");return{shared:o.shared}},async products(){let n=await E({method:"products.list"});if(!Array.isArray(n.products))throw u("unavailable","Invalid host response.");return n.products.map(gt)},async buy(n){let o=H(n,"A product id"),d=Me((await E({method:"product.buy",product:o})).receipt);if(d.product!==o)throw u("unavailable","Invalid host response.");return d},async purchases(){let n=await E({method:"purchases.list"});if(!Array.isArray(n.purchases))throw u("unavailable","Invalid host response.");return n.purchases.map(Me)},async consume(n){x(await E({method:"purchase.consume",receipt:H(n,"A receipt id")}))},async receiptToken(n){let o=(await E({method:"purchase.token",receipt:H(n,"A receipt id")})).token;if(typeof o!="string"||o.length>V.tokenMax||!V.token.test(o))throw u("unavailable","Invalid host response.");return o},async maximize(n=!0){if(typeof n!="boolean")throw u("invalid");g(),x(await f({method:"display.maximize",on:n}))},async fullscreen(n=!0){if(typeof n!="boolean")throw u("invalid");g(),x(await f({method:"display.fullscreen",on:n}))},onPause(n){return l.add(n),()=>{l.delete(n)}},onResume(n){return p.add(n),()=>{p.delete(n)}},onCapture(n){if(typeof n!="function")throw u("invalid","A capture handler is a function.");return v.on(n)},onResize(n){return w.add(n),()=>{w.delete(n)}},onSound(n){return b.add(n),()=>{b.delete(n)}},close(){i||(i=!0,X!==void 0&&window.clearTimeout(X),ee!==void 0&&window.clearTimeout(ee),U?.waiters.forEach(n=>n.reject(u("closed"))),U=null,v.clear(),l.clear(),p.clear(),w.clear(),b.clear(),m.clear(),K.clear(),P.destroy())}},Q=null,ee,Fe=!1,Be=()=>{let n=Q;Q=null,f({method:"ui.progress",value:n}).catch(()=>{})},Dt=q.ready;q.ready=async()=>{Fe=!0,Q=null,await Dt()};for(let n of["ready","load","cards","packs","pack","showPack","showCard","open","player","finish","maximize","fullscreen","leaderboard","showLeaderboard","unlock","achievements","friends","invite","share","products","buy","purchases","consume","receiptToken"]){let o=q[n];q[n]=async(...d)=>{try{return await o(...d)}catch(k){throw se(k,"unavailable")}}}return Object.freeze(q)}var Mt=.05,Lt=Object.freeze(["pointerdown","pointerup","keydown","touchend"]),Ct=Object.freeze({gestures:3,remakes:3});function An(e){if("lifecycle"in e){let t=e.sound;return{active:()=>e.lifecycle.current().active,sound:()=>t?.current()??ne,onActive(r){let a=e.lifecycle.current().active;return e.lifecycle.onChanged(s=>{s.active!==a&&(a=s.active,r(a))})},onSound:r=>t?t.onChanged(r):()=>{}}}return{active:()=>e.active,sound:()=>e.sound??ne,onActive(t){let r=[e.onPause(()=>t(!1)),e.onResume(()=>t(!0))];return()=>{for(let a of r)a()}},onSound:t=>typeof e.onSound=="function"?e.onSound(t):()=>{}}}function $t(e,t={}){let r=An(e),a=()=>new AudioContext({latencyHint:t.latencyHint??"interactive"}),s=t.context??a(),i=s.createGain(),c=!1,l=!1,p=!1,w=r.active(),m=0,b=0,P,v=new Set,f=()=>{let h=r.sound();return h.muted||c||!w?0:h.volume},y=()=>{for(let h of[...v])h()},x=()=>{let h=s.currentTime,j=i.gain;j.cancelScheduledValues(h),j.setValueAtTime(j.value,h),j.linearRampToValueAtTime(f(),h+Mt)},A=()=>!p&&!l&&w,g=()=>{A()&&s.state!=="running"&&s.resume().catch(()=>{})},M=()=>{if(s.state==="running"&&(m=0),s.state==="closed"&&!p){L();return}y()},E=()=>{i.gain.value=f(),i.connect(s.destination),s.addEventListener("statechange",M)};function L(){if(b>=Ct.remakes)return;b++,m=0;let h=s;h.removeEventListener("statechange",M),h.state!=="closed"&&h.close().catch(()=>{});try{s=a()}catch{s=h;return}i=s.createGain(),E(),g(),y()}let H=()=>{clearTimeout(P),P=setTimeout(()=>{P=void 0,!p&&!A()&&s.state==="running"&&s.suspend().catch(()=>{})},Mt*1e3+20)},ie=[r.onSound(()=>{x(),y()}),r.onActive(h=>{w=h,x(),w?(clearTimeout(P),g()):H(),y()})],K=()=>{!A()||s.state==="running"||(++m>Ct.gestures?L():g())},ae=()=>{document.visibilityState==="visible"&&g()};for(let h of Lt)window.addEventListener(h,K,{capture:!0,passive:!0});return document.addEventListener("visibilitychange",ae),E(),g(),{get context(){return s},get master(){return i},get desktop(){return r.sound()},get audible(){let h=r.sound();return!h.muted&&h.volume>0&&!c&&w&&s.state==="running"},get muted(){return c},set muted(h){h!==c&&(c=h,x(),y())},get paused(){return l},set paused(h){h!==l&&(l=h,l?s.suspend().catch(()=>{}):g(),y())},onChange(h){return v.add(h),()=>{v.delete(h)}},close(){if(!p){p=!0,clearTimeout(P);for(let h of ie)h();for(let h of Lt)window.removeEventListener(h,K,{capture:!0});document.removeEventListener("visibilitychange",ae),s.removeEventListener("statechange",M),v.clear(),s.close().catch(()=>{})}}}}return Ht(vn);})();
@@ -1,6 +1,6 @@
1
1
  # Paw Beat
2
2
 
3
- A 3D rhythm game for VibeMarket OS, written in TypeScript with Three.js. Arrows slide down four lanes toward their outlines. Press the matching key as each one lands (arrow keys, WASD or the on-screen pads) and Biscuit the cat dances that step: a side step and point for left and right, a leap with paws up for up, a squat and floor pat for down. Timing is judged perfect, great or good; every ten steps in a row adds 10% to each step, up to double, and combos of 10, 25, 50, 75 and 100 earn a spin and confetti. A miss makes Biscuit stumble. There are six tracks of about a minute each; a random one plays when you start, never the same one twice in a row, and **Next track** on the title card picks another. Each round ends with a results card: grade, score, accuracy, best combo and every judgement, with your personal best on that track marked.
3
+ A 3D rhythm game for VibeMarket OS, written in TypeScript with Three.js. Arrows slide down four lanes toward their outlines. Press the matching key as each one lands (arrow keys, WASD or the on-screen pads) and Biscuit the cat dances that step: a side step and point for left and right, a leap with paws up for up, a squat and floor pat for down. Timing is judged perfect, great or good; every ten steps in a row adds 10% to each step, up to double, and combos of 10, 25, 50, 75 and 100 earn a spin and confetti. A miss makes Biscuit stumble. There are six tracks of about a minute each; a random one plays when you start, never the same one twice in a row, and **Next track** on the title card picks another. Each round ends with a results card: grade, score, accuracy, best combo and every judgement, with your personal best on that track marked, and buttons to share the score and open the leaderboard.
4
4
 
5
5
  ## The tracks
6
6
 
@@ -19,13 +19,13 @@ It is a complete example of the app API and of a small game built entirely in co
19
19
 
20
20
  | File | What it shows |
21
21
  |---|---|
22
- | `game.ts` | The rules as pure TypeScript with no DOM, renderer or audio, so they can be unit-tested: reading a track (note and chord names, sections, swing), a chart generator that writes fair steps from the track's own tune, timing judgement, combo bonus, the grade, picking the next track and the personal bests |
22
+ | `game.ts` | The rules as pure TypeScript with no DOM, renderer or audio, so they can be unit-tested: reading a track (note and chord names, sections, swing), a chart generator that writes fair steps from the track's own tune, timing judgement, combo bonus, the grade, picking the next track, the personal bests and which achievements a round earns |
23
23
  | `tracks.ts` | The six tracks as plain data: tempo, meter, sections, chords, the tune as note names, and the drum, bass, pad and arpeggio patterns |
24
24
  | `synth.ts` | The instruments, all oscillators and noise (four drum kits, five basses, six leads, five pads, arpeggios, risers and cymbal swells), a tempo-synced echo and a small generated room, ducking under the kick and a soft limiter; and the player that turns a track's data into sound |
25
25
  | `cat.ts` | Biscuit, built at runtime: smooth body parts meshed from signed distance functions ("surface nets"), a toon shader with rim light and outline, a face painted by the shader so expressions are a few numbers, two-bone inverse kinematics for arms and legs, a tube tail rewritten every frame, and spring-blended dance moves |
26
26
  | `stage.ts` | The dance floor, backdrop and spotlights as single shader meshes that pulse with the beat and take the track's colours, tinted by each section; the lanes and targets; every note in one instanced mesh; pooled sparks and confetti; camera framings that fit any window size |
27
27
  | `music.ts` | The live song: the chosen track scheduled a beat at a time ahead of the audio clock, which also times the steps, through the SDK's audio helper |
28
- | `main.ts` | `connectVibeMarketApp()`, `fitCanvas` (with WebGL context loss handled), `createLoop` and `createAudio` (the desktop's sound) from the SDK helpers; the title, play and results flow; the track choice; a checkpoint for the personal bests and the sound setting; and `game.finish({ score })` |
28
+ | `main.ts` | `connect()`, `fitCanvas` (with WebGL context loss handled), `createLoop` and `createAudio` (the desktop's sound) from the SDK helpers; the title, play and results flow; the track choice; `os.load` and `os.save` for the personal bests, the sound setting and the coat; `os.finish({ score })`; and the vmOS services: achievements, sharing, the leaderboard panel and buying the midnight coat |
29
29
  | `index.html` | The page: the canvas, the score and progress display, the judgement and combo callout, the touch pads, the title and results cards, all styled inline |
30
30
 
31
31
  Nothing is downloaded or generated outside the game: there are no models, textures, fonts, samples or images in the bundle. It is `index.html`, one script, the manifest and the three store images in `store/`, which are captures of the game itself. Each track's arrangement is fixed; the steps, and some of its phrases, come from a seed, so each round is a little different and any round can be replayed in a test.
@@ -34,6 +34,15 @@ Nothing is downloaded or generated outside the game: there are no models, textur
34
34
 
35
35
  A track is data in `tracks.ts`; nothing else needs to change. Give it an `id`, a `name` and a `mood`; a `bpm`, a `meter` (4, or 3 for a waltz) and a `swing`; and its sections in order, from a one-bar count-in to an outro whose last note is the home note. Each section has a role (which sets how the steps are written and how the stage behaves), a number of bars, its chords ("Am F C G", or "F,G" for two in a bar), which phrases of the tune play, and which drum, bass, pad and arpeggio patterns sound. Write the tune as note names with lengths in eighths ("E5:2 A5:1 r:1"); a list of phrases gives the seed alternatives. Patterns are strings of sixteenth notes, explained at the top of `synth.ts`. Then run the tests: they check that the tune fits its sections, that every pattern exists and is whole bars long, that the chart is fair and about as hard as the others, and that nothing is scheduled in the past or after the end.
36
36
 
37
+ ## Leaderboard, achievements, sharing and the midnight coat
38
+
39
+ These use the vmOS services of `@vibechain/os` 0.6, declared in `vibemarket.json`. Each is optional: on a host older than 0.6 its call answers `unsupported`, the button disappears and the game plays exactly as before.
40
+
41
+ - **Leaderboard.** One board, `score`, named "Top dancers", for all six tracks: a manifest may declare five boards, so a board per track does not fit. `os.finish({ score })` posts each round's score to it (vmOS keeps each player's best). **Leaderboard** on the results card calls `os.showLeaderboard()`, and vmOS draws its own panel over the game.
42
+ - **Achievements.** *First dance* (finish a round), *Fifty in a row* (a 50 combo) and the secret *Clean paws* (a round without a miss). `roundAchievements` in `game.ts` decides which a round earns; `main.ts` calls `os.unlock(id)` for each, every time, because vmOS records each once and shows its own toast only the first time.
43
+ - **Share score.** `os.share({ score, text })` on the results card: vmOS composes the card (the game's name, the player's name, the score and their rank) and the player chooses where to post it, or closes the sheet.
44
+ - **The midnight coat.** One `permanent` product, 25 Printer Cash. The title card's coat button calls `os.buy("midnight-coat")` from its click; vmOS draws the spend dialog and the game learns only the answer. `os.products()` says whether the player owns it on every start and device, and once owned the button switches coats (`cat.setCoat`). It is cosmetic: it changes nothing in the score. Guests see a "sign in" note; a cancelled dialog changes nothing.
45
+
37
46
  ## Controls
38
47
 
39
48
  - Arrow keys or `A` `S` `W` `D`, or tap the pads at the bottom.
@@ -59,7 +68,7 @@ The loop does no allocation per frame and touches the DOM only when a number cha
59
68
 
60
69
  ## Listing in VibeStore
61
70
 
62
- `vibemarket.json` uses manifest schema version 2, so it carries a complete VibeStore listing: a `window` of 960 x 600 that can be resized, and a `store` object with the icon, two screenshots, a plain-text description, the `game` category, a content rating (violence `none`, language `none`, not mature) and a support link.
71
+ `vibemarket.json` uses manifest schema version 3, so it carries a complete VibeStore listing: a `window` of 960 x 600 that can be resized, and a `store` object with the icon, two screenshots, a plain-text description, the `game` category, a content rating (violence `none`, language `none`, not mature) and a support link; and the 0.6 declarations: one leaderboard, three achievements and one product.
63
72
 
64
73
  The requirements are checked when you submit from the VibeStore **Submit** tab, and `os pack` and `os preview` check the same things locally:
65
74
 
@@ -74,7 +83,7 @@ The requirements are checked when you submit from the VibeStore **Submit** tab,
74
83
 
75
84
  ## What the score means
76
85
 
77
- The score is reported to the host with `game.finish` a few seconds after the results card appears, or straight away if you press **Dance again**. The host owns the final results screen and may replace the game's window once it has the score; if it keeps the window open, the card stays as the result. The score is display data: it never sets a reward. Finishing a round may earn the player a small amount of Printer Cash, decided and paid by VibeMarket OS; the game cannot grant or change it. The preview awards nothing.
86
+ The score is reported to the host with `os.finish` a few seconds after the results card appears, or straight away if you press **Dance again**. The host owns the final results screen and may replace the game's window once it has the score; if it keeps the window open, the card stays as the result. The score is display data: it never sets a reward. Finishing a round may earn the player a small amount of Printer Cash, decided and paid by VibeMarket OS; the game cannot grant or change it. The preview awards nothing.
78
87
 
79
88
  ## License
80
89
 
@@ -36,6 +36,8 @@ export interface Cat {
36
36
  setMood(mood: "neutral" | "happy" | "sad"): void;
37
37
  /** Colour of the rim light, from the stage. */
38
38
  setRim(color: THREE.Color): void;
39
+ /** Biscuit's coat: the classic ginger tabby, or the midnight coat a player can buy in the game. */
40
+ setCoat(coat: Coat): void;
39
41
  /**
40
42
  * Advance by `seconds`. `beat` is the song position in beats, so the idle groove lands on the
41
43
  * music; `energy` (0 to 1) is how hard to groove.
@@ -49,6 +51,9 @@ const SCALE = 1.15;
49
51
 
50
52
  // ---- Palette ----
51
53
  const FUR = "#f2923e", STRIPE = "#c4581f", CREAM = "#fff1da", PINK = "#ff8fab", INK = "#2a1a2e";
54
+ export type Coat = "classic" | "midnight";
55
+ /** Fur and stripe colours of each coat; the markings, face and paws stay the same. */
56
+ const COATS: Readonly<Record<Coat, { fur: string; stripe: string }>> = { classic: { fur: FUR, stripe: STRIPE }, midnight: { fur: "#2f3f8f", stripe: "#c9d4ff" } };
52
57
  const IRIS = "#9be15d", IRIS_DARK = "#3f8f3a";
53
58
 
54
59
  // ---- Signed distance functions and the mesher ----
@@ -361,9 +366,12 @@ export function createCat(): Cat {
361
366
  uFace: { value: new THREE.Vector4(1, 0, 0, 0) },
362
367
  uLook: { value: new THREE.Vector2() },
363
368
  };
369
+ /** The fur-coloured materials, recoloured by setCoat. */
370
+ const furs: THREE.ShaderMaterial[] = [];
364
371
  const toon = (base: string, pattern?: "HEAD" | "BODY" | "TAIL" | "EAR" | "LIMB") => {
365
372
  const material = new THREE.ShaderMaterial({ uniforms: { ...shared, uBase: color(base) }, vertexShader: VERTEX, fragmentShader: FRAGMENT, defines: pattern ? { [pattern]: "" } : {} });
366
373
  materials.push(material);
374
+ if (base === FUR) furs.push(material);
367
375
  return material;
368
376
  };
369
377
  const outline = new THREE.ShaderMaterial({ uniforms: { uWidth: { value: 0.0042 }, uInk: shared.uInk }, vertexShader: OUTLINE_VERTEX, fragmentShader: OUTLINE_FRAGMENT, side: THREE.BackSide });
@@ -611,6 +619,11 @@ export function createCat(): Cat {
611
619
  setRim(next) {
612
620
  shared.uRim.value.copy(next);
613
621
  },
622
+ setCoat(coat) {
623
+ const { fur, stripe } = COATS[coat];
624
+ for (const material of furs) (material.uniforms.uBase!.value as THREE.Color).set(fur);
625
+ shared.uStripe.value.set(stripe);
626
+ },
614
627
  animate(seconds, beat, energy = 0.6) {
615
628
  clock += seconds;
616
629
  const e = energy, t = target, swing = Math.sin(Math.PI * beat), dip = 0.5 + 0.5 * Math.cos(2 * Math.PI * beat);
@@ -214,6 +214,8 @@ export interface Progress {
214
214
  readonly muted: boolean;
215
215
  /** The track played last, so the next round picks another. */
216
216
  readonly last: string | null;
217
+ /** The coat Biscuit wears: "midnight" only once the player owns it (the game checks with os.products()). */
218
+ readonly coat: "classic" | "midnight";
217
219
  }
218
220
 
219
221
  /**
@@ -229,7 +231,15 @@ export function readProgress(value: unknown, trackIds: readonly string[]): Progr
229
231
  const best = Math.max(count(record.best), ...Object.values(bests));
230
232
  if (!saved && best > 0 && trackIds[0]) bests[trackIds[0]] = best;
231
233
  const last = typeof record.last === "string" && trackIds.includes(record.last) ? record.last : null;
232
- return { best, bests, rounds: count(record.rounds), muted: record.muted === true, last };
234
+ return { best, bests, rounds: count(record.rounds), muted: record.muted === true, last, coat: record.coat === "midnight" ? "midnight" : "classic" };
235
+ }
236
+
237
+ // ---- Achievements: the ids vibemarket.json declares, and when a round earns each ----
238
+
239
+ export const ACHIEVEMENTS = { firstDance: "first-dance", combo50: "combo-50", fullCombo: "full-combo" } as const;
240
+ /** The achievements a finished round earns. Unlocking one again is harmless, so a round simply names all it earned. */
241
+ export function roundAchievements(round: { bestCombo: number; fullCombo: boolean }): string[] {
242
+ return [ACHIEVEMENTS.firstDance, ...(round.bestCombo >= 50 ? [ACHIEVEMENTS.combo50] : []), ...(round.fullCombo ? [ACHIEVEMENTS.fullCombo] : [])];
233
243
  }
234
244
 
235
245
  /** Progress after a round of `trackId` that scored `score`. */
@@ -124,6 +124,7 @@
124
124
  <p class="note" id="track-mood"></p>
125
125
  <p class="best" id="best">Six tracks, about a minute each.</p>
126
126
  <div><button class="primary" id="start" type="button" disabled>Connecting…</button></div>
127
+ <div class="track"><button class="next" id="coat" type="button" hidden>Midnight coat</button><small id="shop" aria-live="polite"></small></div>
127
128
  </section>
128
129
 
129
130
  <section class="card" id="done" hidden aria-labelledby="grade">
@@ -140,6 +141,7 @@
140
141
  </dl>
141
142
  <p class="note" id="sent"></p>
142
143
  <div class="track"><button class="primary" id="again" type="button">Dance again</button><small id="up-next"></small></div>
144
+ <div class="track"><button class="next" id="share" type="button">Share score</button><button class="next" id="board" type="button">Leaderboard</button></div>
143
145
  </section>
144
146
 
145
147
  <section class="overlay" id="lost" hidden>
@@ -1,11 +1,11 @@
1
1
  import * as THREE from "three";
2
- import { connectVibeMarketApp, type VibeMarketAppSdk } from "@vibechain/os";
2
+ import { connect, OsError, type Os } from "@vibechain/os";
3
3
  import { createAudio, type AppAudio } from "@vibechain/os/audio";
4
4
  import { createLoop } from "@vibechain/os/loop";
5
5
  import { fitCanvas } from "@vibechain/os/canvas";
6
6
  import { createCat } from "./cat";
7
7
  import {
8
- beatSeconds, COMBO_MILESTONES, comboMultiplier, countInBeats, createGame, gradeRound, pickTrack, readProgress, recordRound, sectionAt,
8
+ beatSeconds, COMBO_MILESTONES, comboMultiplier, countInBeats, createGame, gradeRound, pickTrack, readProgress, recordRound, roundAchievements, sectionAt,
9
9
  sectionsOf, songSeconds, type DanceGame, type Judgement, type Lane, type Progress, type SectionRole,
10
10
  } from "./game";
11
11
  import { createMusic, soundLabel } from "./music";
@@ -25,6 +25,7 @@ const startButton = element<HTMLButtonElement>("start"), againButton = element<H
25
25
  const soundButton = element<HTMLButtonElement>("sound"), scoreText = element("score"), multiplierText = element("multiplier");
26
26
  const progress = element("progress"), played = element("played"), nowPlaying = element("now-playing");
27
27
  const trackName = element("track-name"), trackMood = element("track-mood"), nextTrackButton = element<HTMLButtonElement>("next-track"), upNext = element("up-next");
28
+ const shareButton = element<HTMLButtonElement>("share"), boardButton = element<HTMLButtonElement>("board"), coatButton = element<HTMLButtonElement>("coat"), shopNote = element("shop");
28
29
 
29
30
  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: "low-power" });
30
31
  renderer.setPixelRatio(1); // fitCanvas already sizes the backing store in device pixels.
@@ -49,7 +50,7 @@ const ENERGY: Readonly<Record<SectionRole, number>> = { "count-in": 0.4, intro:
49
50
 
50
51
  // ---- Round state ----
51
52
  const TRACK_IDS = TRACKS.map(item => item.id);
52
- let app: VibeMarketAppSdk | undefined;
53
+ let app: Os | undefined;
53
54
  /** The track that plays when the player next presses Start or Dance again. */
54
55
  let chosen = 0;
55
56
  let track: PlayableTrack = TRACKS[0]!;
@@ -71,8 +72,9 @@ const frame: StageFrame = { beat: 0, section: "intro", energy: 0.35, reducedMoti
71
72
  let pendingScore = 0, viewWidth = 0, viewHeight = 0;
72
73
 
73
74
  function save() {
74
- // A failed write only loses the personal best and the sound setting; the game goes on.
75
- void app?.checkpoint.write({ best: saved.best, bests: { ...saved.bests }, rounds: saved.rounds, muted: saved.muted, last: saved.last }).catch(() => {});
75
+ // Kept for the player across opens and devices (a guest's only while the window is open). Saves are coalesced by the SDK,
76
+ // and a failed write only loses the personal bests and settings; the game goes on.
77
+ void app?.save({ best: saved.best, bests: { ...saved.bests }, rounds: saved.rounds, muted: saved.muted, last: saved.last, coat: saved.coat }).catch(() => {});
76
78
  }
77
79
 
78
80
  // ---- Feedback ----
@@ -144,7 +146,7 @@ function release(lane: Lane) {
144
146
  }
145
147
 
146
148
  /** The desktop's sound: from the helper once it exists, else from the host (audible on a host that does not say). */
147
- function desktopSound() { return audio?.desktop ?? app?.sound?.current() ?? { muted: false, volume: 1 }; }
149
+ function desktopSound() { return audio?.desktop ?? app?.sound ?? { muted: false, volume: 1 }; }
148
150
  /** The button says what the player will hear: off by the game's own toggle, off because vmOS is muted, or on. */
149
151
  function drawSound() {
150
152
  const label = soundLabel(!saved.muted, desktopSound());
@@ -225,6 +227,8 @@ function end() {
225
227
  element("full-combo").hidden = !result.fullCombo;
226
228
  for (const kind of ["perfect", "great", "good", "miss"] as const) element(`done-${kind}`).textContent = String(counts[kind]);
227
229
  element("sent").textContent = "Your score goes to VibeMarket OS in a moment.";
230
+ // Achievements cost nothing to ask for: vmOS records each once and shows its own toast the first time.
231
+ for (const id of roundAchievements({ bestCombo, fullCombo: result.fullCombo })) void app?.unlock(id).catch(() => {});
228
232
  done.hidden = false;
229
233
  stage.frame("title", motion.matches);
230
234
  cat.setMood(result.grade === "S" || result.grade === "A" || result.grade === "B" ? "happy" : result.grade === "D" ? "sad" : "neutral");
@@ -242,7 +246,8 @@ function report() {
242
246
  window.clearTimeout(reportTimer);
243
247
  if (reported || phase !== "results") return;
244
248
  reported = true;
245
- app?.game.finish({ score: pendingScore }).then(
249
+ // One board for all six tracks (a manifest may declare five), so the score goes to the default board, "score".
250
+ app?.finish({ score: pendingScore }).then(
246
251
  () => { element("sent").textContent = "Score sent to VibeMarket OS."; },
247
252
  () => { element("sent").textContent = "VibeMarket OS keeps one score per open window, so this one stays here."; },
248
253
  );
@@ -272,6 +277,51 @@ for (const pad of Array.from(pads.querySelectorAll<HTMLButtonElement>("button[da
272
277
  }
273
278
  soundButton.addEventListener("click", () => { setSound(saved.muted); save(); });
274
279
 
280
+ // ---- vmOS services (SDK 0.6). Every one is optional: on a host that predates it the call answers `unsupported` and the
281
+ // button goes away; nothing else in the game depends on them. ----
282
+ /** Hide `button` for good when the host cannot do what it does; true when the error was handled that way. */
283
+ function retire(button: HTMLButtonElement, error: unknown): boolean {
284
+ if (error instanceof OsError && error.code === "unsupported") { button.hidden = true; return true; }
285
+ return false;
286
+ }
287
+ /** Results card: vmOS composes a card with the score and the player's rank, and the player chooses where to post it. */
288
+ shareButton.addEventListener("click", () => {
289
+ app?.share({ score: pendingScore, text: `I scored ${pendingScore.toLocaleString("en-US")} on ${track.name} in Paw Beat!` }).catch(error => {
290
+ if (!retire(shareButton, error) && error instanceof OsError && error.code === "guest") element("sent").textContent = "Sign in to VibeMarket OS to share your score.";
291
+ });
292
+ });
293
+ /** Results card: vmOS draws its own leaderboard panel over the game (everyone and friends, this week and all time). */
294
+ boardButton.addEventListener("click", () => { app?.showLeaderboard().catch(error => { retire(boardButton, error); }); });
295
+
296
+ /** The one product: a cosmetic coat for Biscuit, bought once with Printer Cash in vmOS's own dialog. */
297
+ const COAT_PRODUCT = "midnight-coat";
298
+ let coatOwned = false;
299
+ function wear(coat: Progress["coat"]) {
300
+ saved = { ...saved, coat };
301
+ cat.setCoat(coat);
302
+ drawCoat();
303
+ }
304
+ function drawCoat() {
305
+ coatButton.textContent = !coatOwned ? "Midnight coat · 25 Printer Cash" : saved.coat === "midnight" ? "Wear the ginger coat" : "Wear the midnight coat";
306
+ }
307
+ coatButton.addEventListener("click", () => {
308
+ if (coatOwned) { wear(saved.coat === "midnight" ? "classic" : "midnight"); save(); return; }
309
+ shopNote.textContent = "";
310
+ // buy needs this click: vmOS opens its spend dialog, and the promise settles when the player decides
311
+ app?.buy(COAT_PRODUCT).then(() => { coatOwned = true; wear("midnight"); save(); shopNote.textContent = "The midnight coat is yours."; }, error => {
312
+ if (retire(coatButton, error) || !(error instanceof OsError) || error.code === "cancelled") return;
313
+ shopNote.textContent = error.code === "insufficient" ? "Not enough Printer Cash yet." : error.code === "guest" ? "Sign in to VibeMarket OS to buy." : "The coat could not be bought right now.";
314
+ });
315
+ });
316
+ /** Whether the player owns the coat (on every device): from the host's product list. Without it the button stays hidden. */
317
+ async function readShop(host: Os) {
318
+ try {
319
+ coatOwned = (await host.products()).some(product => product.id === COAT_PRODUCT && product.owned);
320
+ coatButton.hidden = false;
321
+ } catch { coatButton.hidden = true; }
322
+ wear(coatOwned ? saved.coat : "classic");
323
+ }
324
+
275
325
  // ---- HUD: touch the DOM only when a value actually changed ----
276
326
  /** Score, multiplier and combo change only on a hit or a miss, so this runs on those events, not every frame. */
277
327
  function drawScore() {
@@ -321,7 +371,7 @@ function placeCallout() {
321
371
  // ---- Boot: connect, restore, then let the host know the first frame is up. ----
322
372
  async function boot() {
323
373
  try {
324
- app = await connectVibeMarketApp();
374
+ app = await connect();
325
375
  } catch {
326
376
  startButton.textContent = "Open in VibeMarket OS";
327
377
  return;
@@ -395,9 +445,10 @@ async function boot() {
395
445
  if (!contextLost) renderer.render(stage.scene, stage.camera);
396
446
  },
397
447
  });
398
- host.sound?.onChanged(drawSound);
448
+ host.onSound(drawSound);
399
449
 
400
- saved = readProgress(await host.checkpoint.read().catch(() => null), TRACK_IDS);
450
+ saved = readProgress(await host.load().catch(() => null), TRACK_IDS);
451
+ await readShop(host);
401
452
  setSound(!saved.muted);
402
453
  bestLine.textContent = saved.rounds > 0 ? `Best: ${saved.best.toLocaleString("en-US")} over ${plural(saved.rounds, "song")}.` : `${TRACKS.length} tracks, about a minute each.`;
403
454
  choose(pickTrack(TRACKS.length, shuffle, saved.last === null ? null : TRACK_IDS.indexOf(saved.last)));
@@ -409,7 +460,7 @@ async function boot() {
409
460
  againButton.addEventListener("click", begin);
410
461
  await host.ready();
411
462
  startButton.focus();
412
- window.addEventListener("pagehide", () => { report(); music.dispose(); audio?.close(); cat.dispose(); stage.dispose(); renderer.dispose(); host.destroy(); }, { once: true });
463
+ window.addEventListener("pagehide", () => { report(); music.dispose(); audio?.close(); cat.dispose(); stage.dispose(); renderer.dispose(); host.close(); }, { once: true });
413
464
  }
414
465
  canvas.tabIndex = 0;
415
466
  void boot();
@@ -1,21 +1,28 @@
1
1
  {
2
- "schemaVersion": 2,
3
- "sdkVersion": 1,
2
+ "schemaVersion": 3,
4
3
  "id": "paw-beat",
5
- "version": "1.2.0",
4
+ "version": "1.3.0",
6
5
  "name": "Paw Beat",
7
6
  "tagline": "A 3D cat, four arrows and a beat. Hit the steps, keep the combo.",
8
- "category": "vibexp-app",
9
7
  "entry": "index.html",
10
- "permissions": [],
11
- "collectionId": null,
12
8
  "window": { "width": 960, "height": 600, "resizable": true },
13
9
  "store": {
14
10
  "icon": "store/icon.png",
15
11
  "screenshots": ["store/screenshot-1.webp", "store/screenshot-2.webp"],
16
- "description": "Biscuit the cat dances to six original tracks made entirely in code, about a minute each: a dance groove, a swung funk, a fast breakbeat, a music-box waltz, a bossa nova and a chiptune chase. A random track plays each time you start. Arrows slide down four lanes toward their outlines: press the matching arrow key or WASD, or tap the on-screen pads, as each one lands, and Biscuit dances the step (a side step, a leap or a squat) while the stage pulses with the music.\n\nTiming is judged perfect, great or good, and every ten steps in a row adds 10% to each step, up to double. Long combos earn a spin and confetti; a miss makes Biscuit stumble. Each song builds, drops, breaks down and comes back for a finale, and the steps follow its tune, changing a little every round. Each round ends with a grade, your accuracy and every judgement. Your best score on each track and your sound setting are kept while the window stays open.",
12
+ "description": "Biscuit the cat dances to six original tracks made entirely in code, about a minute each: a dance groove, a swung funk, a fast breakbeat, a music-box waltz, a bossa nova and a chiptune chase. A random track plays each time you start. Arrows slide down four lanes toward their outlines: press the matching arrow key or WASD, or tap the on-screen pads, as each one lands, and Biscuit dances the step (a side step, a leap or a squat) while the stage pulses with the music.\n\nTiming is judged perfect, great or good, and every ten steps in a row adds 10% to each step, up to double. Long combos earn a spin and confetti; a miss makes Biscuit stumble. Each song builds, drops, breaks down and comes back for a finale, and the steps follow its tune, changing a little every round. Each round ends with a grade, your accuracy and every judgement. Your best score on each track is kept, your rounds go on the Top dancers leaderboard, three achievements wait to be found, and Biscuit can wear a midnight coat.",
17
13
  "category": "game",
18
14
  "rating": { "violence": "none", "language": "none", "mature": false },
19
15
  "support": "https://vibechain.com/os/docs"
20
- }
16
+ },
17
+ "leaderboards": [
18
+ { "id": "score", "name": "Top dancers" }
19
+ ],
20
+ "achievements": [
21
+ { "id": "first-dance", "name": "First dance", "description": "Finish a round on any track." },
22
+ { "id": "combo-50", "name": "Fifty in a row", "description": "Hit 50 steps in a row without a miss." },
23
+ { "id": "full-combo", "name": "Clean paws", "description": "Finish a track without missing a single step.", "secret": true }
24
+ ],
25
+ "products": [
26
+ { "id": "midnight-coat", "name": "Midnight coat", "description": "Biscuit dances in a midnight-blue coat with silver stripes. Switch coats on the title card.", "price": 25, "kind": "permanent" }
27
+ ]
21
28
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibechain/os",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public",