@vibechain/os 0.5.1 → 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.
Files changed (59) hide show
  1. package/AGENTS.md +52 -11
  2. package/README.md +115 -20
  3. package/SECURITY.md +6 -4
  4. package/dist/app-client.js +20 -4
  5. package/dist/app-host.d.ts +74 -5
  6. package/dist/app-host.js +94 -6
  7. package/dist/app-protocol.d.ts +21 -0
  8. package/dist/app-protocol.js +9 -0
  9. package/dist/app-wire.d.ts +186 -6
  10. package/dist/app-wire.js +213 -7
  11. package/dist/audio.d.ts +65 -0
  12. package/dist/audio.js +162 -0
  13. package/dist/browser.d.ts +2 -1
  14. package/dist/browser.js +2 -1
  15. package/dist/bundle.d.ts +2 -0
  16. package/dist/bundle.js +5 -3
  17. package/dist/check.js +11 -4
  18. package/dist/cli.js +3 -1
  19. package/dist/commands.d.ts +6 -0
  20. package/dist/commands.js +17 -0
  21. package/dist/fake-services.d.ts +88 -0
  22. package/dist/fake-services.js +132 -0
  23. package/dist/index.d.ts +3 -3
  24. package/dist/index.js +1 -1
  25. package/dist/links.d.ts +13 -0
  26. package/dist/links.js +17 -1
  27. package/dist/listing.d.ts +12 -0
  28. package/dist/listing.js +49 -1
  29. package/dist/manifest.d.ts +76 -1
  30. package/dist/manifest.js +170 -5
  31. package/dist/os.d.ts +83 -5
  32. package/dist/os.js +179 -15
  33. package/dist/preview-parent.d.ts +21 -2
  34. package/dist/preview-parent.js +101 -8
  35. package/dist/preview-surfaces.d.ts +36 -0
  36. package/dist/preview-surfaces.js +84 -0
  37. package/dist/preview-ui.js +1 -1
  38. package/dist/preview.js +4 -2
  39. package/dist/templates/plain/game.js +3 -1
  40. package/dist/testing.d.ts +50 -7
  41. package/dist/testing.js +137 -13
  42. package/dist/transport.d.ts +4 -1
  43. package/dist/transport.js +2 -2
  44. package/dist/vibemarket-os.js +1 -1
  45. package/examples/paw-beat/README.md +38 -10
  46. package/examples/paw-beat/cat.ts +13 -0
  47. package/examples/paw-beat/game.ts +290 -123
  48. package/examples/paw-beat/index.html +20 -4
  49. package/examples/paw-beat/main.ts +156 -48
  50. package/examples/paw-beat/music.ts +72 -337
  51. package/examples/paw-beat/stage.ts +23 -9
  52. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  53. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  54. package/examples/paw-beat/synth.ts +477 -0
  55. package/examples/paw-beat/tracks.ts +286 -0
  56. package/examples/paw-beat/vibemarket.json +15 -8
  57. package/examples/vibexp-app/plain/game.ts +6 -2
  58. package/package.json +7 -1
  59. package/skill.md +471 -0
package/dist/manifest.js CHANGED
@@ -23,12 +23,40 @@ export const APP_STORE_LIMITS = {
23
23
  };
24
24
  /** What a schema version 3 app may read of the player's vmOS cards: nothing, its linked packs, or every pack. */
25
25
  export const APP_CARDS_ACCESS = ["none", "linked", "all"];
