@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/app-wire.js CHANGED
@@ -5,9 +5,17 @@
5
5
  */
6
6
  import { gameFinishInput } from "./completion.js";
7
7
  import { APP_LIMITS, FRAME_CHARS, captureId, frameImage, checkpointValue } from "./app-protocol.js";
8
- import { packSlug } from "./manifest.js";
9
- /** The nine stable error codes (section 11.3). Messages may change; codes never do. */
10
- export const OS_ERROR_CODES = ["unsupported", "not-permitted", "invalid", "too-large", "rate-limited", "needs-click", "unavailable", "timeout", "closed"];
8
+ import { GAME_SCORE_LIMIT } from "./completion.js";
9
+ import { LEADERBOARD_FORMATS, LEADERBOARD_ORDERS, PRODUCT_KINDS, assetPath, packSlug, serviceId, } from "./manifest.js";
10
+ /**
11
+ * The stable error codes (VM_OS_APPS_3.md section 11.3, nine since 0.5; VM_OS_APPS_4.md section 9 added four in 0.6:
12
+ * `cancelled`, `insufficient`, `limit` and `guest`). Messages may change; codes never do. A 0.5 client reads a code it does
13
+ * not know as `unavailable`, and a host answers the 0.6 codes only to the 0.6 methods, which a 0.5 client never sends.
14
+ */
15
+ export const OS_ERROR_CODES = [
16
+ "unsupported", "not-permitted", "invalid", "too-large", "rate-limited", "needs-click", "unavailable", "timeout", "closed",
17
+ "cancelled", "insufficient", "limit", "guest",
18
+ ];
11
19
  export const osErrorCode = (value) => typeof value === "string" && OS_ERROR_CODES.includes(value);
12
20
  /** Session-wide numbers of an apps3 host and a protocol 2 client (sections 9 and 10.1). */
13
21
  export const APP_SESSION_LIMITS = Object.freeze({
@@ -35,6 +43,13 @@ export const APP_SESSION_LIMITS = Object.freeze({
35
43
  clientPerSecond: 8, clientPerMinute: 100,
36
44
  /** a player token is reused while more than this remains */
37
45
  tokenReuseMs: 60_000,
46
+ /**
47
+ * SDK 0.6: how recent the click must be for a call that opens a vmOS surface over the app (share, invite, the leaderboard
48
+ * panel, an app link), and for `buy` (VM_OS_APPS_4.md section 8.2: a click within the last second)
49
+ */
50
+ clickMs: 5000, buyClickMs: 1000,
51
+ /** SDK 0.6: how long the SDK waits for a call answered only when the player closes a vmOS surface (buy, share, invite, the panel) */
52
+ surfaceMs: 30 * 60 * 1000,
38
53
  });
39
54
  export const RARITIES = ["common", "rare", "epic", "legendary", "mythic"];
40
55
  /** A card's id inside its pack, as the creator card rule admits it. */
@@ -46,6 +61,23 @@ export const CARD_ID = /^[A-Za-z0-9_-]{1,64}$/;
46
61
  * exactly `-/player/<handle>.bin` under the version prefix, and a three-part JWT of at most 1,500 characters.
47
62
  */
48
63
  export const PLAYER_RULES = 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 });
64
+ export const BOARD_SCOPES = ["everyone", "friends"];
65
+ export const BOARD_PERIODS = ["all", "week"];
66
+ export const PRESENCES = ["playing", "online", "offline"];
67
+ /** The numbers of VM_OS_APPS_4.md sections 3 to 8 that the SDK and the host check on every call. */
68
+ export const APPS4_LIMITS = Object.freeze({
69
+ boardRowsMax: 50, boardRowsDefault: 10, inviteText: 80, inviteData: 256, inviteRecipients: 10, shareText: 140,
70
+ friendsMax: 100, receiptsMax: 100, timeScoreMax: 86_400_000,
71
+ });
72
+ /** A receipt id as the backend issues it. */
73
+ export const RECEIPT_ID = /^[A-Za-z0-9_-]{1,64}$/;
74
+ /** An app id, as a manifest's `id` admits it. */
75
+ export const APP_ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
76
+ export const appId = (value) => typeof value === "string" && value.length <= 60 && APP_ID.test(value);
77
+ /** The feature a host lists when `finish({ score, board })` reaches its board; without it the SDK sends `{ score }` only. */
78
+ export const FINISH_BOARD_FEATURE = "game.finish.board";
79
+ /** The name a secret achievement shows until it is unlocked. */
80
+ export const SECRET_ACHIEVEMENT_NAME = "Secret achievement";
49
81
  const KiB = 1024;
