@vibechain/os 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/AGENTS.md +139 -208
  2. package/README.md +131 -54
  3. package/SECURITY.md +45 -20
  4. package/dist/app-client.d.ts +4 -1
  5. package/dist/app-client.js +4 -1
  6. package/dist/app-host.d.ts +111 -9
  7. package/dist/app-host.js +339 -58
  8. package/dist/app-protocol.d.ts +2 -0
  9. package/dist/app-runtime.d.ts +18 -2
  10. package/dist/app-runtime.js +75 -11
  11. package/dist/app-wire.d.ts +194 -0
  12. package/dist/app-wire.js +253 -0
  13. package/dist/browser.d.ts +2 -0
  14. package/dist/browser.js +2 -0
  15. package/dist/bundle.js +6 -6
  16. package/dist/canvas.d.ts +2 -2
  17. package/dist/canvas.js +3 -1
  18. package/dist/check.d.ts +12 -0
  19. package/dist/check.js +167 -0
  20. package/dist/cli-publish.d.ts +24 -0
  21. package/dist/cli-publish.js +288 -0
  22. package/dist/cli-session.d.ts +108 -0
  23. package/dist/cli-session.js +245 -0
  24. package/dist/cli.d.ts +10 -0
  25. package/dist/cli.js +46 -10
  26. package/dist/index.d.ts +5 -0
  27. package/dist/index.js +3 -0
  28. package/dist/listing.d.ts +3 -3
  29. package/dist/listing.js +1 -1
  30. package/dist/loop.d.ts +18 -2
  31. package/dist/loop.js +13 -1
  32. package/dist/manifest.d.ts +90 -4
  33. package/dist/manifest.js +340 -5
  34. package/dist/os.d.ts +56 -0
  35. package/dist/os.js +354 -0
  36. package/dist/preview-parent.d.ts +36 -0
  37. package/dist/preview-parent.js +122 -11
  38. package/dist/preview-ui.js +1 -1
  39. package/dist/preview.js +25 -7
  40. package/dist/redact.d.ts +6 -0
  41. package/dist/redact.js +16 -0
  42. package/dist/runtime-policy.d.ts +20 -0
  43. package/dist/runtime-policy.js +45 -0
  44. package/dist/scaffold.d.ts +13 -2
  45. package/dist/scaffold.js +99 -29
  46. package/dist/submit-notice.d.ts +26 -0
  47. package/dist/submit-notice.js +34 -0
  48. package/dist/templates/plain/game.js +18 -0
  49. package/dist/testing.d.ts +63 -0
  50. package/dist/testing.js +157 -1
  51. package/dist/transport.d.ts +20 -0
  52. package/dist/transport.js +71 -19
  53. package/dist/vibemarket-os.js +1 -0
  54. package/dist/worker.d.ts +18 -0
  55. package/dist/worker.js +34 -0
  56. package/examples/paw-beat/README.md +20 -8
  57. package/examples/paw-beat/cat.ts +665 -89
  58. package/examples/paw-beat/game.ts +162 -28
  59. package/examples/paw-beat/index.html +114 -40
  60. package/examples/paw-beat/main.ts +264 -149
  61. package/examples/paw-beat/music.ts +314 -65
  62. package/examples/paw-beat/stage.ts +560 -0
  63. package/examples/paw-beat/store/icon.png +0 -0
  64. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  65. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  66. package/examples/paw-beat/vibemarket.json +2 -2
  67. package/examples/vibexp-app/README.md +20 -4
  68. package/examples/vibexp-app/index.html +3 -2
  69. package/examples/vibexp-app/plain/game.ts +20 -0
  70. package/examples/vibexp-app/plain/index.html +6 -0
  71. package/examples/vibexp-app/plain/vibemarket.json +17 -0
  72. package/examples/vibexp-app/src/main.ts +46 -31
  73. package/examples/vibexp-app/store/icon.png +0 -0
  74. package/examples/vibexp-app/store/screenshot-1.png +0 -0
  75. package/examples/vibexp-app/three/README.md +21 -0
  76. package/examples/vibexp-app/three/index.html +4 -0
  77. package/examples/vibexp-app/three/src/main.ts +45 -0
  78. package/examples/vibexp-app/three/vibemarket.json +19 -0
  79. package/examples/vibexp-app/vibemarket.json +27 -1
  80. package/package.json +8 -3
  81. package/examples/chonk-stack/card-slice.ts +0 -17
  82. package/examples/chonk-stack/cat3d.ts +0 -57
  83. package/examples/chonk-stack/game.css +0 -174
  84. package/examples/chonk-stack/index.html +0 -32
  85. package/examples/chonk-stack/main.ts +0 -149
  86. package/examples/chonk-stack/model.ts +0 -40
  87. package/examples/chonk-stack/renderer.ts +0 -263
  88. package/examples/chonk-stack/skins.ts +0 -47
  89. package/examples/chonk-stack/vibemarket.json +0 -21
  90. package/examples/collection-room/index.html +0 -3
  91. package/examples/collection-room/main.ts +0 -31
  92. package/examples/collection-room/vibemarket.json +0 -12
  93. package/examples/tsconfig.json +0 -4
package/dist/testing.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type AppLifecycle, type AppValue, type VibeMarketAppSdk } from "./app-protocol.ts";
2
+ import { type Card, type Pack } from "./app-wire.ts";
2
3
  import { type GameFinishInput } from "./completion.ts";