26
+ /**
27
+ * The id of a leaderboard, achievement or product (VM_OS_APPS_4.md section 2): a lowercase letter, then up to 31 lowercase
28
+ * letters, digits and hyphens. Unique within its list; once in an approved version it keeps its meaning.
29
+ */
30
+ export const SERVICE_ID = /^[a-z][a-z0-9-]{0,31}$/;
31
+ export const serviceId = (value) => typeof value === "string" && SERVICE_ID.test(value);
32
+ /**
33
+ * Bounds of the optional `leaderboards`, `achievements` and `products` (SDK 0.6). Names and descriptions count Unicode code
34
+ * points and are one line. `priceMax` is only the SDK's structural bound on a product's whole Printer Cash price: the
35
+ * store's current maximum is lower, is set by VibeMarket and is checked when a version is submitted.
36
+ */
37
+ export const APP_SERVICE_LIMITS = {
38
+ leaderboards: 5, achievements: 50, products: 50, nameMax: 40, descriptionMax: 120,
39
+ achievementIconSize: 128, achievementIconBytes: 64 * 1024, priceMax: 1_000_000,
40
+ };
41
+ export const LEADERBOARD_ORDERS = ["high", "low"];
42
+ export const LEADERBOARD_FORMATS = ["number", "time"];
43
+ export const PRODUCT_KINDS = ["consumable", "permanent"];
44
+ /** The board every app has unless it declares one with this id: `finish({ score })` posts to it. */
45
+ export const DEFAULT_LEADERBOARD = Object.freeze({ id: "score", name: "High scores", order: "high", format: "number" });
46
+ /** The boards an app has: those it declares, in order, then the default `score` board unless one of them is `score`. */
47
+ export function appLeaderboards(manifest) {
48
+ const declared = (manifest.leaderboards ?? []).map(board => ({ ...board }));
49
+ return declared.some(board => board.id === DEFAULT_LEADERBOARD.id) ? declared : [...declared, { ...DEFAULT_LEADERBOARD }];
50
+ }
26
51
  /** The legacy Market-game bounds. VibeStore bundles use `APP_BUNDLE_LIMITS`. */
27
52
  export const GAME_LIMITS = { archive: 20 * 1024 * 1024, expanded: 64 * 1024 * 1024, file: 16 * 1024 * 1024, files: 256, versions: 100, games: 40 };
28
53
  /** VibeStore bundle bounds: the submitted ZIP, its expanded bytes, the largest file and the entries (files and folders). */
29
54
  export const APP_BUNDLE_LIMITS = { archive: 50 * 1024 * 1024, expanded: 128 * 1024 * 1024, file: 32 * 1024 * 1024, files: 2000 };
30
- /** Schema version 3 bounds: linked packs, declared origins and a pack slug's length. */
31
- export const APP_MANIFEST_LIMITS = { packs: 3, network: 8, packSlugMax: 56 };
55
+ /**
56
+ * Schema version 3 bounds: linked packs, declared origins, a pack slug's length and the size of `vibemarket.json` itself
57
+ * (64 KiB since SDK 0.6, so a manifest that fills every list of APP_SERVICE_LIMITS still fits; 16 KiB before).
58
+ */
59
+ export const APP_MANIFEST_LIMITS = { packs: 3, network: 8, packSlugMax: 56, manifestBytes: 64 * 1024 };
32
60
  /** A pack slug, as `vibemarket/steam/pack-slug.ts` defines it (at most `APP_MANIFEST_LIMITS.packSlugMax` characters). */
33
61
  export const PACK_SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
34
62
  export const packSlug = (value) => typeof value === "string" && value.length <= APP_MANIFEST_LIMITS.packSlugMax && PACK_SLUG.test(value);