50
82
  /**
51
83
  * Request and response JSON bounds (of the request object and the result), the soft rate (answered `rate-limited`) and the
@@ -67,12 +99,33 @@ export const APP_METHODS_2 = Object.freeze({
67
99
  "player.get": { request: 64, response: 2 * KiB, rate: [10, 60_000], states: "LFB" },
68
100
  "display.maximize": { request: 64, response: 64, rate: [2, 1000], states: "F" },
69
101
  "display.fullscreen": { request: 64, response: 64, rate: [1, 1000], states: "F" },
102
+ // 0.6 (VM_OS_APPS_4.md sections 3 to 8)
103
+ "leaderboard.get": { request: 256, response: 32 * KiB, rate: [30, 60_000], states: "LFB" },
104
+ "leaderboard.show": { request: 128, response: 64, rate: [1, 3000], states: "F", click: APP_SESSION_LIMITS.clickMs, surface: true },
105
+ "achievement.unlock": { request: 128, response: 64, rate: [20, 60_000], states: "LFB" },
106
+ "achievements.list": { request: 64, response: 64 * KiB, rate: [10, 60_000], states: "LFB" },
107
+ "friends.list": { request: 64, response: 64 * KiB, rate: [10, 60_000], states: "LFB" },
108
+ "app.launch": { request: 64, response: 2 * KiB, rate: [4, 60_000], states: "LFB" },
109
+ "invite.open": { request: 4 * KiB, response: 64, rate: [1, 10_000], states: "F", click: APP_SESSION_LIMITS.clickMs, guest: true, surface: true },
110
+ "share.open": { request: 2 * KiB, response: 64, rate: [1, 10_000], states: "F", click: APP_SESSION_LIMITS.clickMs, guest: true, surface: true },
111
+ "products.list": { request: 64, response: 64 * KiB, rate: [10, 60_000], states: "LFB" },
112
+ "product.buy": { request: 128, response: 512, rate: [1, 3000], states: "F", click: APP_SESSION_LIMITS.buyClickMs, guest: true, surface: true },
113
+ "purchases.list": { request: 64, response: 32 * KiB, rate: [10, 60_000], states: "LFB" },
114
+ "purchase.consume": { request: 192, response: 64, rate: [30, 60_000], states: "LFB" },
115
+ "purchase.token": { request: 192, response: 2 * KiB, rate: [10, 60_000], states: "LFB" },
116
+ "app.show": { request: 192, response: 64, rate: [1, 10_000], bucket: "show", states: "F", click: APP_SESSION_LIMITS.clickMs },
70
117
  });
118
+ /** The 0.6 methods: a host lists each in hello's features only when it can answer it (AppHostServices), like `card.show`. */
119
+ export const APPS4_METHODS = Object.freeze([
120
+ "leaderboard.get", "leaderboard.show", "achievement.unlock", "achievements.list", "friends.list", "app.launch", "invite.open", "share.open",
121
+ "products.list", "product.buy", "purchases.list", "purchase.consume", "purchase.token", "app.show",
122
+ ]);
71
123
  /**
72
- * Protocol 2 features a hello answers with: the methods beyond protocol 1. `card.show` (0.5.1) is listed only by a host whose
73
- * services can show a card; a 0.5.0 host never lists it, and a client never sends a method its host did not list.
124
+ * Protocol 2 features a hello answers with: the methods beyond protocol 1. `card.show` (0.5.1) and the 0.6 methods are listed
125
+ * only by a host whose services answer them; a 0.5.0 host never lists them, and a client never sends a method its host did
126
+ * not list (it answers `unsupported` itself).
74
127
  */
75
- export const APP_FEATURES_2 = Object.freeze(Object.keys(APP_METHODS_2).filter(method => method !== "host.hello" && method !== "card.show"));
128
+ export const APP_FEATURES_2 = Object.freeze(Object.keys(APP_METHODS_2).filter(method => method !== "host.hello" && method !== "card.show" && !APPS4_METHODS.includes(method)));
76
129
  const encoder = new TextEncoder();
77
130
  export const utf8Bytes = (text) => encoder.encode(text).byteLength;
78
131
  const plain = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
@@ -227,9 +280,127 @@ export function wireHello(value) {
227
280
  throw Error("Invalid hello.");
228
281
  return { protocol: 2, guest: value.guest, features: value.features, root: value.root };
229
282
  }
