@vibechain/os 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/AGENTS.md +22 -9
  2. package/README.md +53 -17
  3. package/SECURITY.md +6 -2
  4. package/dist/app-client.js +29 -5
  5. package/dist/app-host.d.ts +27 -4
  6. package/dist/app-host.js +76 -9
  7. package/dist/app-protocol.d.ts +36 -1
  8. package/dist/app-protocol.js +21 -0
  9. package/dist/app-wire.d.ts +24 -3
  10. package/dist/app-wire.js +19 -4
  11. package/dist/audio.d.ts +65 -0
  12. package/dist/audio.js +162 -0
  13. package/dist/browser.d.ts +2 -0
  14. package/dist/browser.js +2 -0
  15. package/dist/bundle.d.ts +2 -0
  16. package/dist/bundle.js +2 -0
  17. package/dist/capture.d.ts +22 -0
  18. package/dist/capture.js +99 -0
  19. package/dist/cli.js +3 -1
  20. package/dist/commands.d.ts +6 -0
  21. package/dist/commands.js +17 -0
  22. package/dist/index.d.ts +5 -2
  23. package/dist/index.js +1 -0
  24. package/dist/links.d.ts +21 -0
  25. package/dist/links.js +43 -0
  26. package/dist/os.d.ts +33 -8
  27. package/dist/os.js +68 -14
  28. package/dist/preview-parent.d.ts +8 -2
  29. package/dist/preview-parent.js +35 -10
  30. package/dist/preview-ui.js +1 -1
  31. package/dist/preview.js +1 -1
  32. package/dist/templates/plain/game.js +3 -1
  33. package/dist/testing.d.ts +15 -2
  34. package/dist/testing.js +64 -19
  35. package/dist/transport.d.ts +2 -0
  36. package/dist/transport.js +1 -1
  37. package/dist/vibemarket-os.js +1 -1
  38. package/examples/paw-beat/README.md +28 -9
  39. package/examples/paw-beat/game.ts +280 -123
  40. package/examples/paw-beat/index.html +18 -4
  41. package/examples/paw-beat/main.ts +101 -44
  42. package/examples/paw-beat/music.ts +72 -337
  43. package/examples/paw-beat/stage.ts +23 -9
  44. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  45. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  46. package/examples/paw-beat/synth.ts +477 -0
  47. package/examples/paw-beat/tracks.ts +286 -0
  48. package/examples/paw-beat/vibemarket.json +2 -2
  49. package/examples/vibexp-app/plain/game.ts +6 -2
  50. package/package.json +7 -1
  51. package/skill.md +399 -0
package/dist/os.js CHANGED
@@ -3,20 +3,19 @@
3
3
  * says hello and every method works; on an older host `ready`, `finish`, lifecycle, `load` and `save` work (saves use the
4
4
  * window-only checkpoint) and the rest reject with `unsupported`. Every rejection is an OsError with a stable code.
5
5
  */
6
- import { APP_FRAGMENT, APP_LIMITS, appNonce, checkpointJson, lifecycleValue } from "./app-protocol.js";
7
- import { APP_SESSION_LIMITS, AppHostError, osErrorCode, saveJson, saveValue, wireCard, wireCardsEvent, wireHello, wirePack, wirePackSummary, wirePlayer, } from "./app-wire.js";
6
+ import { APP_FRAGMENT, APP_LIMITS, AUDIBLE, appNonce, checkpointJson, lifecycleValue, soundValue } from "./app-protocol.js";
7
+ import { APP_SESSION_LIMITS, AppHostError, CARD_ID, OsError, osErrorCode, saveJson, saveValue, wireCard, wireCardsEvent, wireHello, wirePack, wirePackSummary, wirePlayer, } from "./app-wire.js";
8
+ import { createCapturer } from "./capture.js";
8
9
  import { gameFinishInput } from "./completion.js";
9
10
  import { packSlug } from "./manifest.js";
10
11
  import { connectHostPort, createRpcTransport } from "./transport.js";
12
+ import { parseVmosLink } from "./links.js";
11
13
  export { OS_ERROR_CODES } from "./app-wire.js";
12
14
  /** The SDK version a 0.5 client reports in `host.hello`. */
