@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-host.js CHANGED
@@ -1,8 +1,19 @@
1
1
  import { CHANNEL } from "./channel.js";
2
2
  import { appRuntimeRefusal } from "./app-runtime.js";
3
3
  import { APP_FRAGMENT, APP_LIMITS, FRAME_MESSAGE_BYTES, appJson, appNonce, checkpointJson, createAppNonce, lifecycleValue, parseAppEnvelope, parseAppJson, soundValue } from "./app-protocol.js";
4
- import { APP_FEATURES_2, APP_METHODS_2, APP_SESSION_LIMITS, CARD_ID, cardArtPath, coverArtPath, AppHostError, appRequest2, cardsRevision, frameImage, entryRoot, methodRule, saveJson, saveValue, utf8Bytes, wireCard, wirePack, wirePackSummary, wirePlayer, } from "./app-wire.js";
4
+ import { APP_FEATURES_2, APP_METHODS_2, APP_SESSION_LIMITS, APPS4_LIMITS, APPS4_METHODS, CARD_ID, FINISH_BOARD_FEATURE, PLAYER_RULES, cardArtPath, coverArtPath, AppHostError, appRequest2, apps4Problem, cardsRevision, frameImage, entryRoot, methodRule, saveJson, saveValue, utf8Bytes, wireAchievement, wireCard, wireFriend, wireInvite, wireLeaderboard, wirePack, wirePackSummary, wirePlayer, wireProduct, wireReceipt, } from "./app-wire.js";
5
5
  import { packSlug } from "./manifest.js";
6
+ /** The AppHostServices member that answers each 0.6 method. */
7
+ const HANDLERS = Object.freeze({
8
+ "leaderboard.get": "leaderboard", "leaderboard.show": "showLeaderboard", "achievement.unlock": "unlock", "achievements.list": "achievements",
9
+ "friends.list": "friends", "app.launch": "launch", "invite.open": "invite", "share.open": "share", "products.list": "products", "product.buy": "buy",
10
+ "purchases.list": "purchases", "purchase.consume": "consume", "purchase.token": "receiptToken", "app.show": "showApp",
11
+ });
12
+ const apps4 = (method) => APPS4_METHODS.includes(method);
13
+ /** The 0.6 features a host lists: each method whose handler it supplies, and the finish board with a board read. */
14
+ export function apps4Features(services) {
15
+ return [...APPS4_METHODS.filter(method => typeof services[HANDLERS[method]] === "function"), ...(services.leaderboard ? [FINISH_BOARD_FEATURE] : [])];
16
+ }
6
17
  /**
7
18
  * An apps3 session's request: protocol 1 methods exactly as `parseAppEnvelope` admits them, `host.hello` before hello, and
8
19
  * after hello every protocol 2 method within its request bound. Anything else throws (the session ends).
@@ -38,6 +49,9 @@ const MESSAGE = {
38
49
  slug: "That is not a pack slug.",
39
50
  after: "That page cursor is not valid.",
40
51
  unavailable: "The host could not answer that now; try again.",
52
+ unsupported: "This host does not offer that.",
53
+ guest: "Guests cannot do that; sign in with Steam first.",
54
+ click: "That needs a fresh click in the app.",
41
55
  };
42
56
  /** A single installation/window owns only the JSON this same app host-accepted. */
43
57
  export function createAppController(clock = () => performance.now(), options = {}) {
@@ -172,6 +186,12 @@ export function createAppController(clock = () => performance.now(), options = {
172
186
  }
173
187
  });
174
188
  },
189
+ invite(value) {
190
+ if (!hello || !current())
191
+ return false;
192
+ send({ session, event: "app.invite", state: wireInvite(value) }, 2 * 1024);
193
+ return true;
194
+ },
175
195
  };
176
196
  active = handle;
177
197
  activeFault = attachOptions.fault;
@@ -213,7 +233,7 @@ export function createAppController(clock = () => performance.now(), options = {
213
233
  throw new AppHostError("unavailable", MESSAGE.unavailable);
214
234
  } };