283
+ // ---- 0.6 shapes: strict, so nothing private can ride along (APPS 4 section 10)
284
+ const oneOf = (values, value) => typeof value === "string" && values.includes(value);
285
+ const picture = (value, handle) => value === null || value === playerPicturePath(handle);
286
+ const displayName = (value) => string(value, PLAYER_RULES.nameMax, 1) && !CONTROL.test(value);
287
+ const score = (value) => whole(value, 0, GAME_SCORE_LIMIT);
288
+ const line = (value, max, min = 1) => typeof value === "string" && value.length >= min && [...value].length <= max && !CONTROL.test(value);
289
+ /** An achievement icon on the wire: the manifest's bundle path of a PNG or WebP. */
290
+ const iconPath = (value) => typeof value === "string" && assetPath(value) && /\.(?:png|webp)$/.test(value);
291
+ const playerFields = (value) => handleOf(value.handle) && displayName(value.name) && picture(value.picture, value.handle);
292
+ /** A board read as the host sends it; `query`, when given, is what was asked (the answer must be that board and period). */
293
+ export function wireLeaderboard(value, query) {
294
+ if (!plain(value) || !keysExactly(value, ["board", "name", "order", "format", "period", "entries", "you"]))
295
+ throw Error("Invalid leaderboard.");
296
+ const { board, name, order, format, period, entries, you } = value;
297
+ if (!serviceId(board) || !line(name, 40) || !oneOf(LEADERBOARD_ORDERS, order) || !oneOf(LEADERBOARD_FORMATS, format) || !oneOf(BOARD_PERIODS, period)
298
+ || !Array.isArray(entries) || entries.length > (query?.limit ?? APPS4_LIMITS.boardRowsMax)
299
+ || (query && (board !== query.board || period !== query.period)))
300
+ throw Error("Invalid leaderboard.");
301
+ const rows = entries.map(entry => {
302
+ if (!plain(entry) || !keysExactly(entry, ["rank", "handle", "name", "picture", "score", "you"]) || !whole(entry.rank, 1, Number.MAX_SAFE_INTEGER) || !playerFields(entry)
303
+ || !score(entry.score) || typeof entry.you !== "boolean")
304
+ throw Error("Invalid leaderboard entry.");
305
+ return { rank: entry.rank, handle: entry.handle, name: entry.name, picture: entry.picture, score: entry.score, you: entry.you };
306
+ });
307
+ let mine = null;
308
+ if (you !== null) {
309
+ if (!plain(you) || !keysExactly(you, ["rank", "score"]) || !whole(you.rank, 1, Number.MAX_SAFE_INTEGER) || !score(you.score))
310
+ throw Error("Invalid leaderboard.");
311
+ mine = { rank: you.rank, score: you.score };
312
+ }
313
+ return { board, name, order, format, period, entries: rows, you: mine };
314
+ }
315
+ export function wireAchievement(value) {
316
+ if (!plain(value) || !keysExactly(value, ["id", "name", "description", "icon", "secret", "unlocked", "at"]))
317
+ throw Error("Invalid achievement.");
318
+ const { id, name, description, icon, secret, unlocked, at } = value;
319
+ if (!serviceId(id) || !line(name, 40) || !line(description, 120, 0) || (icon !== null && !iconPath(icon)) || typeof secret !== "boolean" || typeof unlocked !== "boolean"
320
+ || (unlocked ? !whole(at, 0, Number.MAX_SAFE_INTEGER) : at !== null)
321
+ // a secret the player has not found says nothing about itself
322
+ || (secret && !unlocked && (description !== "" || icon !== null)))
323
+ throw Error("Invalid achievement.");
324
+ return { id, name, description, icon, secret, unlocked, at: at };
325
+ }
326
+ export function wireFriend(value) {
327
+ if (!plain(value) || !keysExactly(value, ["handle", "name", "picture", "presence"]) || !playerFields(value) || !oneOf(PRESENCES, value.presence))
328
+ throw Error("Invalid friend.");
329
+ return { handle: value.handle, name: value.name, picture: value.picture, presence: value.presence };
330
+ }
331
+ export function wireInvite(value) {
332
+ if (!plain(value) || !keysExactly(value, ["from", "data"]) || !handleOf(value.from) || (value.data !== null && !string(value.data, APPS4_LIMITS.inviteData)))
333
+ throw Error("Invalid invite.");
334
+ return { from: value.from, data: value.data };
335
+ }
336
+ export function wireProduct(value) {
337
+ if (!plain(value) || !keysExactly(value, ["id", "name", "description", "price", "kind", "owned"]))
338
+ throw Error("Invalid product.");
339
+ const { id, name, description, price, kind, owned } = value;
340
+ if (!serviceId(id) || !line(name, 40) || !line(description, 120) || !whole(price, 1, 1_000_000) || !oneOf(PRODUCT_KINDS, kind) || typeof owned !== "boolean"
341
+ || (owned && kind !== "permanent"))
342
+ throw Error("Invalid product.");
343
+ return { id, name, description, price, kind, owned };
344
+ }
345
+ export function wireReceipt(value) {
346
+ if (!plain(value) || !keysExactly(value, ["id", "product", "kind", "price", "at", "consumed"]))
347
+ throw Error("Invalid receipt.");
348
+ const { id, product, kind, price, at, consumed } = value;
349
+ if (typeof id !== "string" || !RECEIPT_ID.test(id) || !serviceId(product) || !oneOf(PRODUCT_KINDS, kind) || !whole(price, 1, 1_000_000) || !whole(at, 0, Number.MAX_SAFE_INTEGER)
350
+ || typeof consumed !== "boolean" || (consumed && kind !== "consumable"))
351
+ throw Error("Invalid receipt.");
352
+ return { id, product, kind, price, at, consumed };
353
+ }
354
+ /**
355
+ * Why a 0.6 request's values are not acceptable (`invalid`), or null: the exact rules of VM_OS_APPS_4.md sections 3 to 8 on top
356
+ * of `appRequest2`'s structural check. The SDK refuses before sending and the host refuses again before its handler runs.
357
+ */
358
+ export function apps4Problem(request) {
359
+ const board = (value) => value === undefined || serviceId(value);
360
+ switch (request.method) {
361
+ case "leaderboard.get": {
362
+ if (!board(request.board))
363
+ return "That is not a board id.";
364
+ if (request.scope !== undefined && !oneOf(BOARD_SCOPES, request.scope))
365
+ return 'scope is "everyone" or "friends".';
366
+ if (request.period !== undefined && !oneOf(BOARD_PERIODS, request.period))
367
+ return 'period is "all" or "week".';
368
+ if (request.limit !== undefined && !whole(request.limit, 1, APPS4_LIMITS.boardRowsMax))
369
+ return `limit is a whole number from 1 to ${APPS4_LIMITS.boardRowsMax}.`;
370
+ return null;
371
+ }
372
+ case "leaderboard.show": return board(request.board) ? null : "That is not a board id.";
373
+ case "achievement.unlock": return serviceId(request.id) ? null : "That is not an achievement id.";
374
+ case "invite.open":
375
+ if (request.to !== undefined && !handleOf(request.to))
376
+ return "to is a player's handle.";
377
+ if (request.text !== undefined && !line(request.text, APPS4_LIMITS.inviteText, 0))
378
+ return `An invite's text is one line of at most ${APPS4_LIMITS.inviteText} characters.`;
379
+ if (request.data !== undefined && !string(request.data, APPS4_LIMITS.inviteData))
380
+ return `An invite's data is at most ${APPS4_LIMITS.inviteData} characters.`;
381
+ return null;
382
+ case "share.open":
383
+ if (request.text !== undefined && !line(request.text, APPS4_LIMITS.shareText, 0))
384
+ return `A share's text is one line of at most ${APPS4_LIMITS.shareText} characters.`;
385
+ if (request.score !== undefined && !score(request.score))
386
+ return "score is a whole number from 0 to 1,000,000,000.";
387
+ if (!board(request.board))
388
+ return "That is not a board id.";
389
+ if (request.board !== undefined && request.score === undefined)
390
+ return "A board is shared with a score.";
391
+ return null;
392
+ case "product.buy": return serviceId(request.product) ? null : "That is not a product id.";
393
+ case "purchase.consume":
394
+ case "purchase.token": return RECEIPT_ID.test(request.receipt) ? null : "That is not a receipt id.";
395
+ case "app.show": return appId(request.app) ? null : "That is not an app id.";
396
+ default: return null;
397
+ }
398
+ }
230
399
  /** The version prefix relative to the entry document: `./` for `index.html`, `../` for `app/index.html`. */
