@vibechain/os 0.4.1 → 0.5.1

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 (84) hide show
  1. package/AGENTS.md +80 -48
  2. package/README.md +143 -55
  3. package/SECURITY.md +47 -20
  4. package/dist/app-client.d.ts +4 -1
  5. package/dist/app-client.js +15 -4
  6. package/dist/app-host.d.ts +124 -9
  7. package/dist/app-host.js +395 -57
  8. package/dist/app-protocol.d.ts +17 -1
  9. package/dist/app-protocol.js +12 -0
  10. package/dist/app-runtime.d.ts +18 -2
  11. package/dist/app-runtime.js +75 -11
  12. package/dist/app-wire.d.ts +215 -0
  13. package/dist/app-wire.js +268 -0
  14. package/dist/browser.d.ts +3 -0
  15. package/dist/browser.js +3 -0
  16. package/dist/bundle.js +6 -6
  17. package/dist/canvas.d.ts +2 -2
  18. package/dist/canvas.js +3 -1
  19. package/dist/capture.d.ts +22 -0
  20. package/dist/capture.js +99 -0
  21. package/dist/check.d.ts +12 -0
  22. package/dist/check.js +167 -0
  23. package/dist/cli-publish.d.ts +24 -0
  24. package/dist/cli-publish.js +288 -0
  25. package/dist/cli-session.d.ts +108 -0
  26. package/dist/cli-session.js +245 -0
  27. package/dist/cli.d.ts +10 -0
  28. package/dist/cli.js +46 -10
  29. package/dist/index.d.ts +8 -0
  30. package/dist/index.js +4 -0
  31. package/dist/links.d.ts +15 -0
  32. package/dist/links.js +41 -0
  33. package/dist/listing.d.ts +3 -3
  34. package/dist/listing.js +1 -1
  35. package/dist/loop.d.ts +18 -2
  36. package/dist/loop.js +13 -1
  37. package/dist/manifest.d.ts +90 -4
  38. package/dist/manifest.js +340 -5
  39. package/dist/os.d.ts +63 -0
  40. package/dist/os.js +383 -0
  41. package/dist/preview-parent.d.ts +42 -0
  42. package/dist/preview-parent.js +134 -11
  43. package/dist/preview-ui.js +1 -1
  44. package/dist/preview.js +25 -7
  45. package/dist/redact.d.ts +6 -0
  46. package/dist/redact.js +16 -0
  47. package/dist/runtime-policy.d.ts +20 -0
  48. package/dist/runtime-policy.js +45 -0
  49. package/dist/scaffold.d.ts +13 -2
  50. package/dist/scaffold.js +95 -31
  51. package/dist/submit-notice.d.ts +26 -0
  52. package/dist/submit-notice.js +34 -0
  53. package/dist/templates/plain/game.js +18 -0
  54. package/dist/testing.d.ts +68 -0
  55. package/dist/testing.js +181 -1
  56. package/dist/transport.d.ts +22 -0
  57. package/dist/transport.js +71 -19
  58. package/dist/vibemarket-os.js +1 -0
  59. package/dist/worker.d.ts +18 -0
  60. package/dist/worker.js +34 -0
  61. package/examples/paw-beat/README.md +20 -8
  62. package/examples/paw-beat/cat.ts +665 -89
  63. package/examples/paw-beat/game.ts +162 -28
  64. package/examples/paw-beat/index.html +114 -40
  65. package/examples/paw-beat/main.ts +264 -149
  66. package/examples/paw-beat/music.ts +314 -65
  67. package/examples/paw-beat/stage.ts +560 -0
  68. package/examples/paw-beat/store/icon.png +0 -0
  69. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  70. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  71. package/examples/paw-beat/vibemarket.json +2 -2
  72. package/examples/vibexp-app/README.md +7 -7
  73. package/examples/vibexp-app/index.html +3 -2
  74. package/examples/vibexp-app/plain/game.ts +20 -0
  75. package/examples/vibexp-app/plain/index.html +6 -0
  76. package/examples/vibexp-app/plain/vibemarket.json +17 -0
  77. package/examples/vibexp-app/src/main.ts +46 -31
  78. package/examples/vibexp-app/store/icon.png +0 -0
  79. package/examples/vibexp-app/three/README.md +21 -0
  80. package/examples/vibexp-app/three/index.html +4 -0
  81. package/examples/vibexp-app/three/src/main.ts +45 -0
  82. package/examples/vibexp-app/three/vibemarket.json +19 -0
  83. package/examples/vibexp-app/vibemarket.json +17 -11
  84. package/package.json +6 -2
package/dist/app-host.js CHANGED
@@ -1,26 +1,71 @@
1
1
  import { CHANNEL } from "./channel.js";
2
2
  import { appRuntimeRefusal } from "./app-runtime.js";