4
+ import { type Os } from "./os.ts";
3
5
  export interface FakeAppOptions {
4
6
  /** What `checkpoint.read()` returns first. Default: `null`, as on a first open. */
5
7
  checkpoint?: AppValue;
@@ -27,3 +29,64 @@ export interface FakeApp {
27
29
  * Passing here does not replace a run in the preview.
28
30
  */
29
31
  export declare function createFakeApp(options?: FakeAppOptions): FakeApp;
32
+ export interface FakeOsOptions {
33
+ /** What `load()` returns first. Default: `null`, as on a first open. */
34
+ save?: unknown;
35
+ /** The cards the player holds. `art` may be any URL or null. */
36
+ cards?: readonly Card[];
37
+ /** Public card lists of the packs the game can look at (`pack`, and `packs` for held counts). */
38
+ packs?: readonly Pack[];
39
+ /** The manifest's `cards` and `packs`. Default: `"none"` and `[]` (then `cards()` answers `not-permitted`). */
40
+ access?: {
41
+ cards: "none" | "linked" | "all";
42
+ packs?: readonly string[];
43
+ };
44
+ /** Whether the manifest declares `network`: `player()` then also has a token. Default false. */
45
+ network?: boolean;
46
+ /** A guest: `player()` answers `{ guest: true }`. Default false. */
47
+ guest?: boolean;
48
+ /** Who is playing. Default: handle `fake_player`, name `Fake Player`, no username, no picture. */
49
+ player?: {
50
+ handle: string;
51
+ username?: string;
52
+ name: string;
53
+ picture?: string | null;
54
+ };
55
+ /** Starting lifecycle. Default: active, 800 x 600. */
56
+ lifecycle?: Partial<AppLifecycle>;
57
+ /** 1 behaves like a host older than 0.5: saves are the 32 KiB checkpoint and the rest is `unsupported`. Default 2. */
58
+ protocol?: 1 | 2;
59
+ /** The clock `player()` stamps expiry with. Default `Date.now`. */
60
+ now?: () => number;
61
+ }
62
+ export interface FakeOs {
63
+ /** Pass this wherever your game expects the result of `connect()`. */
64
+ readonly os: Os;
65
+ /** Replace the player's cards as a pull, sale or gift would, and call `onCards` listeners with the permitted list. */
66
+ setCards(cards: readonly Card[]): void;
67
+ /** Change the lifecycle as the host would (minimize, restore, resize) and call the pause, resume and resize listeners. */
68
+ setLifecycle(next: Partial<AppLifecycle>): void;
69
+ /** The next `showPack` or `fullscreen` call counts as following a click in the app. */
70
+ click(): void;
71
+ readonly ready: boolean;
72
+ /** Every progress value the game reported, in order. */
73
+ readonly progress: readonly number[];
74
+ /** The value the last accepted `save` stored (parsed again), or what `options.save` started with. */
75
+ readonly save: unknown;
76
+ /** How many `save` calls were accepted. */
77
+ readonly saves: number;
78
+ readonly finished: Readonly<GameFinishInput> | null;
79
+ /** Packs the game asked the host to show, in order. */
80
+ readonly shownPacks: readonly string[];
81
+ readonly maximized: boolean;
82
+ readonly fullscreen: boolean;
83
+ readonly closed: boolean;
84
+ }
85
+ /**
86
+ * An in-memory stand-in for an apps3 host behind `connect()`, for unit tests of cards, saves and the player. It applies
87
+ * the real rules: the save limits and JSON checks, pack slugs, the manifest's card access (`none`, `linked`, `all`),
88
+ * single-shot completion, the click needed by `showPack` and `fullscreen`, the stable error codes, and `protocol: 1`
89
+ * for a host older than this SDK. It has no window, no port, no time limits, no rate limits and no save coalescing
90
+ * (each save is stored at once), so still run the preview before you ship.
91
+ */
92
+ export declare function createFakeOs(options?: FakeOsOptions): FakeOs;
package/dist/testing.js CHANGED
@@ -1,5 +1,8 @@
1
- import { checkpointValue, lifecycleValue } from "./app-protocol.js";
1
+ import { APP_LIMITS, checkpointJson, checkpointValue, lifecycleValue } from "./app-protocol.js";
2
+ import { AppHostError, saveJson, saveValue, wireCard, wirePack } from "./app-wire.js";
2
3
  import { gameFinishInput } from "./completion.js";
4
+ import { packSlug } from "./manifest.js";
5
+ import { OsError } from "./os.js";
3
6
  /**
4
7
  * An in-memory stand-in for the VibeMarket OS host, for unit tests. It applies the same
5
8
  * checkpoint, score and lifecycle validation as the real host and the same single-shot
@@ -47,3 +50,156 @@ export function createFakeApp(options = {}) {
47
50
  get destroyed() { return destroyed; },
48
51
  };
49
52
  }
53
+ /**
54
+ * An in-memory stand-in for an apps3 host behind `connect()`, for unit tests of cards, saves and the player. It applies
55
+ * the real rules: the save limits and JSON checks, pack slugs, the manifest's card access (`none`, `linked`, `all`),
56
+ * single-shot completion, the click needed by `showPack` and `fullscreen`, the stable error codes, and `protocol: 1`
57
+ * for a host older than this SDK. It has no window, no port, no time limits, no rate limits and no save coalescing
58
+ * (each save is stored at once), so still run the preview before you ship.
59
+ */
60
+ export function createFakeOs(options = {}) {
61
+ const protocol = options.protocol ?? 2, access = options.access ?? { cards: "none" }, linked = access.packs ?? [], now = options.now ?? Date.now;
62
+ const fail = (code, message) => new OsError(code, message);
63
+ const checkCards = (cards) => cards.map(card => ({ ...wireCard({ ...card, art: null }), art: card.art }));
64
+ const packs = (options.packs ?? []).map(pack => ({ ...wirePack({ ...pack, art: null, cards: pack.cards.map(card => ({ ...card, art: null })) }), art: pack.art, cards: pack.cards.map(card => ({ ...card })) }));
65
+ let held = checkCards(options.cards ?? []), saved = protocol === 2 ? saveJson(options.save ?? null) : checkpointJson(options.save ?? null);
66
+ let state = lifecycleValue({ active: true, width: 800, height: 600, ...options.lifecycle });
67
+ let ready = false, closed = false, clicked = false, saves = 0, maximized = false, fullscreen = false, finished = null;
68
+ const progress = [], shown = [];
69
+ const pause = new Set(), resume = new Set(), resize = new Set(), watchers = new Set();
70
+ const open = () => { if (closed)
71
+ throw fail("closed", "The session ended. Reopen the app."); };
72
+ const v2 = () => { open(); if (protocol !== 2)
73
+ throw fail("unsupported", "This host is older than this SDK and has no such feature."); };
74
+ const slug = (value) => { if (!packSlug(value))
75
+ throw fail("invalid", "That is not a pack slug."); return value; };
76
+ const readable = (pack) => access.cards === "all" || linked.includes(pack);
77
+ const permitted = () => held.filter(card => readable(card.pack));
78
+ const copy = (cards) => cards.map(card => ({ ...card }));
79
+ const os = Object.freeze({
80
+ get active() { return state.active; },
81
+ get size() { return Object.freeze({ width: state.width, height: state.height }); },
82
+ get guest() { return protocol === 2 && options.guest === true; },
83
+ async ready() { open(); ready = true; },
84
+ progress(fraction) {
85
+ if (typeof fraction !== "number" || !Number.isFinite(fraction) || fraction < 0 || fraction > 1)
86
+ throw fail("invalid", "Progress is a number from 0 to 1.");
87
+ if (protocol === 2 && !ready && !closed)
88
+ progress.push(fraction);
89
+ },
90
+ async load() { open(); return (protocol === 2 ? saveValue(saved) : JSON.parse(saved)); },
91
+ async save(value) {
92
+ open();
93
+ try {
94
+ const text = saveJson(value);
95
+ if (protocol === 1) {
96
+ if (new TextEncoder().encode(text).byteLength > APP_LIMITS.checkpointBytes)
97
+ throw new AppHostError("too-large", "This host keeps at most 32 KiB.");
98
+ checkpointJson(value);
99
+ }
100
+ saved = text;
101
+ saves++;
102
+ }
103
+ catch (error) {
104
+ throw error instanceof AppHostError ? fail(error.code, error.message) : fail("too-large", error.message);
105
+ }
106
+ },
107
+ async cards(pack) {
108
+ const filter = pack === undefined ? undefined : slug(pack);
109
+ v2();
110
+ if (access.cards === "none")
111
+ throw fail("not-permitted", "The manifest does not declare cards.");
112
+ return copy(permitted().filter(card => filter === undefined || card.pack === filter));
113
+ },
114
+ onCards(listener) { watchers.add(listener); return () => { watchers.delete(listener); }; },
115
+ async packs() {
116
+ v2();
117
+ const ids = access.cards === "all" ? [...new Set([...linked, ...held.map(card => card.pack)])] : [...linked];
118
+ return ids.flatMap(id => { const pack = packs.find(item => item.id === id); if (!pack)
119
+ return []; const { cards, ...head } = pack; return [{ ...head, held: access.cards === "none" ? 0 : new Set(held.filter(card => card.pack === id).map(card => card.id)).size }]; });
120
+ },
121
+ async pack(id) {
122
+ const name = slug(id);
123
+ v2();
124
+ const pack = packs.find(item => item.id === name);
125
+ if (!pack || !readable(name))
126
+ throw fail("not-permitted", "This app may not read that pack.");
127
+ return { ...pack, cards: pack.cards.map(card => ({ ...card })) };
128
+ },
129
+ async showPack(id) {
130
+ const name = slug(id);
131
+ v2();
132
+ if (!readable(name))
133
+ throw fail("not-permitted", "This app may not show that pack.");
134
+ if (!clicked)
135
+ throw fail("needs-click", "That needs a fresh click in the app.");
136
+ clicked = false;
137
+ shown.push(name);
138
+ },
139
+ async player() {
140
+ v2();
141
+ if (options.guest === true)
142
+ return { guest: true };
143
+ const who = options.player ?? { handle: "fake_player", name: "Fake Player" };
144
+ const player = { guest: false, handle: who.handle, ...(who.username === undefined ? {} : { username: who.username }), name: who.name, picture: who.picture ?? null };
145
+ return options.network ? { ...player, token: "fake.player.token-for-tests", expiresAt: now() + 300_000 } : player;
146
+ },
147
+ async finish(input) {
148
+ open();
149
+ let result;
150
+ try {
151
+ result = gameFinishInput(input);
152
+ }
153
+ catch (error) {
154
+ throw fail("invalid", error.message);
155
+ }
156
+ if (finished && finished.score !== result.score)
157
+ throw fail("invalid", "This game has already finished.");
158
+ finished ??= result;
159
+ },
160
+ async maximize(on = true) { v2(); maximized = on; },
161
+ async fullscreen(on = true) {
162
+ v2();
163
+ if (on && !clicked)
164
+ throw fail("needs-click", "That needs a fresh click in the app.");
165
+ clicked = false;
166
+ fullscreen = on;
167
+ },
168
+ onPause(listener) { pause.add(listener); return () => { pause.delete(listener); }; },
169
+ onResume(listener) { resume.add(listener); return () => { resume.delete(listener); }; },
170
+ onResize(listener) { resize.add(listener); return () => { resize.delete(listener); }; },
171
+ close() { closed = true; pause.clear(); resume.clear(); resize.clear(); watchers.clear(); },
172
+ });
173
+ return {
174
+ os,
175
+ setCards(cards) {
176
+ held = checkCards(cards);
177
+ if (protocol === 2 && access.cards !== "none")
178
+ for (const listener of [...watchers])
179
+ listener(copy(permitted()));
180
+ },
181
+ setLifecycle(next) {
182
+ const previous = state;
183
+ state = lifecycleValue({ ...state, ...next });
184
+ if (previous.active && !state.active)
185
+ for (const listener of [...pause])
186
+ listener();
187
+ if (!previous.active && state.active)
188
+ for (const listener of [...resume])
189
+ listener();
190
+ if (previous.width !== state.width || previous.height !== state.height)
191
+ for (const listener of [...resize])
192
+ listener(Object.freeze({ width: state.width, height: state.height }));
193
+ },
194
+ click() { clicked = true; },
195
+ get ready() { return ready; },
196
+ get progress() { return [...progress]; },
197
+ get save() { return JSON.parse(saved); },
198
+ get saves() { return saves; },
199
+ get finished() { return finished; },
200
+ get shownPacks() { return [...shown]; },
201
+ get maximized() { return maximized; },
202
+ get fullscreen() { return fullscreen; },
203
+ get closed() { return closed; },
204
+ };
205
+ }
@@ -8,10 +8,30 @@ export interface PortOptions {
8
8
  maxPending?: number;
9
9
  jsonBytes?: number;
10
10
  onEvent?: (value: Record<string, unknown>) => void;
11
+ /** protocol 2: the errors a request rejects with (a host error reply carries `code`) */
12
+ errors?: TransportErrors;
13
+ /**
14
+ * protocol 2: send a request only while fewer than `perSecond` (`perMinute`) earlier requests are unanswered or were
15
+ * answered within the last second (minute). A host counts a request when it reads it, which is between its sending and
16
+ * its answer, so this keeps every host window under the same numbers however late the host reads. Requests over the
17
+ * pace wait in order (at most `maxPending` waiting or unanswered); their timeout starts when they are sent.
18
+ */
19
+ pace?: {
20
+ perSecond: number;
21
+ perMinute: number;
22
+ };
23
+ }
24
+ export interface TransportErrors {
25
+ reply(message: string, code: unknown): Error;
26
+ timeout(): Error;
27
+ closed(): Error;
28
+ busy(): Error;
11
29
  }
12
30
  /** Canonical private-port transport used by both the existing Market client and the app facade. */
13
31
  export declare function createRpcTransport<Request, Result>(port: MessagePort, options?: PortOptions): RpcTransport<Request, Result>;
32
+ /** The port the host transferred, its session, and `protocol: 2` when an apps3 host advertised it (0.4 clients ignore it). */
14
33
  export declare function connectHostPort(signal?: AbortSignal, challenge?: string): Promise<{
15
34
  port: MessagePort;
16
35
  session?: string;
36
+ protocol?: 2;
17
37
  }>;
package/dist/transport.js CHANGED
@@ -2,8 +2,35 @@ import { CHANNEL } from "./channel.js";
2
2
  import { appJson, appNonce, parseAppJson } from "./app-protocol.js";
3
3
  /** Canonical private-port transport used by both the existing Market client and the app facade. */
4
4
  export function createRpcTransport(port, options = {}) {
5
- let sequence = 0, closed = false;
5
+ let sequence = 0, closed = false, pumpTimer;
6
6
  const pending = new Map();
7
+ const appMode = options.jsonBytes !== undefined, errors = options.errors;
8
+ const records = [], waiting = [];
9
+ const finish = (record) => { if (record) {
10
+ record.done = Date.now();
11
+ pump();
12
+ } };
13
+ const closedError = () => errors ? errors.closed() : Error("Game session ended.");
14
+ /** Send waiting requests while the pace allows, else wake when the oldest counted answer leaves its window. */
15
+ function pump() {
16
+ const pace = options.pace;
17
+ while (waiting.length) {
18
+ const now = Date.now();
19
+ for (let i = records.length - 1; i >= 0; i--)
20
+ if (records[i].done !== null && now - records[i].done >= 60_000)
21
+ records.splice(i, 1);
22
+ const recent = records.filter(record => record.done === null || now - record.done < 1000);
23
+ if (recent.length < pace.perSecond && records.length < pace.perMinute) {
24
+ waiting.shift()();
25
+ continue;
26
+ }
27
+ const span = recent.length >= pace.perSecond ? { list: recent, ms: 1000 } : { list: records, ms: 60_000 };
28
+ const answered = span.list.filter(record => record.done !== null).map(record => record.done + span.ms - now);
29
+ if (answered.length && pumpTimer === undefined)
30
+ pumpTimer = window.setTimeout(() => { pumpTimer = undefined; pump(); }, Math.max(1, Math.min(...answered)));
31
+ return;
32
+ }
33
+ }
7
34
  port.onmessage = (event) => {
8
35
  let data;
9
36
  try {
@@ -28,46 +55,70 @@ export function createRpcTransport(port, options = {}) {
28
55
  return;
29
56
  pending.delete(value.id);
30
57
  window.clearTimeout(call.timer);
31
- if (typeof value.error === "string")
32
- call.reject(Error(options.jsonBytes === undefined ? value.error : value.error.slice(0, 500)));
58
+ finish(call.record);
59
+ if (typeof value.error === "string") {
60
+ const message = appMode ? value.error.slice(0, 500) : value.error;
61
+ call.reject(errors ? errors.reply(message, value.code) : Error(message));
62
+ }
33
63
  else if ("result" in value)
34
64
  call.resolve(value.result);
35
65
  else
36
- call.reject(Error("Invalid host response."));
66
+ call.reject(errors ? errors.reply("Invalid host response.", "unavailable") : Error("Invalid host response."));
37
67
  };
38
68
  port.start();
39
69
  return {
40
70
  request(message) {
41
71
  if (closed)
42
- return Promise.reject(Error("Game session ended."));
43
- if (pending.size >= (options.maxPending ?? 16))
44
- return Promise.reject(Error("Too many pending requests."));
72
+ return Promise.reject(closedError());
73
+ if (pending.size + waiting.length >= (options.maxPending ?? 16))
74
+ return Promise.reject(errors ? errors.busy() : Error("Too many pending requests."));
45
75
  const id = String(++sequence);
46
76
  return new Promise((resolve, reject) => {
47
- const timer = window.setTimeout(() => { pending.delete(id); reject(Error(options.jsonBytes === undefined ? "Request timed out. Check your VibeMarket inventory before trying again; a submitted transaction may still complete." : "App request timed out. Restore the window and read its last accepted checkpoint before retrying.")); }, options.timeoutMs ?? 180_000);
48
- pending.set(id, { resolve: value => resolve(value), reject, timer });
49
- try {
50
- const envelope = { id, request: message, ...(options.session === undefined ? {} : { session: options.session }) };
51
- port.postMessage(options.jsonBytes === undefined ? envelope : appJson(envelope, options.jsonBytes));
52
- }
53
- catch (error) {
54
- pending.delete(id);
55
- window.clearTimeout(timer);
56
- reject(error);
77
+ const send = () => {
78
+ const record = options.pace ? { done: null } : undefined;
79
+ if (record)
80
+ records.push(record);
81
+ const timer = window.setTimeout(() => { pending.delete(id); finish(record); reject(errors ? errors.timeout() : Error(options.jsonBytes === undefined ? "Request timed out. Check your VibeMarket inventory before trying again; a submitted transaction may still complete." : "App request timed out. Restore the window and read its last accepted checkpoint before retrying.")); }, options.timeoutMs ?? 180_000);
82
+ pending.set(id, { resolve: value => resolve(value), reject, timer, record });
83
+ try {
84
+ const envelope = { id, request: message, ...(options.session === undefined ? {} : { session: options.session }) };
85
+ port.postMessage(options.jsonBytes === undefined ? envelope : appJson(envelope, options.jsonBytes));
86
+ }
87
+ catch (error) {
88
+ pending.delete(id);
89
+ window.clearTimeout(timer);
90
+ finish(record);
91
+ reject(error);
92
+ }
93
+ };
94
+ if (!options.pace) {
95
+ send();
96
+ return;
57
97
  }
98
+ // ids stay in sending order: a waiting request keeps its place
99
+ waiting.push(() => { if (closed)
100
+ reject(closedError());
101
+ else
102
+ send(); });
103
+ pump();
58
104
  });
59
105
  },
60
106
  destroy() {
61
107
  if (closed)
62
108
  return;
63
109
  closed = true;
64
- pending.forEach(call => { window.clearTimeout(call.timer); call.reject(Error("Game session ended.")); });
110
+ if (pumpTimer !== undefined)
111
+ window.clearTimeout(pumpTimer);
112
+ for (const start of waiting.splice(0))
113
+ start();
114
+ pending.forEach(call => { window.clearTimeout(call.timer); call.reject(closedError()); });
65
115
  pending.clear();
66
116
  port.onmessage = null;
67
117
  port.close();
68
118
  },
69
119
  };
70
120
  }
121
+ /** The port the host transferred, its session, and `protocol: 2` when an apps3 host advertised it (0.4 clients ignore it). */
71
122
  export function connectHostPort(signal, challenge) {
72
123
  return new Promise((resolve, reject) => {
73
124
  let retry;
@@ -84,8 +135,9 @@ export function connectHostPort(signal, challenge) {
84
135
  return;
85
136
  session = event.data.session;
86
137
  }
138
+ const protocol = challenge !== undefined && "protocol" in event.data && event.data.protocol === 2 ? 2 : undefined;
87
139
  cleanup();
88
- resolve({ port: event.ports[0], ...(session === undefined ? {} : { session }) });
140
+ resolve({ port: event.ports[0], ...(session === undefined ? {} : { session }), ...(protocol === undefined ? {} : { protocol }) });
89
141
  };
90
142
  const timeout = window.setTimeout(() => { cleanup(); reject(Error("VibeMarket did not connect. Reopen the game.")); }, 15_000);
91
143
  window.addEventListener("message", connect);
@@ -0,0 +1 @@
1
+ "use strict";var VibemarketOS=(()=>{var X=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var Ne=(e,t)=>{for(var n in t)X(e,n,{get:t[n],enumerable:!0})},$e=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ze(t))!je.call(e,s)&&s!==n&&X(e,s,{get:()=>t[s],enumerable:!(a=Te(t,s))||a.enumerable});return e};var Le=e=>$e(X({},"__esModule",{value:!0}),e);var rt={};Ne(rt,{OsError:()=>z,connect:()=>Oe});function K(e){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw Error("Invalid game completion.");let t=Object.getOwnPropertyDescriptor(e,"score");if(Reflect.ownKeys(e).length!==1||!t||!("value"in t)||!t.enumerable||typeof t.value!="number"||!Number.isInteger(t.value)||t.value<0||t.value>1e9)throw Error("Score must be an integer from 0 to 1,000,000,000.");return Object.freeze({score:t.value})}var le="vibexp";var v=Object.freeze({checkpointBytes:32*1024,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34*1024,responseBytes:34*1024,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:900*1e3,requestTimeoutMs:1e4});function W(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function Y(e,t){let n=JSON.stringify(e);if(typeof n!="string"||n.length>t||new TextEncoder().encode(n).length>t)throw Error("App message exceeds limit.");return n}function pe(e,t){if(typeof e!="string"||e.length>t||new TextEncoder().encode(e).length>t)throw Error("Invalid app message size or encoding.");return JSON.parse(e)}var ue=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Ve=(e,t)=>{let n=Object.keys(e);return n.length===t.length&&Reflect.ownKeys(e).length===n.length&&n.every(a=>t.includes(a)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,a)??{},"value"))};function de(e){let t=0,n=0,a=(i,p)=>{if(++t>v.checkpointNodes||p>v.checkpointDepth)throw Error("App checkpoint is too complex.");if(i===null||typeof i=="boolean")return;if(typeof i=="number"){if(!Number.isFinite(i))throw Error("Checkpoint numbers must be finite.");return}if(typeof i=="string"){if(i.length>v.stringBytes)throw Error("App checkpoint string is too large.");let u=new TextEncoder().encode(i).byteLength;if(u>v.stringBytes||(n+=u)>v.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(i)){if(i.length>v.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(i).length!==i.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let u=0;u<i.length;u++){let f=Object.getOwnPropertyDescriptor(i,u);if(!f||!("value"in f))throw Error("Sparse/accessor checkpoints are unsupported.");a(f.value,p+1)}return}if(!ue(i))throw Error("App checkpoint must contain only JSON values.");let l=Object.keys(i);if(Reflect.ownKeys(i).length!==l.length)throw Error("Checkpoint properties must be enumerable strings.");if(l.length>v.objectKeys)throw Error("App checkpoint has too many keys.");for(let u of l){if(["__proto__","constructor","prototype"].includes(u)||u.length>128)throw Error("Invalid app checkpoint key.");if(n+=new TextEncoder().encode(u).byteLength,n>v.checkpointBytes)throw Error("App checkpoint keys are too large.");let f=Object.getOwnPropertyDescriptor(i,u);if(!f||!("value"in f))throw Error("App checkpoint accessors are unsupported.");a(f.value,p+1)}};a(e,0);let s=JSON.stringify(e);if(new TextEncoder().encode(s).byteLength>v.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return s}function he(e){if(!ue(e)||!Ve(e,["active","width","height"])||typeof e.active!="boolean"||typeof e.width!="number"||!Number.isInteger(e.width)||e.width<0||e.width>4096||typeof e.height!="number"||!Number.isInteger(e.height)||e.height<0||e.height>4096)throw Error("Invalid app lifecycle.");return Object.freeze({active:e.active,width:e.width,height:e.height})}var at={descriptionMin:40,descriptionMax:2e3,supportMax:200,screenshotsMin:1,screenshotsMax:4,iconSize:256,iconBytes:256*1024,screenshotBytes:1024*1024};var ct={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},lt={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},De={packs:3,network:8,packSlugMax:56},We=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,F=e=>typeof e=="string"&&e.length<=De.packSlugMax&&We.test(e);var ge=["unsupported","not-permitted","invalid","too-large","rate-limited","needs-click","unavailable","timeout","closed"],ye=e=>typeof e=="string"&&ge.includes(e),R=Object.freeze({idleMs:900*1e3,sessionMs:14400*1e3,requestsPerSecond:10,requestsPerMinute:120,lifetimeRequests:3e4,inFlight:8,readyMs:15e3,progressReadyMs:12e4,saveBytes:1048576,saveDepth:64,saveIntervalMs:1e4,messageBytes:1101024,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4}),Fe=["common","rare","epic","legendary","mythic"],Be=/^[A-Za-z0-9_-]{1,64}$/,q=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}),B=1024,qe=Object.freeze({"host.hello":{request:256,response:B,states:"LFB"},"ui.progress":{request:64,response:64,rate:[4,1e3],states:"LFB"},"app.save.get":{request:64,response:11e5,rate:[6,6e4],states:"LFB"},"app.save.set":{request:11e5,response:256,rate:[1,1e4],states:"LFB"},"cards.list":{request:256,response:256*B,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*B,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*B,rate:[30,6e4],states:"LFB"},"cards.watch":{request:64,response:64,rate:[30,6e4],states:"LFB"},"pack.show":{request:128,response:64,rate:[1,1e4],states:"F"},"player.get":{request:64,response:2*B,rate:[10,6e4],states:"LFB"},"display.maximize":{request:64,response:64,rate:[2,1e3],states:"F"},"display.fullscreen":{request:64,response:64,rate:[1,1e3],states:"F"}}),ft=Object.freeze(Object.keys(qe).filter(e=>e!=="host.hello")),Ge=new TextEncoder,He=e=>Ge.encode(e).byteLength,I=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),M=(e,t,n=[])=>Reflect.ownKeys(e).every(s=>typeof s=="string"&&(t.includes(s)||n.includes(s))&&"value"in Object.getOwnPropertyDescriptor(e,s))&&t.every(s=>Object.hasOwn(e,s)),T=class extends Error{code;constructor(t,n){super(n),this.name="AppHostError",this.code=t}};function Q(e){let t=s=>new T("invalid",s),n=(s,i)=>{if(!(s===null||typeof s=="boolean"||typeof s=="string")){if(typeof s=="number"){if(!Number.isFinite(s))throw t("A save's numbers must be finite.");return}if(typeof s!="object")throw t("A save must contain only JSON values.");if(i>R.saveDepth)throw t(`A save nests at most ${R.saveDepth} levels deep.`);if(Array.isArray(s)){if(Reflect.ownKeys(s).length!==s.length+1)throw t("A save's arrays cannot have extra properties.");for(let p=0;p<s.length;p++){let l=Object.getOwnPropertyDescriptor(s,p);if(!l||!("value"in l))throw t("A save's arrays cannot be sparse or have accessors.");n(l.value,i+1)}return}if(!I(s))throw t("A save must contain only plain objects, arrays and JSON values.");for(let p of Reflect.ownKeys(s)){let l=Object.getOwnPropertyDescriptor(s,p);if(typeof p!="string"||!l||!("value"in l)||!l.enumerable)throw t("A save's properties must be plain enumerable data.");n(l.value,i+1)}}};n(e,1);let a=JSON.stringify(e);if(He(a)>R.saveBytes)throw new T("too-large",`A save is at most ${R.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return a}function we(e){let t;try{t=JSON.parse(e)}catch{throw new T("invalid","The saved data is not JSON.")}return Q(t),t}var _=(e,t,n=0)=>typeof e=="string"&&e.length>=n&&e.length<=t,J=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Ke=e=>typeof e=="string"&&Fe.includes(e),ee=".bin",Je=(e,t)=>`-/card/${e}/${t}${ee}`,Ze=e=>`-/cover/${e}${ee}`,Ue=e=>`-/player/${e}${ee}`;function be(e,t){if(!I(e)||!M(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:n,pack:a,name:s,art:i}=e,p=typeof n=="string"?n.slice(n.indexOf("/")+1):"";if(!F(a)||n!==`${a}/${p}`||!Be.test(p)||!_(s,120)||!Ke(e.rarity)||t&&!J(e.count,1,1e6)||i!==null&&i!==Je(a,p))throw Error("Invalid card.");return{id:n,pack:a,name:s,rarity:e.rarity,...t?{count:e.count}:{},art:i}}function te(e){return be(e,!0)}function Xe(e){return be(e,!1)}function ke(e){let{id:t,name:n,creator:a,art:s,total:i}=e;if(!F(t)||!_(n,120,1)||a!==null&&!_(a,64,1)||s!==null&&s!==Ze(t)||!J(i,0,1e4))throw Error("Invalid pack.");return{id:t,name:n,creator:a,art:s,total:i}}function Ae(e){if(!I(e)||!M(e,["id","name","creator","art","held","total"])||!J(e.held,0,1e4))throw Error("Invalid pack.");let t=ke(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function xe(e){if(!I(e)||!M(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=ke(e),n=e.cards.map(Xe);if(n.some(a=>a.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:n}}var Ye=/[\u0000-\u001F\u007F-\u009F]/,me=e=>typeof e=="string"&&q.handle.test(e);function ve(e){if(I(e)&&M(e,["guest"])&&e.guest===!0)return{guest:!0};if(!I(e)||!M(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:n,name:a,picture:s,token:i,expiresAt:p}=e;if(!me(t)||!_(a,q.nameMax,1)||Ye.test(a)||n!==void 0&&(!me(n)||n===t)||s!==null&&s!==Ue(t)||"token"in e!="expiresAt"in e||i!==void 0&&(!_(i,q.tokenMax,q.tokenMin)||!q.token.test(i)||!J(p,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...n===void 0?{}:{username:n},name:a,picture:s,...i===void 0?{}:{token:i,expiresAt:p}}}var fe=e=>_(e,64,1);function Ee(e){if(I(e)&&M(e,["reset","revision"])&&e.reset===!0&&fe(e.revision))return{reset:!0,revision:e.revision};if(!I(e)||!M(e,["changed","removed","revision"])||!Array.isArray(e.changed)||!Array.isArray(e.removed)||!fe(e.revision)||e.removed.some(t=>!_(t,130,3)))throw Error("Invalid cards event.");return{changed:e.changed.map(te),removed:e.removed,revision:e.revision}}function Pe(e){if(!I(e)||!M(e,["protocol","guest","features","root"])||e.protocol!==2||typeof e.guest!="boolean"||!Array.isArray(e.features)||e.features.length>64||e.features.some(t=>!_(t,40,1))||typeof e.root!="string"||!/^(?:\.\/|(?:\.\.\/){1,32})$/.test(e.root))throw Error("Invalid hello.");return{protocol:2,guest:e.guest,features:e.features,root:e.root}}var re="vibemarket.game.v1";function Se(e,t={}){let n=0,a=!1,s,i=new Map,p=t.jsonBytes!==void 0,l=t.errors,u=[],f=[],m=d=>{d&&(d.done=Date.now(),S())},g=()=>l?l.closed():Error("Game session ended.");function S(){let d=t.pace;for(;f.length;){let w=Date.now();for(let b=u.length-1;b>=0;b--)u[b].done!==null&&w-u[b].done>=6e4&&u.splice(b,1);let y=u.filter(b=>b.done===null||w-b.done<1e3);if(y.length<d.perSecond&&u.length<d.perMinute){f.shift()();continue}let A=y.length>=d.perSecond?{list:y,ms:1e3}:{list:u,ms:6e4},x=A.list.filter(b=>b.done!==null).map(b=>b.done+A.ms-w);x.length&&s===void 0&&(s=window.setTimeout(()=>{s=void 0,S()},Math.max(1,Math.min(...x))));return}}return e.onmessage=d=>{let w;try{w=t.jsonBytes===void 0?d.data:pe(d.data,t.jsonBytes)}catch{return}if(a||!w||typeof w!="object"||Array.isArray(w))return;let y=w;if(t.session!==void 0&&y.session!==t.session)return;if("event"in y){t.onEvent?.(y);return}if(typeof y.id!="string")return;let A=i.get(y.id);if(A)if(i.delete(y.id),window.clearTimeout(A.timer),m(A.record),typeof y.error=="string"){let x=p?y.error.slice(0,500):y.error;A.reject(l?l.reply(x,y.code):Error(x))}else"result"in y?A.resolve(y.result):A.reject(l?l.reply("Invalid host response.","unavailable"):Error("Invalid host response."))},e.start(),{request(d){if(a)return Promise.reject(g());if(i.size+f.length>=(t.maxPending??16))return Promise.reject(l?l.busy():Error("Too many pending requests."));let w=String(++n);return new Promise((y,A)=>{let x=()=>{let b=t.pace?{done:null}:void 0;b&&u.push(b);let j=window.setTimeout(()=>{i.delete(w),m(b),A(l?l.timeout():Error(t.jsonBytes===void 0?"Request timed out. Check your VibeMarket inventory before trying again; a submitted transaction may still complete.":"App request timed out. Restore the window and read its last accepted checkpoint before retrying."))},t.timeoutMs??18e4);i.set(w,{resolve:O=>y(O),reject:A,timer:j,record:b});try{let O={id:w,request:d,...t.session===void 0?{}:{session:t.session}};e.postMessage(t.jsonBytes===void 0?O:Y(O,t.jsonBytes))}catch(O){i.delete(w),window.clearTimeout(j),m(b),A(O)}};if(!t.pace){x();return}f.push(()=>{a?A(g()):x()}),S()})},destroy(){if(!a){a=!0,s!==void 0&&window.clearTimeout(s);for(let d of f.splice(0))d();i.forEach(d=>{window.clearTimeout(d.timer),d.reject(g())}),i.clear(),e.onmessage=null,e.close()}}}}function Re(e,t){return new Promise((n,a)=>{let s,i=()=>{window.clearTimeout(u),s!==void 0&&window.clearInterval(s),window.removeEventListener("message",l),e?.removeEventListener("abort",p)},p=()=>{i(),a(Error("Game session ended."))},l=m=>{if(m.source!==window.parent||!m.data||typeof m.data!="object"||!("channel"in m.data)||m.data.channel!==re||m.ports.length!==1)return;let g;if(t!==void 0){if(!("challenge"in m.data)||m.data.challenge!==t||!("session"in m.data)||!W(m.data.session))return;g=m.data.session}let S=t!==void 0&&"protocol"in m.data&&m.data.protocol===2?2:void 0;i(),n({port:m.ports[0],...g===void 0?{}:{session:g},...S===void 0?{}:{protocol:S}})},u=window.setTimeout(()=>{i(),a(Error("VibeMarket did not connect. Reopen the game."))},15e3);if(window.addEventListener("message",l),e?.addEventListener("abort",p,{once:!0}),e?.aborted){p();return}let f=()=>{let m={channel:re,type:"connect",...t===void 0?{}:{challenge:t}};window.parent.postMessage(t===void 0?m:Y(m,256),"*")};f(),t!==void 0&&(s=window.setInterval(f,250))})}var Qe="0.5.0",z=class extends Error{code;constructor(t,n){super(n),this.name="OsError",this.code=t}},et={unsupported:"This host is older than this SDK and has no such feature.","not-permitted":"The manifest does not declare that, or the app is behind another window.",invalid:"That argument is not valid.","too-large":"That is too large.","rate-limited":"Too many requests; try again later.","needs-click":"That needs a fresh click in the app.",unavailable:"The host could not answer now; try again.",timeout:"The host did not answer in 10 seconds.",closed:"The session ended. Reopen the app."},h=(e,t=et[e])=>new z(e,t),G=(e,t)=>e instanceof z?e:e instanceof T?new z(e.code,e.message):h(t,e.message),ne=e=>{if(!F(e))throw h("invalid","That is not a pack slug.");return e};async function Oe(e={}){let t=new URLSearchParams(window.location.hash.slice(1)).get(le);if(!W(t))throw h("unsupported","Open this app in VibeMarket OS or the SDK preview.");let n;try{n=await Re(e.signal,t)}catch(a){throw h(e.signal?.aborted?"closed":"timeout",a.message)}return tt(n.port,n.session,n.protocol??1,window.location.href)}async function tt(e,t,n,a){if(!W(t))throw h("unavailable","Invalid app session.");let s=Object.freeze({active:!0,width:0,height:0}),i=!1,p=new Set,l=new Set,u=new Set,f=new Set,m=Se(e,{session:t,timeoutMs:v.requestTimeoutMs,maxPending:n===2?64:v.inFlight,jsonBytes:n===2?R.messageBytes:v.responseBytes,errors:{reply:(r,o)=>h(ye(o)?o:"unavailable",r),timeout:()=>h("timeout"),closed:()=>h("closed"),busy:()=>h("rate-limited","Too many requests are waiting; try again later.")},...n===2?{pace:{perSecond:R.clientPerSecond,perMinute:R.clientPerMinute}}:{},onEvent(r){if(r.event==="app.cards"){Ie(r.state);return}if(r.event!=="app.lifecycle")return;let o;try{o=he(r.state)}catch{return}let c=s;if(s=Object.freeze({active:o.active,width:o.width,height:o.height}),c.active&&!o.active)for(let k of[...p])k();if(!c.active&&o.active)for(let k of[...l])k();if(c.width!==o.width||c.height!==o.height)for(let k of[...u])k(Object.freeze({width:o.width,height:o.height}))}}),g=async r=>{if(i)throw h("closed");let o=await m.request(r);if(!o||typeof o!="object"||Array.isArray(o))throw h("unavailable","Invalid host response.");return o},S=r=>{if(r.completed!==!0)throw h("unavailable","Invalid host acknowledgement.")},d=null;if(n===2)try{d=Pe(await g({method:"host.hello",protocol:2,sdk:Qe}))}catch(r){throw m.destroy(),G(r,"unavailable")}let w=()=>{if(!d)throw h("unsupported");return d},y=r=>r===null?null:new URL(w().root+r,a).href,A=r=>({...r,art:y(r.art)}),x=null,b=!1,j=null,O=async r=>{for(let o=0;o<4;o++){let c=[],k=null,E=null,H=!0;do{let P=await g({method:"cards.list",...r===void 0?{}:{pack:r},...k===null?{}:{after:k}});if(!Array.isArray(P.cards)||P.after!==null&&typeof P.after!="string"||typeof P.revision!="string")throw h("unavailable","Invalid host response.");if(E!==null&&P.revision!==E){H=!1;break}E=P.revision,k=P.after;for(let Ce of P.cards)c.push(A(te(Ce)))}while(k!==null);if(H&&E!==null)return r===void 0&&(x={revision:E,cards:new Map(c.map(P=>[P.id,P]))}),{cards:c,revision:E}}throw h("unavailable","The cards kept changing while they were read; try again.")},se=()=>{let r=[...x.cards.values()];for(let o of[...f])o(r.slice())},oe=r=>j??=(async()=>{try{do b=!1,await O();while(b);r&&se()}catch{}finally{j=null}})();function Ie(r){if(!f.size)return;let o;try{o=Ee(r)}catch{return}if(j){b=!0;return}if("reset"in o||!x){oe(!0);return}for(let c of o.removed)x.cards.delete(c);for(let c of o.changed)x.cards.set(c.id,A(c));x={revision:o.revision,cards:x.cards},se()}let C=null,Z=!1,ie=-1/0,N,Me=n===2?R.saveIntervalMs:0,U=()=>{if(Z||!C||N!==void 0)return;let r=ie+Me-Date.now();if(r>0){N=window.setTimeout(()=>{N=void 0,U()},r);return}let{text:o,waiters:c}=C;C=null,Z=!0;let k=JSON.parse(o);g(n===2?{method:"app.save.set",value:k}:{method:"app.checkpoint.set",value:k}).then(E=>{if(n===2?typeof E.savedAt!="string":E.completed!==!0)throw h("unavailable","Invalid host acknowledgement.")}).then(()=>{for(let E of c)E.resolve()},E=>{let H=G(E,"unavailable");for(let P of c)P.reject(H)}).finally(()=>{Z=!1,ie=Date.now(),U()})},$=null,L={get active(){return s.active},get size(){return Object.freeze({width:s.width,height:s.height})},get guest(){return d?.guest??!1},async ready(){S(await g({method:"ui.ready"}))},progress(r){if(typeof r!="number"||!Number.isFinite(r)||r<0||r>1)throw h("invalid","Progress is a number from 0 to 1.");!d||ae||(V=r,D===void 0&&(ce(),D=window.setTimeout(()=>{D=void 0,V!==null&&ce()},1e3)))},async load(){if(d){let o=await g({method:"app.save.get"});return o.value===null?null:we(JSON.stringify(o.value))}let r=await g({method:"app.checkpoint.get"});if(!("checkpoint"in r))throw h("unavailable","Invalid host response.");return r.checkpoint},save(r){let o;try{if(o=Q(r),!d){if(new TextEncoder().encode(o).byteLength>v.checkpointBytes)throw h("too-large","This host keeps at most 32 KiB, and only while the window is open.");try{de(r)}catch(c){throw h("too-large",c.message)}}}catch(c){return Promise.reject(G(c,"invalid"))}return i?Promise.reject(h("closed")):new Promise((c,k)=>{C={text:o,waiters:[...C?.waiters??[],{resolve:c,reject:k}]},U()})},async cards(r){let o=r===void 0?void 0:ne(r);return w(),(await O(o)).cards},onCards(r){return f.add(r),d&&f.size===1&&g({method:"cards.watch",on:!0}).then(()=>{x||oe(!1)},()=>{}),()=>{!f.delete(r)||f.size||!d||i||g({method:"cards.watch",on:!1}).catch(()=>{})}},async packs(){w();let r=await g({method:"cards.packs"});if(!Array.isArray(r.packs))throw h("unavailable","Invalid host response.");return r.packs.map(o=>{let c=Ae(o);return{...c,art:y(c.art)}})},async pack(r){let o=ne(r);w();let c=xe((await g({method:"cards.pack",pack:o})).pack);return{...c,art:y(c.art),cards:c.cards.map(k=>({...k,art:y(k.art)}))}},async showPack(r){let o=ne(r);if(w(),(await g({method:"pack.show",pack:o})).shown!==!0)throw h("unavailable","Invalid host acknowledgement.")},async player(){if(w(),$&&$.expiresAt-Date.now()>R.tokenReuseMs)return{...$};let r=ve(await g({method:"player.get"}));if(r.guest)return $=null,r;let o={...r,picture:y(r.picture)};return $=o.token?o:null,{...o}},async finish(r){let o;try{o=K(r)}catch(c){throw G(c,"invalid")}S(await g({method:"game.finish",...o}))},async maximize(r=!0){if(typeof r!="boolean")throw h("invalid");w(),S(await g({method:"display.maximize",on:r}))},async fullscreen(r=!0){if(typeof r!="boolean")throw h("invalid");w(),S(await g({method:"display.fullscreen",on:r}))},onPause(r){return p.add(r),()=>{p.delete(r)}},onResume(r){return l.add(r),()=>{l.delete(r)}},onResize(r){return u.add(r),()=>{u.delete(r)}},close(){i||(i=!0,N!==void 0&&window.clearTimeout(N),D!==void 0&&window.clearTimeout(D),C?.waiters.forEach(r=>r.reject(h("closed"))),C=null,p.clear(),l.clear(),u.clear(),f.clear(),m.destroy())}},V=null,D,ae=!1,ce=()=>{let r=V;V=null,g({method:"ui.progress",value:r}).catch(()=>{})},_e=L.ready;L.ready=async()=>{ae=!0,V=null,await _e()};for(let r of["ready","load","cards","packs","pack","showPack","player","finish","maximize","fullscreen"]){let o=L[r];L[r]=async(...c)=>{try{return await o(...c)}catch(k){throw G(k,"unavailable")}}}return Object.freeze(L)}return Le(rt);})();
@@ -0,0 +1,18 @@
1
+ export interface SpawnedWorker {
2
+ readonly worker: Worker;
3
+ terminate(): void;
4
+ }
5
+ /** The browser pieces `spawnWorker` uses; the real ones by default. */
6
+ export interface WorkerHost {
7
+ fetch(url: string): Promise<Pick<Response, "ok" | "status" | "text">>;
8
+ createObjectURL(blob: Blob): string;
9
+ revokeObjectURL(url: string): void;
10
+ Worker: new (url: string, options?: WorkerOptions) => Worker;
11
+ base: string;
12
+ }
13
+ /**
14
+ * Fetch `url` (a script in your bundle, relative to the page) and start it as a worker. `terminate()` stops the worker and
15
+ * releases its blob URL. Rejects with an OsError: `invalid` for a URL outside the bundle's own scripts, `unavailable` when
16
+ * the script cannot be read.
17
+ */
18
+ export declare function spawnWorker(url: string, options?: WorkerOptions, host?: WorkerHost): Promise<SpawnedWorker>;
package/dist/worker.js ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Workers in a VibeMarket OS app (VM_OS_APPS_3.md section 9.3). The runtime policy allows workers only from `blob:` URLs
3
+ * (`worker-src blob:`), so a bundled worker script is fetched from the app's own files and started from a blob. Bundle the
4
+ * worker into one file: a blob worker cannot resolve relative imports. No threads: `SharedArrayBuffer` is unavailable.
5
+ */
6
+ import { OsError } from "./os.js";
7
+ const browser = () => ({
8
+ fetch: url => fetch(url), createObjectURL: blob => URL.createObjectURL(blob), revokeObjectURL: url => URL.revokeObjectURL(url), Worker, base: location.href,
9
+ });
10
+ /**
11
+ * Fetch `url` (a script in your bundle, relative to the page) and start it as a worker. `terminate()` stops the worker and
12
+ * releases its blob URL. Rejects with an OsError: `invalid` for a URL outside the bundle's own scripts, `unavailable` when
13
+ * the script cannot be read.
14
+ */
15
+ export async function spawnWorker(url, options = {}, host = browser()) {
16
+ const target = new URL(url, host.base), base = new URL(host.base);
17
+ if (target.origin !== base.origin || !/\.m?js$/.test(target.pathname))
18
+ throw new OsError("invalid", "A worker is a .js file of your own bundle.");
19
+ let source;
20
+ try {
21
+ const response = await host.fetch(target.href);
22
+ if (!response.ok)
23
+ throw Error(`HTTP ${response.status}`);
24
+ source = await response.text();
25
+ }
26
+ catch (error) {
27
+ throw new OsError("unavailable", `The worker script could not be read (${error instanceof Error ? error.message : "unknown"}).`);
28
+ }
29
+ const blob = host.createObjectURL(new Blob([source], { type: "text/javascript" }));
30
+ const worker = new host.Worker(blob, options);
31
+ let ended = false;
32
+ return { worker, terminate() { if (ended)
33
+ return; ended = true; worker.terminate(); host.revokeObjectURL(blob); } };
34
+ }
@@ -1,17 +1,25 @@
1
1
  # Paw Beat
2
2
 
3
- A 3D rhythm game for VibeMarket OS, written in TypeScript with Three.js. Arrows slide down four lanes toward their targets. Press the matching key as each one lands (arrow keys, WASD or the on-screen pads) and Biscuit the cat dances the step. Timing is judged perfect, great or good; every ten steps in a row adds 10% to each step, up to double. One song lasts about a minute.
3
+ A 3D rhythm game for VibeMarket OS, written in TypeScript with Three.js. Arrows slide down four lanes toward their outlines. Press the matching key as each one lands (arrow keys, WASD or the on-screen pads) and Biscuit the cat dances that step: a side step and point for left and right, a leap with paws up for up, a squat and floor pat for down. Timing is judged perfect, great or good; every ten steps in a row adds 10% to each step, up to double, and combos of 10, 25, 50, 75 and 100 earn a spin and confetti. A miss makes Biscuit stumble. One song lasts about a minute and ends with a results card: grade, score, accuracy, best combo and every judgement, with your personal best marked.
4
4
 
5
- It is a complete example of the app API:
5
+ It is a complete example of the app API and of a small game built entirely in code:
6
6
 
7
7
  | File | What it shows |
8
8
  |---|---|
9
- | `game.ts` | The chart generator and judging as pure TypeScript with no DOM, renderer or audio, so they can be unit-tested |
10
- | `cat.ts` | A procedural 3D cat built from primitives at runtime; no model or texture files |
11
- | `music.ts` | The whole song synthesized with Web Audio and scheduled on the audio clock, which also times the steps |
12
- | `main.ts` | `connectVibeMarketApp()`, `fitCanvas` and `createLoop` from the SDK helpers, a checkpoint for the personal best, and `game.finish({ score })` |
9
+ | `game.ts` | The rules as pure TypeScript with no DOM, renderer or audio, so they can be unit-tested: the song's sections and melody as data, a chart generator that writes steps from them, timing judgement, combo bonus and the grade |
10
+ | `cat.ts` | Biscuit, built at runtime: smooth body parts meshed from signed distance functions ("surface nets"), a toon shader with rim light and outline, a face painted by the shader so expressions are a few numbers, two-bone inverse kinematics for arms and legs, a tube tail rewritten every frame, and spring-blended dance moves |
11
+ | `stage.ts` | The dance floor, backdrop and spotlights as single shader meshes that pulse with the beat and take each section's colours; the lanes and targets; every note in one instanced mesh; pooled sparks and confetti; camera framings that fit any window size |
12
+ | `music.ts` | The whole song synthesized with Web Audio (drums, bass, pads, lead, bell, risers) through a soft limiter, scheduled ahead on the audio clock, which also times the steps |
13
+ | `main.ts` | `connectVibeMarketApp()`, `fitCanvas` (with WebGL context loss handled) and `createLoop` from the SDK helpers; the title, play and results flow; a checkpoint for the personal best and the sound setting; and `game.finish({ score })` |
14
+ | `index.html` | The page: the canvas, the score and progress display, the judgement and combo callout, the touch pads, the title and results cards, all styled inline |
13
15
 
14
- Everything in the game is generated in code, so the bundle is `index.html`, one script, the manifest and the three store images in `store/`. The steps and the lead melody come from a seed, so each round is a little different and any round can be replayed in a test.
16
+ Nothing is downloaded or generated outside the game: there are no models, textures, fonts, samples or images in the bundle. It is `index.html`, one script, the manifest and the three store images in `store/`, which are captures of the game itself. The song's arrangement is fixed; the steps, and the way the drop's tune is answered, come from a seed, so each round is a little different and any round can be replayed in a test.
17
+
18
+ ## Controls
19
+
20
+ - Arrow keys or `A` `S` `W` `D`, or tap the pads at the bottom.
21
+ - `M` or the sound button turns the music off and on. Sound starts with your first press of **Start dancing**, as browsers require.
22
+ - The game follows `prefers-reduced-motion`: the camera cuts instead of gliding, the spotlights hold still and the floor stops flashing on each bar.
15
23
 
16
24
  ## Build and run
17
25
 
@@ -26,6 +34,10 @@ npx os preview dist
26
34
 
27
35
  Open the printed `http://127.0.0.1:PORT` address. Use a unique `id` and `version` in `vibemarket.json` before packaging your own game.
28
36
 
37
+ ## How it stays fast
38
+
39
+ The loop does no allocation per frame and touches the DOM only when a number changes. The floor, backdrop and lights are three meshes whose shaders read a handful of uniforms; the notes are one instanced draw; the cat is seventeen small meshes, each drawn a second time for its outline. There are no shadow maps: the cat's shadow is painted by the floor shader. The canvas is sized by `fitCanvas`, which caps the pixel ratio, and the loop stops whenever the host says the window is not active.
40
+
29
41
  ## Listing in VibeStore
30
42
 
31
43
  `vibemarket.json` uses manifest schema version 2, so it carries a complete VibeStore listing: a `window` of 960 x 600 that can be resized, and a `store` object with the icon, two screenshots, a plain-text description, the `game` category, a content rating (violence `none`, language `none`, not mature) and a support link.
@@ -43,7 +55,7 @@ The requirements are checked when you submit from the VibeStore **Submit** tab,
43
55
 
44
56
  ## What the score means
45
57
 
46
- The score is reported to the host with `game.finish`. It is display data. The game cannot grant Cash, XP or items, and the preview awards nothing.
58
+ The score is reported to the host with `game.finish` a few seconds after the results card appears, or straight away if you press **Dance again**. The host owns the final results screen and may replace the game's window once it has the score; if it keeps the window open, the card stays as the result. The score is display data: the game cannot grant Cash, XP or items, and the preview awards nothing.
47
59
 
48
60
  ## License
49
61