231
400
  export const entryRoot = (entry) => entry.includes("/") ? "../".repeat(entry.split("/").length - 1) : "./";
232
401
  export { captureId, frameImage };
402
+ /** The keys whose value is not undefined (an optional field is either a value or absent, never `undefined` on the wire). */
403
+ const defined = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
233
404
  /**
234
405
  * A protocol 2 request, structurally checked (a violation ends the session). Values a well-behaved client could still get
235
406
  * wrong (a bad slug, a save over the limit) are left for the controller to answer `invalid` or `too-large`.
@@ -239,7 +410,11 @@ export function appRequest2(request) {
239
410
  switch (method) {
240
411
  case "ui.ready":
241
412
  case "app.checkpoint.get": return only() ? { method } : null;
242
- case "game.finish": return only("score") ? { method, ...gameFinishInput({ score: request.score }) } : null;
413
+ case "game.finish":
414
+ // 0.6: a board, only to a host that listed FINISH_BOARD_FEATURE (a 0.5 host ends the session on it)
415
+ if (keysExactly(request, ["method", "score"], ["board"]) && "board" in request)
416
+ return serviceId(request.board) ? { method, ...gameFinishInput({ score: request.score }), board: request.board } : null;
417
+ return only("score") ? { method, ...gameFinishInput({ score: request.score }) } : null;
243
418
  case "app.checkpoint.set": return only("value") ? { method, value: checkpointValue(request.value) } : null;
244
419
  case "host.hello": return only("protocol", "sdk") && request.protocol === 2 && string(request.sdk, 20, 1) && /^[\x20-\x7e]+$/.test(request.sdk) ? { method, protocol: 2, sdk: request.sdk } : null;
245
420
  case "ui.progress": return only("value") && typeof request.value === "number" && Number.isFinite(request.value) ? { method, value: request.value } : null;
@@ -259,6 +434,37 @@ export function appRequest2(request) {
259
434
  case "display.maximize":
260
435
  case "display.fullscreen":
261
436
  case "cards.watch": return only("on") && typeof request.on === "boolean" ? { method, on: request.on } : null;
437
+ // 0.6: types and loose bounds here (a violation ends the session); the exact rules are apps4Problem's soft `invalid`
438
+ case "leaderboard.get": {
439
+ const { board, scope, period, limit } = request;
440
+ if (!keysExactly(request, ["method"], ["board", "scope", "period", "limit"]) || (board !== undefined && !string(board, 64, 1)) || (scope !== undefined && !string(scope, 16, 1))
441
+ || (period !== undefined && !string(period, 16, 1)) || (limit !== undefined && typeof limit !== "number"))
442
+ return null;
443
+ return { method, ...defined({ board, scope, period, limit }) };
444
+ }
445
+ case "leaderboard.show": return keysExactly(request, ["method"], ["board"]) && (request.board === undefined || string(request.board, 64, 1)) ? { method, ...defined({ board: request.board }) } : null;
446
+ case "achievement.unlock": return only("id") && string(request.id, 64, 1) ? { method, id: request.id } : null;
447
+ case "achievements.list":
448
+ case "friends.list":
449
+ case "app.launch":
450
+ case "products.list":
451
+ case "purchases.list": return only() ? { method } : null;
452
+ case "invite.open": {
453
+ const { to, text, data } = request;
454
+ if (!keysExactly(request, ["method"], ["to", "text", "data"]) || (to !== undefined && !string(to, 64, 1)) || (text !== undefined && !string(text, 1024)) || (data !== undefined && !string(data, 1024)))
455
+ return null;
456
+ return { method, ...defined({ to, text, data }) };
457
+ }
458
+ case "share.open": {
459
+ const { text, score, board } = request;
460
+ if (!keysExactly(request, ["method"], ["text", "score", "board"]) || (text !== undefined && !string(text, 1024)) || (score !== undefined && typeof score !== "number") || (board !== undefined && !string(board, 64, 1)))
461
+ return null;
462
+ return { method, ...defined({ text, score, board }) };
463
+ }
464
+ case "product.buy": return only("product") && string(request.product, 64, 1) ? { method, product: request.product } : null;
465
+ case "purchase.consume":
466
+ case "purchase.token": return only("receipt") && string(request.receipt, 64, 1) ? { method, receipt: request.receipt } : null;
467
+ case "app.show": return only("app") && string(request.app, 64, 1) ? { method, app: request.app } : null;
262
468
  default: return null;
263
469
  }
264
470
  }
package/dist/browser.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /** The no-bundler build's entry: `dist/vibemarket-os.js` exposes exactly these as the global `VibemarketOS`. */
2
2
  export { connect, OsError } from "./os.ts";