3
- import { APP_FRAGMENT, APP_LIMITS, appJson, appNonce, checkpointJson, createAppNonce, lifecycleValue, parseAppEnvelope, parseAppJson } from "./app-protocol.js";
3
+ import { APP_FRAGMENT, APP_LIMITS, FRAME_MESSAGE_BYTES, appJson, appNonce, checkpointJson, createAppNonce, lifecycleValue, parseAppEnvelope, parseAppJson } 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";
5
+ import { packSlug } from "./manifest.js";
6
+ /**
7
+ * An apps3 session's request: protocol 1 methods exactly as `parseAppEnvelope` admits them, `host.hello` before hello, and
8
+ * after hello every protocol 2 method within its request bound. Anything else throws (the session ends).
9
+ */
10
+ function envelope2(data, session, hello) {
11
+ if (!data || typeof data !== "object" || Array.isArray(data) || Object.getPrototypeOf(data) !== Object.prototype || Object.keys(data).length !== 3
12
+ || !("session" in data) || data.session !== session || !("id" in data) || typeof data.id !== "string" || !/^[A-Za-z0-9_-]{1,80}$/.test(data.id)
13
+ || !("request" in data) || !data.request || typeof data.request !== "object" || Array.isArray(data.request))
14
+ throw Error("Invalid app session request.");
15
+ const request = appRequest2(data.request);
16
+ const legacy = request !== null && !Object.hasOwn(APP_METHODS_2, request.method);
17
+ // app.frame is also admitted before hello: a 0.4 client never says hello and still answers the desktop camera
18
+ if (!request || (!hello && !legacy && request.method !== "host.hello" && request.method !== "app.frame"))
19
+ throw Error("This app has no permission for that method.");
20
+ if (utf8Bytes(JSON.stringify(data.request)) > methodRule(request.method).request)
21
+ throw Error("App request exceeds its bound.");
22
+ return { id: data.id, request };
23
+ }
24
+ /** A sliding window of recent times, at most `limit` of them within `windowMs`. */
25
+ function slidingWindow(limit, windowMs) {
26
+ let times = [];
27
+ return (now) => {
28
+ times = times.filter(time => now - time < windowMs);
29
+ if (times.length >= limit)
30
+ return false;
31
+ times.push(now);
32
+ return true;
33
+ };
34
+ }
35
+ const MESSAGE = {
36
+ states: "That is not available while the app is loading or behind another window.",
37
+ rate: "Too many requests of that kind; try again later.",
38
+ slug: "That is not a pack slug.",
39
+ after: "That page cursor is not valid.",
40
+ unavailable: "The host could not answer that now; try again.",
41
+ };
4
42
  /** A single installation/window owns only the JSON this same app host-accepted. */