@@ -202,7 +230,7 @@ export function networkOrigin(value) { return networkOriginCheck(value).origin;
202
230
  /** `path: message`, the line `os check` prints and the text `parseManifest` throws for schema version 3. */
203
231
  export const manifestProblemText = (problem) => problem.path ? `${problem.path}: ${problem.message}` : problem.message;
204
232
  const V3_REQUIRED = ["schemaVersion", "id", "version", "name", "tagline", "entry", "window", "store"];
205
- const V3_OPTIONAL = ["packs", "cards", "network"];
233
+ const V3_OPTIONAL = ["packs", "cards", "network", "leaderboards", "achievements", "products"];
206
234
  const V3_REMOVED = ["sdkVersion", "category", "permissions", "collectionId"];
207
235
  // origins are distinct by then, so two are never equal
208
236
  const compareText = (a, b) => a < b ? -1 : 1;
@@ -277,10 +305,147 @@ function inspectV3(data) {
277
305
  cards = null;
278
306
  }
279
307
  const network = inspectNetwork(data.network, add);
280
- if (problems.length || id === null || version === null || name === null || tagline === null || entry === null || !window || !store || !packs || !cards || !network)
308
+ const services = inspectServices(data, add);
309
+ if (problems.length || id === null || version === null || name === null || tagline === null || entry === null || !window || !store || !packs || !cards || !network || !services)
281
310
  return { manifest: null, problems };
282
- return { manifest: { schemaVersion: 3, id, version, name, tagline, entry, window, store, packs, cards, network }, problems };
311
+ return { manifest: { schemaVersion: 3, id, version, name, tagline, entry, window, store, packs, cards, network, ...services }, problems };
312
+ }
313
+ // Every control character, newlines included: names and descriptions of boards, achievements and products are one line.
314
+ const LINE_CONTROL = /[\u0000-\u001F\u007F-\u009F]/;
315
+ /** One line of 1 to `max` code points with no surrounding spaces, or a problem at `path`. */
316
+ function line(value, path, max, add) {
317
+ if (typeof value !== "string")
318
+ add(path, "must be a string.");
319
+ else if (!value.trim())
320
+ add(path, "must not be empty.");
321
+ else if (value !== value.trim())
322
+ add(path, "must not start or end with spaces.");
323
+ else if (LINE_CONTROL.test(value))
324
+ add(path, "must be one line of plain text, with no line breaks or control characters.");
325
+ else if ([...value].length > max)
326
+ add(path, `must be at most ${max} characters.`);
327
+ else
328
+ return value;
329
+ return null;
330
+ }
331
+ /**
332
+ * The optional `leaderboards`, `achievements` and `products` (VM_OS_APPS_4.md section 2): each a list of objects with exact
333
+ * fields, at most the APP_SERVICE_LIMITS count, ids unique within the list. Only the lists the file has are returned, so a
334
+ * manifest without them normalizes exactly as before SDK 0.6. `null` when any of them has a problem.
335
+ */
336
+ function inspectServices(data, add) {
337
+ const limits = APP_SERVICE_LIMITS;
338
+ let ok = true;
339
+ const list = (key, max, noun, required, optional, item) => {
340
+ if (!(key in data))
341
+ return undefined;
342
+ const input = data[key];
343
+ if (!Array.isArray(input)) {
344
+ add(key, `must be a list of ${noun} objects.`);
345
+ ok = false;
346
+ return undefined;
347
+ }
348
+ if (input.length > max) {
349
+ add(key, `may declare at most ${max} ${noun}s.`);
350
+ ok = false;
351
+ }
352
+ const out = [], ids = new Set();
353
+ input.forEach((value, index) => {
354
+ const path = `${key}[${index}]`;
355
+ if (!record(value)) {
356
+ add(path, `must be an object with ${listOf(required)}.`);
357
+ ok = false;
358
+ return;
359
+ }
360
+ const before = fieldProblems(value, `${path}.`, required, optional);
361
+ for (const problem of before)
362
+ add(problem.path, problem.message);
363
+ let good = !before.length;
364
+ if ("id" in value) {
365
+ if (!serviceId(value.id)) {
366
+ add(`${path}.id`, "must be a lowercase letter followed by up to 31 lowercase letters, digits and hyphens, such as high-score.");
367
+ good = false;
368
+ }
369
+ else if (ids.has(value.id)) {
370
+ add(`${path}.id`, `repeats another ${noun}'s id; each id is used once.`);
371
+ good = false;
372
+ }
373
+ else
374
+ ids.add(value.id);
375
+ }
376
+ const made = item(value, path);
377
+ if (good && made !== null)
378
+ out.push(made);
379
+ else
380
+ ok = false;
381
+ });
382
+ return out;
383
+ };
384
+ const choice = (value, key, path, values, fallback) => {
385
+ if (!(key in value))
386
+ return fallback;
387
+ if (typeof value[key] === "string" && values.includes(value[key]))
388
+ return value[key];
389
+ add(`${path}.${key}`, `must be ${listOf(values.map(item => `"${item}"`), "or")}.`);
390
+ return null;
391
+ };
392
+ const leaderboards = list("leaderboards", limits.leaderboards, "leaderboard", ["id", "name"], ["order", "format"], (value, path) => {
393
+ const name = "name" in value ? line(value.name, `${path}.name`, limits.nameMax, add) : null;
394
+ const order = choice(value, "order", path, LEADERBOARD_ORDERS, "high"), format = choice(value, "format", path, LEADERBOARD_FORMATS, "number");
395
+ return name === null || order === null || format === null ? null : { id: value.id, name, order, format };
396
+ });
397
+ const achievements = list("achievements", limits.achievements, "achievement", ["id", "name", "description"], ["icon", "secret"], (value, path) => {
398
+ const name = "name" in value ? line(value.name, `${path}.name`, limits.nameMax, add) : null;
399
+ const description = "description" in value ? line(value.description, `${path}.description`, limits.descriptionMax, add) : null;
400
+ let icon = null, fine = true;
401
+ if ("icon" in value) {
402
+ const file = value.icon;
403
+ if (typeof file !== "string" || !assetPath(file) || !/\.(?:png|webp)$/.test(file)) {
404
+ add(`${path}.icon`, "must be the relative path of a .png or .webp file in the bundle, such as achievements/first.png.");
405
+ fine = false;
406
+ }
407
+ else
408
+ icon = file;
409
+ }
410
+ if ("secret" in value && typeof value.secret !== "boolean") {
411
+ add(`${path}.secret`, "must be true or false.");
412
+ fine = false;
413
+ }
414
+ return name === null || description === null || !fine ? null : { id: value.id, name, description, icon, secret: value.secret === true };
415
+ });
416
+ const products = list("products", limits.products, "product", ["id", "name", "description", "price", "kind"], [], (value, path) => {
417
+ const name = "name" in value ? line(value.name, `${path}.name`, limits.nameMax, add) : null;
418
+ const description = "description" in value ? line(value.description, `${path}.description`, limits.descriptionMax, add) : null;
419
+ const { price } = value;
420
+ let fine = true;
421
+ if ("price" in value && (typeof price !== "number" || !Number.isInteger(price) || price < 1 || price > limits.priceMax)) {
422
+ add(`${path}.price`, "must be a whole number of Printer Cash, at least 1, within the store's maximum price.");
423
+ fine = false;
424
+ }
425
+ const kind = "kind" in value ? choice(value, "kind", path, PRODUCT_KINDS, "consumable") : null;
426
+ return name === null || description === null || kind === null || !fine ? null : { id: value.id, name, description, price: price, kind };
427
+ });
428
+ if (!ok)
429
+ return null;
430
+ return { ...(leaderboards ? { leaderboards } : {}), ...(achievements ? { achievements } : {}), ...(products ? { products } : {}) };
431
+ }
432
+ /**
433
+ * The `leaderboards`, `achievements` and `products` of a manifest-shaped object, normalized by the manifest's own rules (for
434
+ * the testing fakes and the preview); throws the first problem as `parseManifest` would.
435
+ */
436
+ export function parseServices(input) {
437
+ const problems = [];
438
+ const data = {};
439
+ for (const key of ["leaderboards", "achievements", "products"])
440
+ if (input[key] !== undefined)
441
+ data[key] = input[key];
442
+ const services = inspectServices(data, (path, message) => { problems.push({ path, message }); });
443
+ if (!services)
444
+ throw Error(manifestProblemText(problems[0]));
445
+ return services;
283
446
  }