3
- export { cardLink, packLink, parseVmosLink } from "./links.ts";
3
+ export { appLink, cardLink, packLink, parseVmosLink } from "./links.ts";
4
4
  export { createAudio } from "./audio.ts";
package/dist/browser.js CHANGED
@@ -1,4 +1,4 @@
1
1
  /** The no-bundler build's entry: `dist/vibemarket-os.js` exposes exactly these as the global `VibemarketOS`. */
2
2
  export { connect, OsError } from "./os.js";
3
- export { cardLink, packLink, parseVmosLink } from "./links.js";
3
+ export { appLink, cardLink, packLink, parseVmosLink } from "./links.js";
4
4
  export { createAudio } from "./audio.js";
package/dist/bundle.js CHANGED
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { lstat, open, opendir, realpath } from "node:fs/promises";
3
3
  import { constants } from "node:fs";
4
4
  import path from "node:path";
5
- import { APP_BUNDLE_LIMITS, assetPath, parseManifest } from "./manifest.js";
5
+ import { APP_BUNDLE_LIMITS, APP_MANIFEST_LIMITS, assetPath, parseManifest } from "./manifest.js";
6
6
  import { checkListing } from "./listing.js";
7
7
  const TYPES = {
8
8
  html: "text/html; charset=utf-8", js: "text/javascript; charset=utf-8", mjs: "text/javascript; charset=utf-8",
@@ -72,8 +72,8 @@ export async function readBuiltBundle(directory) {
72
72
  }
73
73
  await walk("");
74
74
  const input = files["vibemarket.json"];
75
- if (!input || input.byteLength > 16 * 1024)
76
- throw Error("A manifest of at most16KiB is required.");
75
+ if (!input || input.byteLength > APP_MANIFEST_LIMITS.manifestBytes)
76
+ throw Error(`A manifest of at most ${APP_MANIFEST_LIMITS.manifestBytes / 1024} KiB is required.`);
77
77
  const manifest = parseManifest(JSON.parse(new TextDecoder().decode(input)));
78
78
  if (!files[manifest.entry])
79
79
  throw Error("Manifest entry is missing from the app bundle.");
package/dist/check.js CHANGED
@@ -7,8 +7,8 @@ import { lstat, opendir } from "node:fs/promises";
7
7
  import path from "node:path";
8
8
  import { zipSync } from "fflate";
9
9
  import { assetType, compareAssetNames, readBoundedAsset } from "./bundle.js";
10
- import { imageKind, pngSize } from "./listing.js";
11
- import { APP_BUNDLE_LIMITS, APP_STORE_LIMITS, assetPath, checkManifest, manifestNotices, manifestProblemText, parseManifest } from "./manifest.js";
10
+ import { achievementIconProblem, imageKind, pngSize } from "./listing.js";
11
+ import { APP_BUNDLE_LIMITS, APP_MANIFEST_LIMITS, APP_STORE_LIMITS, assetPath, checkManifest, manifestNotices, manifestProblemText, parseManifest } from "./manifest.js";
12
12
  const KiB = 1024, MiB = 1024 * 1024;
13
13
  const size = (bytes) => bytes >= MiB ? `${(bytes / MiB).toFixed(1)} MiB` : `${Math.ceil(bytes / KiB)} KiB`;
14
14
  const missing = (error) => error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT";
@@ -116,12 +116,12 @@ function listingProblems(icon, screenshots, files) {
116
116
  async function manifestAt(file, label) {
117
117
  let bytes;
118
118
  try {
119
- bytes = await readBoundedAsset(file, 16 * KiB);
119
+ bytes = await readBoundedAsset(file, APP_MANIFEST_LIMITS.manifestBytes);
120
120
  }
121
121
  catch (error) {
122
122
  if (missing(error))
123
123
  return null;
124
- return { problem: `${label}: must be a file of at most 16 KiB.` };
124
+ return { problem: `${label}: must be a file of at most ${APP_MANIFEST_LIMITS.manifestBytes / KiB} KiB.` };
125
125
  }
126
126
  try {
127
127
  return { value: JSON.parse(new TextDecoder().decode(bytes)) };
@@ -158,6 +158,13 @@ export async function checkApp(directory, limits = APP_BUNDLE_LIMITS) {
158
158
  problems.push(...listingProblems(parsed.store.icon, parsed.store.screenshots, files));
159
159
  else
160
160
  notices.push("schemaVersion: 1 has no store listing and cannot be submitted to VibeStore; use 3.");
161
+ // SDK 0.6: each achievement's icon, by the same rule as the store's checkListing
162
+ if (parsed.schemaVersion === 3)
163
+ (parsed.achievements ?? []).forEach((achievement, index) => {
164
+ const problem = achievement.icon === null ? null : achievementIconProblem(achievement.icon, files.get(achievement.icon));
165
+ if (problem)
166
+ problems.push(`achievements[${index}].icon: ${problem}`);
167
+ });
161
168
  if (!problems.length) {
162
169
  const zip = zipSync(Object.fromEntries([...files].map(([name, bytes]) => [name, bytes])), { level: 6 });
163
170
  if (zip.length > limits.archive)
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The in-memory stand-in for the vmOS services of SDK 0.6 (VM_OS_APPS_4.md sections 3 to 8): boards, achievements, friends,
3
+ * invites, sharing and spending. One implementation serves both the testing module (`createFakeOs`) and the local preview
4
+ * (`os preview`), so a game tested against one behaves the same in the other. It keeps the rules a game can rely on (declared
5
+ * ids, best score by the board's order, an unlock counted once, secret achievements, guests, owned permanent products,
6
+ * receipts that stay until consumed, at most 20 unconsumed, never spending more than the player has) and leaves out what only
7
+ * the server knows: rounds and their timing, rate limits, daily caps and the week's reset (`period: "week"` reads the same
8
+ * rows as all time). Pure: no DOM, no Node, no clock but the one given.
9
+ */
10
+ import { type Achievement, type Friend, type InviteOptions, type Leaderboard, type LeaderboardQuery, type Product, type Receipt, type ShareOptions } from "./app-wire.ts";
11
+ import { type AppAchievement, type AppLeaderboard, type AppProduct } from "./manifest.ts";
12
+ /** Another player's best score on a board (default `score`). `friend` puts them in the player's friends scope too. */
13
+ export interface FakeScore {
14
+ board?: string;
15
+ handle: string;
16
+ name: string;
17
+ picture?: string | null;
18
+ score: number;
19
+ friend?: boolean;
20
+ }
21
+ export interface FakeServicesOptions {
22
+ /** the manifest's declared lists, normalized (`parseServices`); the board `score` is added unless declared */
23
+ leaderboards?: readonly AppLeaderboard[];
24
+ achievements?: readonly AppAchievement[];
25
+ products?: readonly AppProduct[];
26
+ /** who is playing, or null for a guest */
27
+ player: {
28
+ handle: string;
29
+ name: string;
30
+ picture: string | null;
31
+ } | null;
32
+ scores?: readonly FakeScore[];
33
+ /** the player's friends who have the app */
34
+ friends?: readonly Friend[];
35
+ /** the player's Printer Cash; the fake never tells the app this number. Default 1,000. */
36
+ printerCash?: number;
37
+ /** whether the manifest declares `network` (receipt tokens) */
38
+ network?: boolean;
39
+ now: () => number;
40
+ }
41
+ /** What a game did, for a test to assert. */
42
+ export interface FakeServicesState {
43
+ /** every score a finish posted and the fake recorded, in order */
44
+ readonly posted: readonly {
45
+ board: string;
46
+ score: number;
47
+ }[];
48
+ /** achievement ids in the order they were first unlocked */
49
+ readonly unlocked: readonly string[];
50
+ readonly shares: readonly (ShareOptions & {
51
+ board?: string;
52
+ })[];
53
+ readonly invites: readonly (InviteOptions & {
54
+ sent: number;
55
+ })[];
56
+ /** every receipt, consumed or not */
57
+ readonly receipts: readonly Receipt[];
58
+ readonly printerCash: number;
59
+ }
60
+ export interface FakeServices {
61
+ /** a finished round's score: recorded as the player's best when it beats it; false when it is not recorded (a guest, an undeclared board, a time out of range) */
62
+ post(score: number, board?: string): boolean;
63
+ leaderboard(query: LeaderboardQuery): Leaderboard;
64
+ unlock(id: string): {
65
+ unlocked: boolean;
66
+ };
67
+ achievements(): Achievement[];
68
+ friends(): Friend[];
69
+ /** `confirmed`: whether the player confirmed the sheet */
70
+ invite(options: InviteOptions, confirmed: boolean): {
71
+ sent: number;
72
+ };
73
+ share(options: ShareOptions, confirmed: boolean): {
74
+ shared: boolean;
75
+ };
76
+ products(): Product[];
77
+ /** `confirmed`: whether the player confirmed the spend dialog */
78
+ buy(product: string, confirmed: boolean): Receipt;
79
+ purchases(): Receipt[];
80
+ consume(receipt: string): void;
81
+ receiptToken(receipt: string): string;
82
+ /** a product's declaration, for drawing its dialog */
83
+ product(id: string): AppProduct;
84
+ readonly state: FakeServicesState;
85
+ }
86
+ /** The most unconsumed receipts of one app a player may hold (VM_OS_APPS_4.md section 8.4). */
87
+ export declare const UNCONSUMED_RECEIPTS_MAX = 20;
88
+ export declare function createFakeServices(options: FakeServicesOptions): FakeServices;
@@ -0,0 +1,132 @@
1
+ /**
2
+ * The in-memory stand-in for the vmOS services of SDK 0.6 (VM_OS_APPS_4.md sections 3 to 8): boards, achievements, friends,
3
+ * invites, sharing and spending. One implementation serves both the testing module (`createFakeOs`) and the local preview
4
+ * (`os preview`), so a game tested against one behaves the same in the other. It keeps the rules a game can rely on (declared
5
+ * ids, best score by the board's order, an unlock counted once, secret achievements, guests, owned permanent products,
6
+ * receipts that stay until consumed, at most 20 unconsumed, never spending more than the player has) and leaves out what only
7
+ * the server knows: rounds and their timing, rate limits, daily caps and the week's reset (`period: "week"` reads the same
8
+ * rows as all time). Pure: no DOM, no Node, no clock but the one given.
9
+ */
10
+ import { APPS4_LIMITS, AppHostError, SECRET_ACHIEVEMENT_NAME, } from "./app-wire.js";
11
+ import { appLeaderboards } from "./manifest.js";
12
+ /** The most unconsumed receipts of one app a player may hold (VM_OS_APPS_4.md section 8.4). */
13
+ export const UNCONSUMED_RECEIPTS_MAX = 20;
14
+ const fail = (code, message) => new AppHostError(code, message);
15
+ export function createFakeServices(options) {
16
+ const boards = appLeaderboards({ leaderboards: [...(options.leaderboards ?? [])] }), declared = options.achievements ?? [], catalog = options.products ?? [];
17
+ const friends = (options.friends ?? []).map(friend => ({ ...friend }));
18
+ const others = (options.scores ?? []).map(entry => ({ board: entry.board ?? "score", handle: entry.handle, name: entry.name, picture: entry.picture ?? null, score: entry.score, friend: entry.friend === true }));
19
+ const best = new Map(), unlockedAt = new Map();
20
+ const posted = [], shares = [], invites = [], receipts = [];
21
+ let cash = options.printerCash ?? 1000, sequence = 0;
22
+ const player = options.player;
23
+ const signedIn = (what) => { if (!player)
24
+ throw fail("guest", `Guests cannot ${what}; the player has to sign in.`); return player; };
25
+ const board = (id) => { const found = boards.find(item => item.id === id); if (!found)
26
+ throw fail("invalid", `The board ${id} is not declared in the manifest.`); return found; };
27
+ const product = (id) => { const found = catalog.find(item => item.id === id); if (!found)
28
+ throw fail("invalid", `The product ${id} is not declared in the manifest.`); return found; };
29
+ const receipt = (id) => { const found = receipts.find(item => item.id === id); if (!found)
30
+ throw fail("invalid", "There is no such receipt."); return found; };
31
+ const better = (order, a, b) => order === "high" ? a > b : a < b;
32
+ return {
33
+ post(score, id = "score") {
34
+ const found = boards.find(item => item.id === id);
35
+ if (!player || !found || (found.format === "time" && score > APPS4_LIMITS.timeScoreMax))
36
+ return false;
37
+ const held = best.get(id);
38
+ if (!held || better(found.order, score, held.score))
39
+ best.set(id, { score, at: options.now() });
40
+ posted.push({ board: id, score });
41
+ return true;
42
+ },
43
+ leaderboard(query) {
44
+ const found = board(query.board), friendly = new Set(friends.map(friend => friend.handle));
45
+ const rows = others.filter(row => row.board === found.id && (query.scope === "everyone" || row.friend || friendly.has(row.handle)))
46
+ .map((row, index) => ({ handle: row.handle, name: row.name, picture: row.picture, score: row.score, you: false, at: index - others.length }));
47
+ const mine = best.get(found.id);
48
+ if (player && mine)
49
+ rows.push({ handle: player.handle, name: player.name, picture: player.picture, score: mine.score, you: true, at: mine.at });
50
+ // the better score first; a tie goes to the earlier one (seeded rows are older than anything the player posts)
51
+ rows.sort((a, b) => a.score === b.score ? a.at - b.at : better(found.order, a.score, b.score) ? -1 : 1);
52
+ const ranked = rows.map((row, index) => ({ rank: index + 1, handle: row.handle, name: row.name, picture: row.picture, score: row.score, you: row.you }));
53
+ const you = ranked.find(row => row.you);
54
+ return { board: found.id, name: found.name, order: found.order, format: found.format, period: query.period, entries: ranked.slice(0, query.limit), you: you ? { rank: you.rank, score: you.score } : null };
55
+ },
56
+ unlock(id) {
57
+ if (!declared.some(item => item.id === id))
58
+ throw fail("invalid", `The achievement ${id} is not declared in the manifest.`);
59
+ if (!player || unlockedAt.has(id))
60
+ return { unlocked: false };
61
+ unlockedAt.set(id, options.now());
62
+ return { unlocked: true };
63
+ },
64
+ achievements() {
65
+ return declared.map(item => {
66
+ const at = unlockedAt.get(item.id) ?? null, unlocked = at !== null;
67
+ if (item.secret && !unlocked)
68
+ return { id: item.id, name: SECRET_ACHIEVEMENT_NAME, description: "", icon: null, secret: true, unlocked: false, at: null };
69
+ return { id: item.id, name: item.name, description: item.description, icon: item.icon, secret: item.secret, unlocked, at };
70
+ });
71
+ },
72
+ friends() {
73
+ const rank = { playing: 0, online: 1, offline: 2 };
74
+ return friends.slice().sort((a, b) => rank[a.presence] - rank[b.presence] || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)).slice(0, APPS4_LIMITS.friendsMax).map(friend => ({ ...friend }));
75
+ },
76
+ invite(given, confirmed) {
77
+ signedIn("invite friends");
78
+ const chosen = given.to !== undefined && friends.some(friend => friend.handle === given.to) ? 1 : Math.min(friends.length, APPS4_LIMITS.inviteRecipients);
79
+ const sent = confirmed ? chosen : 0;
80
+ invites.push({ ...given, sent });
81
+ return { sent };
82
+ },
83
+ share(given, confirmed) {
84
+ signedIn("share");
85
+ if (given.score !== undefined)
86
+ board(given.board ?? "score");
87
+ if (!confirmed)
88
+ return { shared: false };
89
+ shares.push({ ...given, ...(given.score !== undefined ? { board: given.board ?? "score" } : {}) });
90
+ return { shared: true };
91
+ },
92
+ products() {
93
+ return catalog.map(item => ({ ...item, owned: item.kind === "permanent" && receipts.some(row => row.product === item.id) }));
94
+ },
95
+ buy(id, confirmed) {
96
+ const item = product(id);
97
+ signedIn("buy");
98
+ if (!confirmed)
99
+ throw fail("cancelled", "The player closed the dialog without spending.");
100
+ const owned = item.kind === "permanent" ? receipts.find(row => row.product === item.id) : undefined;
101
+ if (owned)
102
+ return { ...owned };
103
+ if (receipts.filter(row => row.kind === "consumable" && !row.consumed).length >= UNCONSUMED_RECEIPTS_MAX)
104
+ throw fail("limit", "Too many purchases are waiting to be consumed; consume them first.");
105
+ if (cash < item.price)
106
+ throw fail("insufficient", "The player does not have enough Printer Cash for that.");
107
+ cash -= item.price;
108
+ const made = { id: `fake-r${++sequence}`, product: item.id, kind: item.kind, price: item.price, at: options.now(), consumed: false };
109
+ receipts.push(made);
110
+ return { ...made };
111
+ },
112
+ purchases() { return receipts.filter(row => !row.consumed).map(row => ({ ...row })); },
113
+ consume(id) {
114
+ const found = receipt(id);
115
+ if (found.kind !== "consumable")
116
+ throw fail("invalid", "Only a consumable's receipt is consumed.");
117
+ found.consumed = true;
118
+ },
119
+ receiptToken(id) {
120
+ if (!options.network)
121
+ throw fail("not-permitted", "Receipt tokens are for apps that declare network.");
122
+ return `fake.receipt-token.${receipt(id).id}`;
123
+ },
124
+ product,
125
+ get state() {
126
+ return {
127
+ posted: posted.map(row => ({ ...row })), unlocked: [...unlockedAt.keys()], shares: shares.map(row => ({ ...row })), invites: invites.map(row => ({ ...row })),
128
+ receipts: receipts.map(row => ({ ...row })), printerCash: cash,
129
+ };
130
+ },
131
+ };
132
+ }
package/dist/index.d.ts CHANGED
@@ -2,10 +2,10 @@ export { connectGameSdk, createPortSdk } from "./client.ts";
2
2
  export { CHANNEL } from "./channel.ts";
3
3
  export { watchInventory } from "./inventory.ts";
4
4
  export { connect, OsError, OS_ERROR_CODES, OS_SDK_VERSION } from "./os.ts";
5
- export type { Card, Os, OsErrorCode, OsSize, OsSound, Pack, PackCard, PackSummary, Player, Rarity, SignedInPlayer } from "./os.ts";
5
+ export type { Achievement, BoardPeriod, BoardScope, Card, Friend, Invite, InviteOptions, Leaderboard, LeaderboardEntry, LeaderboardFormat, LeaderboardOptions, LeaderboardOrder, Os, OsErrorCode, OsLaunch, OsSize, OsSound, Pack, PackCard, PackSummary, Player, Presence, Product, ProductKind, Rarity, Receipt, ShareOptions, SignedInPlayer, } from "./os.ts";
6
6
  export type { CaptureResult } from "./capture.ts";
7
7
  export { spawnWorker } from "./worker.ts";
8
- export { cardLink, packLink, parseVmosLink, VMOS_LINK_MAX } from "./links.ts";
8
+ export { appLink, cardLink, packLink, parseVmosLink, VMOS_LINK_MAX } from "./links.ts";
9
9
  export type { VmosLink } from "./links.ts";
10
10
  export type { SpawnedWorker, WorkerHost } from "./worker.ts";
11
11
  /** @deprecated Use `connect()`: the same readiness, lifecycle and score, plus saves that outlive the window, cards and more. */
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ export { CHANNEL } from "./channel.js";
3
3
  export { watchInventory } from "./inventory.js";
4
4
  export { connect, OsError, OS_ERROR_CODES, OS_SDK_VERSION } from "./os.js";
5
5
  export { spawnWorker } from "./worker.js";
6
- export { cardLink, packLink, parseVmosLink, VMOS_LINK_MAX } from "./links.js";
6
+ export { appLink, cardLink, packLink, parseVmosLink, VMOS_LINK_MAX } from "./links.js";
7
7
  /** @deprecated Use `connect()`: the same readiness, lifecycle and score, plus saves that outlive the window, cards and more. */
8
8
  export { connectVibeMarketApp } from "./app-client.js";
9
9
  export { GAME_SCORE_LIMIT } from "./completion.js";
package/dist/links.d.ts CHANGED
@@ -5,16 +5,23 @@ export type VmosLink = {
5
5
  kind: "card";
6
6
  pack: string;
7
7
  card: string;
8
+ } | {
9
+ kind: "app";
10
+ app: string;
8
11
  };
9
12
  export declare const VMOS_LINK_MAX = 200;
10
- /** The three accepted forms, exactly as parseVmosLink matches them (the agent skill prints these). */
13
+ /** The accepted forms, exactly as parseVmosLink matches them (the agent skill prints these). */
11
14
  export declare const VMOS_LINK_PATTERNS: Readonly<{
12
15
  pack: RegExp;
13
16
  card: RegExp;
14
17
  web: RegExp;
18
+ app: RegExp;
19
+ webApp: RegExp;
15
20
  }>;
16
21
  /** The target a link names, or null when it is not exactly one of the three forms. */
17
22
  export declare function parseVmosLink(text: unknown): VmosLink | null;
23
+ /** `vmos://app/<appId>` (0.6); throws an OsError `invalid` for a value that is not an app id. */
24
+ export declare function appLink(id: string): string;
18
25
  /** `vmos://pack/<slug>`; throws an OsError `invalid` for a value that is not a pack slug. */
19
26
  export declare function packLink(slug: string): string;
20
27
  /** `vmos://card/<slug>/<cardId>`; throws an OsError `invalid` for a value that is not a pack slug or a card id. */