@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.
package/dist/os.js CHANGED
@@ -4,15 +4,15 @@
4
4
  * window-only checkpoint) and the rest reject with `unsupported`. Every rejection is an OsError with a stable code.
5
5
  */
6
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";
7
+ import { APP_METHODS_2, APP_SESSION_LIMITS, APPS4_LIMITS, AppHostError, CARD_ID, FINISH_BOARD_FEATURE, OsError, PLAYER_RULES, apps4Problem, osErrorCode, saveJson, saveValue, wireAchievement, wireCard, wireCardsEvent, wireFriend, wireHello, wireInvite, wireLeaderboard, wirePack, wirePackSummary, wirePlayer, wireProduct, wireReceipt, } from "./app-wire.js";
8
8
  import { createCapturer } from "./capture.js";
9
9
  import { gameFinishInput } from "./completion.js";
10
- import { packSlug } from "./manifest.js";
10
+ import { packSlug, serviceId } from "./manifest.js";
11
11
  import { connectHostPort, createRpcTransport } from "./transport.js";
12
12
  import { parseVmosLink } from "./links.js";
13
13
  export { OS_ERROR_CODES } from "./app-wire.js";
14
- /** The SDK version a 0.5 client reports in `host.hello`. */
15
- export const OS_SDK_VERSION = "0.5.2";
14
+ /** The SDK version a client reports in `host.hello`. */
15
+ export const OS_SDK_VERSION = "0.6.0";
16
16
  export { OsError } from "./app-wire.js";
17
17
  /** What each code means, as the SDK's own rejections say it (also the agent skill's error table). */
18
18
  export const OS_ERROR_MESSAGES = Object.freeze({
@@ -25,6 +25,10 @@ export const OS_ERROR_MESSAGES = Object.freeze({
25
25
  unavailable: "The host could not answer now; try again.",
26
26
  timeout: "The host did not answer in 10 seconds.",
27
27
  closed: "The session ended. Reopen the app.",
28
+ cancelled: "The player closed the dialog without confirming.",
29
+ insufficient: "The player does not have enough Printer Cash for that.",
30
+ limit: "A limit was reached; try again another day.",
31
+ guest: "Guests cannot do that; the player has to sign in.",
28
32
  });
29
33
  const MESSAGES = OS_ERROR_MESSAGES;
30
34
  const fail = (code, message = MESSAGES[code]) => new OsError(code, message);
@@ -76,6 +80,10 @@ export async function createOs(port, session, protocol, href) {
76
80
  soundEvent(value.state);
77
81
  return;
78
82
  }
83
+ if (value.event === "app.invite") {
84
+ inviteEvent(value.state);
85
+ return;
86
+ }
79
87
  if (value.event !== "app.lifecycle")
80
88
  return;
81
89
  let next;
@@ -99,10 +107,10 @@ export async function createOs(port, session, protocol, href) {
99
107
  },
100
108
  });
101
109
  const capturer = createCapturer((id, image) => { call({ method: "app.frame", id, image }).catch(() => { }); }, () => protocol !== 2 || !hello || closed);