447
+ /** "a, b and c" (or "or") of two or more values, with backticks left to the caller. */
448
+ const listOf = (values, last = "and") => `${values.slice(0, -1).join(", ")} ${last} ${values.at(-1)}`;
284
449
  function inspectWindow(input, add) {
285
450
  if (!record(input)) {
286
451
  add("window", "must be an object with width, height and resizable.");
package/dist/os.d.ts CHANGED
@@ -1,20 +1,58 @@
1
- import { type Card, type Pack, type PackSummary, type Player } from "./app-wire.ts";
1
+ /**
2
+ * `connect()`: the one app API of @vibechain/os 0.5 (VM_OS_APPS_3.md section 11). On a host that advertises protocol 2 it
3
+ * says hello and every method works; on an older host `ready`, `finish`, lifecycle, `load` and `save` work (saves use the
4
+ * window-only checkpoint) and the rest reject with `unsupported`. Every rejection is an OsError with a stable code.
5
+ */
6
+ import { type AppSound } from "./app-protocol.ts";
7
+ import { type Achievement, type BoardPeriod, type BoardScope, type Card, type Friend, type Invite, type Leaderboard, type OsErrorCode, type Pack, type PackSummary, type Player, type Product, type Receipt } from "./app-wire.ts";
2
8
  import { type CaptureResult } from "./capture.ts";
3
- export type { Card, OsErrorCode, Pack, PackCard, PackSummary, Player, Rarity, SignedInPlayer } from "./app-wire.ts";
9
+ export type { Achievement, BoardPeriod, BoardScope, Card, Friend, Invite, Leaderboard, LeaderboardEntry, OsErrorCode, Pack, PackCard, PackSummary, Player, Presence, Product, Receipt, Rarity, SignedInPlayer, } from "./app-wire.ts";
10
+ export type { LeaderboardFormat, LeaderboardOrder, ProductKind } from "./manifest.ts";
4
11
  export { OS_ERROR_CODES } from "./app-wire.ts";
5
- /** The SDK version a 0.5 client reports in `host.hello`. */
6
- export declare const OS_SDK_VERSION = "0.5.1";
12
+ /** The SDK version a client reports in `host.hello`. */
13
+ export declare const OS_SDK_VERSION = "0.6.0";
14
+ /** `os.leaderboard()` options; each falls back to the board `score`, everyone, all time and 10 rows (1 to 50). */
15
+ export interface LeaderboardOptions {
16
+ board?: string;
17
+ scope?: BoardScope;
18
+ period?: BoardPeriod;
19
+ limit?: number;
20
+ }
21
+ /** `os.invite()` options: a friend's handle to preselect, a line of at most 80 characters, and up to 256 characters of data for your app. */
22
+ export interface InviteOptions {
23
+ to?: string;
24
+ text?: string;
25
+ data?: string;
26
+ }
27
+ /** `os.share()` options: a caption of at most 140 characters, and a score with its board (default `score`). */
28
+ export interface ShareOptions {
29
+ text?: string;
30
+ score?: number;
31
+ board?: string;
32
+ }
33
+ /** What the app was opened with: a friend's invite, or null. */
34
+ export interface OsLaunch {
35
+ readonly invite: Readonly<Invite> | null;
36
+ }
7
37
  export { OsError } from "./app-wire.ts";
8
38
  export type OsSize = Readonly<{
9
39
  width: number;
10
40
  height: number;
11
41
  }>;
42
+ /** The desktop's sound for games: `muted` (the taskbar speaker, or games sound off) and the level games play at, from 0 to 1. */
43
+ export type OsSound = Readonly<AppSound>;
12
44
  export interface Os {
13
45
  /** false while the window is minimized or behind another window */
14
46
  readonly active: boolean;
15
47
  readonly size: OsSize;
16
48
  /** a guest's save lives only while the window is open */
17
49
  readonly guest: boolean;
50
+ /**
51
+ * The desktop's sound, which the app must follow: silent while `muted`, scaled by `volume` (0 to 1). Set before `connect()`
52
+ * resolves on a host that controls sound; `{ muted: false, volume: 1 }` on an older host. `createAudio(os)` from
53
+ * `@vibechain/os/audio` follows it for you.
54
+ */
55
+ readonly sound: OsSound;
18
56
  /** hide the host's loading screen */
19
57
  ready(): Promise<void>;
20
58
  /** 0 to 1 while loading; keeps a long load inside the host's readiness rule */
@@ -34,18 +72,56 @@ export interface Os {
34
72
  showPack(id: string): Promise<void>;
35
73
  /** the host opens that card in its pack's page; needs a click in the app (0.5.1 hosts) */
36
74
  showCard(pack: string, cardId: string): Promise<void>;
37
- /** open an app link (`vmos://pack/<slug>`, `vmos://card/<slug>/<cardId>`, `https://vibechain.com/os/pack/<slug>`); needs a click */
75
+ /** open an app link (`vmos://pack/<slug>`, `vmos://card/<slug>/<cardId>`, `vmos://app/<appId>` and the `https://vibechain.com/os/...` forms); needs a click */
38
76
  open(link: string): Promise<void>;
39
77
  /** who is playing: handle, name and picture, or `{ guest: true }`; plus a 5-minute token for your own server with `network` */
40
78
  player(): Promise<Player>;
79
+ /** end the round: one integer score, 0 to 1,000,000,000, once per open window; since 0.6 posted to `board` (default `score`) */
41
80
  finish(result: {
42
81
  score: number;
82
+ board?: string;
43
83
  }): Promise<void>;
84
+ /** a board's top rows and the player's own place (0.6) */
85
+ leaderboard(options?: LeaderboardOptions): Promise<Leaderboard>;
86
+ /** vmOS opens its leaderboard panel over the app; resolves when the player closes it; needs a click (0.6) */
87
+ showLeaderboard(board?: string): Promise<void>;
88
+ /** record an achievement the manifest declares; `unlocked` is true only the first time (0.6) */
89
+ unlock(id: string): Promise<{
90
+ unlocked: boolean;
91
+ }>;
92
+ /** the manifest's achievements and which the player has (0.6) */
93
+ achievements(): Promise<Achievement[]>;
94
+ /** the player's friends who have this app, with a coarse presence (0.6) */
95
+ friends(): Promise<Friend[]>;
96
+ /** vmOS opens its invite sheet; resolves with how many friends were invited; needs a click; not for guests (0.6) */
97
+ invite(options?: InviteOptions): Promise<{
98
+ sent: number;
99
+ }>;
100
+ /** what the app was opened with: `launch.invite` is a friend's invite or null; read it once at start (0.6) */
101
+ readonly launch: OsLaunch;
102
+ /** a friend's invite arrived while the app is open; returns unsubscribe (0.6) */
103
+ onInvite(listener: (invite: Invite) => void): () => void;
104
+ /** vmOS opens its share sheet with a card it composes; `shared` is false when the player closes it; needs a click; not for guests (0.6) */
105
+ share(options: ShareOptions): Promise<{
106
+ shared: boolean;
107
+ }>;
108
+ /** the manifest's products as approved, with `owned` for permanent ones the player bought (0.6) */
109
+ products(): Promise<Product[]>;
110
+ /** vmOS asks the player to spend Printer Cash on a product; the receipt on confirmation; needs a click in the last second; not for guests (0.6) */
111
+ buy(productId: string): Promise<Receipt>;
112
+ /** permanent receipts and consumables not yet consumed (0.6) */
113
+ purchases(): Promise<Receipt[]>;
114
+ /** after granting a consumable, so it leaves `purchases()` (0.6) */
115
+ consume(receiptId: string): Promise<void>;
116
+ /** a 5-minute signed token of a receipt for your server; `network` apps only (0.6) */
117
+ receiptToken(receiptId: string): Promise<string>;
44
118
  maximize(on?: boolean): Promise<void>;
45
119
  fullscreen(on?: boolean): Promise<void>;
46
120
  onPause(listener: () => void): () => void;
47
121
  onResume(listener: () => void): () => void;
48
122
  onResize(listener: (size: OsSize) => void): () => void;
123
+ /** called with the new state whenever the desktop's sound changes; returns unsubscribe */
124
+ onSound(listener: (sound: OsSound) => void): () => void;
49
125
  /**
50
126
  * The desktop camera asks for a picture of the app. By default the SDK sends the largest visible canvas; register a handler
51
127
  * to draw one yourself (DOM apps, a custom view). It may return a canvas, a PNG/JPEG/WebP data URL (at most 1,000,000
@@ -55,6 +131,8 @@ export interface Os {
55
131
  /** release the port */
56
132
  close(): void;
57
133
  }
134
+ /** What each code means, as the SDK's own rejections say it (also the agent skill's error table). */
135
+ export declare const OS_ERROR_MESSAGES: Readonly<Record<OsErrorCode, string>>;
58
136
  /** Connect to the host: the handshake, then hello on a protocol 2 host. Call once, early. */
59
137
  export declare function connect(options?: {
60
138
  signal?: AbortSignal;
package/dist/os.js CHANGED
@@ -3,18 +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, CARD_ID, OsError, 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_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.1";
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
- const MESSAGES = {
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({
18
19
  unsupported: "This host is older than this SDK and has no such feature.",
19
20
  "not-permitted": "The manifest does not declare that, or the app is behind another window.",
20
21
  invalid: "That argument is not valid.",
@@ -24,7 +25,12 @@ const MESSAGES = {
24
25
  unavailable: "The host could not answer now; try again.",
25
26
  timeout: "The host did not answer in 10 seconds.",
26
27
  closed: "The session ended. Reopen the app.",
27
- };
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.",
32
+ });
33
+ const MESSAGES = OS_ERROR_MESSAGES;
28
34
  const fail = (code, message = MESSAGES[code]) => new OsError(code, message);
29
35
  /** Errors the SDK raises itself keep their code; anything else is `invalid` (an argument) unless said otherwise. */
30
36
  const asOsError = (error, fallback) => error instanceof OsError ? error
@@ -50,8 +56,9 @@ export async function connect(options = {}) {
50
56
  export async function createOs(port, session, protocol, href) {
51
57
  if (!appNonce(session))
52
58
  throw fail("unavailable", "Invalid app session.");
53
- let state = Object.freeze({ active: true, width: 0, height: 0 }), closed = false;
59
+ let state = Object.freeze({ active: true, width: 0, height: 0 }), closed = false, sound = AUDIBLE;
54
60
  const pause = new Set(), resume = new Set(), resize = new Set(), watchers = new Set();
61
+ const sounds = new Set();
55
62
  const transport = createRpcTransport(port, {
56
63
  session, timeoutMs: APP_LIMITS.requestTimeoutMs,
57
64
  maxPending: protocol === 2 ? 64 : APP_LIMITS.inFlight, jsonBytes: protocol === 2 ? APP_SESSION_LIMITS.messageBytes : APP_LIMITS.responseBytes,
@@ -69,6 +76,14 @@ export async function createOs(port, session, protocol, href) {
69
76
  capturer.event(value.id);
70
77
  return;
71
78
  }
79
+ if (value.event === "app.sound") {
80
+ soundEvent(value.state);
81
+ return;
82
+ }
83
+ if (value.event === "app.invite") {
84
+ inviteEvent(value.state);
85
+ return;
86
+ }
72
87
  if (value.event !== "app.lifecycle")
73
88
  return;
74
89
  let next;
@@ -92,14 +107,29 @@ export async function createOs(port, session, protocol, href) {
92
107
  },
93
108
  });
94
109
  const capturer = createCapturer((id, image) => { call({ method: "app.frame", id, image }).catch(() => { }); }, () => protocol !== 2 || !hello || closed);
95
- const call = async (request) => {
110
+ const call = async (request, timeoutMs) => {
96
111
  if (closed)
97
112
  throw fail("closed");
98
- const result = await transport.request(request);
113
+ const result = await transport.request(request, timeoutMs === undefined ? {} : { timeoutMs });
99
114
  if (!result || typeof result !== "object" || Array.isArray(result))
100
115
  throw fail("unavailable", "Invalid host response.");
101
116
  return result;
102
117
  };
118
+ /** Declared ahead so the transport can call it: a valid, changed state is kept and told to every listener. */
119
+ function soundEvent(value) {
120
+ let next;
121
+ try {
122
+ next = soundValue(value);
123
+ }
124
+ catch {
125
+ return;
126
+ }
127
+ if (next.muted === sound.muted && next.volume === sound.volume)
128
+ return;
129
+ sound = next;
130
+ for (const listener of [...sounds])
131
+ listener(sound);
132
+ }
103
133
  const completed = (result) => { if (result.completed !== true)
104
134
  throw fail("unavailable", "Invalid host acknowledgement."); };
105
135
  let hello = null;
@@ -114,6 +144,49 @@ export async function createOs(port, session, protocol, href) {
114
144
  }
115
145
  const v2 = () => { if (!hello)
116
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
+ }
117
190
  const absolute = (art) => art === null ? null : new URL(v2().root + art, href).href;
118
191
  const card = (wire) => ({ ...wire, art: absolute(wire.art) });
119
192
  // ---- cards: whole-list paging and live updates
@@ -225,6 +298,7 @@ export async function createOs(port, session, protocol, href) {
225
298
  get active() { return state.active; },
226
299
  get size() { return Object.freeze({ width: state.width, height: state.height }); },
227
300
  get guest() { return hello?.guest ?? false; },
301
+ get sound() { return sound; },
228
302
  async ready() { completed(await call({ method: "ui.ready" })); },
229
303
  progress(fraction) {
230
304
  if (typeof fraction !== "number" || !Number.isFinite(fraction) || fraction < 0 || fraction > 1)
@@ -308,7 +382,13 @@ export async function createOs(port, session, protocol, href) {
308
382
  async open(link) {
309
383
  const target = parseVmosLink(link);
310
384
  if (!target)
311
- 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
+ }
312
392
  await (target.kind === "pack" ? show({ method: "pack.show", pack: target.pack }) : show({ method: "card.show", pack: target.pack, card: target.card }));
313
393
  },
314
394
  async player() {
@@ -325,14 +405,94 @@ export async function createOs(port, session, protocol, href) {
325
405
  return { ...player };
326
406
  },
327
407
  async finish(result) {
328
- let input;
408
+ let input, board;
329
409
  try {
330
- 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);
331
415
  }
332
416
  catch (error) {
333
417
  throw asOsError(error, "invalid");
334
418
  }
335
- 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;
336
496
  },
337
497
  async maximize(on = true) { if (typeof on !== "boolean")
338
498
  throw fail("invalid"); v2(); completed(await call({ method: "display.maximize", on })); },
@@ -346,6 +506,7 @@ export async function createOs(port, session, protocol, href) {
346
506
  return capturer.on(handler);
347
507
  },
348
508
  onResize(listener) { resize.add(listener); return () => { resize.delete(listener); }; },
509
+ onSound(listener) { sounds.add(listener); return () => { sounds.delete(listener); }; },
349
510
  close() {
350
511
  if (closed)
351
512
  return;
@@ -360,7 +521,9 @@ export async function createOs(port, session, protocol, href) {
360
521
  pause.clear();
361
522
  resume.clear();
362
523
  resize.clear();
524
+ sounds.clear();
363
525
  watchers.clear();
526
+ invites.clear();
364
527
  transport.destroy();
365
528
  },
366
529
  };
@@ -370,7 +533,8 @@ export async function createOs(port, session, protocol, href) {
370
533
  const ready = os.ready;
371
534
  os.ready = async () => { readied = true; progressValue = null; await ready(); };
372
535
  // every rejection is an OsError: a malformed host answer is `unavailable`
373
- 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"]) {
374
538
  const method = os[key];
375
539
  os[key] = async (...args) => { try {
376
540
  return await method(...args);