5
- export function createAppController(clock = () => performance.now()) {
43
+ export function createAppController(clock = () => performance.now(), options = {}) {
44
+ const services = options.services, apps3 = services !== undefined;
6
45
  let checkpoint = "null", disposed = false, active;
7
46
  let completion, completionNotified = false;
8
47
  const startedAt = clock();
9
48
  if (!Number.isFinite(startedAt))
10
49
  throw Error("App clock is invalid.");
11
- let lastClock = startedAt, intervalAt = startedAt, requests = 0, total = 0;
50
+ let lastClock = startedAt, intervalAt = startedAt, requests = 0, total = 0, lastActivity = startedAt;
12
51
  let terminalReason, activeFault;
52
+ let idleTimer, idleNotified = false;
53
+ let cards;
54
+ const perMinute = slidingWindow(APP_SESSION_LIMITS.requestsPerMinute, 60_000);
55
+ const lifetimeMs = apps3 ? APP_SESSION_LIMITS.sessionMs : APP_LIMITS.sessionMs, lifetimeRequests = apps3 ? APP_SESSION_LIMITS.lifetimeRequests : APP_LIMITS.lifetimeRequests;
56
+ const expired = apps3 ? "App session reached its 4-hour limit. Reopen the app to keep playing." : "App session expired. Reopen the app.";
13
57
  const terminate = (reason) => {
14
58
  if (disposed || terminalReason)
15
59
  return;
16
60
  terminalReason = reason;
17
61
  clearTimeout(expiry);
62
+ clearTimeout(idleTimer);
18
63
  checkpoint = "null";
19
64
  const fault = activeFault;
20
65
  active?.close();
21
66
  fault?.(reason);
22
67
  };
23
- const expiry = setTimeout(() => terminate("App session expired. Reopen the app."), APP_LIMITS.sessionMs);
68
+ const expiry = setTimeout(() => terminate(expired), lifetimeMs);
24
69
  const readTime = () => {
25
70
  let now;
26
71
  try {
@@ -35,14 +80,39 @@ export function createAppController(clock = () => performance.now()) {
35
80
  return undefined;
36
81
  }
37
82
  lastClock = now;
38
- if (now - startedAt >= APP_LIMITS.sessionMs) {
39
- terminate("App session expired. Reopen the app.");
83
+ if (now - startedAt >= lifetimeMs) {
84
+ terminate(expired);
40
85
  return undefined;
41
86
  }
42
87
  return now;
43
88
  };
44
- return {
45
- attach(port, session, options) {
89
+ // apps3 only: the idle prompt after 15 minutes without activity (re-armed by any activity, never extending the 4 hours)
90
+ const armIdle = (delay) => {
91
+ clearTimeout(idleTimer);
92
+ idleTimer = setTimeout(() => {
93
+ const now = readTime();
94
+ if (now === undefined)
95
+ return;
96
+ const quiet = now - lastActivity;
97
+ if (quiet < APP_SESSION_LIMITS.idleMs) {
98
+ armIdle(APP_SESSION_LIMITS.idleMs - quiet);
99
+ return;
100
+ }
101
+ if (!idleNotified) {
102
+ idleNotified = true;
103
+ options.idle?.();
104
+ }
105
+ }, delay);
106
+ };
107
+ const touch = (now) => { lastActivity = now; if (idleNotified) {
108
+ idleNotified = false;
109
+ armIdle(APP_SESSION_LIMITS.idleMs);
110
+ } };
111
+ if (apps3)
112
+ armIdle(APP_SESSION_LIMITS.idleMs);
113
+ const controller = {
114
+ protocol: apps3 ? 2 : 1,
115
+ attach(port, session, attachOptions) {
46
116
  if (disposed || terminalReason || !appNonce(session)) {
47
117
  port.close();
48
118
  throw Error(terminalReason ?? "App controller is closed.");
@@ -52,23 +122,171 @@ export function createAppController(clock = () => performance.now()) {
52
122
  throw Error(terminalReason);
53
123
  }
54
124
  active?.close();
55
- let stopped = false, inFlight = 0;
125
+ let stopped = false, inFlight = 0, hello = false, ready = false, lastId = 0, saving = false, watching = false;
126
+ let baseline;
56
127
  const seen = new Set();
57
- const close = () => { if (stopped)
58
- return; stopped = true; port.onmessage = null; port.onmessageerror = null; port.close(); if (active === handle) {
59
- active = undefined;
60
- activeFault = undefined;
128
+ const soft = new Map();
129
+ let captureSeq = 0, capturing;
130
+ const endCapture = (image) => { const waiting = capturing; capturing = undefined; if (waiting) {
131
+ clearTimeout(waiting.timer);
132
+ waiting.resolve(image);
61
133
  } };
134
+ const close = () => {
135
+ endCapture(null);
136
+ if (stopped)
137
+ return;
138
+ stopped = true;
139
+ port.onmessage = null;
140
+ port.onmessageerror = null;
141
+ port.close();
142
+ if (active === handle) {
143
+ active = undefined;
144
+ activeFault = undefined;
145
+ cards = undefined;
146
+ }
147
+ };
62
148
  const refuse = (reason) => { if (stopped)
63
- return; close(); options.fault(reason); };
64
- const current = () => !stopped && !disposed && options.current();
149
+ return; close(); attachOptions.fault(reason); };
150
+ const current = () => !stopped && !disposed && attachOptions.current();
151
+ const foreground = attachOptions.foreground ?? (() => true);
152
+ const send = (value, bytes) => { if (current())
153
+ port.postMessage(appJson(value, bytes)); };
65
154
  const handle = {
66
155
  lifecycle(value) { if (current())
67
156
  port.postMessage(appJson({ session, event: "app.lifecycle", state: lifecycleValue(value) }, APP_LIMITS.responseBytes)); },
68
157
  close,
158
+ capture(timeoutMs = APP_SESSION_LIMITS.captureMs) {
159
+ endCapture(null);
160
+ if (!current())
161
+ return Promise.resolve(null);
162
+ const id = String(++captureSeq), wait = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) ? Math.max(0, timeoutMs) : APP_SESSION_LIMITS.captureMs;
163
+ return new Promise(resolve => {
164
+ capturing = { id, resolve, timer: setTimeout(() => { if (capturing?.id === id)
165
+ endCapture(null); }, wait) };
166
+ try {
167
+ send({ session, event: "app.capture", id }, 256);
168
+ }
169
+ catch {
170
+ endCapture(null);
171
+ }
172
+ });
173
+ },
69
174
  };
70
175
  active = handle;
71
- activeFault = options.fault;
176
+ activeFault = attachOptions.fault;
177
+ // A watching app is told what changed since the list it last read whole (or the last event), or to read again.
178
+ if (services)
179
+ cards = async () => {
180
+ if (!watching || !baseline || !current())
181
+ return;
182
+ const next = await services.cards();
183
+ if (!current() || !watching || !baseline || !cardsRevision(next.revision) || next.revision === baseline.revision)
184
+ return;
185
+ const fresh = new Map(next.cards.map(card => { const checked = wireCard(card); return [checked.id, checked]; }));
186
+ const changed = [...fresh.values()].filter(card => JSON.stringify(baseline.cards.get(card.id)) !== JSON.stringify(card));
187
+ const removed = [...baseline.cards.keys()].filter(id => !fresh.has(id));
188
+ let event = { changed, removed, revision: next.revision };
189
+ if (utf8Bytes(JSON.stringify(event)) > APP_SESSION_LIMITS.cardsEventBytes)
190
+ event = { reset: true, revision: next.revision };
191
+ baseline = { revision: next.revision, cards: fresh };
192
+ send({ session, event: "app.cards", state: event }, APP_SESSION_LIMITS.cardsEventBytes + 1024);
193
+ };
194
+ /** The answer to an `app.frame` on any protocol: ignore a late id, refuse a bad picture softly, else hand it to the pending capture. */
195
+ const frameAnswer = (request) => {
196
+ const pending = capturing?.id === request.id;
197
+ if (request.image !== null && !frameImage(request.image)) {
198
+ if (pending)
199
+ endCapture(null);
200
+ throw new AppHostError("invalid", "That is not a PNG, JPEG or WebP data URL of at most 1,000,000 characters.");
201
+ }
202
+ if (pending)
203
+ endCapture(request.image);
204
+ return { completed: true };
205
+ };
206
+ /** One protocol 2 answer. A thrown AppHostError is a soft refusal; anything else from the services is `unavailable`. */
207
+ const answer2 = async (services, request) => {
208
+ const check = (value, valid) => { try {
209
+ return valid(value);
210
+ }
211
+ catch {
212
+ throw new AppHostError("unavailable", MESSAGE.unavailable);
213
+ } };
214
+ switch (request.method) {
215
+ case "host.hello": return { protocol: 2, guest: services.guest, features: [...APP_FEATURES_2, ...(services.showCard ? ["card.show"] : [])], root: entryRoot(services.entry) };
216
+ case "ui.progress":
217
+ // ignored once the app is ready
218
+ if (!ready) {
219
+ if (request.value < 0 || request.value > 1)
220
+ throw new AppHostError("invalid", "Progress is a number from 0 to 1.");
221
+ attachOptions.progress?.(request.value);
222
+ }
223
+ return { completed: true };
224
+ case "app.frame": return frameAnswer(request);
225
+ case "app.save.get": {
226
+ const stored = await services.saveGet();
227
+ return { value: stored.value === null ? null : check(stored.value, saveValue), savedAt: stored.savedAt === null ? null : check(stored.savedAt, value => { if (typeof value !== "string" || value.length > 30)
228
+ throw Error(); return value; }) };
229
+ }
230
+ case "app.save.set": {
231
+ const text = saveJson(request.value);
232
+ if (saving)
233
+ throw new AppHostError("rate-limited", "A save is already being written.");
234
+ saving = true;
235
+ try {
236
+ const { savedAt } = await services.saveSet(text);
237
+ return { savedAt: check(savedAt, value => { if (typeof value !== "string" || value.length > 30)
238
+ throw Error(); return value; }) };
239
+ }
240
+ finally {
241
+ saving = false;
242
+ }
243
+ }
244
+ case "cards.list": {
245
+ if (request.pack !== undefined && !packSlug(request.pack))
246
+ throw new AppHostError("invalid", MESSAGE.slug);
247
+ const start = request.after === undefined ? 0 : /^(?:0|[1-9]\d{0,5})$/.test(request.after) ? Number(request.after) : -1;
248
+ if (start < 0)
249
+ throw new AppHostError("invalid", MESSAGE.after);
250
+ const all = await services.cards();
251
+ const listed = check(all, value => { if (!cardsRevision(value.revision) || !Array.isArray(value.cards))
252
+ throw Error(); return value.cards.map(wireCard); });
253
+ if (request.pack === undefined && start === 0)
254
+ baseline = { revision: all.revision, cards: new Map(listed.map(card => [card.id, card])) };
255
+ const chosen = request.pack === undefined ? listed : listed.filter(card => card.pack === request.pack);
256
+ const end = start + APP_SESSION_LIMITS.cardsPage;
257
+ return { cards: chosen.slice(start, end), after: end < chosen.length ? String(end) : null, revision: all.revision };
258
+ }
259
+ case "cards.packs": return { packs: check(await services.packs(), value => { if (!Array.isArray(value) || value.length > 200)
260
+ throw Error(); return value.map(wirePackSummary); }) };
261
+ case "cards.pack":
262
+ if (!packSlug(request.pack))
263
+ throw new AppHostError("invalid", MESSAGE.slug);
264
+ return { pack: check(await services.pack(request.pack), value => { const pack = wirePack(value); if (pack.id !== request.pack)
265
+ throw Error(); return pack; }) };
266
+ case "cards.watch":
267
+ watching = request.on;
268
+ return { completed: true };
269
+ case "pack.show":
270
+ if (!packSlug(request.pack))
271
+ throw new AppHostError("invalid", MESSAGE.slug);
272
+ await services.showPack(request.pack);
273
+ return { shown: true };
274
+ case "card.show":
275
+ if (!services.showCard)
276
+ throw new AppHostError("unsupported", "This host cannot show a card.");
277
+ if (!packSlug(request.pack) || !CARD_ID.test(request.card))
278
+ throw new AppHostError("invalid", "That is not a pack slug and a card id.");
279
+ await services.showCard(request.pack, request.card);
280
+ return { shown: true };
281
+ case "player.get": return check(await services.player(), wirePlayer);
282
+ case "display.maximize":
283
+ await services.maximize(request.on);
284
+ return { completed: true };
285
+ case "display.fullscreen":
286
+ await services.fullscreen(request.on);
287
+ return { completed: true };
288
+ }
289
+ };
72
290
  port.onmessage = (event) => {
73
291
  if (!current()) {
74
292
  close();
@@ -81,78 +299,172 @@ export function createAppController(clock = () => performance.now()) {
81
299
  intervalAt = now;
82
300
  requests = 0;
83
301
  }
84
- if (++requests > APP_LIMITS.requestsPerSecond || ++total > APP_LIMITS.lifetimeRequests || inFlight >= APP_LIMITS.inFlight) {
302
+ if (++requests > APP_LIMITS.requestsPerSecond || ++total > lifetimeRequests || inFlight >= (hello ? APP_SESSION_LIMITS.inFlight : APP_LIMITS.inFlight)
303
+ || (apps3 && !perMinute(now))) {
85
304
  refuse("App request limit exceeded.");
86
305
  return;
87
306
  }
88
- let message;
307
+ let id, request;
89
308
  try {
90
- message = parseAppEnvelope(parseAppJson(event.data, APP_LIMITS.requestBytes), session);
309
+ if (!apps3)
310
+ ({ id, request } = parseAppEnvelope(parseAppJson(event.data, FRAME_MESSAGE_BYTES), session));
311
+ else
312
+ ({ id, request } = envelope2(parseAppJson(event.data, APP_SESSION_LIMITS.messageBytes), session, hello));
91
313
  }
92
314
  catch {
93
315
  refuse("Invalid or unpermitted app request.");
94
316
  return;
95
317
  }
96
- if (seen.has(message.id)) {
97
- refuse("App request was replayed.");
98
- return;
318
+ if (apps3) {
319
+ // every client this package has shipped numbers its requests 1, 2, 3, ... per session
320
+ if (!/^[1-9]\d{0,15}$/.test(id) || Number(id) <= lastId) {
321
+ refuse("App request was replayed.");
322
+ return;
323
+ }
324
+ lastId = Number(id);
325
+ }
326
+ else {
327
+ if (seen.has(id)) {
328
+ refuse("App request was replayed.");
329
+ return;
330
+ }
331
+ seen.add(id);
332
+ }
333
+ if (request.method === "host.hello") {
334
+ if (hello) {
335
+ refuse("App said hello twice.");
336
+ return;
337
+ }
338
+ hello = true;
99
339
  }
100
- seen.add(message.id);
101
340
  inFlight++;
341
+ if (apps3)
342
+ touch(now);
343
+ const method = request.method;
344
+ const legacy = method === "ui.ready" || method === "game.finish" || method === "app.checkpoint.get" || method === "app.checkpoint.set";
345
+ // protocol 1 answers synchronously in the first microtask, exactly as before; protocol 2 returns its promise
102
346
  void Promise.resolve().then(() => {
103
347
  if (!current())
104
348
  return;
105
- let result;
106
- switch (message.request.method) {
107
- case "ui.ready":
108
- options.ready();
109
- result = { completed: true };
110
- break;
111
- case "game.finish":
112
- if (completion && completion.score !== message.request.score)
113
- throw Error("This game has already finished.");
114
- completion ??= Object.freeze({ score: message.request.score });
115
- result = { completed: true };
116
- break;
117
- case "app.checkpoint.get":
118
- result = { checkpoint: JSON.parse(checkpoint) };
119
- break;
120
- case "app.checkpoint.set":
121
- checkpoint = checkpointJson(message.request.value);
122
- result = { completed: true };
123
- break;
349
+ // backgrounded: a write is withheld exactly as a suspended app's would be lost (see AppAttachOptions)
350
+ if (!foreground() && (method === "game.finish" || method === "app.checkpoint.set"))
351
+ return;
352
+ if (request.method === "app.frame" && !apps3) {
353
+ try {
354
+ const result = frameAnswer(request);
355
+ if (current())
356
+ port.postMessage(appJson({ session, id, result }, APP_LIMITS.responseBytes));
357
+ }
358
+ catch (error) {
359
+ if (current())
360
+ port.postMessage(appJson({ session, id, error: error.message, code: "invalid" }, APP_LIMITS.responseBytes));
361
+ }
362
+ return;
124
363
  }
125
- const response = { session, id: message.id, result };
126
- if (current()) {
127
- port.postMessage(appJson(response, APP_LIMITS.responseBytes));
128
- if (message.request.method === "game.finish" && completion && !completionNotified && current()) {
129
- completionNotified = true;
130
- options.finish?.(completion);
364
+ if (legacy) {
365
+ let result;
366
+ switch (request.method) {
367
+ case "ui.ready":
368
+ ready = true;
369
+ attachOptions.ready();
370
+ result = { completed: true };
371
+ break;
372
+ case "game.finish":
373
+ if (completion && completion.score !== request.score) {
374
+ // an apps3 host answers a changed score as a policy refusal; protocol 1 hosts end the session as before
375
+ if (!apps3)
376
+ throw Error("This game has already finished.");
377
+ send({ session, id, error: "This game has already finished.", code: "invalid" }, APP_LIMITS.responseBytes);
378
+ return;
379
+ }
380
+ completion ??= Object.freeze({ score: request.score });
381
+ result = { completed: true };
382
+ break;
383
+ case "app.checkpoint.get":
384
+ result = { checkpoint: JSON.parse(checkpoint) };
385
+ break;
386
+ default:
387
+ checkpoint = checkpointJson(request.value);
388
+ result = { completed: true };
389
+ break;
131
390
  }
391
+ if (current()) {
392
+ port.postMessage(appJson({ session, id, result }, APP_LIMITS.responseBytes));
393
+ if (method === "game.finish" && completion && !completionNotified && current()) {
394
+ completionNotified = true;
395
+ attachOptions.finish?.(completion);
396
+ }
397
+ }
398
+ return;
132
399
  }
400
+ return reply2(id, request, method, now);
133
401
  }).catch(() => { if (!stopped)
134
402
  refuse("App request could not complete."); }).finally(() => { inFlight--; });
135
403
  };
404
+ const reply2 = async (id, request, method, now) => {
405
+ const rule = methodRule(method);
406
+ let reply;
407
+ try {
408
+ const state = !ready ? "L" : foreground() ? "F" : "B";
409
+ if (!rule.states.includes(state))
410
+ throw new AppHostError("not-permitted", MESSAGE.states);
411
+ // leaving fullscreen is always allowed (section 9.2)
412
+ if (rule.rate && !(request.method === "display.fullscreen" && !request.on)) {
413
+ const key = rule.bucket ?? method;
414
+ let limiter = soft.get(key);
415
+ if (!limiter) {
416
+ limiter = slidingWindow(rule.rate[0], rule.rate[1]);
417
+ soft.set(key, limiter);
418
+ }
419
+ if (!limiter(now))
420
+ throw new AppHostError("rate-limited", MESSAGE.rate);
421
+ }
422
+ const result = await answer2(services, request);
423
+ if (utf8Bytes(JSON.stringify(result)) > rule.response)
424
+ throw new AppHostError("unavailable", "The answer is larger than this request may return.");
425
+ reply = { session, id, result };
426
+ }
427
+ catch (error) {
428
+ const code = error instanceof AppHostError ? error.code : "unavailable";
429
+ reply = { session, id, error: error instanceof AppHostError ? error.message.slice(0, 300) : MESSAGE.unavailable, code };
430
+ }
431
+ send(reply, APP_SESSION_LIMITS.messageBytes);
432
+ };
136
433
  port.onmessageerror = () => refuse("App message could not be decoded.");
137
434
  port.start();
138
435
  return handle;
139
436
  },
140
437
  suspend() { active?.close(); },
141
438
  dispose() { if (disposed)
142
- return; disposed = true; clearTimeout(expiry); active?.close(); checkpoint = "null"; },
439
+ return; disposed = true; clearTimeout(expiry); clearTimeout(idleTimer); active?.close(); checkpoint = "null"; },
143
440
  };
441
+ if (apps3) {
442
+ controller.activity = () => { const now = readTime(); if (now !== undefined)
443
+ touch(now); };
444
+ controller.cardsChanged = async () => { try {
445
+ await cards?.();
446
+ }
447
+ catch { /* the next change or read answers again */ } };
448
+ }
449
+ return controller;
144
450
  }
145
- /** Caller supplies the already-validated immutable URL, including this generation's fragment. */
451
+ /**
452
+ * Caller supplies the already-validated immutable URL, including this generation's fragment. With a protocol 2
453
+ * controller the transfer advertises `protocol: 2`, and readiness is `ready()` within 15 s, or `progress()` at least
454
+ * every 15 s and `ready()` within 120 s.
455
+ */
146
456
  export function mountAppFrame(frame, options) {
147
457
  const refusal = appRuntimeRefusal(window);
148
458
  if (refusal)
149
459
  throw Error(refusal);
150
460
  if (!appNonce(options.challenge) || new URL(frame.src).hash !== `#${APP_FRAGMENT}=${options.challenge}`)
151
461
  throw Error("Invalid app frame challenge.");
152
- let ended = false, loaded = false, connected = false, bootstrapMessages = 0, session;
462
+ const protocol2 = options.controller.protocol === 2;
463
+ let ended = false, loaded = false, connected = false, bootstrapMessages = 0, session, readied = false;
153
464
  let bounds = lifecycleValue({ active: true, width: 0, height: 0 });
465
+ const slow = () => fault("App took too long to become ready.");
154
466
  const dispose = () => { if (ended)
155
- return; ended = true; clearTimeout(timeout); frame.removeEventListener("load", load); window.removeEventListener("message", connect); session?.close(); };
467
+ return; ended = true; clearTimeout(timeout); clearTimeout(ceiling); frame.removeEventListener("load", load); window.removeEventListener("message", connect); session?.close(); };
156
468
  const fault = (message) => { if (ended)
157
469
  return; dispose(); options.fault(message); };
158
470
  const load = () => { if (loaded)
@@ -184,12 +496,19 @@ export function mountAppFrame(frame, options) {
184
496
  window.removeEventListener("message", connect);
185
497
  const ports = new MessageChannel(), nonce = createAppNonce();
186
498
  try {
187
- session = options.controller.attach(ports.port1, nonce, { current: options.current,
188
- ready() { clearTimeout(timeout); options.ready(); }, finish: options.finish, fault });
499
+ session = options.controller.attach(ports.port1, nonce, { current: options.current, foreground: options.foreground,
500
+ ready() { readied = true; clearTimeout(timeout); clearTimeout(ceiling); options.ready(); }, finish: options.finish, fault,
501
+ progress(fraction) {
502
+ if (readied || ended)
503
+ return;
504
+ clearTimeout(timeout);
505
+ timeout = setTimeout(slow, APP_SESSION_LIMITS.readyMs);
506
+ options.progress?.(fraction);
507
+ } });
189
508
  // Opaque frames require wildcard targetOrigin; the exact WindowProxy/challenge bind this transfer.
190
509
  if (!frame.contentWindow)
191
510
  throw Error("App frame is unavailable.");
192
- frame.contentWindow.postMessage({ channel: CHANNEL, challenge: options.challenge, session: nonce }, "*", [ports.port2]);
511
+ frame.contentWindow.postMessage({ channel: CHANNEL, challenge: options.challenge, session: nonce, ...(protocol2 ? { protocol: 2 } : {}) }, "*", [ports.port2]);
193
512
  session.lifecycle(bounds);
194
513
  }
195
514
  catch {
@@ -198,11 +517,30 @@ export function mountAppFrame(frame, options) {
198
517
  fault("App connection could not complete.");
199
518
  }
200
519
  };
201
- const timeout = setTimeout(() => fault("App took too long to become ready."), 15_000);
520
+ let timeout = setTimeout(slow, APP_SESSION_LIMITS.readyMs);
521
+ const ceiling = protocol2 ? setTimeout(slow, APP_SESSION_LIMITS.progressReadyMs) : undefined;
202
522
  frame.addEventListener("load", load);
203
523
  window.addEventListener("message", connect);
204
524
  return {
205
- resize(width, height) { bounds = lifecycleValue({ active: true, width: Math.min(4096, Math.max(0, Math.floor(width))), height: Math.min(4096, Math.max(0, Math.floor(height))) }); session?.lifecycle(bounds); },
525
+ resize(width, height) { bounds = lifecycleValue({ active: bounds.active, width: Math.min(4096, Math.max(0, Math.floor(width))), height: Math.min(4096, Math.max(0, Math.floor(height))) }); session?.lifecycle(bounds); },
526
+ setActive(active) { if (active === bounds.active)
527
+ return; bounds = lifecycleValue({ ...bounds, active }); session?.lifecycle(bounds); },
206
528
  dispose,
529
+ capture(timeoutMs) { return ended || !session ? Promise.resolve(null) : session.capture(timeoutMs); },
530
+ };
531
+ }
532
+ /**
533
+ * The backend's card read as an app sees it, for an apps3 host's services: rarity numbers named, ids joined, and art as the
534
+ * path after the version prefix only where the backend has servable art and the card id can be a path segment.
535
+ */
536
+ export function appCardsView(reply) {
537
+ const rarities = ["common", "rare", "epic", "legendary", "mythic"];
538
+ return {
539
+ packs: reply.packs.map(pack => wirePackSummary({ id: pack.slug, name: pack.name, creator: pack.creator, art: pack.cover ? coverArtPath(pack.slug) : null, held: pack.held, total: pack.total })),
540
+ cards: reply.cards.map(card => wireCard({
541
+ id: `${card.pack}/${card.card}`, pack: card.pack, name: card.name, rarity: rarities[card.rarity] ?? "common", count: card.count,
542
+ art: card.art && CARD_ID.test(card.card) ? cardArtPath(card.pack, card.card) : null,
543
+ })),
544
+ revision: reply.revision,
207
545
  };
208
546
  }
@@ -18,6 +18,18 @@ export declare const APP_LIMITS: Readonly<{
18
18
  sessionMs: number;
19
19
  requestTimeoutMs: 10000;
20
20
  }>;
21
+ /** A captured frame (`app.frame`) is a PNG, JPEG or WebP data URL of at most this many characters; its message may be this much larger than a protocol 1 request. */
22
+ export declare const FRAME_CHARS = 1000000;
23
+ export declare const FRAME_MESSAGE_BYTES: number;
24
+ /** A capture id: the host counts 1, 2, 3 ... per session. */
25
+ export declare const captureId: (value: unknown) => value is string;
26
+ export declare const frameImage: (value: unknown) => value is string;
27
+ /** The desktop camera's answer. Allowed on protocol 1 sessions too; `image` is checked by the host (a bad one is a soft `invalid`). */
28
+ export type AppFrameRequest = {
29
+ method: "app.frame";
30
+ id: string;
31
+ image: string | null;
32
+ };
21
33
  export type AppValue = null | boolean | number | string | AppValue[] | {
22
34
  [key: string]: AppValue;
23
35
  };
@@ -39,11 +51,13 @@ export interface AppLifecycle {
39
51
  width: number;
40
52
  height: number;
41
53
  }
54
+ /** @deprecated The 0.4 app API. Use `connect()` and its `Os`; `checkpoint` (32 KiB, the open window only) is replaced by `load()` and `save()`. */
42
55
  export interface VibeMarketAppSdk {
43
56
  game: {
44
57
  finish(input: GameFinishInput): Promise<void>;
45
58
  };
46
59
  ready(): Promise<void>;
60
+ /** @deprecated Use `os.load()` and `os.save()` from `connect()`. */
47
61
  checkpoint: {
48
62
  read(): Promise<AppValue>;
49
63
  write(value: AppValue): Promise<void>;
@@ -52,6 +66,8 @@ export interface VibeMarketAppSdk {
52
66
  current(): Readonly<AppLifecycle>;
53
67
  onChanged(listener: (state: Readonly<AppLifecycle>) => void): () => void;
54
68
  };
69
+ /** The desktop camera asks for a picture: by default the largest canvas is sent; register a handler (canvas, data URL or null) to draw your own. Latest wins; returns unsubscribe. */
70
+ onCapture?(handler: () => HTMLCanvasElement | string | null | Promise<HTMLCanvasElement | string | null>): () => void;
55
71
  destroy(): void;
56
72
  }
57
73
  export declare function appNonce(value: unknown): value is string;
@@ -63,6 +79,6 @@ export declare function checkpointJson(input: unknown): string;
63
79
  export declare function checkpointValue(input: unknown): AppValue;
64
80
  export declare function parseAppEnvelope(input: unknown, session: string): {
65
81
  id: string;
66
- request: AppRequest;
82
+ request: AppRequest | AppFrameRequest;
67
83
  };
68
84
  export declare function lifecycleValue(input: unknown): Readonly<AppLifecycle>;
@@ -10,6 +10,12 @@ export const APP_LIMITS = Object.freeze({
10
10
  requestsPerSecond: 10, inFlight: 4, lifetimeRequests: 5000,
11
11
  sessionMs: 15 * 60 * 1000, requestTimeoutMs: 10_000,
12
12
  });
13
+ /** A captured frame (`app.frame`) is a PNG, JPEG or WebP data URL of at most this many characters; its message may be this much larger than a protocol 1 request. */
14
+ export const FRAME_CHARS = 1_000_000;
15
+ export const FRAME_MESSAGE_BYTES = 1_100_000 + 1024;
16
+ /** A capture id: the host counts 1, 2, 3 ... per session. */
17
+ export const captureId = (value) => typeof value === "string" && /^[1-9]\d{0,15}$/.test(value);
18
+ export const frameImage = (value) => typeof value === "string" && value.length <= FRAME_CHARS && /^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(value);
13
19
  export function appNonce(value) { return typeof value === "string" && /^[a-f0-9]{32}$/.test(value); }
14
20
  export function createAppNonce() {
15
21
  return [...crypto.getRandomValues(new Uint8Array(16))].map(value => value.toString(16).padStart(2, "0")).join("");
@@ -97,6 +103,12 @@ export function parseAppEnvelope(input, session) {
97
103
  || typeof input.id !== "string" || input.id.length > 80 || !/^[A-Za-z0-9_-]{1,80}$/.test(input.id) || !plain(input.request))
98
104
  throw Error("Invalid app session request.");
99
105
  const request = input.request;
106
+ if (request.method === "app.frame") {
107
+ if (!exact(request, ["method", "id", "image"]) || !captureId(request.id) || (request.image !== null && typeof request.image !== "string"))
108
+ throw Error("Invalid app frame.");
109
+ return { id: input.id, request: { method: "app.frame", id: request.id, image: request.image } };
110
+ }
111
+ appJson(input, APP_LIMITS.requestBytes); // every other request keeps its 34 KiB bound
100
112
  if (request.method === "game.finish" && exact(request, ["method", "score"]))
101
113
  return { id: input.id, request: { method: "game.finish", ...gameFinishInput({ score: request.score }) } };
102
114
  if ((request.method === "ui.ready" || request.method === "app.checkpoint.get") && exact(request, ["method"]))