13
- export const OS_SDK_VERSION = "0.5.0";
14
- /** Every rejection of the app API. Branch on `code`; `message` is a plain sentence that may change. */
15
- export class OsError extends Error {
16
- code;
17
- constructor(code, message) { super(message); this.name = "OsError"; this.code = code; }
18
- }
19
- const MESSAGES = {
15
+ export const OS_SDK_VERSION = "0.5.2";
16
+ export { OsError } from "./app-wire.js";
17
+ /** What each code means, as the SDK's own rejections say it (also the agent skill's error table). */
18
+ export const OS_ERROR_MESSAGES = Object.freeze({
20
19
  unsupported: "This host is older than this SDK and has no such feature.",
21
20
  "not-permitted": "The manifest does not declare that, or the app is behind another window.",
22
21
  invalid: "That argument is not valid.",
@@ -26,7 +25,8 @@ const MESSAGES = {
26
25
  unavailable: "The host could not answer now; try again.",
27
26
  timeout: "The host did not answer in 10 seconds.",
28
27
  closed: "The session ended. Reopen the app.",
29
- };
28
+ });
29
+ const MESSAGES = OS_ERROR_MESSAGES;
30
30
  const fail = (code, message = MESSAGES[code]) => new OsError(code, message);
31
31
  /** Errors the SDK raises itself keep their code; anything else is `invalid` (an argument) unless said otherwise. */
32
32
  const asOsError = (error, fallback) => error instanceof OsError ? error
@@ -52,8 +52,9 @@ export async function connect(options = {}) {
52
52
  export async function createOs(port, session, protocol, href) {
53
53
  if (!appNonce(session))
54
54
  throw fail("unavailable", "Invalid app session.");
55
- let state = Object.freeze({ active: true, width: 0, height: 0 }), closed = false;
55
+ let state = Object.freeze({ active: true, width: 0, height: 0 }), closed = false, sound = AUDIBLE;
56
56
  const pause = new Set(), resume = new Set(), resize = new Set(), watchers = new Set();
57
+ const sounds = new Set();
57
58
  const transport = createRpcTransport(port, {
58
59
  session, timeoutMs: APP_LIMITS.requestTimeoutMs,
59
60
  maxPending: protocol === 2 ? 64 : APP_LIMITS.inFlight, jsonBytes: protocol === 2 ? APP_SESSION_LIMITS.messageBytes : APP_LIMITS.responseBytes,
@@ -67,6 +68,14 @@ export async function createOs(port, session, protocol, href) {
67
68
  cardsEvent(value.state);
68
69
  return;
69
70
  }
71
+ if (value.event === "app.capture") {
72
+ capturer.event(value.id);
73
+ return;
74
+ }
75
+ if (value.event === "app.sound") {
76
+ soundEvent(value.state);
77
+ return;
78
+ }
70
79
  if (value.event !== "app.lifecycle")
71
80
  return;
72
81
  let next;
@@ -89,6 +98,7 @@ export async function createOs(port, session, protocol, href) {
89
98
  listener(Object.freeze({ width: next.width, height: next.height }));
90
99
  },
91
100
  });
101
+ const capturer = createCapturer((id, image) => { call({ method: "app.frame", id, image }).catch(() => { }); }, () => protocol !== 2 || !hello || closed);
92
102
  const call = async (request) => {
93
103
  if (closed)
94
104
  throw fail("closed");
@@ -97,6 +107,21 @@ export async function createOs(port, session, protocol, href) {
97
107
  throw fail("unavailable", "Invalid host response.");
98
108
  return result;
99
109
  };
110
+ /** Declared ahead so the transport can call it: a valid, changed state is kept and told to every listener. */
111
+ function soundEvent(value) {
112
+ let next;
113
+ try {
114
+ next = soundValue(value);
115
+ }
116
+ catch {
117
+ return;
118
+ }
119
+ if (next.muted === sound.muted && next.volume === sound.volume)
120
+ return;
121
+ sound = next;
122
+ for (const listener of [...sounds])
123
+ listener(sound);
124
+ }
100
125
  const completed = (result) => { if (result.completed !== true)
101
126
  throw fail("unavailable", "Invalid host acknowledgement."); };
102
127
  let hello = null;
@@ -209,10 +234,20 @@ export async function createOs(port, session, protocol, href) {
209
234
  .finally(() => { writing = false; lastWrite = Date.now(); flush(); });
210
235
  };
211
236
  let token = null;
237
+ /** pack.show or card.show; a host that did not list card.show (0.5.0) is answered here, never sent a method it cannot read */
238
+ const show = async (request) => {
239
+ const hello = v2();
240
+ if (request.method === "card.show" && !hello.features.includes("card.show"))
241
+ throw fail("unsupported");
242
+ const result = await call(request);
243
+ if (result.shown !== true)
244
+ throw fail("unavailable", "Invalid host acknowledgement.");
245
+ };
212
246
  const os = {
213
247
  get active() { return state.active; },
214
248
  get size() { return Object.freeze({ width: state.width, height: state.height }); },
215
249
  get guest() { return hello?.guest ?? false; },
250
+ get sound() { return sound; },
216
251
  async ready() { completed(await call({ method: "ui.ready" })); },
217
252
  progress(fraction) {
218
253
  if (typeof fraction !== "number" || !Number.isFinite(fraction) || fraction < 0 || fraction > 1)
@@ -286,8 +321,19 @@ export async function createOs(port, session, protocol, href) {
286
321
  const pack = wirePack((await call({ method: "cards.pack", pack: name })).pack);
287
322
  return { ...pack, art: absolute(pack.art), cards: pack.cards.map(item => ({ ...item, art: absolute(item.art) })) };
288
323
  },
289
- async showPack(id) { const name = slug(id); v2(); const result = await call({ method: "pack.show", pack: name }); if (result.shown !== true)
290
- throw fail("unavailable", "Invalid host acknowledgement."); },
324
+ async showPack(id) { const name = slug(id); v2(); await show({ method: "pack.show", pack: name }); },
325
+ async showCard(pack, cardId) {
326
+ const name = slug(pack);
327
+ if (typeof cardId !== "string" || !CARD_ID.test(cardId))
328
+ throw fail("invalid", "That is not a card id.");
329
+ await show({ method: "card.show", pack: name, card: cardId });
330
+ },
331
+ async open(link) {
332
+ const target = parseVmosLink(link);
333
+ if (!target)
334
+ throw fail("invalid", "That is not a vmOS pack or card link.");
335
+ await (target.kind === "pack" ? show({ method: "pack.show", pack: target.pack }) : show({ method: "card.show", pack: target.pack, card: target.card }));
336
+ },
291
337
  async player() {
292
338
  v2();
293
339
  if (token && token.expiresAt - Date.now() > APP_SESSION_LIMITS.tokenReuseMs)
@@ -317,7 +363,13 @@ export async function createOs(port, session, protocol, href) {
317
363
  throw fail("invalid"); v2(); completed(await call({ method: "display.fullscreen", on })); },
318
364
  onPause(listener) { pause.add(listener); return () => { pause.delete(listener); }; },
319
365
  onResume(listener) { resume.add(listener); return () => { resume.delete(listener); }; },
366
+ onCapture(handler) {
367
+ if (typeof handler !== "function")
368
+ throw fail("invalid", "A capture handler is a function.");
369
+ return capturer.on(handler);
370
+ },
320
371
  onResize(listener) { resize.add(listener); return () => { resize.delete(listener); }; },
372
+ onSound(listener) { sounds.add(listener); return () => { sounds.delete(listener); }; },
321
373
  close() {
322
374
  if (closed)
323
375
  return;
@@ -328,9 +380,11 @@ export async function createOs(port, session, protocol, href) {
328
380
  window.clearTimeout(progressTimer);
329
381
  pendingSave?.waiters.forEach(waiter => waiter.reject(fail("closed")));
330
382
  pendingSave = null;
383
+ capturer.clear();
331
384
  pause.clear();
332
385
  resume.clear();
333
386
  resize.clear();
387
+ sounds.clear();
334
388
  watchers.clear();
335
389
  transport.destroy();
336
390
  },
@@ -341,7 +395,7 @@ export async function createOs(port, session, protocol, href) {
341
395
  const ready = os.ready;
342
396
  os.ready = async () => { readied = true; progressValue = null; await ready(); };
343
397
  // every rejection is an OsError: a malformed host answer is `unavailable`
344
- for (const key of ["ready", "load", "cards", "packs", "pack", "showPack", "player", "finish", "maximize", "fullscreen"]) {
398
+ for (const key of ["ready", "load", "cards", "packs", "pack", "showPack", "showCard", "open", "player", "finish", "maximize", "fullscreen"]) {
345
399
  const method = os[key];
346
400
  os[key] = async (...args) => { try {
347
401
  return await method(...args);
@@ -10,13 +10,19 @@ export interface PreviewMetadata {
10
10
  network: string[];
11
11
  }
12
12
  export declare function previewMetadata(input: unknown): PreviewMetadata;
13
+ /** A public pack every preview knows, linked or not, for trying `os.pack`, `os.showPack`, `os.showCard` and `os.open`. */
14
+ export declare const PREVIEW_PUBLIC_PACK = "preview-public";
13
15
  /**
14
16
  * The preview's stand-in for VibeMarket: six cards in each linked pack (or one sample pack for `cards: "all"`), of which
15
- * the player holds the first three; `pull()` adds a copy of a random card, as a pull would. Art is the bundle's listing
16
- * icon, served under the version prefix like the website's art route.
17
+ * the player holds the first three, and one more public pack nobody linked (`PREVIEW_PUBLIC_PACK`); `pull()` adds a copy
18
+ * of a random held-pack card, as a pull would. Art is the bundle's listing icon, served under the version prefix like the
19
+ * website's art route.
17
20
  */
18
21
  export declare function previewCatalog(meta: Pick<PreviewMetadata, "packs" | "cards">, random?: () => number): {
22
+ /** any public pack's face, linked or not (the host's rule since 0.5.1) */
19
23
  pack(slug: string): WirePack;
24
+ /** one card of a public pack, or `invalid` */
25
+ card(slug: string, card: string): WirePack["cards"][number];
20
26
  cards(): {
21
27
  cards: WireCard[];
22
28
  revision: string;
@@ -16,27 +16,38 @@ export function previewMetadata(input) {
16
16
  }
17
17
  /** A pack name from its slug: "rooftop-rats" reads "Rooftop Rats". */
18
18
  const title = (slug) => slug.split("-").map(word => word[0].toUpperCase() + word.slice(1)).join(" ");
19
+ /** A public pack every preview knows, linked or not, for trying `os.pack`, `os.showPack`, `os.showCard` and `os.open`. */
20
+ export const PREVIEW_PUBLIC_PACK = "preview-public";
19
21
  /**
20
22
  * The preview's stand-in for VibeMarket: six cards in each linked pack (or one sample pack for `cards: "all"`), of which
21
- * the player holds the first three; `pull()` adds a copy of a random card, as a pull would. Art is the bundle's listing
22
- * icon, served under the version prefix like the website's art route.
23
+ * the player holds the first three, and one more public pack nobody linked (`PREVIEW_PUBLIC_PACK`); `pull()` adds a copy
24
+ * of a random held-pack card, as a pull would. Art is the bundle's listing icon, served under the version prefix like the
25
+ * website's art route.
23
26
  */
24
27
  export function previewCatalog(meta, random = Math.random) {
25
28
  const slugs = meta.packs.length ? meta.packs : meta.cards === "all" ? ["preview-pack"] : [];
26
- const packs = slugs.map(slug => ({
29
+ const make = (slug) => ({
27
30
  id: slug, name: title(slug), creator: "Preview", art: coverArtPath(slug), total: 6,
28
31
  cards: Array.from({ length: 6 }, (_, index) => ({ id: `${slug}/c${index + 1}`, pack: slug, name: `${title(slug)} #${index + 1}`, rarity: RARITIES[index % RARITIES.length], art: cardArtPath(slug, `c${index + 1}`) })),
29
- }));
32
+ });
33
+ const packs = slugs.map(make), everyPublic = [...packs, ...(slugs.includes(PREVIEW_PUBLIC_PACK) ? [] : [make(PREVIEW_PUBLIC_PACK)])];
30
34
  const counts = new Map(packs.flatMap(pack => pack.cards.slice(0, 3).map(card => [card.id, 1])));
31
35
  let revision = 1;
32
- const readable = (slug) => meta.cards === "all" ? slugs.includes(slug) : meta.packs.includes(slug);
33
36
  return {
37
+ /** any public pack's face, linked or not (the host's rule since 0.5.1) */
34
38
  pack(slug) {
35
- const pack = packs.find(item => item.id === slug);
36
- if (!pack || !readable(slug))
37
- throw new AppHostError("not-permitted", "This app may not read that pack.");
39
+ const pack = everyPublic.find(item => item.id === slug);
40
+ if (!pack)
41
+ throw new AppHostError("invalid", "There is no such public pack.");
38
42
  return pack;
39
43
  },
44
+ /** one card of a public pack, or `invalid` */
45
+ card(slug, card) {
46
+ const found = this.pack(slug).cards.find(item => item.id === `${slug}/${card}`);
47
+ if (!found)
48
+ throw new AppHostError("invalid", "That card is not in that pack.");
49
+ return found;
50
+ },
40
51
  cards() {
41
52
  if (meta.cards === "none")
42
53
  throw new AppHostError("not-permitted", "The manifest does not declare cards.");
@@ -79,8 +90,10 @@ export async function startPreviewParent() {
79
90
  if (refusal)
80
91
  throw Error(refusal);
81
92
  const surface = document.getElementById("surface"), status = document.getElementById("status"), toggle = document.getElementById("toggle"), reset = document.getElementById("reset"), pull = document.getElementById("pull");
93
+ const speaker = document.getElementById("sound"), volume = document.getElementById("volume");
82
94
  const result = document.getElementById("result"), score = document.getElementById("score");
83
- if (!surface || !status || !result || !score || !(toggle instanceof HTMLButtonElement) || !(reset instanceof HTMLButtonElement) || !(pull instanceof HTMLButtonElement))
95
+ if (!surface || !status || !result || !score || !(toggle instanceof HTMLButtonElement) || !(reset instanceof HTMLButtonElement) || !(pull instanceof HTMLButtonElement)
96
+ || !(speaker instanceof HTMLButtonElement) || !(volume instanceof HTMLInputElement))
84
97
  throw Error("Preview controls are missing.");
85
98
  const meta = previewMetadata(await (await fetch("/preview.json", { credentials: "omit" })).json());
86
99
  const runtime = new URL(meta.runtime);
@@ -97,6 +110,7 @@ export async function startPreviewParent() {
97
110
  async packs() { return catalog.packs(); },
98
111
  async pack(slug) { return catalog.pack(slug); },
99
112
  async showPack(slug) { catalog.pack(slug); clicked(); status.textContent = `VibeMarket would open the pack ${slug} in its market window here.`; },
113
+ async showCard(slug, card) { const shown = catalog.card(slug, card); clicked(); status.textContent = `VibeMarket would open the card ${shown.name} (${card}) on the pack ${slug}'s page here.`; },
100
114
  // a stand-in identity; the preview has no account and signs nothing
101
115
  async player() {
102
116
  const player = { guest: false, handle: "preview_player", username: "preview", name: "Preview Player", picture: null };
@@ -117,6 +131,8 @@ export async function startPreviewParent() {
117
131
  let controller = owner(), frame = null;
118
132
  let mounted = null, observer = null, minimized = false;
119
133
  let completion = null;
134
+ // the desktop's sound, as the taskbar speaker and volume would set it: the app must follow it (createAudio does)
135
+ let sound = { muted: false, volume: 1 };
120
136
  const detach = () => { mounted?.dispose(); mounted = null; controller.suspend(); observer?.disconnect(); observer = null; frame?.remove(); frame = null; };
121
137
  const draw = () => {
122
138
  detach();
@@ -143,7 +159,7 @@ export async function startPreviewParent() {
143
159
  frame.referrerPolicy = "no-referrer";
144
160
  frame.src = source.href;
145
161
  surface.appendChild(frame);
146
- mounted = mountAppFrame(frame, { controller, challenge, current: () => !minimized && !document.hidden,
162
+ mounted = mountAppFrame(frame, { controller, challenge, sound, current: () => !minimized && !document.hidden,
147
163
  ready: () => { status.textContent = "App ready · Minimize and restore to check its saved work."; },
148
164
  progress: fraction => { status.textContent = `Loading the isolated app… ${Math.round(fraction * 100)}%`; },
149
165
  finish: value => { completion = value; reset.textContent = "Play again"; draw(); },
@@ -156,6 +172,15 @@ export async function startPreviewParent() {
156
172
  };
157
173
  toggle.onclick = () => { minimized = !minimized; toggle.textContent = minimized ? "Restore" : "Minimize"; draw(); };
158
174
  reset.onclick = () => { detach(); controller.dispose(); controller = owner(); completion = null; minimized = false; toggle.textContent = "Minimize"; reset.textContent = "Close / reset"; draw(); };
175
+ const setSound = (next) => {
176
+ sound = next;
177
+ mounted?.setSound(sound);
178
+ speaker.textContent = sound.muted ? "Sound off" : "Sound on";
179
+ speaker.setAttribute("aria-pressed", String(!sound.muted));
180
+ status.textContent = sound.muted ? "Desktop sound off: the app must be silent." : `Desktop sound on at ${Math.round(sound.volume * 100)}%: the app follows this volume.`;
181
+ };
182
+ speaker.onclick = () => setSound({ muted: !sound.muted, volume: sound.volume });
183
+ volume.oninput = () => setSound({ muted: sound.muted, volume: Math.min(1, Math.max(0, Number(volume.value) / 100)) });
159
184
  pull.onclick = () => {
160
185
  const name = catalog.pull();
161
186
  status.textContent = name ? `Pulled ${name}. The app hears about it through onCards.` : "This app links no packs and does not read all cards, so there is nothing to pull.";
@@ -1 +1 @@
1
- var Ee="vibemarket.game.v1";var ot=["127.0.0.1","localhost"],it=["vibechain.com","www.vibechain.com"],at=["__VM_STEAM__","__TAURI_INTERNALS__"],Ve=["__TAURI__","vibeNative","ReactNativeWebView"],ct=/\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i,lt="Third-party apps are available only on vibechain.com and in the local browser developer preview.",pt="Third-party apps require a top-level browser host.",ut="Third-party apps are disabled in native shells until their IPC isolation is verified.";function dt({protocol:e,hostname:t,port:r}){return e==="http:"?ot.includes(t)?"local":null:e==="https:"&&it.includes(t)&&r===""?"production":null}function je(e,t){let r=Object.getOwnPropertyDescriptor(e,t);return r&&"value"in r?r.value:void 0}var mt=Object.freeze({windows:1,macos:1,linux:1}),ht=[["windows",/^Mozilla\/5\.0 \(Windows NT \d+\.\d+; Win64; x64\) AppleWebKit\/537\.36 \(KHTML, like Gecko\) Chrome\/\d+(?:\.\d+){3} Safari\/537\.36 Edg\/\d+(?:\.\d+){3}$/],["macos",/^Mozilla\/5\.0 \(Macintosh; Intel Mac OS X \d+(?:_\d+){1,2}\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)$/],["linux",/^Mozilla\/5\.0 \(X11; Linux (?:x86_64|aarch64)\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)(?: Version\/\d+(?:\.\d+){0,3} Safari\/\d+(?:\.\d+){0,3})?$/]];function ft(e){return ht.find(([,t])=>t.test(e))?.[0]??null}function gt(e,t,r){let n=je(e,"__VM_STEAM__");if(typeof n!="object"||n===null)return!1;let s=Object.getPrototypeOf(n);if(s!==Object.prototype&&s!==null)return!1;if(je(n,"appFrames")===1)return!0;let o=ft(t);return o!==null&&r[o]===1}function se(e,t=mt){let r=dt(e.location);if(r===null)return lt;if(e.top!==e.self)return pt;let n=e.navigator.userAgent;return(r==="production"&&gt(e,n,t)?Ve:[...at,...Ve]).some(o=>o in e)||ct.test(n)?ut:null}function oe(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 ae="vibexp";var k=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});function Se(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function ce(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,"0")).join("")}function le(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 pe(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 ie=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),X=(e,t)=>{let r=Object.keys(e);return r.length===t.length&&Reflect.ownKeys(e).length===r.length&&r.every(n=>t.includes(n)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,n)??{},"value"))};function Pe(e){let t=0,r=0,n=(o,p)=>{if(++t>k.checkpointNodes||p>k.checkpointDepth)throw Error("App checkpoint is too complex.");if(o===null||typeof o=="boolean")return;if(typeof o=="number"){if(!Number.isFinite(o))throw Error("Checkpoint numbers must be finite.");return}if(typeof o=="string"){if(o.length>k.stringBytes)throw Error("App checkpoint string is too large.");let a=new TextEncoder().encode(o).byteLength;if(a>k.stringBytes||(r+=a)>k.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(o)){if(o.length>k.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(o).length!==o.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let a=0;a<o.length;a++){let c=Object.getOwnPropertyDescriptor(o,a);if(!c||!("value"in c))throw Error("Sparse/accessor checkpoints are unsupported.");n(c.value,p+1)}return}if(!ie(o))throw Error("App checkpoint must contain only JSON values.");let i=Object.keys(o);if(Reflect.ownKeys(o).length!==i.length)throw Error("Checkpoint properties must be enumerable strings.");if(i.length>k.objectKeys)throw Error("App checkpoint has too many keys.");for(let a of i){if(["__proto__","constructor","prototype"].includes(a)||a.length>128)throw Error("Invalid app checkpoint key.");if(r+=new TextEncoder().encode(a).byteLength,r>k.checkpointBytes)throw Error("App checkpoint keys are too large.");let c=Object.getOwnPropertyDescriptor(o,a);if(!c||!("value"in c))throw Error("App checkpoint accessors are unsupported.");n(c.value,p+1)}};n(e,0);let s=JSON.stringify(e);if(new TextEncoder().encode(s).byteLength>k.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return s}function Me(e){return JSON.parse(Pe(e))}function We(e,t){if(!ie(e)||!X(e,["id","session","request"])||e.session!==t||typeof e.id!="string"||e.id.length>80||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!ie(e.request))throw Error("Invalid app session request.");let r=e.request;if(r.method==="game.finish"&&X(r,["method","score"]))return{id:e.id,request:{method:"game.finish",...oe({score:r.score})}};if((r.method==="ui.ready"||r.method==="app.checkpoint.get")&&X(r,["method"]))return{id:e.id,request:{method:r.method}};if(r.method==="app.checkpoint.set"&&X(r,["method","value"]))return{id:e.id,request:{method:r.method,value:Me(r.value)}};throw Error("This app has no permission for that method.")}function Y(e){if(!ie(e)||!X(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 Lt={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},$t={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},yt={packs:3,network:8,packSlugMax:56},wt=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,j=e=>typeof e=="string"&&e.length<=yt.packSlugMax&&wt.test(e);function Fe(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 A=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,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4}),ue=["common","rare","epic","legendary","mythic"],De=/^[A-Za-z0-9_-]{1,64}$/,ee=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}),Q=1024,te=Object.freeze({"host.hello":{request:256,response:Q,states:"LFB"},"ui.progress":{request:64,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*Q,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*Q,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*Q,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],states:"F"},"player.get":{request:64,response:2*Q,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"}}),Ge=Object.freeze(Object.keys(te).filter(e=>e!=="host.hello")),kt=new TextEncoder,re=e=>kt.encode(e).byteLength,J=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),q=(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)),b=class extends Error{code;constructor(t,r){super(r),this.name="AppHostError",this.code=t}};function Re(e){let t=s=>new b("invalid",s),r=(s,o)=>{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(o>A.saveDepth)throw t(`A save nests at most ${A.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 p=0;p<s.length;p++){let i=Object.getOwnPropertyDescriptor(s,p);if(!i||!("value"in i))throw t("A save's arrays cannot be sparse or have accessors.");r(i.value,o+1)}return}if(!J(s))throw t("A save must contain only plain objects, arrays and JSON values.");for(let p of Reflect.ownKeys(s)){let i=Object.getOwnPropertyDescriptor(s,p);if(typeof p!="string"||!i||!("value"in i)||!i.enumerable)throw t("A save's properties must be plain enumerable data.");r(i.value,o+1)}}};r(e,1);let n=JSON.stringify(e);if(re(n)>A.saveBytes)throw new b("too-large",`A save is at most ${A.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return n}function He(e){let t;try{t=JSON.parse(e)}catch{throw new b("invalid","The saved data is not JSON.")}return Re(t),t}var $=(e,t,r=0)=>typeof e=="string"&&e.length>=r&&e.length<=t,de=(e,t,r)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=r,bt=e=>typeof e=="string"&&ue.includes(e),_e=".bin",me=(e,t)=>`-/card/${e}/${t}${_e}`,he=e=>`-/cover/${e}${_e}`,At=e=>`-/player/${e}${_e}`;function qe(e,t){if(!J(e)||!q(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:r,pack:n,name:s,art:o}=e,p=typeof r=="string"?r.slice(r.indexOf("/")+1):"";if(!j(n)||r!==`${n}/${p}`||!De.test(p)||!$(s,120)||!bt(e.rarity)||t&&!de(e.count,1,1e6)||o!==null&&o!==me(n,p))throw Error("Invalid card.");return{id:r,pack:n,name:s,rarity:e.rarity,...t?{count:e.count}:{},art:o}}function Ie(e){return qe(e,!0)}function vt(e){return qe(e,!1)}function Je(e){let{id:t,name:r,creator:n,art:s,total:o}=e;if(!j(t)||!$(r,120,1)||n!==null&&!$(n,64,1)||s!==null&&s!==he(t)||!de(o,0,1e4))throw Error("Invalid pack.");return{id:t,name:r,creator:n,art:s,total:o}}function Ke(e){if(!J(e)||!q(e,["id","name","creator","art","held","total"])||!de(e.held,0,1e4))throw Error("Invalid pack.");let t=Je(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function Ue(e){if(!J(e)||!q(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=Je(e),r=e.cards.map(vt);if(r.some(n=>n.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:r}}var xt=/[\u0000-\u001F\u007F-\u009F]/,Be=e=>typeof e=="string"&&ee.handle.test(e);function Ze(e){if(J(e)&&q(e,["guest"])&&e.guest===!0)return{guest:!0};if(!J(e)||!q(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:r,name:n,picture:s,token:o,expiresAt:p}=e;if(!Be(t)||!$(n,ee.nameMax,1)||xt.test(n)||r!==void 0&&(!Be(r)||r===t)||s!==null&&s!==At(t)||"token"in e!="expiresAt"in e||o!==void 0&&(!$(o,ee.tokenMax,ee.tokenMin)||!ee.token.test(o)||!de(p,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...r===void 0?{}:{username:r},name:n,picture:s,...o===void 0?{}:{token:o,expiresAt:p}}}var Oe=e=>$(e,64,1);var Xe=e=>e.includes("/")?"../".repeat(e.split("/").length-1):"./";function Ye(e){let t=e.method,r=(...n)=>q(e,["method",...n]);switch(t){case"ui.ready":case"app.checkpoint.get":return r()?{method:t}:null;case"game.finish":return r("score")?{method:t,...oe({score:e.score})}:null;case"app.checkpoint.set":return r("value")?{method:t,value:Me(e.value)}:null;case"host.hello":return r("protocol","sdk")&&e.protocol===2&&$(e.sdk,20,1)&&/^[\x20-\x7e]+$/.test(e.sdk)?{method:t,protocol:2,sdk:e.sdk}:null;case"ui.progress":return r("value")&&typeof e.value=="number"&&Number.isFinite(e.value)?{method:t,value:e.value}:null;case"app.save.get":case"cards.packs":case"player.get":return r()?{method:t}:null;case"app.save.set":return r("value")?{method:t,value:e.value}:null;case"cards.list":return!q(e,["method"],["pack","after"])||"pack"in e&&!$(e.pack,64,1)||"after"in e&&!$(e.after,64,1)?null:{method:t,..."pack"in e?{pack:e.pack}:{},..."after"in e?{after:e.after}:{}};case"cards.pack":case"pack.show":return r("pack")&&$(e.pack,64,1)?{method:t,pack:e.pack}:null;case"display.maximize":case"display.fullscreen":case"cards.watch":return r("on")&&typeof e.on=="boolean"?{method:t,on:e.on}:null;default:return null}}function Ce(e){return Object.hasOwn(te,e)?te[e]:{request:k.requestBytes,response:k.responseBytes,states:"LFB"}}function Et(e,t,r){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype||Object.keys(e).length!==3||!("session"in e)||e.session!==t||!("id"in e)||typeof e.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!("request"in e)||!e.request||typeof e.request!="object"||Array.isArray(e.request))throw Error("Invalid app session request.");let n=Ye(e.request),s=n!==null&&!Object.hasOwn(te,n.method);if(!n||!r&&!s&&n.method!=="host.hello")throw Error("This app has no permission for that method.");if(re(JSON.stringify(e.request))>Ce(n.method).request)throw Error("App request exceeds its bound.");return{id:e.id,request:n}}function Qe(e,t){let r=[];return n=>(r=r.filter(s=>n-s<t),r.length>=e?!1:(r.push(n),!0))}var D={states:"That is not available while the app is loading or behind another window.",rate:"Too many requests of that kind; try again later.",slug:"That is not a pack slug.",after:"That page cursor is not valid.",unavailable:"The host could not answer that now; try again."};function et(e=()=>performance.now(),t={}){let r=t.services,n=r!==void 0,s="null",o=!1,p,i,a=!1,c=e();if(!Number.isFinite(c))throw Error("App clock is invalid.");let P=c,z=c,W=0,O=0,V=c,E,g,_,v=!1,f,I=Qe(A.requestsPerMinute,6e4),C=n?A.sessionMs:k.sessionMs,T=n?A.lifetimeRequests:k.lifetimeRequests,ne=n?"App session reached its 4-hour limit. Reopen the app to keep playing.":"App session expired. Reopen the app.",y=h=>{if(o||E)return;E=h,clearTimeout(K),clearTimeout(_),s="null";let M=g;p?.close(),M?.(h)},K=setTimeout(()=>y(ne),C),N=()=>{let h;try{h=e()}catch{y("App clock changed. Reopen the app.");return}if(!Number.isFinite(h)||h<P){y("App clock changed. Reopen the app.");return}if(P=h,h-c>=C){y(ne);return}return h},fe=h=>{clearTimeout(_),_=setTimeout(()=>{let M=N();if(M===void 0)return;let L=M-V;if(L<A.idleMs){fe(A.idleMs-L);return}v||(v=!0,t.idle?.())},h)},Te=h=>{V=h,v&&(v=!1,fe(A.idleMs))};n&&fe(A.idleMs);let ge={protocol:n?2:1,attach(h,M,L){if(o||E||!Se(M))throw h.close(),Error(E??"App controller is closed.");if(N()===void 0)throw h.close(),Error(E);p?.close();let U=!1,ye=0,Z=!1,we=!1,Ne=0,ke=!1,be=!1,G,Le=new Set,$e=new Map,Ae=()=>{U||(U=!0,h.onmessage=null,h.onmessageerror=null,h.close(),p===xe&&(p=void 0,g=void 0,f=void 0))},H=m=>{U||(Ae(),L.fault(m))},F=()=>!U&&!o&&L.current(),ze=L.foreground??(()=>!0),ve=(m,l)=>{F()&&h.postMessage(le(m,l))},xe={lifecycle(m){F()&&h.postMessage(le({session:M,event:"app.lifecycle",state:Y(m)},k.responseBytes))},close:Ae};p=xe,g=L.fault,r&&(f=async()=>{if(!be||!G||!F())return;let m=await r.cards();if(!F()||!be||!G||!Oe(m.revision)||m.revision===G.revision)return;let l=new Map(m.cards.map(x=>{let S=Ie(x);return[S.id,S]})),w=[...l.values()].filter(x=>JSON.stringify(G.cards.get(x.id))!==JSON.stringify(x)),u=[...G.cards.keys()].filter(x=>!l.has(x)),d={changed:w,removed:u,revision:m.revision};re(JSON.stringify(d))>A.cardsEventBytes&&(d={reset:!0,revision:m.revision}),G={revision:m.revision,cards:l},ve({session:M,event:"app.cards",state:d},A.cardsEventBytes+1024)});let nt=async(m,l)=>{let w=(u,d)=>{try{return d(u)}catch{throw new b("unavailable",D.unavailable)}};switch(l.method){case"host.hello":return{protocol:2,guest:m.guest,features:[...Ge],root:Xe(m.entry)};case"ui.progress":if(!we){if(l.value<0||l.value>1)throw new b("invalid","Progress is a number from 0 to 1.");L.progress?.(l.value)}return{completed:!0};case"app.save.get":{let u=await m.saveGet();return{value:u.value===null?null:w(u.value,He),savedAt:u.savedAt===null?null:w(u.savedAt,d=>{if(typeof d!="string"||d.length>30)throw Error();return d})}}case"app.save.set":{let u=Re(l.value);if(ke)throw new b("rate-limited","A save is already being written.");ke=!0;try{let{savedAt:d}=await m.saveSet(u);return{savedAt:w(d,x=>{if(typeof x!="string"||x.length>30)throw Error();return x})}}finally{ke=!1}}case"cards.list":{if(l.pack!==void 0&&!j(l.pack))throw new b("invalid",D.slug);let u=l.after===void 0?0:/^(?:0|[1-9]\d{0,5})$/.test(l.after)?Number(l.after):-1;if(u<0)throw new b("invalid",D.after);let d=await m.cards(),x=w(d,R=>{if(!Oe(R.revision)||!Array.isArray(R.cards))throw Error();return R.cards.map(Ie)});l.pack===void 0&&u===0&&(G={revision:d.revision,cards:new Map(x.map(R=>[R.id,R]))});let S=l.pack===void 0?x:x.filter(R=>R.pack===l.pack),B=u+A.cardsPage;return{cards:S.slice(u,B),after:B<S.length?String(B):null,revision:d.revision}}case"cards.packs":return{packs:w(await m.packs(),u=>{if(!Array.isArray(u)||u.length>200)throw Error();return u.map(Ke)})};case"cards.pack":if(!j(l.pack))throw new b("invalid",D.slug);return{pack:w(await m.pack(l.pack),u=>{let d=Ue(u);if(d.id!==l.pack)throw Error();return d})};case"cards.watch":return be=l.on,{completed:!0};case"pack.show":if(!j(l.pack))throw new b("invalid",D.slug);return await m.showPack(l.pack),{shown:!0};case"player.get":return w(await m.player(),Ze);case"display.maximize":return await m.maximize(l.on),{completed:!0};case"display.fullscreen":return await m.fullscreen(l.on),{completed:!0}}};h.onmessage=m=>{if(!F()){Ae();return}let l=N();if(l===void 0)return;if(l-z>=1e3&&(z=l,W=0),++W>k.requestsPerSecond||++O>T||ye>=(Z?A.inFlight:k.inFlight)||n&&!I(l)){H("App request limit exceeded.");return}let w,u;try{n?{id:w,request:u}=Et(pe(m.data,Z?A.messageBytes:k.requestBytes),M,Z):{id:w,request:u}=We(pe(m.data,k.requestBytes),M)}catch{H("Invalid or unpermitted app request.");return}if(n){if(!/^[1-9]\d{0,15}$/.test(w)||Number(w)<=Ne){H("App request was replayed.");return}Ne=Number(w)}else{if(Le.has(w)){H("App request was replayed.");return}Le.add(w)}if(u.method==="host.hello"){if(Z){H("App said hello twice.");return}Z=!0}ye++,n&&Te(l);let d=u.method,x=d==="ui.ready"||d==="game.finish"||d==="app.checkpoint.get"||d==="app.checkpoint.set";Promise.resolve().then(()=>{if(F()&&!(!ze()&&(d==="game.finish"||d==="app.checkpoint.set"))){if(x){let S;switch(u.method){case"ui.ready":we=!0,L.ready(),S={completed:!0};break;case"game.finish":if(i&&i.score!==u.score){if(!n)throw Error("This game has already finished.");ve({session:M,id:w,error:"This game has already finished.",code:"invalid"},k.responseBytes);return}i??=Object.freeze({score:u.score}),S={completed:!0};break;case"app.checkpoint.get":S={checkpoint:JSON.parse(s)};break;default:s=Pe(u.value),S={completed:!0};break}F()&&(h.postMessage(le({session:M,id:w,result:S},k.responseBytes)),d==="game.finish"&&i&&!a&&F()&&(a=!0,L.finish?.(i)));return}return st(w,u,d,l)}}).catch(()=>{U||H("App request could not complete.")}).finally(()=>{ye--})};let st=async(m,l,w,u)=>{let d=Ce(w),x;try{let S=we?ze()?"F":"B":"L";if(!d.states.includes(S))throw new b("not-permitted",D.states);if(d.rate&&!(l.method==="display.fullscreen"&&!l.on)){let R=$e.get(w);if(R||(R=Qe(d.rate[0],d.rate[1]),$e.set(w,R)),!R(u))throw new b("rate-limited",D.rate)}let B=await nt(r,l);if(re(JSON.stringify(B))>d.response)throw new b("unavailable","The answer is larger than this request may return.");x={session:M,id:m,result:B}}catch(S){let B=S instanceof b?S.code:"unavailable";x={session:M,id:m,error:S instanceof b?S.message.slice(0,300):D.unavailable,code:B}}ve(x,A.messageBytes)};return h.onmessageerror=()=>H("App message could not be decoded."),h.start(),xe},suspend(){p?.close()},dispose(){o||(o=!0,clearTimeout(K),clearTimeout(_),p?.close(),s="null")}};return n&&(ge.activity=()=>{let h=N();h!==void 0&&Te(h)},ge.cardsChanged=async()=>{try{await f?.()}catch{}}),ge}function tt(e,t){let r=se(window);if(r)throw Error(r);if(!Se(t.challenge)||new URL(e.src).hash!==`#${ae}=${t.challenge}`)throw Error("Invalid app frame challenge.");let n=t.controller.protocol===2,s=!1,o=!1,p=!1,i=0,a,c=!1,P=Y({active:!0,width:0,height:0}),z=()=>O("App took too long to become ready."),W=()=>{s||(s=!0,clearTimeout(g),clearTimeout(_),e.removeEventListener("load",V),window.removeEventListener("message",E),a?.close())},O=v=>{s||(W(),t.fault(v))},V=()=>{o?O("App navigation ended this session."):o=!0},E=v=>{if(s||p||!t.current()||v.source!==e.contentWindow)return;if(++i>32){O("App connection limit exceeded.");return}if(!o||v.origin!=="null")return;let f;try{f=pe(v.data,256)}catch{O("Invalid app connection message.");return}if(!f||typeof f!="object"||Array.isArray(f)||!("channel"in f)||f.channel!==Ee||!("type"in f)||f.type!=="connect"||!("challenge"in f)||f.challenge!==t.challenge||Object.keys(f).length!==3)return;p=!0,window.removeEventListener("message",E);let I=new MessageChannel,C=ce();try{if(a=t.controller.attach(I.port1,C,{current:t.current,foreground:t.foreground,ready(){c=!0,clearTimeout(g),clearTimeout(_),t.ready()},finish:t.finish,fault:O,progress(T){c||s||(clearTimeout(g),g=setTimeout(z,A.readyMs),t.progress?.(T))}}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:Ee,challenge:t.challenge,session:C,...n?{protocol:2}:{}},"*",[I.port2]),a.lifecycle(P)}catch{I.port1.close(),I.port2.close(),O("App connection could not complete.")}},g=setTimeout(z,A.readyMs),_=n?setTimeout(z,A.progressReadyMs):void 0;return e.addEventListener("load",V),window.addEventListener("message",E),{resize(v,f){P=Y({active:P.active,width:Math.min(4096,Math.max(0,Math.floor(v))),height:Math.min(4096,Math.max(0,Math.floor(f)))}),a?.lifecycle(P)},setActive(v){v!==P.active&&(P=Y({...P,active:v}),a?.lifecycle(P))},dispose:W}}function St(e){if(!e||typeof e!="object"||!("runtime"in e)||typeof e.runtime!="string")throw Error("Invalid preview metadata.");let t=e,r=(o,p)=>Array.isArray(o)&&o.length<=8&&o.every(p)?o:null,n=r(t.packs,j),s=r(t.network,o=>typeof o=="string");if(typeof t.name!="string"||typeof t.id!="string"||typeof t.entry!="string"||!Fe(t.entry)||!n||!s||!(t.cards==="none"||t.cards==="linked"||t.cards==="all"))throw Error("Invalid preview metadata.");return{name:t.name,runtime:e.runtime,id:t.id,entry:t.entry,packs:n,cards:t.cards,network:s}}var rt=e=>e.split("-").map(t=>t[0].toUpperCase()+t.slice(1)).join(" ");function Pt(e,t=Math.random){let r=e.packs.length?e.packs:e.cards==="all"?["preview-pack"]:[],n=r.map(i=>({id:i,name:rt(i),creator:"Preview",art:he(i),total:6,cards:Array.from({length:6},(a,c)=>({id:`${i}/c${c+1}`,pack:i,name:`${rt(i)} #${c+1}`,rarity:ue[c%ue.length],art:me(i,`c${c+1}`)}))})),s=new Map(n.flatMap(i=>i.cards.slice(0,3).map(a=>[a.id,1]))),o=1,p=i=>e.cards==="all"?r.includes(i):e.packs.includes(i);return{pack(i){let a=n.find(c=>c.id===i);if(!a||!p(i))throw new b("not-permitted","This app may not read that pack.");return a},cards(){if(e.cards==="none")throw new b("not-permitted","The manifest does not declare cards.");return{cards:n.flatMap(a=>a.cards.filter(c=>s.has(c.id)).map(c=>({...c,count:s.get(c.id)}))),revision:String(o)}},packs(){return n.map(({cards:i,...a})=>({...a,held:e.cards==="none"?0:i.filter(c=>s.has(c.id)).length}))},pull(){let i=n.flatMap(c=>c.cards);if(!i.length)return null;let a=i[Math.min(i.length-1,Math.floor(t()*i.length))];return s.set(a.id,(s.get(a.id)??0)+1),o++,a.name}}}function Mt(e,t){let r=`vmos-preview-save:${e}`,n={value:null,savedAt:null};return{get(){try{let s=t().getItem(r);if(s)return JSON.parse(s)}catch{}return n},set(s){n={value:s,savedAt:new Date().toISOString()};try{t().setItem(r,JSON.stringify(n))}catch{}return{savedAt:n.savedAt}}}}async function Rt(){let e=se(window);if(e)throw Error(e);let t=document.getElementById("surface"),r=document.getElementById("status"),n=document.getElementById("toggle"),s=document.getElementById("reset"),o=document.getElementById("pull"),p=document.getElementById("result"),i=document.getElementById("score");if(!t||!r||!p||!i||!(n instanceof HTMLButtonElement)||!(s instanceof HTMLButtonElement)||!(o instanceof HTMLButtonElement))throw Error("Preview controls are missing.");let a=St(await(await fetch("/preview.json",{credentials:"omit"})).json()),c=new URL(a.runtime);if(c.origin!==`http://localhost:${window.location.port}`||!/^\/game-assets\/[a-f0-9]{64}\//.test(c.pathname)||c.search||c.hash)throw Error("Invalid preview runtime.");let P=Pt(a),z=Mt(a.id,()=>window.localStorage),W=()=>{if(!navigator.userActivation?.isActive)throw new b("needs-click","That needs a fresh click in the app.")},O={guest:!1,entry:a.entry,async saveGet(){return z.get()},async saveSet(y){return z.set(y)},async cards(){return P.cards()},async packs(){return P.packs()},async pack(y){return P.pack(y)},async showPack(y){P.pack(y),W(),r.textContent=`VibeMarket would open the pack ${y} in its market window here.`},async player(){let y={guest:!1,handle:"preview_player",username:"preview",name:"Preview Player",picture:null};return a.network.length?{...y,token:"preview.not-a-real-token.unsigned",expiresAt:Date.now()+3e5}:y},async maximize(y){t.classList.toggle("maximized",y)},async fullscreen(y){if(!y){document.fullscreenElement&&await document.exitFullscreen();return}W(),await t.requestFullscreen()}},V=()=>et(void 0,{services:O,idle:()=>{r.textContent="Still playing? VibeMarket asks here after 15 minutes without input."}}),E=V(),g=null,_=null,v=null,f=!1,I=null,C=()=>{_?.dispose(),_=null,E.suspend(),v?.disconnect(),v=null,g?.remove(),g=null},T=()=>{if(C(),t.hidden=f||document.hidden||I!==null,p.hidden=!0,f||document.hidden){r.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}if(I){p.hidden=!1,i.textContent=String(I.score),r.textContent="Round complete. No Cash reward for this preview.";return}let y=ce(),K=new URL(c);K.hash=`${ae}=${y}`,g=document.createElement("iframe"),g.title="VibeMarket OS app",g.sandbox.add("allow-scripts","allow-pointer-lock"),g.allow="autoplay; gamepad",g.setAttribute("credentialless",""),g.referrerPolicy="no-referrer",g.src=K.href,t.appendChild(g),_=tt(g,{controller:E,challenge:y,current:()=>!f&&!document.hidden,ready:()=>{r.textContent="App ready \xB7 Minimize and restore to check its saved work."},progress:N=>{r.textContent=`Loading the isolated app\u2026 ${Math.round(N*100)}%`},finish:N=>{I=N,s.textContent="Play again",T()},fault:N=>{C(),E.dispose(),E=V(),r.textContent=N}}),v=new ResizeObserver(()=>{g&&_?.resize(g.clientWidth,g.clientHeight)}),v.observe(g),r.textContent="Loading the isolated app\u2026"};n.onclick=()=>{f=!f,n.textContent=f?"Restore":"Minimize",T()},s.onclick=()=>{C(),E.dispose(),E=V(),I=null,f=!1,n.textContent="Minimize",s.textContent="Close / reset",T()},o.onclick=()=>{let y=P.pull();r.textContent=y?`Pulled ${y}. The app hears about it through onCards.`:"This app links no packs and does not read all cards, so there is nothing to pull.",E.cardsChanged?.()};let ne=window.setInterval(()=>{navigator.userActivation?.isActive&&E.activity?.()},1e4);document.addEventListener("visibilitychange",T),window.addEventListener("pagehide",()=>{window.clearInterval(ne),C(),E.dispose(),document.removeEventListener("visibilitychange",T)},{once:!0}),T()}typeof window<"u"&&typeof document<"u"&&Rt().catch(e=>{let t=document.getElementById("status");t&&(t.textContent=e instanceof Error?e.message:"Preview failed.")});export{Pt as previewCatalog,St as previewMetadata,Mt as previewSaves,Rt as startPreviewParent};
1
+ var _e="vibemarket.game.v1";var gt=["127.0.0.1","localhost"],yt=["vibechain.com","www.vibechain.com"],wt=["__VM_STEAM__","__TAURI_INTERNALS__"],Ke=["__TAURI__","vibeNative","ReactNativeWebView"],kt=/\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i,bt="Third-party apps are available only on vibechain.com and in the local browser developer preview.",At="Third-party apps require a top-level browser host.",vt="Third-party apps are disabled in native shells until their IPC isolation is verified.";function Et({protocol:e,hostname:t,port:r}){return e==="http:"?gt.includes(t)?"local":null:e==="https:"&&yt.includes(t)&&r===""?"production":null}function Ue(e,t){let r=Object.getOwnPropertyDescriptor(e,t);return r&&"value"in r?r.value:void 0}var xt=Object.freeze({windows:1,macos:1,linux:1}),St=[["windows",/^Mozilla\/5\.0 \(Windows NT \d+\.\d+; Win64; x64\) AppleWebKit\/537\.36 \(KHTML, like Gecko\) Chrome\/\d+(?:\.\d+){3} Safari\/537\.36 Edg\/\d+(?:\.\d+){3}$/],["macos",/^Mozilla\/5\.0 \(Macintosh; Intel Mac OS X \d+(?:_\d+){1,2}\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)$/],["linux",/^Mozilla\/5\.0 \(X11; Linux (?:x86_64|aarch64)\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)(?: Version\/\d+(?:\.\d+){0,3} Safari\/\d+(?:\.\d+){0,3})?$/]];function Pt(e){return St.find(([,t])=>t.test(e))?.[0]??null}function Mt(e,t,r){let n=Ue(e,"__VM_STEAM__");if(typeof n!="object"||n===null)return!1;let o=Object.getPrototypeOf(n);if(o!==Object.prototype&&o!==null)return!1;if(Ue(n,"appFrames")===1)return!0;let s=Pt(t);return s!==null&&r[s]===1}function me(e,t=xt){let r=Et(e.location);if(r===null)return bt;if(e.top!==e.self)return At;let n=e.navigator.userAgent;return(r==="production"&&Mt(e,n,t)?Ke:[...wt,...Ke]).some(s=>s in e)||kt.test(n)?vt:null}function he(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 fe="vibexp";var v=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}),Ce=1e6,qe=1101024,Ie=e=>typeof e=="string"&&/^[1-9]\d{0,15}$/.test(e),Oe=e=>typeof e=="string"&&e.length<=Ce&&/^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 ge(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,"0")).join("")}function X(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 ye(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 se=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Z=(e,t)=>{let r=Object.keys(e);return r.length===t.length&&Reflect.ownKeys(e).length===r.length&&r.every(n=>t.includes(n)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,n)??{},"value"))};function Le(e){let t=0,r=0,n=(s,l)=>{if(++t>v.checkpointNodes||l>v.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>v.stringBytes)throw Error("App checkpoint string is too large.");let a=new TextEncoder().encode(s).byteLength;if(a>v.stringBytes||(r+=a)>v.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(s)){if(s.length>v.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 a=0;a<s.length;a++){let m=Object.getOwnPropertyDescriptor(s,a);if(!m||!("value"in m))throw Error("Sparse/accessor checkpoints are unsupported.");n(m.value,l+1)}return}if(!se(s))throw Error("App checkpoint must contain only JSON values.");let f=Object.keys(s);if(Reflect.ownKeys(s).length!==f.length)throw Error("Checkpoint properties must be enumerable strings.");if(f.length>v.objectKeys)throw Error("App checkpoint has too many keys.");for(let a of f){if(["__proto__","constructor","prototype"].includes(a)||a.length>128)throw Error("Invalid app checkpoint key.");if(r+=new TextEncoder().encode(a).byteLength,r>v.checkpointBytes)throw Error("App checkpoint keys are too large.");let m=Object.getOwnPropertyDescriptor(s,a);if(!m||!("value"in m))throw Error("App checkpoint accessors are unsupported.");n(m.value,l+1)}};n(e,0);let o=JSON.stringify(e);if(new TextEncoder().encode(o).byteLength>v.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return o}function Ne(e){return JSON.parse(Le(e))}function Ze(e,t){if(!se(e)||!Z(e,["id","session","request"])||e.session!==t||typeof e.id!="string"||e.id.length>80||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!se(e.request))throw Error("Invalid app session request.");let r=e.request;if(r.method==="app.frame"){if(!Z(r,["method","id","image"])||!Ie(r.id)||r.image!==null&&typeof r.image!="string")throw Error("Invalid app frame.");return{id:e.id,request:{method:"app.frame",id:r.id,image:r.image}}}if(X(e,v.requestBytes),r.method==="game.finish"&&Z(r,["method","score"]))return{id:e.id,request:{method:"game.finish",...he({score:r.score})}};if((r.method==="ui.ready"||r.method==="app.checkpoint.get")&&Z(r,["method"]))return{id:e.id,request:{method:r.method}};if(r.method==="app.checkpoint.set"&&Z(r,["method","value"]))return{id:e.id,request:{method:r.method,value:Ne(r.value)}};throw Error("This app has no permission for that method.")}var Gt=Object.freeze({muted:!1,volume:1});function we(e){if(!se(e)||!Z(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 ie(e){if(!se(e)||!Z(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 Jt={descriptionMin:40,descriptionMax:2e3,supportMax:200,screenshotsMin:1,screenshotsMax:4,iconSize:256,iconBytes:256*1024,screenshotBytes:1024*1024};var Kt={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},Ut={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},Rt={packs:3,network:8,packSlugMax:56},_t=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,j=e=>typeof e=="string"&&e.length<=Rt.packSlugMax&&_t.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 E=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:Ce,captureMs:1200,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4}),ke=["common","rare","epic","legendary","mythic"],$e=/^[A-Za-z0-9_-]{1,64}$/,ce=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}),ae=1024,le=Object.freeze({"host.hello":{request:256,response:ae,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*ae,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*ae,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*ae,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*ae,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"}}),Qe=Object.freeze(Object.keys(le).filter(e=>e!=="host.hello"&&e!=="card.show")),Ct=new TextEncoder,pe=e=>Ct.encode(e).byteLength,ee=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Y=(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));var w=class extends Error{code;constructor(t,r){super(r),this.name="AppHostError",this.code=t}};function ze(e){let t=o=>new w("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>E.saveDepth)throw t(`A save nests at most ${E.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 f=Object.getOwnPropertyDescriptor(o,l);if(!f||!("value"in f))throw t("A save's arrays cannot be sparse or have accessors.");r(f.value,s+1)}return}if(!ee(o))throw t("A save must contain only plain objects, arrays and JSON values.");for(let l of Reflect.ownKeys(o)){let f=Object.getOwnPropertyDescriptor(o,l);if(typeof l!="string"||!f||!("value"in f)||!f.enumerable)throw t("A save's properties must be plain enumerable data.");r(f.value,s+1)}}};r(e,1);let n=JSON.stringify(e);if(pe(n)>E.saveBytes)throw new w("too-large",`A save is at most ${E.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return n}function et(e){let t;try{t=JSON.parse(e)}catch{throw new w("invalid","The saved data is not JSON.")}return ze(t),t}var T=(e,t,r=0)=>typeof e=="string"&&e.length>=r&&e.length<=t,be=(e,t,r)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=r,It=e=>typeof e=="string"&&ke.includes(e),Fe=".bin",Ae=(e,t)=>`-/card/${e}/${t}${Fe}`,ve=e=>`-/cover/${e}${Fe}`,Ot=e=>`-/player/${e}${Fe}`;function tt(e,t){if(!ee(e)||!Y(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:r,pack:n,name:o,art:s}=e,l=typeof r=="string"?r.slice(r.indexOf("/")+1):"";if(!j(n)||r!==`${n}/${l}`||!$e.test(l)||!T(o,120)||!It(e.rarity)||t&&!be(e.count,1,1e6)||s!==null&&s!==Ae(n,l))throw Error("Invalid card.");return{id:r,pack:n,name:o,rarity:e.rarity,...t?{count:e.count}:{},art:s}}function Ve(e){return tt(e,!0)}function Tt(e){return tt(e,!1)}function rt(e){let{id:t,name:r,creator:n,art:o,total:s}=e;if(!j(t)||!T(r,120,1)||n!==null&&!T(n,64,1)||o!==null&&o!==ve(t)||!be(s,0,1e4))throw Error("Invalid pack.");return{id:t,name:r,creator:n,art:o,total:s}}function nt(e){if(!ee(e)||!Y(e,["id","name","creator","art","held","total"])||!be(e.held,0,1e4))throw Error("Invalid pack.");let t=rt(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function ot(e){if(!ee(e)||!Y(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=rt(e),r=e.cards.map(Tt);if(r.some(n=>n.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:r}}var Lt=/[\u0000-\u001F\u007F-\u009F]/,Ye=e=>typeof e=="string"&&ce.handle.test(e);function st(e){if(ee(e)&&Y(e,["guest"])&&e.guest===!0)return{guest:!0};if(!ee(e)||!Y(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:r,name:n,picture:o,token:s,expiresAt:l}=e;if(!Ye(t)||!T(n,ce.nameMax,1)||Lt.test(n)||r!==void 0&&(!Ye(r)||r===t)||o!==null&&o!==Ot(t)||"token"in e!="expiresAt"in e||s!==void 0&&(!T(s,ce.tokenMax,ce.tokenMin)||!ce.token.test(s)||!be(l,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...r===void 0?{}:{username:r},name:n,picture:o,...s===void 0?{}:{token:s,expiresAt:l}}}var je=e=>T(e,64,1);var it=e=>e.includes("/")?"../".repeat(e.split("/").length-1):"./";function at(e){let t=e.method,r=(...n)=>Y(e,["method",...n]);switch(t){case"ui.ready":case"app.checkpoint.get":return r()?{method:t}:null;case"game.finish":return r("score")?{method:t,...he({score:e.score})}:null;case"app.checkpoint.set":return r("value")?{method:t,value:Ne(e.value)}:null;case"host.hello":return r("protocol","sdk")&&e.protocol===2&&T(e.sdk,20,1)&&/^[\x20-\x7e]+$/.test(e.sdk)?{method:t,protocol:2,sdk:e.sdk}:null;case"ui.progress":return r("value")&&typeof e.value=="number"&&Number.isFinite(e.value)?{method:t,value:e.value}:null;case"app.frame":return r("id","image")&&Ie(e.id)&&(e.image===null||typeof e.image=="string")?{method:t,id:e.id,image:e.image}:null;case"app.save.get":case"cards.packs":case"player.get":return r()?{method:t}:null;case"app.save.set":return r("value")?{method:t,value:e.value}:null;case"cards.list":return!Y(e,["method"],["pack","after"])||"pack"in e&&!T(e.pack,64,1)||"after"in e&&!T(e.after,64,1)?null:{method:t,..."pack"in e?{pack:e.pack}:{},..."after"in e?{after:e.after}:{}};case"cards.pack":case"pack.show":return r("pack")&&T(e.pack,64,1)?{method:t,pack:e.pack}:null;case"card.show":return r("pack","card")&&T(e.pack,64,1)&&T(e.card,64,1)?{method:t,pack:e.pack,card:e.card}:null;case"display.maximize":case"display.fullscreen":case"cards.watch":return r("on")&&typeof e.on=="boolean"?{method:t,on:e.on}:null;default:return null}}function We(e){return Object.hasOwn(le,e)?le[e]:{request:v.requestBytes,response:v.responseBytes,states:"LFB"}}function Nt(e,t,r){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype||Object.keys(e).length!==3||!("session"in e)||e.session!==t||!("id"in e)||typeof e.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!("request"in e)||!e.request||typeof e.request!="object"||Array.isArray(e.request))throw Error("Invalid app session request.");let n=at(e.request),o=n!==null&&!Object.hasOwn(le,n.method);if(!n||!r&&!o&&n.method!=="host.hello"&&n.method!=="app.frame")throw Error("This app has no permission for that method.");if(pe(JSON.stringify(e.request))>We(n.method).request)throw Error("App request exceeds its bound.");return{id:e.id,request:n}}function ct(e,t){let r=[];return n=>(r=r.filter(o=>n-o<t),r.length>=e?!1:(r.push(n),!0))}var H={states:"That is not available while the app is loading or behind another window.",rate:"Too many requests of that kind; try again later.",slug:"That is not a pack slug.",after:"That page cursor is not valid.",unavailable:"The host could not answer that now; try again."};function lt(e=()=>performance.now(),t={}){let r=t.services,n=r!==void 0,o="null",s=!1,l,f,a=!1,m=e();if(!Number.isFinite(m))throw Error("App clock is invalid.");let d=m,R=m,I=0,J=0,O=m,z,L,P,A=!1,b,k=ct(E.requestsPerMinute,6e4),_=n?E.sessionMs:v.sessionMs,F=n?E.lifetimeRequests:v.lifetimeRequests,C=n?"App session reached its 4-hour limit. Reopen the app to keep playing.":"App session expired. Reopen the app.",W=p=>{if(s||z)return;z=p,clearTimeout(B),clearTimeout(P),o="null";let M=L;l?.close(),M?.(p)},B=setTimeout(()=>W(C),_),K=()=>{let p;try{p=e()}catch{W("App clock changed. Reopen the app.");return}if(!Number.isFinite(p)||p<d){W("App clock changed. Reopen the app.");return}if(d=p,p-m>=_){W(C);return}return p},te=p=>{clearTimeout(P),P=setTimeout(()=>{let M=K();if(M===void 0)return;let V=M-O;if(V<E.idleMs){te(E.idleMs-V);return}A||(A=!0,t.idle?.())},p)},g=p=>{O=p,A&&(A=!1,te(E.idleMs))};n&&te(E.idleMs);let D={protocol:n?2:1,attach(p,M,V){if(s||z||!Te(M))throw p.close(),Error(z??"App controller is closed.");if(K()===void 0)throw p.close(),Error(z);l?.close();let re=!1,Ee=0,ue=!1,xe=!1,Be=0,Se=!1,Pe=!1,U,De=new Set,Ge=new Map,mt=0,ne,Q=c=>{let i=ne;ne=void 0,i&&(clearTimeout(i.timer),i.resolve(c))},Me=()=>{Q(null),!re&&(re=!0,p.onmessage=null,p.onmessageerror=null,p.close(),l===Re&&(l=void 0,L=void 0,b=void 0))},q=c=>{re||(Me(),V.fault(c))},N=()=>!re&&!s&&V.current(),He=V.foreground??(()=>!0),oe=(c,i)=>{N()&&p.postMessage(X(c,i))},Re={lifecycle(c){N()&&p.postMessage(X({session:M,event:"app.lifecycle",state:ie(c)},v.responseBytes))},sound(c){oe({session:M,event:"app.sound",state:we(c)},256)},close:Me,capture(c=E.captureMs){if(Q(null),!N())return Promise.resolve(null);let i=String(++mt),y=typeof c=="number"&&Number.isFinite(c)?Math.max(0,c):E.captureMs;return new Promise(u=>{ne={id:i,resolve:u,timer:setTimeout(()=>{ne?.id===i&&Q(null)},y)};try{oe({session:M,event:"app.capture",id:i},256)}catch{Q(null)}})}};l=Re,L=V.fault,r&&(b=async()=>{if(!Pe||!U||!N())return;let c=await r.cards();if(!N()||!Pe||!U||!je(c.revision)||c.revision===U.revision)return;let i=new Map(c.cards.map(S=>{let x=Ve(S);return[x.id,x]})),y=[...i.values()].filter(S=>JSON.stringify(U.cards.get(S.id))!==JSON.stringify(S)),u=[...U.cards.keys()].filter(S=>!i.has(S)),h={changed:y,removed:u,revision:c.revision};pe(JSON.stringify(h))>E.cardsEventBytes&&(h={reset:!0,revision:c.revision}),U={revision:c.revision,cards:i},oe({session:M,event:"app.cards",state:h},E.cardsEventBytes+1024)});let Je=c=>{let i=ne?.id===c.id;if(c.image!==null&&!Oe(c.image))throw i&&Q(null),new w("invalid","That is not a PNG, JPEG or WebP data URL of at most 1,000,000 characters.");return i&&Q(c.image),{completed:!0}},ht=async(c,i)=>{let y=(u,h)=>{try{return h(u)}catch{throw new w("unavailable",H.unavailable)}};switch(i.method){case"host.hello":return{protocol:2,guest:c.guest,features:[...Qe,...c.showCard?["card.show"]:[]],root:it(c.entry)};case"ui.progress":if(!xe){if(i.value<0||i.value>1)throw new w("invalid","Progress is a number from 0 to 1.");V.progress?.(i.value)}return{completed:!0};case"app.frame":return Je(i);case"app.save.get":{let u=await c.saveGet();return{value:u.value===null?null:y(u.value,et),savedAt:u.savedAt===null?null:y(u.savedAt,h=>{if(typeof h!="string"||h.length>30)throw Error();return h})}}case"app.save.set":{let u=ze(i.value);if(Se)throw new w("rate-limited","A save is already being written.");Se=!0;try{let{savedAt:h}=await c.saveSet(u);return{savedAt:y(h,S=>{if(typeof S!="string"||S.length>30)throw Error();return S})}}finally{Se=!1}}case"cards.list":{if(i.pack!==void 0&&!j(i.pack))throw new w("invalid",H.slug);let u=i.after===void 0?0:/^(?:0|[1-9]\d{0,5})$/.test(i.after)?Number(i.after):-1;if(u<0)throw new w("invalid",H.after);let h=await c.cards(),S=y(h,$=>{if(!je($.revision)||!Array.isArray($.cards))throw Error();return $.cards.map(Ve)});i.pack===void 0&&u===0&&(U={revision:h.revision,cards:new Map(S.map($=>[$.id,$]))});let x=i.pack===void 0?S:S.filter($=>$.pack===i.pack),G=u+E.cardsPage;return{cards:x.slice(u,G),after:G<x.length?String(G):null,revision:h.revision}}case"cards.packs":return{packs:y(await c.packs(),u=>{if(!Array.isArray(u)||u.length>200)throw Error();return u.map(nt)})};case"cards.pack":if(!j(i.pack))throw new w("invalid",H.slug);return{pack:y(await c.pack(i.pack),u=>{let h=ot(u);if(h.id!==i.pack)throw Error();return h})};case"cards.watch":return Pe=i.on,{completed:!0};case"pack.show":if(!j(i.pack))throw new w("invalid",H.slug);return await c.showPack(i.pack),{shown:!0};case"card.show":if(!c.showCard)throw new w("unsupported","This host cannot show a card.");if(!j(i.pack)||!$e.test(i.card))throw new w("invalid","That is not a pack slug and a card id.");return await c.showCard(i.pack,i.card),{shown:!0};case"player.get":return y(await c.player(),st);case"display.maximize":return await c.maximize(i.on),{completed:!0};case"display.fullscreen":return await c.fullscreen(i.on),{completed:!0}}};p.onmessage=c=>{if(!N()){Me();return}let i=K();if(i===void 0)return;if(i-R>=1e3&&(R=i,I=0),++I>v.requestsPerSecond||++J>F||Ee>=(ue?E.inFlight:v.inFlight)||n&&!k(i)){q("App request limit exceeded.");return}let y,u;try{n?{id:y,request:u}=Nt(ye(c.data,E.messageBytes),M,ue):{id:y,request:u}=Ze(ye(c.data,qe),M)}catch{q("Invalid or unpermitted app request.");return}if(n){if(!/^[1-9]\d{0,15}$/.test(y)||Number(y)<=Be){q("App request was replayed.");return}Be=Number(y)}else{if(De.has(y)){q("App request was replayed.");return}De.add(y)}if(u.method==="host.hello"){if(ue){q("App said hello twice.");return}ue=!0}Ee++,n&&g(i);let h=u.method,S=h==="ui.ready"||h==="game.finish"||h==="app.checkpoint.get"||h==="app.checkpoint.set";Promise.resolve().then(()=>{if(N()&&!(!He()&&(h==="game.finish"||h==="app.checkpoint.set"))){if(u.method==="app.frame"&&!n){try{let x=Je(u);N()&&p.postMessage(X({session:M,id:y,result:x},v.responseBytes))}catch(x){N()&&p.postMessage(X({session:M,id:y,error:x.message,code:"invalid"},v.responseBytes))}return}if(S){let x;switch(u.method){case"ui.ready":xe=!0,V.ready(),x={completed:!0};break;case"game.finish":if(f&&f.score!==u.score){if(!n)throw Error("This game has already finished.");oe({session:M,id:y,error:"This game has already finished.",code:"invalid"},v.responseBytes);return}f??=Object.freeze({score:u.score}),x={completed:!0};break;case"app.checkpoint.get":x={checkpoint:JSON.parse(o)};break;default:o=Le(u.value),x={completed:!0};break}N()&&(p.postMessage(X({session:M,id:y,result:x},v.responseBytes)),h==="game.finish"&&f&&!a&&N()&&(a=!0,V.finish?.(f)));return}return ft(y,u,h,i)}}).catch(()=>{re||q("App request could not complete.")}).finally(()=>{Ee--})};let ft=async(c,i,y,u)=>{let h=We(y),S;try{let x=xe?He()?"F":"B":"L";if(!h.states.includes(x))throw new w("not-permitted",H.states);if(h.rate&&!(i.method==="display.fullscreen"&&!i.on)){let $=h.bucket??y,de=Ge.get($);if(de||(de=ct(h.rate[0],h.rate[1]),Ge.set($,de)),!de(u))throw new w("rate-limited",H.rate)}let G=await ht(r,i);if(pe(JSON.stringify(G))>h.response)throw new w("unavailable","The answer is larger than this request may return.");S={session:M,id:c,result:G}}catch(x){let G=x instanceof w?x.code:"unavailable";S={session:M,id:c,error:x instanceof w?x.message.slice(0,300):H.unavailable,code:G}}oe(S,E.messageBytes)};return p.onmessageerror=()=>q("App message could not be decoded."),p.start(),Re},suspend(){l?.close()},dispose(){s||(s=!0,clearTimeout(B),clearTimeout(P),l?.close(),o="null")}};return n&&(D.activity=()=>{let p=K();p!==void 0&&g(p)},D.cardsChanged=async()=>{try{await b?.()}catch{}}),D}function pt(e,t){let r=me(window);if(r)throw Error(r);if(!Te(t.challenge)||new URL(e.src).hash!==`#${fe}=${t.challenge}`)throw Error("Invalid app frame challenge.");let n=t.controller.protocol===2,o=!1,s=!1,l=!1,f=0,a,m=!1,d=ie({active:!0,width:0,height:0}),R=t.sound===void 0?null:we(t.sound),I=()=>O("App took too long to become ready."),J=()=>{o||(o=!0,clearTimeout(P),clearTimeout(A),e.removeEventListener("load",z),window.removeEventListener("message",L),a?.close())},O=b=>{o||(J(),t.fault(b))},z=()=>{s?O("App navigation ended this session."):s=!0},L=b=>{if(o||l||!t.current()||b.source!==e.contentWindow)return;if(++f>32){O("App connection limit exceeded.");return}if(!s||b.origin!=="null")return;let k;try{k=ye(b.data,256)}catch{O("Invalid app connection message.");return}if(!k||typeof k!="object"||Array.isArray(k)||!("channel"in k)||k.channel!==_e||!("type"in k)||k.type!=="connect"||!("challenge"in k)||k.challenge!==t.challenge||Object.keys(k).length!==3)return;l=!0,window.removeEventListener("message",L);let _=new MessageChannel,F=ge();try{if(a=t.controller.attach(_.port1,F,{current:t.current,foreground:t.foreground,ready(){m=!0,clearTimeout(P),clearTimeout(A),t.ready()},finish:t.finish,fault:O,progress(C){m||o||(clearTimeout(P),P=setTimeout(I,E.readyMs),t.progress?.(C))}}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:_e,challenge:t.challenge,session:F,...n?{protocol:2}:{}},"*",[_.port2]),a.lifecycle(d),R&&a.sound(R)}catch{_.port1.close(),_.port2.close(),O("App connection could not complete.")}},P=setTimeout(I,E.readyMs),A=n?setTimeout(I,E.progressReadyMs):void 0;return e.addEventListener("load",z),window.addEventListener("message",L),{resize(b,k){d=ie({active:d.active,width:Math.min(4096,Math.max(0,Math.floor(b))),height:Math.min(4096,Math.max(0,Math.floor(k)))}),a?.lifecycle(d)},setActive(b){b!==d.active&&(d=ie({...d,active:b}),a?.lifecycle(d))},setSound(b){let k=we(b);R&&R.muted===k.muted&&R.volume===k.volume||(R=k,a?.sound(k))},dispose:J,capture(b){return o||!a?Promise.resolve(null):a.capture(b)}}}function $t(e){if(!e||typeof e!="object"||!("runtime"in e)||typeof e.runtime!="string")throw Error("Invalid preview metadata.");let t=e,r=(s,l)=>Array.isArray(s)&&s.length<=8&&s.every(l)?s:null,n=r(t.packs,j),o=r(t.network,s=>typeof s=="string");if(typeof t.name!="string"||typeof t.id!="string"||typeof t.entry!="string"||!Xe(t.entry)||!n||!o||!(t.cards==="none"||t.cards==="linked"||t.cards==="all"))throw Error("Invalid preview metadata.");return{name:t.name,runtime:e.runtime,id:t.id,entry:t.entry,packs:n,cards:t.cards,network:o}}var ut=e=>e.split("-").map(t=>t[0].toUpperCase()+t.slice(1)).join(" "),dt="preview-public";function zt(e,t=Math.random){let r=e.packs.length?e.packs:e.cards==="all"?["preview-pack"]:[],n=a=>({id:a,name:ut(a),creator:"Preview",art:ve(a),total:6,cards:Array.from({length:6},(m,d)=>({id:`${a}/c${d+1}`,pack:a,name:`${ut(a)} #${d+1}`,rarity:ke[d%ke.length],art:Ae(a,`c${d+1}`)}))}),o=r.map(n),s=[...o,...r.includes(dt)?[]:[n(dt)]],l=new Map(o.flatMap(a=>a.cards.slice(0,3).map(m=>[m.id,1]))),f=1;return{pack(a){let m=s.find(d=>d.id===a);if(!m)throw new w("invalid","There is no such public pack.");return m},card(a,m){let d=this.pack(a).cards.find(R=>R.id===`${a}/${m}`);if(!d)throw new w("invalid","That card is not in that pack.");return d},cards(){if(e.cards==="none")throw new w("not-permitted","The manifest does not declare cards.");return{cards:o.flatMap(m=>m.cards.filter(d=>l.has(d.id)).map(d=>({...d,count:l.get(d.id)}))),revision:String(f)}},packs(){return o.map(({cards:a,...m})=>({...m,held:e.cards==="none"?0:a.filter(d=>l.has(d.id)).length}))},pull(){let a=o.flatMap(d=>d.cards);if(!a.length)return null;let m=a[Math.min(a.length-1,Math.floor(t()*a.length))];return l.set(m.id,(l.get(m.id)??0)+1),f++,m.name}}}function Ft(e,t){let r=`vmos-preview-save:${e}`,n={value:null,savedAt:null};return{get(){try{let o=t().getItem(r);if(o)return JSON.parse(o)}catch{}return n},set(o){n={value:o,savedAt:new Date().toISOString()};try{t().setItem(r,JSON.stringify(n))}catch{}return{savedAt:n.savedAt}}}}async function Vt(){let e=me(window);if(e)throw Error(e);let t=document.getElementById("surface"),r=document.getElementById("status"),n=document.getElementById("toggle"),o=document.getElementById("reset"),s=document.getElementById("pull"),l=document.getElementById("sound"),f=document.getElementById("volume"),a=document.getElementById("result"),m=document.getElementById("score");if(!t||!r||!a||!m||!(n instanceof HTMLButtonElement)||!(o instanceof HTMLButtonElement)||!(s instanceof HTMLButtonElement)||!(l instanceof HTMLButtonElement)||!(f instanceof HTMLInputElement))throw Error("Preview controls are missing.");let d=$t(await(await fetch("/preview.json",{credentials:"omit"})).json()),R=new URL(d.runtime);if(R.origin!==`http://localhost:${window.location.port}`||!/^\/game-assets\/[a-f0-9]{64}\//.test(R.pathname)||R.search||R.hash)throw Error("Invalid preview runtime.");let I=zt(d),J=Ft(d.id,()=>window.localStorage),O=()=>{if(!navigator.userActivation?.isActive)throw new w("needs-click","That needs a fresh click in the app.")},z={guest:!1,entry:d.entry,async saveGet(){return J.get()},async saveSet(g){return J.set(g)},async cards(){return I.cards()},async packs(){return I.packs()},async pack(g){return I.pack(g)},async showPack(g){I.pack(g),O(),r.textContent=`VibeMarket would open the pack ${g} in its market window here.`},async showCard(g,D){let p=I.card(g,D);O(),r.textContent=`VibeMarket would open the card ${p.name} (${D}) on the pack ${g}'s page here.`},async player(){let g={guest:!1,handle:"preview_player",username:"preview",name:"Preview Player",picture:null};return d.network.length?{...g,token:"preview.not-a-real-token.unsigned",expiresAt:Date.now()+3e5}:g},async maximize(g){t.classList.toggle("maximized",g)},async fullscreen(g){if(!g){document.fullscreenElement&&await document.exitFullscreen();return}O(),await t.requestFullscreen()}},L=()=>lt(void 0,{services:z,idle:()=>{r.textContent="Still playing? VibeMarket asks here after 15 minutes without input."}}),P=L(),A=null,b=null,k=null,_=!1,F=null,C={muted:!1,volume:1},W=()=>{b?.dispose(),b=null,P.suspend(),k?.disconnect(),k=null,A?.remove(),A=null},B=()=>{if(W(),t.hidden=_||document.hidden||F!==null,a.hidden=!0,_||document.hidden){r.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}if(F){a.hidden=!1,m.textContent=String(F.score),r.textContent="Round complete. No Cash reward for this preview.";return}let g=ge(),D=new URL(R);D.hash=`${fe}=${g}`,A=document.createElement("iframe"),A.title="VibeMarket OS app",A.sandbox.add("allow-scripts","allow-pointer-lock"),A.allow="autoplay; gamepad",A.setAttribute("credentialless",""),A.referrerPolicy="no-referrer",A.src=D.href,t.appendChild(A),b=pt(A,{controller:P,challenge:g,sound:C,current:()=>!_&&!document.hidden,ready:()=>{r.textContent="App ready \xB7 Minimize and restore to check its saved work."},progress:p=>{r.textContent=`Loading the isolated app\u2026 ${Math.round(p*100)}%`},finish:p=>{F=p,o.textContent="Play again",B()},fault:p=>{W(),P.dispose(),P=L(),r.textContent=p}}),k=new ResizeObserver(()=>{A&&b?.resize(A.clientWidth,A.clientHeight)}),k.observe(A),r.textContent="Loading the isolated app\u2026"};n.onclick=()=>{_=!_,n.textContent=_?"Restore":"Minimize",B()},o.onclick=()=>{W(),P.dispose(),P=L(),F=null,_=!1,n.textContent="Minimize",o.textContent="Close / reset",B()};let K=g=>{C=g,b?.setSound(C),l.textContent=C.muted?"Sound off":"Sound on",l.setAttribute("aria-pressed",String(!C.muted)),r.textContent=C.muted?"Desktop sound off: the app must be silent.":`Desktop sound on at ${Math.round(C.volume*100)}%: the app follows this volume.`};l.onclick=()=>K({muted:!C.muted,volume:C.volume}),f.oninput=()=>K({muted:C.muted,volume:Math.min(1,Math.max(0,Number(f.value)/100))}),s.onclick=()=>{let g=I.pull();r.textContent=g?`Pulled ${g}. The app hears about it through onCards.`:"This app links no packs and does not read all cards, so there is nothing to pull.",P.cardsChanged?.()};let te=window.setInterval(()=>{navigator.userActivation?.isActive&&P.activity?.()},1e4);document.addEventListener("visibilitychange",B),window.addEventListener("pagehide",()=>{window.clearInterval(te),W(),P.dispose(),document.removeEventListener("visibilitychange",B)},{once:!0}),B()}typeof window<"u"&&typeof document<"u"&&Vt().catch(e=>{let t=document.getElementById("status");t&&(t.textContent=e instanceof Error?e.message:"Preview failed.")});export{dt as PREVIEW_PUBLIC_PACK,zt as previewCatalog,$t as previewMetadata,Ft as previewSaves,Vt as startPreviewParent};
package/dist/preview.js CHANGED
@@ -6,7 +6,7 @@ import { appRuntimeCsp, appRuntimeHeaders } from "./runtime-policy.js";
6
6
  import { CARD_ID } from "./app-wire.js";
7
7
  import { packSlug } from "./manifest.js";
8
8
  const CSS = `body{margin:0;background:#387bd8;font:14px Arial;color:#17233a}main{max-width:1000px;margin:40px auto}header{display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:space-between;background:linear-gradient(#1684ff,#0049d9);color:white;padding:8px;border-radius:8px 8px 0 0}h1{font-size:15px;margin:0}.frame{background:#ece9d8;border:3px solid #0059e9;min-height:520px}iframe{border:0;width:100%;height:540px;display:block}button{padding:6px 12px}#status{padding:10px;background:#ece9d8;margin:0}small{display:block;padding:12px;color:#fff}#result{background:#ece9d8;border:3px solid #0059e9;text-align:center;padding:48px 24px;min-height:300px}#result h2{font-size:32px;margin:0 0 24px}#score{display:block;font-size:clamp(32px,10vw,72px);overflow-wrap:anywhere;max-width:100%;color:#176844;margin:16px}.maximized iframe{height:calc(100vh - 140px)}#surface:fullscreen iframe{height:100vh}`;
9
- const HTML = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>VibeMarket OS App Preview</title><link rel="stylesheet" href="/preview.css"></head><body><main><header><h1>VibeMarket OS · App Preview</h1><div><button id="toggle" type="button">Minimize</button> <button id="pull" type="button">Pull a card</button> <button id="reset" type="button">Close / reset</button></div></header><div id="surface" class="frame"></div><section id="result" hidden aria-label="Game results"><h2>Round complete</h2><p>Your score: <strong id="score"></strong></p><p>No Cash reward for this preview.</p></section><p id="status" role="status">Loading the isolated app…</p><small>Local development only · fake cards, a fake player token and a save kept in this browser; no account, Cash, Steam or wallet. Build again and restart this preview to load changed files.</small></main><script type="module" src="/sdk/preview-ui.js"></script></body></html>`;
9
+ const HTML = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>VibeMarket OS App Preview</title><link rel="stylesheet" href="/preview.css"></head><body><main><header><h1>VibeMarket OS · App Preview</h1><div><button id="toggle" type="button">Minimize</button> <button id="pull" type="button">Pull a card</button> <button id="sound" type="button" aria-pressed="true">Sound on</button> <input id="volume" type="range" min="0" max="100" value="100" aria-label="Desktop volume"> <button id="reset" type="button">Close / reset</button></div></header><div id="surface" class="frame"></div><section id="result" hidden aria-label="Game results"><h2>Round complete</h2><p>Your score: <strong id="score"></strong></p><p>No Cash reward for this preview.</p></section><p id="status" role="status">Loading the isolated app…</p><small>Local development only · fake cards, a fake player token and a save kept in this browser; no account, Cash, Steam or wallet. Build again and restart this preview to load changed files.</small></main><script type="module" src="/sdk/preview-ui.js"></script></body></html>`;
10
10
  const MODULES = new Set(["preview-ui.js"]);
11
11
  /** One immutable in-memory bundle. No file serving by arbitrary URL, proxy, credential or write endpoint. */
12
12
  export async function startAppPreview(directory, port = 0) {
@@ -2,7 +2,9 @@
2
2
  (() => {
3
3
  VibemarketOS.connect().then(async (os) => {
4
4
  const cat = document.getElementById("cat");
5
- const best = (await os.load())?.best ?? 0;
5
+ if (!(cat instanceof HTMLButtonElement)) return;
6
+ const saved = await os.load();
7
+ const best = saved !== null && typeof saved === "object" && "best" in saved && typeof saved.best === "number" ? saved.best : 0;
6
8
  let taps = 0;
7
9
  cat.onclick = () => {
8
10
  taps++;
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type AppLifecycle, type AppValue, type VibeMarketAppSdk } from "./app-protocol.ts";
1
+ import { type AppLifecycle, type AppSound, type AppValue, type VibeMarketAppSdk } from "./app-protocol.ts";
2
2
  import { type Card, type Pack } from "./app-wire.ts";
3
3
  import { type GameFinishInput } from "./completion.ts";
4
4
  import { type Os } from "./os.ts";
@@ -7,12 +7,16 @@ export interface FakeAppOptions {
7
7
  checkpoint?: AppValue;
8
8
  /** Starting lifecycle. Default: active, 800 x 600. */
9
9
  lifecycle?: Partial<AppLifecycle>;
10
+ /** The desktop's sound at the start. Default: audible at full volume, as on a host that does not control sound. */
11
+ sound?: Partial<AppSound>;
10
12
  }
11
13
  export interface FakeApp {
12
14
  /** Pass this wherever your game expects the result of `connectVibeMarketApp()`. */
13
15
  readonly app: VibeMarketAppSdk;
14
16
  /** Change the lifecycle as the host would (minimize, restore, resize) and notify listeners. */
15
17
  setLifecycle(next: Partial<AppLifecycle>): void;
18
+ /** Change the desktop's sound as the taskbar speaker or volume would, and notify `sound.onChanged` listeners. */
19
+ setSound(next: Partial<AppSound>): void;
16
20
  /** True once the game called `ready()`. */
17
21
  readonly ready: boolean;
18
22
  /** The score the game finished with, or null. */
@@ -34,7 +38,7 @@ export interface FakeOsOptions {
34
38
  save?: unknown;
35
39
  /** The cards the player holds. `art` may be any URL or null. */
36
40
  cards?: readonly Card[];
37
- /** Public card lists of the packs the game can look at (`pack`, and `packs` for held counts). */
41
+ /** Every public pack the fake knows: `pack`, `showPack`, `showCard` and `open` work for any of them; `packs()` lists the readable ones. */
38
42
  packs?: readonly Pack[];
39
43
  /** The manifest's `cards` and `packs`. Default: `"none"` and `[]` (then `cards()` answers `not-permitted`). */
40
44
  access?: {
@@ -54,6 +58,8 @@ export interface FakeOsOptions {
54
58
  };
55
59
  /** Starting lifecycle. Default: active, 800 x 600. */
56
60
  lifecycle?: Partial<AppLifecycle>;
61
+ /** The desktop's sound at the start. Default: audible at full volume, as on a host that does not control sound. */
62
+ sound?: Partial<AppSound>;
57
63
  /** 1 behaves like a host older than 0.5: saves are the 32 KiB checkpoint and the rest is `unsupported`. Default 2. */
58
64
  protocol?: 1 | 2;
59
65
  /** The clock `player()` stamps expiry with. Default `Date.now`. */
@@ -66,6 +72,8 @@ export interface FakeOs {
66
72
  setCards(cards: readonly Card[]): void;
67
73
  /** Change the lifecycle as the host would (minimize, restore, resize) and call the pause, resume and resize listeners. */
68
74
  setLifecycle(next: Partial<AppLifecycle>): void;
75
+ /** Change the desktop's sound as the taskbar speaker or volume would, and call the `onSound` listeners. */
76
+ setSound(next: Partial<AppSound>): void;
69
77
  /** The next `showPack` or `fullscreen` call counts as following a click in the app. */
70
78
  click(): void;
71
79
  readonly ready: boolean;
@@ -78,6 +86,11 @@ export interface FakeOs {
78
86
  readonly finished: Readonly<GameFinishInput> | null;
79
87
  /** Packs the game asked the host to show, in order. */
80
88
  readonly shownPacks: readonly string[];
89
+ /** Cards the game asked the host to show (`showCard`, or `open` of a card link), in order. */
90
+ readonly shownCards: readonly {
91
+ pack: string;
92
+ card: string;
93
+ }[];
81
94
  readonly maximized: boolean;
82
95
  readonly fullscreen: boolean;
83
96
  readonly closed: boolean;