215
235
  switch (request.method) {
216
- case "host.hello": return { protocol: 2, guest: services.guest, features: [...APP_FEATURES_2, ...(services.showCard ? ["card.show"] : [])], root: entryRoot(services.entry) };
236
+ case "host.hello": return { protocol: 2, guest: services.guest, features: [...APP_FEATURES_2, ...(services.showCard ? ["card.show"] : []), ...apps4Features(services)], root: entryRoot(services.entry) };
217
237
  case "ui.progress":
218
238
  // ignored once the app is ready
219
239
  if (!ready) {
@@ -286,6 +306,51 @@ export function createAppController(clock = () => performance.now(), options = {
286
306
  case "display.fullscreen":
287
307
  await services.fullscreen(request.on);
288
308
  return { completed: true };
309
+ default: return answer4(services, request, check);
310
+ }
311
+ };
312
+ /** A 0.6 answer, after reply2's checks: the handler's value, checked against its strict wire shape. */
313
+ const answer4 = async (services, request, check) => {
314
+ const list = (value, max, item) => { if (!Array.isArray(value) || value.length > max)
315
+ throw Error(); return value.map(item); };
316
+ switch (request.method) {
317
+ case "leaderboard.get": {
318
+ const query = { board: request.board ?? "score", scope: request.scope ?? "everyone", period: request.period ?? "all", limit: request.limit ?? APPS4_LIMITS.boardRowsDefault };
319
+ return { leaderboard: check(await services.leaderboard(query), value => wireLeaderboard(value, query)) };
320
+ }
321
+ case "leaderboard.show":
322
+ await services.showLeaderboard(request.board ?? "score");
323
+ return { shown: true };
324
+ case "achievement.unlock": return check(await services.unlock(request.id), value => { if (!value || typeof value.unlocked !== "boolean")
325
+ throw Error(); return { unlocked: value.unlocked }; });
326
+ case "achievements.list": return { achievements: check(await services.achievements(), value => list(value, 50, wireAchievement)) };
327
+ case "friends.list": return { friends: check(await services.friends(), value => list(value, APPS4_LIMITS.friendsMax, wireFriend)) };
328
+ case "app.launch": return { invite: check(await services.launch(), value => value === null ? null : wireInvite(value)) };
329
+ case "invite.open": {
330
+ const { method: _method, ...options } = request;
331
+ return check(await services.invite(options), value => { if (!value || !Number.isInteger(value.sent) || value.sent < 0 || value.sent > APPS4_LIMITS.inviteRecipients)
332
+ throw Error(); return { sent: value.sent }; });
333
+ }
334
+ case "share.open": {
335
+ const { method: _method, ...options } = request;
336
+ return check(await services.share(options), value => { if (!value || typeof value.shared !== "boolean")
337
+ throw Error(); return { shared: value.shared }; });
338
+ }
339
+ case "products.list": return { products: check(await services.products(), value => list(value, 50, wireProduct)) };
340
+ case "product.buy": return { receipt: check(await services.buy(request.product), value => { const receipt = wireReceipt(value); if (receipt.product !== request.product)
341
+ throw Error(); return receipt; }) };
342
+ case "purchases.list": return { purchases: check(await services.purchases(), value => list(value, APPS4_LIMITS.receiptsMax, wireReceipt)) };
343
+ case "purchase.consume":
344
+ await services.consume(request.receipt);
345
+ return { completed: true };
346
+ case "purchase.token": return { token: check(await services.receiptToken(request.receipt), value => {
347
+ if (typeof value !== "string" || value.length < PLAYER_RULES.tokenMin || value.length > PLAYER_RULES.tokenMax || !PLAYER_RULES.token.test(value))
348
+ throw Error();
349
+ return value;
350
+ }) };
351
+ case "app.show":
352
+ await services.showApp(request.app);
353
+ return { shown: true };
289
354
  }
290
355
  };
291
356
  port.onmessage = (event) => {
@@ -371,14 +436,14 @@ export function createAppController(clock = () => performance.now(), options = {
371
436
  result = { completed: true };
372
437
  break;
373
438
  case "game.finish":
374
- if (completion && completion.score !== request.score) {
439
+ if (completion && (completion.score !== request.score || completion.board !== request.board)) {
375
440
  // an apps3 host answers a changed score as a policy refusal; protocol 1 hosts end the session as before
376
441
  if (!apps3)
377
442
  throw Error("This game has already finished.");
378
443
  send({ session, id, error: "This game has already finished.", code: "invalid" }, APP_LIMITS.responseBytes);
379
444
  return;
380
445
  }
381
- completion ??= Object.freeze({ score: request.score });
446
+ completion ??= Object.freeze({ score: request.score, ...(request.board === undefined ? {} : { board: request.board }) });
382
447
  result = { completed: true };
383
448
  break;
384
449
  case "app.checkpoint.get":
@@ -409,6 +474,18 @@ export function createAppController(clock = () => performance.now(), options = {
409
474
  const state = !ready ? "L" : foreground() ? "F" : "B";
410
475
  if (!rule.states.includes(state))
411
476
  throw new AppHostError("not-permitted", MESSAGE.states);
477
+ // 0.6: the handler, the arguments, guests and the click, before the soft rate counts the call (AppHostServices)
478
+ if (apps4(method)) {
479
+ if (typeof services[HANDLERS[method]] !== "function")
480
+ throw new AppHostError("unsupported", MESSAGE.unsupported);
481
+ const problem = apps4Problem(request);
482
+ if (problem)
483
+ throw new AppHostError("invalid", problem);
484
+ if (rule.guest && services.guest)
485
+ throw new AppHostError("guest", MESSAGE.guest);
486
+ if (rule.click !== undefined && services.clicked?.(rule.click) !== true)
487
+ throw new AppHostError("needs-click", MESSAGE.click);
488
+ }
412
489
  // leaving fullscreen is always allowed (section 9.2)
413
490
  if (rule.rate && !(request.method === "display.fullscreen" && !request.on)) {
414
491
  const key = rule.bucket ?? method;
@@ -537,6 +614,7 @@ export function mountAppFrame(frame, options) {
537
614
  },
538
615
  dispose,
539
616
  capture(timeoutMs) { return ended || !session ? Promise.resolve(null) : session.capture(timeoutMs); },
617
+ invite(value) { return !ended && session?.invite?.(value) === true; },
540
618
  };
541
619
  }
542
620
  /**
@@ -1,6 +1,11 @@
1
1
  import { captureId, frameImage, type AppRequest, type AppValue } from "./app-protocol.ts";
2
- /** The nine stable error codes (section 11.3). Messages may change; codes never do. */
3
- export declare const OS_ERROR_CODES: readonly ["unsupported", "not-permitted", "invalid", "too-large", "rate-limited", "needs-click", "unavailable", "timeout", "closed"];
2
+ import { type LeaderboardFormat, type LeaderboardOrder, type ProductKind } from "./manifest.ts";
3
+ /**
4
+ * 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:
5
+ * `cancelled`, `insufficient`, `limit` and `guest`). Messages may change; codes never do. A 0.5 client reads a code it does
6
+ * 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.
7
+ */
8
+ export declare const OS_ERROR_CODES: readonly ["unsupported", "not-permitted", "invalid", "too-large", "rate-limited", "needs-click", "unavailable", "timeout", "closed", "cancelled", "insufficient", "limit", "guest"];
4
9
  export type OsErrorCode = typeof OS_ERROR_CODES[number];
5
10
  export declare const osErrorCode: (value: unknown) => value is OsErrorCode;
6
11
  /** Session-wide numbers of an apps3 host and a protocol 2 client (sections 9 and 10.1). */
@@ -35,6 +40,14 @@ export declare const APP_SESSION_LIMITS: Readonly<{
35
40
  clientPerMinute: 100;
36
41
  /** a player token is reused while more than this remains */
37
42
  tokenReuseMs: 60000;
43
+ /**
44
+ * SDK 0.6: how recent the click must be for a call that opens a vmOS surface over the app (share, invite, the leaderboard
45
+ * panel, an app link), and for `buy` (VM_OS_APPS_4.md section 8.2: a click within the last second)
46
+ */
47
+ clickMs: 5000;
48
+ buyClickMs: 1000;
49
+ /** 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) */
50
+ surfaceMs: number;
38
51
  }>;
39
52
  export declare const RARITIES: readonly ["common", "rare", "epic", "legendary", "mythic"];
40
53
  export type Rarity = typeof RARITIES[number];
@@ -111,7 +124,123 @@ export interface AppHello {
111
124
  features: string[];
112
125
  root: string;
113
126
  }
114
- export type AppRequest2 = AppRequest | {
127
+ export type BoardScope = "everyone" | "friends";
128
+ export type BoardPeriod = "all" | "week";
129
+ export declare const BOARD_SCOPES: readonly ["everyone", "friends"];
130
+ export declare const BOARD_PERIODS: readonly ["all", "week"];
131
+ /** A row of a board. `picture` is the player's picture (absolute in the SDK; on the wire the path after the version prefix). */
132
+ export interface LeaderboardEntry {
133
+ rank: number;
134
+ handle: string;
135
+ name: string;
136
+ picture: string | null;
137
+ score: number;
138
+ you: boolean;
139
+ }
140
+ /** A board read: up to `limit` rows from the top, and the player's own place (also when outside `entries`), or null. */
141
+ export interface Leaderboard {
142
+ board: string;
143
+ name: string;
144
+ order: LeaderboardOrder;
145
+ format: LeaderboardFormat;
146
+ period: BoardPeriod;
147
+ entries: LeaderboardEntry[];
148
+ you: {
149
+ rank: number;
150
+ score: number;
151
+ } | null;
152
+ }
153
+ /**
154
+ * One of the app's achievements and whether the player has it. `at` is when it was unlocked (epoch milliseconds) or null. A
155
+ * secret achievement the player has not unlocked comes as `name` "Secret achievement", an empty description and no icon.
156
+ * `icon` is absolute in the SDK; on the wire it is the bundle path the manifest names.
157
+ */
158
+ export interface Achievement {
159
+ id: string;
160
+ name: string;
161
+ description: string;
162
+ icon: string | null;
163
+ secret: boolean;
164
+ unlocked: boolean;
165
+ at: number | null;
166
+ }
167
+ export declare const PRESENCES: readonly ["playing", "online", "offline"];
168
+ export type Presence = typeof PRESENCES[number];
169
+ /** A friend of the player who has this app installed, with the public fields of a player and a coarse presence. */
170
+ export interface Friend {
171
+ handle: string;
172
+ name: string;
173
+ picture: string | null;
174
+ presence: Presence;
175
+ }
176
+ /** An invite to this app from a friend: their handle, and the `data` the sender's app attached (or null). */
177
+ export interface Invite {
178
+ from: string;
179
+ data: string | null;
180
+ }
181
+ /** A product the manifest declares, as approved, and whether the player owns it (a `permanent` product they bought). */
182
+ export interface Product {
183
+ id: string;
184
+ name: string;
185
+ description: string;
186
+ price: number;
187
+ kind: ProductKind;
188
+ owned: boolean;
189
+ }
190
+ /** A purchase. `consumed` is true once the app called `consume` on a consumable; a permanent product's receipt is never consumed. */
191
+ export interface Receipt {
192
+ id: string;
193
+ product: string;
194
+ kind: ProductKind;
195
+ price: number;
196
+ at: number;
197
+ consumed: boolean;
198
+ }
199
+ /** A board read as the host passes it to its handler: every option resolved to its value or default. */
200
+ export interface LeaderboardQuery {
201
+ board: string;
202
+ scope: BoardScope;
203
+ period: BoardPeriod;
204
+ limit: number;
205
+ }
206
+ export interface InviteOptions {
207
+ to?: string;
208
+ text?: string;
209
+ data?: string;
210
+ }
211
+ export interface ShareOptions {
212
+ text?: string;
213
+ score?: number;
214
+ board?: string;
215
+ }
216
+ /** The numbers of VM_OS_APPS_4.md sections 3 to 8 that the SDK and the host check on every call. */
217
+ export declare const APPS4_LIMITS: Readonly<{
218
+ boardRowsMax: 50;
219
+ boardRowsDefault: 10;
220
+ inviteText: 80;
221
+ inviteData: 256;
222
+ inviteRecipients: 10;
223
+ shareText: 140;
224
+ friendsMax: 100;
225
+ receiptsMax: 100;
226
+ timeScoreMax: 86400000;
227
+ }>;
228
+ /** A receipt id as the backend issues it. */
229
+ export declare const RECEIPT_ID: RegExp;
230
+ /** An app id, as a manifest's `id` admits it. */
231
+ export declare const APP_ID: RegExp;
232
+ export declare const appId: (value: unknown) => value is string;
233
+ /** The feature a host lists when `finish({ score, board })` reaches its board; without it the SDK sends `{ score }` only. */
234
+ export declare const FINISH_BOARD_FEATURE = "game.finish.board";
235
+ /** The name a secret achievement shows until it is unlocked. */
236
+ export declare const SECRET_ACHIEVEMENT_NAME = "Secret achievement";
237
+ export type AppRequest2 = Exclude<AppRequest, {
238
+ method: "game.finish";
239
+ }> | {
240
+ method: "game.finish";
241
+ score: number;
242
+ board?: string;
243
+ } | {
115
244
  method: "host.hello";
116
245
  protocol: 2;
117
246
  sdk: string;
@@ -141,17 +270,52 @@ export type AppRequest2 = AppRequest | {
141
270
  } | {
142
271
  method: "display.maximize" | "display.fullscreen" | "cards.watch";
143
272
  on: boolean;
273
+ } | {
274
+ method: "leaderboard.get";
275
+ board?: string;
276
+ scope?: BoardScope;
277
+ period?: BoardPeriod;
278
+ limit?: number;
279
+ } | {
280
+ method: "leaderboard.show";
281
+ board?: string;
282
+ } | {
283
+ method: "achievement.unlock";
284
+ id: string;
285
+ } | {
286
+ method: "achievements.list" | "friends.list" | "app.launch" | "products.list" | "purchases.list";
287
+ } | ({
288
+ method: "invite.open";
289
+ } & InviteOptions) | ({
290
+ method: "share.open";
291
+ } & ShareOptions) | {
292
+ method: "product.buy";
293
+ product: string;
294
+ } | {
295
+ method: "purchase.consume" | "purchase.token";
296
+ receipt: string;
297
+ } | {
298
+ method: "app.show";
299
+ app: string;
144
300
  };
145
301
  export type AppMethod2 = AppRequest2["method"];
146
302
  /** L loading (before ready), F ready and in front, B behind another window (the grace). */
147
303
  type States = "LFB" | "L" | "F";
148
- /** `bucket` names a soft rate shared by several methods (pack.show and card.show: one per 10 s together). */
304
+ /**
305
+ * `bucket` names a soft rate shared by several methods (pack.show, card.show and app.show: one per 10 s together). 0.6 adds:
306
+ * `click`, a user activation in the app's window within this many milliseconds, checked by the host before the call runs
307
+ * (`needs-click`); `guest`, refused for a guest (`guest`); `surface`, answered only when the player closes a vmOS surface,
308
+ * so the SDK waits `APP_SESSION_LIMITS.surfaceMs` instead of the usual 10 s.
309
+ */
149
310
  interface MethodRule {
150
311
  request: number;
151
312
  response: number;
152
313
  rate?: readonly [count: number, windowMs: number];
153
314
  bucket?: string;
154
315
  states: States;
316
+ click?: number;
317
+ guest?: true;
318
+ surface?: true;
155
319
  }
156
320
  /**
157
321
  * Request and response JSON bounds (of the request object and the result), the soft rate (answered `rate-limited`) and the
@@ -159,9 +323,13 @@ interface MethodRule {
159
323
  * is this package's addition to the contract's table: it is how the host learns the app has an `onCards` listener.
160
324
  */
161
325
  export declare const APP_METHODS_2: Readonly<Record<Exclude<AppMethod2, AppRequest["method"]>, MethodRule>>;
326
+ /** The 0.6 methods: a host lists each in hello's features only when it can answer it (AppHostServices), like `card.show`. */
327
+ export declare const APPS4_METHODS: readonly ["leaderboard.get", "leaderboard.show", "achievement.unlock", "achievements.list", "friends.list", "app.launch", "invite.open", "share.open", "products.list", "product.buy", "purchases.list", "purchase.consume", "purchase.token", "app.show"];
328
+ export type Apps4Method = typeof APPS4_METHODS[number];
162
329
  /**
163
- * Protocol 2 features a hello answers with: the methods beyond protocol 1. `card.show` (0.5.1) is listed only by a host whose
164
- * 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.
330
+ * Protocol 2 features a hello answers with: the methods beyond protocol 1. `card.show` (0.5.1) and the 0.6 methods are listed
331
+ * 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
332
+ * not list (it answers `unsupported` itself).
165
333
  */
166
334
  export declare const APP_FEATURES_2: readonly string[];
167
335
  export declare const utf8Bytes: (text: string) => number;
@@ -203,6 +371,18 @@ export declare function wirePlayer(value: unknown): Player;
203
371
  export declare const cardsRevision: (value: unknown) => value is string;
204
372
  export declare function wireCardsEvent(value: unknown): AppCardsEvent;
205
373
  export declare function wireHello(value: unknown): AppHello;
374
+ /** A board read as the host sends it; `query`, when given, is what was asked (the answer must be that board and period). */
375
+ export declare function wireLeaderboard(value: unknown, query?: Pick<LeaderboardQuery, "board" | "period" | "limit">): Leaderboard;
376
+ export declare function wireAchievement(value: unknown): Achievement;
377
+ export declare function wireFriend(value: unknown): Friend;
378
+ export declare function wireInvite(value: unknown): Invite;
379
+ export declare function wireProduct(value: unknown): Product;
380
+ export declare function wireReceipt(value: unknown): Receipt;
381
+ /**
382
+ * 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
383
+ * of `appRequest2`'s structural check. The SDK refuses before sending and the host refuses again before its handler runs.
384
+ */
385
+ export declare function apps4Problem(request: AppRequest2): string | null;
206
386
  /** The version prefix relative to the entry document: `./` for `index.html`, `../` for `app/index.html`. */
207
387
  export declare const entryRoot: (entry: string) => string;
208
388
  export { captureId, frameImage };