102
- const call = async (request) => {
110
+ const call = async (request, timeoutMs) => {
103
111
  if (closed)
104
112
  throw fail("closed");
105
- const result = await transport.request(request);
113
+ const result = await transport.request(request, timeoutMs === undefined ? {} : { timeoutMs });
106
114
  if (!result || typeof result !== "object" || Array.isArray(result))
107
115
  throw fail("unavailable", "Invalid host response.");
108
116
  return result;
@@ -136,6 +144,49 @@ export async function createOs(port, session, protocol, href) {
136
144
  }
137
145
  const v2 = () => { if (!hello)
138
146
  throw fail("unsupported"); return hello; };
147
+ const has = (feature) => hello?.features.includes(feature) === true;
148
+ // ---- 0.6: a method its host did not list is answered here, never sent (an older host ends the session on it)
149
+ const call4 = async (request) => {
150
+ const problem = apps4Problem(request);
151
+ if (problem)
152
+ throw fail("invalid", problem);
153
+ if (!has(request.method))
154
+ throw fail("unsupported");
155
+ return call(request, APP_METHODS_2[request.method].surface ? APP_SESSION_LIMITS.surfaceMs : undefined);
156
+ };
157
+ /** An options object: undefined, or a plain object with only `keys`; keys set to undefined are left out. */
158
+ const options = (value, keys) => {
159
+ if (value === undefined)
160
+ return {};
161
+ if (value === null || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some(key => !keys.includes(key)))
162
+ throw fail("invalid", `The options are an object with ${keys.join(", ")}.`);
163
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
164
+ };
165
+ const text = (value, what) => { if (typeof value !== "string")
166
+ throw fail("invalid", `${what} is a string.`); return value; };
167
+ const people = (item) => ({ ...item, picture: absolute(item.picture) });
168
+ const invites = new Set();
169
+ /** Declared ahead so the transport can call it. */
170
+ function inviteEvent(value) {
171
+ let invite;
172
+ try {
173
+ invite = wireInvite(value);
174
+ }
175
+ catch {
176
+ return;
177
+ }
178
+ for (const listener of [...invites])
179
+ listener({ ...invite });
180
+ }
181
+ // the launch invite is read once, here; a host without it (or a failed read) means none
182
+ let launch = Object.freeze({ invite: null });
183
+ if (has("app.launch")) {
184
+ try {
185
+ const invite = (await call({ method: "app.launch" })).invite;
186
+ launch = Object.freeze({ invite: invite === null ? null : Object.freeze(wireInvite(invite)) });
187
+ }
188
+ catch { /* no invite */ }
189
+ }
139
190
  const absolute = (art) => art === null ? null : new URL(v2().root + art, href).href;
140
191
  const card = (wire) => ({ ...wire, art: absolute(wire.art) });
141
192
  // ---- cards: whole-list paging and live updates
@@ -331,7 +382,13 @@ export async function createOs(port, session, protocol, href) {
331
382
  async open(link) {
332
383
  const target = parseVmosLink(link);
333
384
  if (!target)
334
- throw fail("invalid", "That is not a vmOS pack or card link.");
385
+ throw fail("invalid", "That is not a vmOS pack, card or app link.");
386
+ if (target.kind === "app") {
387
+ v2();
388
+ if ((await call4({ method: "app.show", app: target.app })).shown !== true)
389
+ throw fail("unavailable", "Invalid host acknowledgement.");
390
+ return;
391
+ }
335
392
  await (target.kind === "pack" ? show({ method: "pack.show", pack: target.pack }) : show({ method: "card.show", pack: target.pack, card: target.card }));
336
393
  },
337
394
  async player() {
@@ -348,14 +405,94 @@ export async function createOs(port, session, protocol, href) {
348
405
  return { ...player };
349
406
  },
350
407
  async finish(result) {
351
- let input;
408
+ let input, board;
352
409
  try {
353
- input = gameFinishInput(result);
410
+ const { board: named, ...rest } = (result && typeof result === "object" ? result : {});
411
+ if (named !== undefined && !serviceId(named))
412
+ throw fail("invalid", "That is not a board id.");
413
+ board = named;
414
+ input = gameFinishInput(result && typeof result === "object" ? rest : result);
354
415
  }
355
416
  catch (error) {
356
417
  throw asOsError(error, "invalid");
357
418
  }
358
- completed(await call({ method: "game.finish", ...input }));
419
+ // a host that cannot post to a board still ends the round: the score goes without it
420
+ completed(await call({ method: "game.finish", ...input, ...(board !== undefined && has(FINISH_BOARD_FEATURE) ? { board } : {}) }));
421
+ },
422
+ async leaderboard(given) {
423
+ const asked = options(given, ["board", "scope", "period", "limit"]);
424
+ const request = { method: "leaderboard.get", ...asked };
425
+ const result = await call4(request);
426
+ const board = wireLeaderboard(result.leaderboard, { board: asked.board ?? "score", period: asked.period ?? "all", limit: asked.limit ?? APPS4_LIMITS.boardRowsDefault });
427
+ return { ...board, entries: board.entries.map(people) };
428
+ },
429
+ async showLeaderboard(board) {
430
+ const result = await call4({ method: "leaderboard.show", ...(board === undefined ? {} : { board: text(board, "A board id") }) });
431
+ if (result.shown !== true)
432
+ throw fail("unavailable", "Invalid host acknowledgement.");
433
+ },
434
+ async unlock(id) {
435
+ const result = await call4({ method: "achievement.unlock", id: text(id, "An achievement id") });
436
+ if (typeof result.unlocked !== "boolean")
437
+ throw fail("unavailable", "Invalid host response.");
438
+ return { unlocked: result.unlocked };
439
+ },
440
+ async achievements() {
441
+ const result = await call4({ method: "achievements.list" });
442
+ if (!Array.isArray(result.achievements))
443
+ throw fail("unavailable", "Invalid host response.");
444
+ return result.achievements.map(item => { const achievement = wireAchievement(item); return { ...achievement, icon: absolute(achievement.icon) }; });
445
+ },
446
+ async friends() {
447
+ const result = await call4({ method: "friends.list" });
448
+ if (!Array.isArray(result.friends))
449
+ throw fail("unavailable", "Invalid host response.");
450
+ return result.friends.map(item => people(wireFriend(item)));
451
+ },
452
+ async invite(given) {
453
+ const result = await call4({ method: "invite.open", ...options(given, ["to", "text", "data"]) });
454
+ if (typeof result.sent !== "number" || !Number.isInteger(result.sent) || result.sent < 0 || result.sent > APPS4_LIMITS.inviteRecipients)
455
+ throw fail("unavailable", "Invalid host response.");
456
+ return { sent: result.sent };
457
+ },
458
+ get launch() { return launch; },
459
+ onInvite(listener) {
460
+ if (typeof listener !== "function")
461
+ throw fail("invalid", "An invite listener is a function.");
462
+ invites.add(listener);
463
+ return () => { invites.delete(listener); };
464
+ },
465
+ async share(given) {
466
+ const result = await call4({ method: "share.open", ...options(given, ["text", "score", "board"]) });
467
+ if (typeof result.shared !== "boolean")
468
+ throw fail("unavailable", "Invalid host response.");
469
+ return { shared: result.shared };
470
+ },
471
+ async products() {
472
+ const result = await call4({ method: "products.list" });
473
+ if (!Array.isArray(result.products))
474
+ throw fail("unavailable", "Invalid host response.");
475
+ return result.products.map(wireProduct);
476
+ },
477
+ async buy(productId) {
478
+ const product = text(productId, "A product id");
479
+ const receipt = wireReceipt((await call4({ method: "product.buy", product })).receipt);
480
+ if (receipt.product !== product)
481
+ throw fail("unavailable", "Invalid host response.");
482
+ return receipt;
483
+ },
484
+ async purchases() {
485
+ const result = await call4({ method: "purchases.list" });
486
+ if (!Array.isArray(result.purchases))
487
+ throw fail("unavailable", "Invalid host response.");
488
+ return result.purchases.map(wireReceipt);
489
+ },
490
+ async consume(receiptId) { completed(await call4({ method: "purchase.consume", receipt: text(receiptId, "A receipt id") })); },
491
+ async receiptToken(receiptId) {
492
+ const token = (await call4({ method: "purchase.token", receipt: text(receiptId, "A receipt id") })).token;
493
+ if (typeof token !== "string" || token.length > PLAYER_RULES.tokenMax || !PLAYER_RULES.token.test(token))
494
+ throw fail("unavailable", "Invalid host response.");
495
+ return token;
359
496
  },
360
497
  async maximize(on = true) { if (typeof on !== "boolean")
361
498
  throw fail("invalid"); v2(); completed(await call({ method: "display.maximize", on })); },
@@ -386,6 +523,7 @@ export async function createOs(port, session, protocol, href) {
386
523
  resize.clear();
387
524
  sounds.clear();
388
525
  watchers.clear();
526
+ invites.clear();
389
527
  transport.destroy();
390
528
  },
391
529
  };
@@ -395,7 +533,8 @@ export async function createOs(port, session, protocol, href) {
395
533
  const ready = os.ready;
396
534
  os.ready = async () => { readied = true; progressValue = null; await ready(); };
397
535
  // every rejection is an OsError: a malformed host answer is `unavailable`
398
- for (const key of ["ready", "load", "cards", "packs", "pack", "showPack", "showCard", "open", "player", "finish", "maximize", "fullscreen"]) {
536
+ for (const key of ["ready", "load", "cards", "packs", "pack", "showPack", "showCard", "open", "player", "finish", "maximize", "fullscreen", "leaderboard", "showLeaderboard", "unlock",
537
+ "achievements", "friends", "invite", "share", "products", "buy", "purchases", "consume", "receiptToken"]) {
399
538
  const method = os[key];
400
539
  os[key] = async (...args) => { try {
401
540
  return await method(...args);
@@ -1,5 +1,9 @@
1
- import { type WireCard, type WirePack, type WirePackSummary } from "./app-wire.ts";
2
- /** What preview.json says about the app (preview.ts). */
1
+ import { type AppHostServices } from "./app-host.ts";
2
+ import { type Friend, type WireCard, type WirePack, type WirePackSummary } from "./app-wire.ts";
3
+ import { type FakeScore, type FakeServices } from "./fake-services.ts";
4
+ import { type AppAchievement, type AppLeaderboard, type AppProduct } from "./manifest.ts";
5
+ import { type PreviewSurfaces } from "./preview-surfaces.ts";
6
+ /** What preview.json says about the app (preview.ts); the 0.6 lists only when the manifest declares them. */
3
7
  export interface PreviewMetadata {
4
8
  name: string;
5
9
  runtime: string;
@@ -8,8 +12,23 @@ export interface PreviewMetadata {
8
12
  packs: string[];
9
13
  cards: "none" | "linked" | "all";
10
14
  network: string[];
15
+ leaderboards?: AppLeaderboard[];
16
+ achievements?: AppAchievement[];
17
+ products?: AppProduct[];
11
18
  }
12
19
  export declare function previewMetadata(input: unknown): PreviewMetadata;
20
+ /** The preview's other players: friends with each presence, and three scores on every board the app has. */
21
+ export declare const PREVIEW_FRIENDS: readonly Friend[];
22
+ export declare function previewScores(boards: readonly AppLeaderboard[]): FakeScore[];
23
+ /** The Printer Cash the preview's player starts with. */
24
+ export declare const PREVIEW_PRINTER_CASH = 500;
25
+ /**
26
+ * The 0.6 services of the preview: the testing module's fakes (fake-services.ts), with the vmOS surfaces drawn as preview
27
+ * stand-ins. `clicked` is the page's own user activation (a click in the app's frame activates the page too).
28
+ */
29
+ export declare function previewServices(meta: PreviewMetadata, surfaces: PreviewSurfaces, note: (text: string) => void, active: () => boolean, fakes?: FakeServices): Required<Pick<AppHostServices, "clicked" | "leaderboard" | "showLeaderboard" | "unlock" | "achievements" | "friends" | "launch" | "invite" | "share" | "products" | "buy" | "purchases" | "consume" | "receiptToken" | "showApp">> & {
30
+ fakes: FakeServices;
31
+ };
13
32
  /** A public pack every preview knows, linked or not, for trying `os.pack`, `os.showPack`, `os.showCard` and `os.open`. */
14
33
  export declare const PREVIEW_PUBLIC_PACK = "preview-public";
15
34
  /**
@@ -2,7 +2,9 @@ import { createAppController, mountAppFrame } from "./app-host.js";
2
2
  import { APP_FRAGMENT, createAppNonce } from "./app-protocol.js";
3
3
  import { appRuntimeRefusal } from "./app-runtime.js";
4
4
  import { AppHostError, cardArtPath, coverArtPath, RARITIES } from "./app-wire.js";
5
- import { assetPath, packSlug } from "./manifest.js";
5
+ import { createFakeServices } from "./fake-services.js";
6
+ import { appLeaderboards, assetPath, packSlug, parseServices } from "./manifest.js";
7
+ import { createPreviewSurfaces, formatScore } from "./preview-surfaces.js";
6
8
  export function previewMetadata(input) {
7
9
  if (!input || typeof input !== "object" || !("runtime" in input) || typeof input.runtime !== "string")
8
10
  throw Error("Invalid preview metadata.");
@@ -12,7 +14,79 @@ export function previewMetadata(input) {
12
14
  if (typeof value.name !== "string" || typeof value.id !== "string" || typeof value.entry !== "string" || !assetPath(value.entry) || !packs || !network
13
15
  || !(value.cards === "none" || value.cards === "linked" || value.cards === "all"))
14
16
  throw Error("Invalid preview metadata.");
15
- return { name: value.name, runtime: input.runtime, id: value.id, entry: value.entry, packs, cards: value.cards, network };
17
+ let services;
18
+ // preview.json carries the normalized lists: an achievement without an icon reads `icon: null`, which a manifest file omits
19
+ const achievements = Array.isArray(value.achievements) ? value.achievements.map(item => item && typeof item === "object" && item.icon === null ? Object.fromEntries(Object.entries(item).filter(([key]) => key !== "icon")) : item) : value.achievements;
20
+ try {
21
+ services = parseServices({ leaderboards: value.leaderboards, achievements, products: value.products });
22
+ }
23
+ catch {
24
+ throw Error("Invalid preview metadata.");
25
+ }
26
+ return { name: value.name, runtime: input.runtime, id: value.id, entry: value.entry, packs, cards: value.cards, network, ...services };
27
+ }
28
+ /** The preview's other players: friends with each presence, and three scores on every board the app has. */
29
+ export const PREVIEW_FRIENDS = Object.freeze([
30
+ { handle: "preview_friend", name: "Preview Friend", picture: null, presence: "playing" },
31
+ { handle: "sample_cat", name: "Sample Cat", picture: null, presence: "online" },
32
+ { handle: "quiet_one", name: "Quiet One", picture: null, presence: "offline" },
33
+ ]);
34
+ export function previewScores(boards) {
35
+ return boards.flatMap(board => (board.format === "time" ? [65_000, 80_000, 95_000] : [1200, 800, 400]).map((score, index) => ({
36
+ board: board.id, handle: ["preview_friend", "sample_cat", "stranger_dog"][index], name: ["Preview Friend", "Sample Cat", "Stranger Dog"][index], score, friend: index < 2,
37
+ })));
38
+ }
39
+ /** The Printer Cash the preview's player starts with. */
40
+ export const PREVIEW_PRINTER_CASH = 500;
41
+ /**
42
+ * The 0.6 services of the preview: the testing module's fakes (fake-services.ts), with the vmOS surfaces drawn as preview
43
+ * stand-ins. `clicked` is the page's own user activation (a click in the app's frame activates the page too).
44
+ */
45
+ export function previewServices(meta, surfaces, note, active, fakes = createFakeServices({
46
+ ...meta, player: { handle: "preview_player", name: "Preview Player", picture: null }, scores: previewScores(appLeaderboards(meta)), friends: PREVIEW_FRIENDS,
47
+ printerCash: PREVIEW_PRINTER_CASH, network: meta.network.length > 0, now: Date.now,
48
+ })) {
49
+ const names = (texts) => texts.filter((text) => text !== undefined);
50
+ return {
51
+ fakes,
52
+ clicked: () => active(),
53
+ async leaderboard(query) { return fakes.leaderboard(query); },
54
+ async showLeaderboard(board) { await surfaces.board(fakes.leaderboard({ board, scope: "everyone", period: "all", limit: 10 })); },
55
+ async unlock(id) {
56
+ const result = fakes.unlock(id);
57
+ if (result.unlocked)
58
+ surfaces.toast(`Achievement unlocked: ${meta.achievements.find(item => item.id === id).name}`);
59
+ return result;
60
+ },
61
+ async achievements() { return fakes.achievements(); },
62
+ async friends() { return fakes.friends(); },
63
+ async launch() { return null; },
64
+ async invite(options) {
65
+ const confirmed = await surfaces.ask({ title: "Invite friends", lines: names([`vmOS would let the player choose friends who have ${meta.name}${options.to ? `, with ${options.to} chosen` : ""}.`, options.text, options.data === undefined ? undefined : `Your app's data: ${options.data}`]), confirm: "Send invites", cancel: "Close" });
66
+ return fakes.invite(options, confirmed);
67
+ },
68
+ async share(options) {
69
+ const board = options.score === undefined ? undefined : fakes.leaderboard({ board: options.board ?? "score", scope: "everyone", period: "all", limit: 1 });
70
+ const confirmed = await surfaces.ask({ title: "Share", lines: names([`vmOS would compose a card for ${meta.name} with the player's name${board ? ` and ${formatScore(options.score, board.format)} on ${board.name}` : ""}; the player picks a friend in chat or their VibeSpace status.`, options.text === undefined ? undefined : `Caption: ${options.text}`]), confirm: "Post", cancel: "Close" });
71
+ return fakes.share(options, confirmed);
72
+ },
73
+ async products() { return fakes.products(); },
74
+ async buy(id) {
75
+ const product = fakes.product(id), owned = fakes.products().some(item => item.id === id && item.owned);
76
+ if (owned)
77
+ return fakes.buy(id, true);
78
+ const cash = fakes.state.printerCash;
79
+ const confirmed = await surfaces.ask({
80
+ title: product.name, holdMs: 600, confirm: `Spend ${product.price} Printer Cash`, cancel: "Cancel",
81
+ lines: [product.description, cash >= product.price ? `Printer Cash: ${cash} now, ${cash - product.price} after.` : `Printer Cash: ${cash}. That is not enough.`, "In the preview nothing is spent."],
82
+ });
83
+ return fakes.buy(id, confirmed);
84
+ },
85
+ async purchases() { return fakes.purchases(); },
86
+ async consume(receipt) { fakes.consume(receipt); },
87
+ async receiptToken(receipt) { fakes.receiptToken(receipt); return "preview.not-a-real-receipt-token.unsigned"; },
88
+ async showApp(app) { note(`VibeMarket OS would open ${app}'s page in MiniVibe here.`); },
89
+ };
16
90
  }
17
91
  /** A pack name from its slug: "rooftop-rats" reads "Rooftop Rats". */
18
92
  const title = (slug) => slug.split("-").map(word => word[0].toUpperCase() + word.slice(1)).join(" ");
@@ -90,9 +164,10 @@ export async function startPreviewParent() {
90
164
  if (refusal)
91
165
  throw Error(refusal);
92
166
  const surface = document.getElementById("surface"), status = document.getElementById("status"), toggle = document.getElementById("toggle"), reset = document.getElementById("reset"), pull = document.getElementById("pull");
167
+ const layer = document.getElementById("surfaces");
93
168
  const speaker = document.getElementById("sound"), volume = document.getElementById("volume");
94
169
  const result = document.getElementById("result"), score = document.getElementById("score");
95
- if (!surface || !status || !result || !score || !(toggle instanceof HTMLButtonElement) || !(reset instanceof HTMLButtonElement) || !(pull instanceof HTMLButtonElement)
170
+ if (!surface || !status || !result || !score || !layer || !(toggle instanceof HTMLButtonElement) || !(reset instanceof HTMLButtonElement) || !(pull instanceof HTMLButtonElement)
96
171
  || !(speaker instanceof HTMLButtonElement) || !(volume instanceof HTMLInputElement))
97
172
  throw Error("Preview controls are missing.");
98
173
  const meta = previewMetadata(await (await fetch("/preview.json", { credentials: "omit" })).json());
@@ -100,8 +175,11 @@ export async function startPreviewParent() {
100
175
  if (runtime.origin !== `http://localhost:${window.location.port}` || !/^\/game-assets\/[a-f0-9]{64}\//.test(runtime.pathname) || runtime.search || runtime.hash)
101
176
  throw Error("Invalid preview runtime.");
102
177
  const catalog = previewCatalog(meta), saves = previewSaves(meta.id, () => window.localStorage);
103
- const clicked = () => { if (!navigator.userActivation?.isActive)
178
+ const active = () => navigator.userActivation?.isActive === true;
179
+ const clicked = () => { if (!active())
104
180
  throw new AppHostError("needs-click", "That needs a fresh click in the app."); };
181
+ const surfaces = createPreviewSurfaces({ root: layer, document, setTimeout: (callback, ms) => window.setTimeout(callback, ms) });
182
+ const { fakes, ...apps4 } = previewServices(meta, surfaces, text => { status.textContent = text; }, active);
105
183
  const services = {
106
184
  guest: false, entry: meta.entry,
107
185
  async saveGet() { return saves.get(); },
@@ -126,6 +204,7 @@ export async function startPreviewParent() {
126
204
  clicked();
127
205
  await surface.requestFullscreen();
128
206
  },
207
+ ...apps4,
129
208
  };
130
209
  const owner = () => createAppController(undefined, { services, idle: () => { status.textContent = "Still playing? VibeMarket asks here after 15 minutes without input."; } });
131
210
  let controller = owner(), frame = null;
@@ -145,7 +224,8 @@ export async function startPreviewParent() {
145
224
  if (completion) {
146
225
  result.hidden = false;
147
226
  score.textContent = String(completion.score);
148
- status.textContent = "Round complete. No Cash reward for this preview.";
227
+ const board = appLeaderboards(meta).find(item => item.id === (completion.board ?? "score"));
228
+ status.textContent = `Round complete. No Cash reward for this preview.${board ? ` The score is on the preview's ${board.name} board.` : ""}`;
149
229
  return;
150
230
  }
151
231
  const challenge = createAppNonce(), source = new URL(runtime);
@@ -162,7 +242,7 @@ export async function startPreviewParent() {
162
242
  mounted = mountAppFrame(frame, { controller, challenge, sound, current: () => !minimized && !document.hidden,
163
243
  ready: () => { status.textContent = "App ready · Minimize and restore to check its saved work."; },
164
244
  progress: fraction => { status.textContent = `Loading the isolated app… ${Math.round(fraction * 100)}%`; },
165
- finish: value => { completion = value; reset.textContent = "Play again"; draw(); },
245
+ finish: value => { completion = value; fakes.post(value.score, value.board); reset.textContent = "Play again"; draw(); },
166
246
  fault: message => { detach(); controller.dispose(); controller = owner(); status.textContent = message; },
167
247
  });
168
248
  observer = new ResizeObserver(() => { if (frame)
@@ -171,7 +251,7 @@ export async function startPreviewParent() {
171
251
  status.textContent = "Loading the isolated app…";
172
252
  };
173
253
  toggle.onclick = () => { minimized = !minimized; toggle.textContent = minimized ? "Restore" : "Minimize"; draw(); };
174
- reset.onclick = () => { detach(); controller.dispose(); controller = owner(); completion = null; minimized = false; toggle.textContent = "Minimize"; reset.textContent = "Close / reset"; draw(); };
254
+ reset.onclick = () => { surfaces.clear(); detach(); controller.dispose(); controller = owner(); completion = null; minimized = false; toggle.textContent = "Minimize"; reset.textContent = "Close / reset"; draw(); };
175
255
  const setSound = (next) => {
176
256
  sound = next;
177
257
  mounted?.setSound(sound);
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The local preview's minimal stand-ins for the surfaces vmOS draws over an app in SDK 0.6 (VM_OS_APPS_4.md section 1): the
3
+ * spend dialog, the share and invite sheets, the leaderboard panel and the achievement toast. Each says "Preview" first, so
4
+ * nobody mistakes it for vmOS: the real ones are drawn by the desk, outside the app's frame, in its own style and words.
5
+ * They are drawn in the preview page, never in the app's frame, as on the desk.
6
+ */
7
+ import type { Leaderboard } from "./app-wire.ts";
8
+ /** A dialog's text and buttons. Cancel has the focus; confirm stays disabled for `holdMs` (the spend dialog's 600 ms). */
9
+ export interface PreviewAsk {
10
+ title: string;
11
+ lines: readonly string[];
12
+ confirm: string;
13
+ cancel: string;
14
+ holdMs?: number;
15
+ }
16
+ export interface PreviewSurfaces {
17
+ /** Show a dialog; true when the player confirms, false when they cancel. One at a time: a second waits for the first. */
18
+ ask(question: PreviewAsk): Promise<boolean>;
19
+ /** Show a board's rows; resolves when closed. */
20
+ board(board: Leaderboard): Promise<void>;
21
+ /** A toast for 4 seconds, one at a time; more than five waiting are collapsed into one. */
22
+ toast(text: string): void;
23
+ /** Close everything (a reset): open dialogs answer cancel, waiting toasts are dropped. */
24
+ clear(): void;
25
+ }
26
+ export interface PreviewSurfaceHost {
27
+ /** where dialogs and toasts are appended (the page's `#surfaces`) */
28
+ root: HTMLElement;
29
+ document: Pick<Document, "createElement">;
30
+ setTimeout(callback: () => void, ms: number): unknown;
31
+ }
32
+ /** How long a toast stays, and how many may wait before they are collapsed. */
33
+ export declare const PREVIEW_TOAST_MS = 4000, PREVIEW_TOAST_QUEUE = 5;
34
+ /** "1:05.20" for a time board (milliseconds), "1,234" otherwise. */
35
+ export declare function formatScore(score: number, format: Leaderboard["format"]): string;
36
+ export declare function createPreviewSurfaces(host: PreviewSurfaceHost): PreviewSurfaces;
@@ -0,0 +1,84 @@
1
+ /** How long a toast stays, and how many may wait before they are collapsed. */
2
+ export const PREVIEW_TOAST_MS = 4000, PREVIEW_TOAST_QUEUE = 5;
3
+ /** "1:05.20" for a time board (milliseconds), "1,234" otherwise. */
4
+ export function formatScore(score, format) {
5
+ if (format === "number")
6
+ return score.toLocaleString("en-US");
7
+ const minutes = Math.floor(score / 60_000), seconds = Math.floor((score % 60_000) / 1000), hundredths = Math.floor((score % 1000) / 10);
8
+ return `${minutes}:${String(seconds).padStart(2, "0")}.${String(hundredths).padStart(2, "0")}`;
9
+ }
10
+ export function createPreviewSurfaces(host) {
11
+ const make = (tag, className, text) => {
12
+ const node = host.document.createElement(tag);
13
+ node.className = className;
14
+ if (text !== undefined)
15
+ node.textContent = text;
16
+ return node;
17
+ };
18
+ let queue = Promise.resolve(), open = null;
19
+ const toasts = [];
20
+ let showing = false;
21
+ /** One dialog: the "Preview" label, a title, lines and buttons; resolves with the button pressed. */
22
+ const dialog = (title, lines, buttons) => {
23
+ const run = queue.then(() => new Promise(resolve => {
24
+ const node = make("section", "pv-surface");
25
+ node.setAttribute("role", "dialog");
26
+ node.setAttribute("aria-modal", "true");
27
+ node.setAttribute("aria-label", `Preview: ${title}`);
28
+ node.append(make("small", "pv-label", "Preview · vmOS draws this itself"), make("h2", "pv-title", title));
29
+ for (const text of lines)
30
+ node.append(make("p", "pv-line", text));
31
+ const row = make("div", "pv-buttons");
32
+ let focus = null;
33
+ const finish = (value) => { if (open?.node !== node)
34
+ return; open = null; node.remove(); resolve(value); };
35
+ for (const button of buttons) {
36
+ const element = make("button", button.value ? "pv-confirm" : "pv-cancel", button.label);
37
+ element.type = "button";
38
+ element.addEventListener("click", () => finish(button.value));
39
+ if (button.hold) {
40
+ element.disabled = true;
41
+ host.setTimeout(() => { element.disabled = false; }, button.hold);
42
+ }
43
+ if (button.focus)
44
+ focus = element;
45
+ row.append(element);
46
+ }
47
+ node.append(row);
48
+ host.root.append(node);
49
+ open = { node, done: () => finish(false) };
50
+ focus?.focus();
51
+ }));
52
+ queue = run;
53
+ return run;
54
+ };
55
+ const nextToast = () => {
56
+ if (showing || !toasts.length)
57
+ return;
58
+ showing = true;
59
+ const node = make("div", "pv-toast", `Preview · ${toasts.shift()}`);
60
+ node.setAttribute("role", "status");
61
+ host.root.append(node);
62
+ host.setTimeout(() => { node.remove(); showing = false; nextToast(); }, PREVIEW_TOAST_MS);
63
+ };
64
+ return {
65
+ ask(question) {
66
+ return dialog(question.title, question.lines, [
67
+ { label: question.cancel, value: false, focus: true },
68
+ { label: question.confirm, value: true, ...(question.holdMs ? { hold: question.holdMs } : {}) },
69
+ ]);
70
+ },
71
+ async board(board) {
72
+ const rows = board.entries.map(entry => `${entry.rank}. ${entry.name}${entry.you ? " (you)" : ""}: ${formatScore(entry.score, board.format)}`);
73
+ const mine = board.you && !board.entries.some(entry => entry.you) ? [`You: #${board.you.rank}, ${formatScore(board.you.score, board.format)}`] : [];
74
+ await dialog(board.name, [...(rows.length ? rows : ["No scores yet."]), ...mine], [{ label: "Close", value: false, focus: true }]);
75
+ },
76
+ toast(text) {
77
+ toasts.push(text);
78
+ if (toasts.length > PREVIEW_TOAST_QUEUE)
79
+ toasts.splice(0, toasts.length, `${toasts.length} achievements unlocked`);
80
+ nextToast();
81
+ },
82
+ clear() { toasts.length = 0; open?.done(); },
83
+ };
84
+ }