@vibechain/os 0.5.1 → 0.5.2

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 (43) hide show
  1. package/AGENTS.md +15 -6
  2. package/README.md +35 -10
  3. package/SECURITY.md +3 -1
  4. package/dist/app-client.js +20 -4
  5. package/dist/app-host.d.ts +12 -2
  6. package/dist/app-host.js +12 -2
  7. package/dist/app-protocol.d.ts +21 -0
  8. package/dist/app-protocol.js +9 -0
  9. package/dist/audio.d.ts +65 -0
  10. package/dist/audio.js +162 -0
  11. package/dist/browser.d.ts +1 -0
  12. package/dist/browser.js +1 -0
  13. package/dist/bundle.d.ts +2 -0
  14. package/dist/bundle.js +2 -0
  15. package/dist/cli.js +3 -1
  16. package/dist/commands.d.ts +6 -0
  17. package/dist/commands.js +17 -0
  18. package/dist/index.d.ts +2 -2
  19. package/dist/links.d.ts +6 -0
  20. package/dist/links.js +2 -0
  21. package/dist/os.d.ts +20 -2
  22. package/dist/os.js +30 -5
  23. package/dist/preview-parent.js +15 -2
  24. package/dist/preview-ui.js +1 -1
  25. package/dist/preview.js +1 -1
  26. package/dist/templates/plain/game.js +3 -1
  27. package/dist/testing.d.ts +9 -1
  28. package/dist/testing.js +27 -6
  29. package/dist/vibemarket-os.js +1 -1
  30. package/examples/paw-beat/README.md +28 -9
  31. package/examples/paw-beat/game.ts +280 -123
  32. package/examples/paw-beat/index.html +18 -4
  33. package/examples/paw-beat/main.ts +101 -44
  34. package/examples/paw-beat/music.ts +72 -337
  35. package/examples/paw-beat/stage.ts +23 -9
  36. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  37. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  38. package/examples/paw-beat/synth.ts +477 -0
  39. package/examples/paw-beat/tracks.ts +286 -0
  40. package/examples/paw-beat/vibemarket.json +2 -2
  41. package/examples/vibexp-app/plain/game.ts +6 -2
  42. package/package.json +7 -1
  43. package/skill.md +399 -0
package/AGENTS.md CHANGED
@@ -1,9 +1,10 @@
1
- # VibeStore app author contract — @vibechain/os 0.5.1
1
+ # VibeStore app author contract — @vibechain/os 0.5.2
2
2
 
3
3
  This is the contract for people and agents building apps for VibeStore, the app
4
4
  store inside VibeMarket OS. Read it with [README.md](README.md) (API, helpers and
5
5
  the listing table) and [SECURITY.md](SECURITY.md) (sandbox and limits). The public
6
- guide is https://vibechain.com/os/docs.
6
+ guide is https://vibechain.com/os/docs. Coding agents: start from the agent skill,
7
+ https://vibechain.com/os/skill.md, generated from this package for its version.
7
8
 
8
9
  ## What you build
9
10
 
@@ -18,7 +19,7 @@ declares in `network` (below).
18
19
  ## Start
19
20
 
20
21
  ```sh
21
- npx --yes @vibechain/os@0.5.1 init my-app # TypeScript + canvas; or --template three, or --template plain
22
+ npx --yes @vibechain/os@0.5.2 init my-app # TypeScript + canvas; or --template three, or --template plain
22
23
  cd my-app
23
24
  npm install
24
25
  npm run build
@@ -51,7 +52,7 @@ Every rejection is an `OsError` with a stable `code` (`unsupported`,
51
52
  `not-permitted`, `invalid`, `too-large`, `rate-limited`, `needs-click`,
52
53
  `unavailable`, `timeout`, `closed`); refusals keep the app running. `game.finish`
53
54
  takes one integer score from 0 to 1,000,000,000, once per open window; the host
54
- owns the results screen and the score grants nothing. Saves are coalesced (one
55
+ owns the results screen. The score is display data: it never sets a reward. A finished round of an approved app may earn the player a small amount of Printer Cash, decided and paid by VibeMarket OS within per-player daily caps. The app cannot grant, see or influence the amount, and nothing an app sends is trusted for it. Saves are coalesced (one
55
56
  write per 10 seconds) and kept on the server, except a guest's, which last only
56
57
  while the window is open. `os.pack(slug)`, `os.showPack(slug)`,
57
58
  `os.showCard(slug, cardId)` and `os.open(link)` (app links `vmos://pack/<slug>`,
@@ -63,6 +64,14 @@ gamepads, audio, WebAssembly and `blob:` workers (`spawnWorker`) work; threads
63
64
  and `SharedArrayBuffer` do not. `os.fullscreen()` asks the host after a click.
64
65
  The optional `os.onCapture?.(() => canvasOrDataUrl)` customises the picture the desktop camera takes of your app (by default the SDK sends the largest visible canvas, so canvas and WebGL games need nothing; apps built with an older SDK show a placeholder in desktop photos). Optional helpers: `@vibechain/os/loop`, `@vibechain/os/canvas` and
65
66
  `@vibechain/os/testing` (`createFakeOs`, an in-memory host for unit tests).
67
+
68
+ **Sound belongs to the desktop.** Follow `os.sound` (`{ muted, volume }`) and
69
+ `os.onSound`: silent while muted, scaled by the volume, live. A sandboxed frame
70
+ cannot be muted from outside, so review checks that the app follows it. Use
71
+ `createAudio(os)` from `@vibechain/os/audio` and connect everything you play to
72
+ `audio.master`; a game's own sound button is `audio.muted`, an extra mute that
73
+ never overrides the desktop's, and the game never says "sound on" while the
74
+ desktop is muted.
66
75
  `connectVibeMarketApp()` (0.4) still works and is deprecated.
67
76
 
68
77
  ## What an app cannot do
@@ -147,8 +156,8 @@ npm run pack # os pack dist app.zip
147
156
  Submit only what you are willing to publish permanently. Staff choose which
148
157
  approved version is live.
149
158
 
150
- Apps open in the browser version of VibeMarket OS. The Steam client shows a
151
- notice with a link instead of opening them, and the mobile apps do not run them.
159
+ Apps open in VibeMarket OS in the browser and in the VibeMarket Steam client;
160
+ the mobile apps do not run them.
152
161
 
153
162
  ## Market-game API (not for VibeStore apps)
154
163
 
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # @vibechain/os
2
2
 
3
- Build games, tools and desktop apps for VibeMarket OS. One `connect()` gives your app readiness, a save that follows the player, who is playing, their vmOS cards and packs, a signed statement of the player for your own server, and a score. Use TypeScript with a bundler, or two `<script>` tags and nothing to install.
3
+ Build games, tools and desktop apps for VibeMarket OS. Coding agents: read the agent skill, https://vibechain.com/os/skill.md. One `connect()` gives your app readiness, a save that follows the player, who is playing, their vmOS cards and packs, a signed statement of the player for your own server, and a score. Use TypeScript with a bundler, or two `<script>` tags and nothing to install.
4
4
 
5
5
  ## Quickstart
6
6
 
7
7
  ```sh
8
- npx --yes @vibechain/os@0.5.1 init my-app # TypeScript, esbuild and a 2D canvas (the default)
9
- npx --yes @vibechain/os@0.5.1 init my-app --template three # TypeScript, esbuild and Three.js: a spinning vmOS card
10
- npx --yes @vibechain/os@0.5.1 init my-app --template plain # index.html + game.js, nothing to install
8
+ npx --yes @vibechain/os@0.5.2 init my-app # TypeScript, esbuild and a 2D canvas (the default)
9
+ npx --yes @vibechain/os@0.5.2 init my-app --template three # TypeScript, esbuild and Three.js: a spinning vmOS card
10
+ npx --yes @vibechain/os@0.5.2 init my-app --template plain # index.html + game.js, nothing to install
11
11
  ```
12
12
 
13
13
  For `canvas` and `three`: `cd my-app`, `npm install`, `npm run build`, `npm run dev`, and open the printed `http://127.0.0.1:PORT` address. `npm run check` (`os check`) lists every problem with the manifest and the build at once, and `npm run pack` writes `app.zip`. For `plain`: `npx @vibechain/os preview my-app`; the folder is already the app, so zip it to submit. Every template's `vibemarket.json` is a complete schema version 3 listing with placeholder text and pictures you must replace first (an unchanged starter is rejected at review).
@@ -15,7 +15,7 @@ For `canvas` and `three`: `cd my-app`, `npm install`, `npm run build`, `npm run
15
15
  To install from a downloaded SDK archive, supply its absolute path to npm and the initializer:
16
16
 
17
17
  ```sh
18
- npm exec --yes --package=/absolute/path/vibechain-os-0.5.1.tgz -- os init my-app /absolute/path/vibechain-os-0.5.1.tgz
18
+ npm exec --yes --package=/absolute/path/vibechain-os-0.5.2.tgz -- os init my-app /absolute/path/vibechain-os-0.5.2.tgz
19
19
  ```
20
20
 
21
21
  That keeps a `file:` archive dependency; retain the archive for later reinstalls. Use a supported Node.js release: `^22.23.4`, `^24.22.1` or `^26.12.1`. The library is ESM-only (`import`, or dynamic `import()` from CommonJS); browsers without a bundler use `vibemarket-os.js` (below).
@@ -45,7 +45,8 @@ await os.finish({ score: 42 }); // one integer score, 0 to 1,000,000,00
45
45
 
46
46
  os.onPause(() => {}); os.onResume(() => {});
47
47
  os.onResize(({ width, height }) => {});
48
- os.size; os.active; os.guest; // current values
48
+ os.onSound(({ muted, volume }) => {}); // the desktop's speaker and volume changed
49
+ os.size; os.active; os.guest; os.sound; // current values; os.sound is { muted, volume } (0 to 1)
49
50
  await os.maximize(); await os.fullscreen();
50
51
  os.close(); // release the port
51
52
  ```
@@ -101,7 +102,7 @@ VibemarketOS.connect().then(async os => {
101
102
 
102
103
  ## Game helpers
103
104
 
104
- `@vibechain/os/loop` and `@vibechain/os/canvas` take the result of `connect()` (or of the legacy `connectVibeMarketApp()`) and follow its lifecycle, so a game stops drawing when its window is not active.
105
+ `@vibechain/os/loop`, `@vibechain/os/canvas` and `@vibechain/os/audio` take the result of `connect()` (or of the legacy `connectVibeMarketApp()`) and follow its lifecycle, so a game stops drawing when its window is not active.
105
106
 
106
107
  ```ts
107
108
  import { connect } from "@vibechain/os";
@@ -116,6 +117,21 @@ os.ready();
116
117
  window.addEventListener("pagehide", () => { loop.stop(); os.close(); }, { once: true });
117
118
  ```
118
119
 
120
+ ### Sound
121
+
122
+ The desktop owns sound: its taskbar speaker and its game volume (on the website's desk, master volume × the Games fader) reach the app as `os.sound` and `os.onSound` (0.5.2; on an older host `os.sound` is `{ muted: false, volume: 1 }` and never changes). A sandboxed frame cannot be muted from outside in a browser, so this is cooperative: the app must follow it, and VibeStore review checks that it does. `@vibechain/os/audio` makes that the default:
123
+
124
+ ```ts
125
+ import { createAudio } from "@vibechain/os/audio";
126
+
127
+ const audio = createAudio(os); // ideally inside the first click; also takes connectVibeMarketApp()'s object
128
+ music.connect(audio.master); // connect everything you play to the master
129
+ audio.muted = !soundButtonOn; // optional: your own extra mute, which never overrides the desktop's
130
+ audio.onChange(() => { /* redraw a sound label; on a new audio.context, rebuild your nodes */ });
131
+ ```
132
+
133
+ The master is silent while the desktop is muted, follows its volume and ramps over 50 ms on every change (no clicks). The context is suspended after the ramp while the window is behind another one or minimized, and resumed when it comes back. A context the browser stopped (`suspended`, or WebKit's `interrupted` after an audio interruption, sleep or an output change) is resumed on every click, tap or key in the frame; one the browser closed, or one still stopped after 3 gestures, is replaced (at most 3 times), and `audio.context` and `audio.master` then name the new ones. `audio.paused = true` holds it suspended for your own pause (a menu, a lost GPU). `createLoop`'s pause and the helper's follow the same lifecycle and never fight. Show the real state: never "sound on" while `os.sound.muted` is true.
134
+
119
135
  `createLoop` runs a fixed-timestep simulation (default 60 steps per second, at most 5 catch-up steps per frame) and renders once per animation frame. It pauses while the app is inactive and discards that time instead of simulating it on return. `fitCanvas` sizes the canvas backing store from the host surface with the device pixel ratio capped (default 2, and at most 3840 x 2160 pixels), resizes only when the size changes, and keeps a lost WebGL context restorable through `onContextLost` and `onContextRestored`.
120
136
 
121
137
  ### Testing your game
@@ -151,7 +167,7 @@ await app.game.finish({ score: 42 });
151
167
 
152
168
  `score` must be an integer from 0 through 1,000,000,000, with no other input fields. It is a reported game score. The host owns the final screen and Play again control. Completion is single-shot for that open controller, including suspended generations: retrying the same score acknowledges the accepted result; changing the score is rejected. The host posts acknowledgement before showing results. If the frame closes before it receives that acknowledgement, inspect the host result rather than assuming the completion failed.
153
169
 
154
- Completion does not grant Cash, XP, inventory or a wallet action. The local preview and collection host report score only. An approved host may show an existing Cash award only after its own registered game policy and server reward flow confirm it; the frame cannot select a reward amount or supply proof of payment. Older hosts may not understand this additive method; use a matching 0.2.x host/preview.
170
+ The score is display data: it never sets a reward. A finished round of an approved app may earn the player a small amount of Printer Cash, decided and paid by VibeMarket OS within per-player daily caps. The app cannot grant, see or influence the amount, and nothing an app sends is trusted for it. See [Rewards](https://vibechain.com/os/docs#rewards). Completion never grants XP, inventory or a wallet action, and the local preview and collection host report the score only. Older hosts may not understand this additive method; use a matching 0.2.x host/preview.
155
171
 
156
172
  ## Listing in VibeStore
157
173
 
@@ -193,7 +209,7 @@ Unknown fields are refused at every level, and version 3 refuses the four consta
193
209
 
194
210
  ## Publishing status
195
211
 
196
- Publish by submitting your packed ZIP from the VibeStore **Submit** tab in VibeMarket OS, or with `os submit` from your terminal; see [Publish](https://vibechain.com/os/docs#publish) and [Review](https://vibechain.com/os/docs#review). Installing the SDK does not list your app. An approved version is archived to public IPFS, so approval is publication: removing an app from VibeStore later does not recall that copy. Third-party apps open in the browser version of VibeMarket OS; the Steam client does not run them yet. The app API grants no native, payment, wallet or reward access, and card reads only as the manifest declares them. Existing Market games continue to use their separate permissioned API.
212
+ Publish by submitting your packed ZIP from the VibeStore **Submit** tab in VibeMarket OS, or with `os submit` from your terminal; see [Publish](https://vibechain.com/os/docs#publish) and [Review](https://vibechain.com/os/docs#review). Installing the SDK does not list your app. An approved version is archived to public IPFS, so approval is publication: removing an app from VibeStore later does not recall that copy. Third-party apps open in VibeMarket OS in the browser and in the VibeMarket Steam client. The app API grants no native, payment or wallet access and cannot grant, see or influence a reward, and card reads only as the manifest declares them. Existing Market games continue to use their separate permissioned API.
197
213
 
198
214
  See the [SDK docs](https://vibechain.com/os/docs) for the app API and [SECURITY.md](SECURITY.md) for the sandbox and resource limits.
199
215
 
@@ -219,16 +235,25 @@ npx os logout # revokes this computer's sign-in, then deletes it
219
235
 
220
236
  ## Maintainer workflow
221
237
 
238
+ The agent skill for app developers, **https://vibechain.com/os/skill.md**, is generated from this package: `tools/skill.ts` fills `tools/skill-template.md` with the version, the `Os` methods, the error and submission codes, the limits, the link grammar, the commands, the smallest app and the token check, and writes `skill.md`, which the website serves. `tests/skill.test.ts` (and the website's own test of the route) re-render it and fail on any difference, so an SDK change that alters one of those facts needs `pnpm skill` and the regenerated file in the same commit. A release bumps `package.json` and `OS_SDK_VERSION` together (a test binds them), then runs `pnpm skill`.
239
+
222
240
  ```sh
223
241
  pnpm install --frozen-lockfile
242
+ pnpm skill # regenerate skill.md from the SDK; pnpm review fails while it is stale
224
243
  pnpm review
225
244
  pnpm build
226
245
  pnpm check:package
227
- pnpm release:preview --version 0.5.1
246
+ pnpm release:preview --version 0.5.2
228
247
  ```
229
248
 
230
249
  `pnpm build` emits JavaScript/declarations, the bundled preview host UI, `dist/vibemarket-os.js` (the no-bundler IIFE) and `dist/templates/plain/game.js` (built from `examples/vibexp-app/plain/game.ts`, so the repository holds no authored JavaScript). Only `examples/paw-beat` and `examples/vibexp-app` (with its `plain` and `three` templates) are published; `examples/card-game` and `examples/verify-player.ts` are type-checked and tested here and shown on the docs site. The store images of both examples are generated by scripts in `tools/` (not published), which drive headless, muted Chromium through Playwright. Read [SECURITY.md](SECURITY.md) before integrating any untrusted app.
231
250
 
251
+ ## Changes in 0.5.2 (since 0.5.1)
252
+
253
+ - **New: the desktop's sound.** The host sends `app.sound` (`{ muted, volume }`) with the port, before any answer, and on every change; `Os.sound` and `Os.onSound` are new, and the 0.4 object gains `sound.current()` and `sound.onChanged()`. `@vibechain/os/audio` (`createAudio`, also on the `VibemarketOS` global) gives an AudioContext and a master that follow it, the window and the browser's gesture rule, and recover a stopped or closed context. Nothing existing changed: older apps ignore the event, and on an older host the sound reads audible at full volume. The fake hosts (`setSound`) and the preview (a speaker and volume in its header) let you test it.
254
+ - **Paw Beat 1.2.0.** The bundled example has six original tracks; a random one plays each round, with a best score per track.
255
+
256
+
232
257
  ## Changes in 0.5.1 (since 0.5.0)
233
258
 
234
259
  - **New, optional: desktop photos.** The host may send `app.capture` and the SDK answers with a new `app.frame` request carrying the app's picture (by default its largest visible canvas). `Os.onCapture` and `VibeMarketAppSdk.onCapture` are new optional hooks to supply your own picture. Nothing existing was renamed or removed, and no app needs a code change: an app built with an older SDK, or one that sends nothing, is shown as its icon and name in desktop photos.
package/SECURITY.md CHANGED
@@ -33,7 +33,7 @@ The flag is a claim made by the client's page-level marker, not a credential. On
33
33
  - The additive app codec uses bounded JSON on the existing channel/envelope/port transport. Legacy Market messages stay unchanged. Wrong session, replayed IDs, unknown methods, invalid schemas, malformed/oversized messages and quota exhaustion close the port. No implicit Market permissions are inherited.
34
34
  - Close, navigation, minimize, hidden document, identity or package change revoke the active generation, and so does losing the front to another desktop window once a 60 second grace has run out. Within the grace the website's desk keeps the backgrounded frame and its session: the app is sent `active: false`, the frame is `display: none` and inert (never painted, hit or focused; the keyboard goes back to the desk), and its `game.finish` and `app.checkpoint.set` requests are withheld, neither applied nor answered, as they would be lost for a suspended app; reads are answered, saves (`app.save.set`, protocol 2) are accepted because that is when a game saves, `pack.show` and the display methods answer `not-permitted`, and every request still counts against the limits below. Returning in front within the grace re-activates the same frame, controller and session. The grace timer is the host's, starts when the window leaves the front, and nothing the app sends extends it; at most one app frame lives on the page, and opening another app tears the backgrounded one down at once. This is a cooperative pause, not a sandbox: until the host's frame-time watchdog exists (it does not yet), a hostile backgrounded app can keep its timers, workers and audio running for up to 60 seconds (Chromium stops a hidden frame's animation frames; WebKit does not), bounded only by the one-frame cap, the grace and the immediate teardown on a hidden page. Revocation preserves only the same app's host-accepted bounded checkpoint. Restore after revocation creates a fresh iframe, challenge and session. Host focus uses desktop policy, not the browser `blur` event caused by focusing the child itself.
35
35
  - The app receives no session, Steam ID, account id, balance, wallet address, Steam ticket, native handle, money, arbitrary HTTP relay or credential for any vibechain.com route. What it can receive (protocol 2, after `host.hello`): its own save (JSON it wrote, at most 1 MiB, parsed and validated, never merged into host objects); the card holdings its manifest declares (`cards: "linked"` for its effective linked packs, `cards: "all"` for every vmOS pack the player holds, with no prompt; card id, pack slug, name, rarity, count and an art path under the app's own prefix, never an internal pack id, pull id, Nugget or Printer Cash amount or foil); public pack card lists; and who is playing (owner decision 2026-11-23, "just tell the app who the user is"): for every schema 3 app, without a permission, the player's public vmOS identity, exactly what their public profile shows anyone (the fixed `handle`, the @`username` when it differs, the display `name` and the profile `picture` as a path under the app's own prefix), or `{ guest: true }` for a guest; and, only for apps whose manifest declares `network`, a 5-minute Ed25519 token stating that identity, whose audience is the app id and which no vibechain.com route accepts. The host re-checks every card, pack and player value against strict shapes before it reaches the app, so an extra field cannot ride along. There is no anonymous or per-app id: the same player is the same handle in every app, so apps can recognize and correlate a player, and everything an app sends to its declared servers (identity, holdings, save, gameplay) reaches them tied to the player's public profile, together with the player's IP address. The listing says what an app can see and where it connects. Checkpoints (legacy) contain only the app's own JSON. An app must not ask people to enter secrets inside its UI.
36
- - `game.finish` accepts only an integer score from 0 through 1,000,000,000. It cannot carry Cash, XP, receipts or grant instructions. The first score is retained across suspension; same-score retries acknowledge without a second host callback, and changed scores are refused. The host posts its acknowledgement before notifying its results UI. Callback throws or acknowledgement failure never authorize another award. Stale generations cannot notify the host. A reported score is not reward proof; only a separately registered host/server policy can confirm an existing Cash award.
36
+ - `game.finish` accepts only an integer score from 0 through 1,000,000,000. It cannot carry Cash, XP, receipts or grant instructions. The first score is retained across suspension; same-score retries acknowledge without a second host callback, and changed scores are refused. The host posts its acknowledgement before notifying its results UI. Callback throws or acknowledgement failure never authorize another award. Stale generations cannot notify the host. A reported score is not reward proof. The score is display data: it never sets a reward. A finished round of an approved app may earn the player a small amount of Printer Cash, decided and paid by VibeMarket OS within per-player daily caps. The app cannot grant, see or influence the amount, and nothing an app sends is trusted for it.
37
37
 
38
38
  ## Enforced accepted-work limits
39
39
 
@@ -65,6 +65,8 @@ The browser allocates structured-clone data before host validation. Message byte
65
65
 
66
66
  The runtime policy (`appRuntimeCsp`, `@vibechain/os/policy`) limits scripts, styles and workers' first scripts to the version's own files, and every fetch, image, media and font to those files plus, for a version whose manifest declares `network`, its declared origins: every origin in `connect-src`, the `https://` ones also in `img-src`, `media-src` and `font-src`, and never in `script-src`, `style-src`, `worker-src`, `child-src`, `frame-src` or `object-src`. Declared origins are re-validated (`networkOrigin`: https or wss, a public DNS name, no IP address in any form, no local, reserved or wildcard-DNS name, no Vibechain domain) and a list that is not normalized throws rather than produce a partial policy. What it cannot stop: text fetched from a declared server run in a `blob:` worker (`worker-src blob:` stays, for engines and decoders), `WebAssembly.instantiate` on fetched bytes, fetched CSS put into a `<style>` element, an interpreter in the bundle running server-sent programs, and server data driving behaviour. So "the reviewed code is the code that runs" holds for the files VibeStore hosts and is listing policy for everything else: an app whose behaviour changes after review because its server says so breaches the listing rules and is removed by revocation; it is not confined. A declared name can also resolve to a private address; Chromium's Private Network Access narrows that in one engine only. Every declared server sees the player's IP address. Network apps may not embed third-party advertising or analytics SDKs (review rule, owner decision 2026-11-23). WebRTC is not governed by CSP: an app can open peer connections in every measured engine, so the listing allows WebRTC only for play between players signalled through declared servers. A sandboxed app can also navigate its own frame to an external URL; navigation revokes the session after load, but a request may already have occurred. Do not describe any of this as a network firewall or supply secrets that require one. Known native bridge markers and embedded user agents are denied, except the Steam client's own two markers when it claims app frames (see Host admission); their absence does not certify unknown webviews, and that claim does not certify the client. Native IPC provenance tests on each platform remain the client's gate before a build sets the flag.
67
67
 
68
+ **Sound (0.5.2).** The desktop's speaker and volume reach an app only as the `app.sound` event (`{ muted, volume }`, validated exactly by both ends): sent with the port before any answer, and on every change. It is cooperative, not enforcement: a browser cannot mute a sandboxed cross-origin frame from outside, so an app that ignores it, or a client older than 0.5.2, keeps sounding until its window goes behind another (then the lifecycle and, after the grace, teardown stop it) or the app is closed. Following the desktop's sound is a review rule, and `@vibechain/os/audio` follows it by default. The event tells the app nothing about the player beyond the desktop's own sound setting.
69
+
68
70
  **Showing packs and cards (0.5.1).** Any app may show any public pack (one that exists and is not taken down), linked or not: `cards.pack` answers the pack's public face, exactly what its public page shows (name, creator, cover, card names, rarities and art under the app's own prefix) and never holdings, which come only from `cards.list` as the manifest declares. `pack.show` and `card.show` ask the host to open the pack or one card in VibeMarket's market window. `os.open(link)` accepts only the exact app-link grammar (`vmos://pack/<slug>`, `vmos://card/<slug>/<cardId>`, `https://vibechain.com/os/pack/<slug>` or `www.`, at most 200 characters, no percent-encoding, query, fragment, port, user or other host), parses it in the SDK and sends only the parsed slug and card id; neither the SDK nor the host navigates to the string. The host acts only while the app is ready and in front and on fresh user activation on its own page (`needs-click`), at most once per 10 seconds across both methods (`rate-limited`), and answers `invalid` for an unknown or taken-down pack or a card not in it. The market window's Buy and Open controls are the host's own and ignore clicks for 500 ms after it opens, and the app is never told whether anything was bought or opened, so showing a pack tells it nothing new about the player and grants it nothing.
69
71
 
70
72
  **Player identity.** An app learns the player's public identity and nothing private: the handle, @name, display name and picture their public profile already shows. The token is a 5-minute Ed25519 JWT (`sub` = the handle, plus `username`, `name`, `guest: false`, `aud` = the app id) signed by the backend only, for apps that declare `network`, so their servers can trust who is playing instead of a handle the client claims; guests get none; public keys are at `https://vibechain.com/.well-known/vmos-app-keys.json`. It is a statement for the app's own server, not a credential: no vibechain.com route accepts it. A server that does not check `aud` would accept another app's tokens; the verification sample in the docs (https://vibechain.com/os/docs#sdk-05-verify) checks it. Within its 5 minutes a token can be replayed; servers that need one-time use keep `jti`.
@@ -1,4 +1,4 @@
1
- import { APP_FRAGMENT, APP_LIMITS, appNonce, checkpointValue, lifecycleValue, FRAME_MESSAGE_BYTES } from "./app-protocol.js";
1
+ import { APP_FRAGMENT, APP_LIMITS, AUDIBLE, appNonce, checkpointValue, lifecycleValue, soundValue, FRAME_MESSAGE_BYTES } from "./app-protocol.js";
2
2
  import { connectHostPort, createRpcTransport } from "./transport.js";
3
3
  import { createCapturer } from "./capture.js";
4
4
  import { gameFinishInput } from "./completion.js";
@@ -20,8 +20,8 @@ export async function connectVibeMarketApp(signal) {
20
20
  export function createAppPortSdk(port, session) {
21
21
  if (!appNonce(session))
22
22
  throw Error("Invalid app session.");
23
- let state = Object.freeze({ active: true, width: 0, height: 0 });
24
- const listeners = new Set();
23
+ let state = Object.freeze({ active: true, width: 0, height: 0 }), sound = AUDIBLE;
24
+ const listeners = new Set(), sounds = new Set();
25
25
  const transport = createRpcTransport(port, {
26
26
  session, timeoutMs: APP_LIMITS.requestTimeoutMs, maxPending: APP_LIMITS.inFlight, jsonBytes: APP_LIMITS.responseBytes, outBytes: FRAME_MESSAGE_BYTES,
27
27
  onEvent(value) {
@@ -29,6 +29,21 @@ export function createAppPortSdk(port, session) {
29
29
  capturer.event(value.id);
30
30
  return;
31
31
  }
32
+ if (value.event === "app.sound") {
33
+ let next;
34
+ try {
35
+ next = soundValue(value.state);
36
+ }
37
+ catch {
38
+ return;
39
+ }
40
+ if (next.muted === sound.muted && next.volume === sound.volume)
41
+ return;
42
+ sound = next;
43
+ for (const listener of [...sounds])
44
+ listener(sound);
45
+ return;
46
+ }
32
47
  if (value.event !== "app.lifecycle")
33
48
  return;
34
49
  try {
@@ -54,7 +69,8 @@ export function createAppPortSdk(port, session) {
54
69
  async write(value) { complete(await transport.request({ method: "app.checkpoint.set", value: checkpointValue(value) })); },
55
70
  }),
56
71
  lifecycle: Object.freeze({ current: () => state, onChanged(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; } }),
72
+ sound: Object.freeze({ current: () => sound, onChanged(listener) { sounds.add(listener); return () => { sounds.delete(listener); }; } }),
57
73
  onCapture(handler) { return capturer.on(handler); },
58
- destroy() { destroyed = true; capturer.clear(); listeners.clear(); transport.destroy(); },
74
+ destroy() { destroyed = true; capturer.clear(); listeners.clear(); sounds.clear(); transport.destroy(); },
59
75
  });
60
76
  }
@@ -1,9 +1,11 @@
1
1
  import type { GameFinishInput } from "./completion.ts";
2
- import { type AppLifecycle } from "./app-protocol.ts";
2
+ import { type AppLifecycle, type AppSound } from "./app-protocol.ts";
3
3
  import { type Player, type WireCard, type WirePack, type WirePackSummary } from "./app-wire.ts";
4
4
  export interface AppSession {
5
5
  lifecycle(value: AppLifecycle): void;
6
6
  close(): void;
7
+ /** Tell the app the desktop's sound (`app.sound`, any protocol; clients before 0.5.2 ignore it). */
8
+ sound(value: AppSound): void;
7
9
  /**
8
10
  * Ask a protocol 2 app for its current frame (`app.capture` / `app.frame`): a PNG, JPEG or WebP data URL, or null when
9
11
  * there is none (protocol 1, no hello yet, the app has no picture, the timeout, the session ended, a newer capture took
@@ -100,12 +102,20 @@ export interface AppFrameOptions {
100
102
  finish?: (result: Readonly<GameFinishInput>) => void;
101
103
  /** protocol 2: the app's loading progress, 0 to 1, for the host's loading bar */
102
104
  progress?: (fraction: number) => void;
105
+ /**
106
+ * The desktop's sound when the frame connects (0.5.2). It reaches the app with the port, ahead of any answer, so a 0.5.2
107
+ * `connect()` has it when it resolves; send every change with `setSound`. Without it the app hears nothing about sound and
108
+ * plays at full volume.
109
+ */
110
+ sound?: AppSound;
103
111
  }
104
- /** One mounted frame. `setActive` sends the app its lifecycle's `active` flag; `resize` keeps it. */
112
+ /** One mounted frame. `setActive` sends the app its lifecycle's `active` flag; `resize` keeps it; `setSound` sends the desktop's sound. */
105
113
  export interface MountedAppFrame {
106
114
  resize(width: number, height: number): void;
107
115
  setActive(active: boolean): void;
108
116
  dispose(): void;
117
+ /** the desktop's sound changed (the taskbar speaker or the volume): the app hears it at once, and a frame that connects later on connecting */
118
+ setSound(sound: AppSound): void;
109
119
  /** the app's current frame as a data URL (see `AppSession.capture`), or null; also null when there is no session or it ended */
110
120
  capture(timeoutMs?: number): Promise<string | null>;
111
121
  }
package/dist/app-host.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CHANNEL } from "./channel.js";
2
2
  import { appRuntimeRefusal } from "./app-runtime.js";
3
- import { APP_FRAGMENT, APP_LIMITS, FRAME_MESSAGE_BYTES, 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, soundValue } from "./app-protocol.js";
4
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
5
  import { packSlug } from "./manifest.js";
6
6
  /**
@@ -154,6 +154,7 @@ export function createAppController(clock = () => performance.now(), options = {
154
154
  const handle = {
155
155
  lifecycle(value) { if (current())
156
156
  port.postMessage(appJson({ session, event: "app.lifecycle", state: lifecycleValue(value) }, APP_LIMITS.responseBytes)); },
157
+ sound(value) { send({ session, event: "app.sound", state: soundValue(value) }, 256); },
157
158
  close,
158
159
  capture(timeoutMs = APP_SESSION_LIMITS.captureMs) {
159
160
  endCapture(null);
@@ -461,7 +462,7 @@ export function mountAppFrame(frame, options) {
461
462
  throw Error("Invalid app frame challenge.");
462
463
  const protocol2 = options.controller.protocol === 2;
463
464
  let ended = false, loaded = false, connected = false, bootstrapMessages = 0, session, readied = false;
464
- let bounds = lifecycleValue({ active: true, width: 0, height: 0 });
465
+ let bounds = lifecycleValue({ active: true, width: 0, height: 0 }), sound = options.sound === undefined ? null : soundValue(options.sound);
465
466
  const slow = () => fault("App took too long to become ready.");
466
467
  const dispose = () => { if (ended)
467
468
  return; ended = true; clearTimeout(timeout); clearTimeout(ceiling); frame.removeEventListener("load", load); window.removeEventListener("message", connect); session?.close(); };
@@ -510,6 +511,8 @@ export function mountAppFrame(frame, options) {
510
511
  throw Error("App frame is unavailable.");
511
512
  frame.contentWindow.postMessage({ channel: CHANNEL, challenge: options.challenge, session: nonce, ...(protocol2 ? { protocol: 2 } : {}) }, "*", [ports.port2]);
512
513
  session.lifecycle(bounds);
514
+ if (sound)
515
+ session.sound(sound);
513
516
  }
514
517
  catch {
515
518
  ports.port1.close();
@@ -525,6 +528,13 @@ export function mountAppFrame(frame, options) {
525
528
  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
529
  setActive(active) { if (active === bounds.active)
527
530
  return; bounds = lifecycleValue({ ...bounds, active }); session?.lifecycle(bounds); },
531
+ setSound(next) {
532
+ const value = soundValue(next);
533
+ if (sound && sound.muted === value.muted && sound.volume === value.volume)
534
+ return;
535
+ sound = value;
536
+ session?.sound(value);
537
+ },
528
538
  dispose,
529
539
  capture(timeoutMs) { return ended || !session ? Promise.resolve(null) : session.capture(timeoutMs); },
530
540
  };
@@ -66,6 +66,14 @@ export interface VibeMarketAppSdk {
66
66
  current(): Readonly<AppLifecycle>;
67
67
  onChanged(listener: (state: Readonly<AppLifecycle>) => void): () => void;
68
68
  };
69
+ /**
70
+ * The desktop's sound (0.5.2): audible at full volume until the host says otherwise, then every change. Optional only so
71
+ * that objects written against 0.5.1 still type-check; `connectVibeMarketApp()` always provides it.
72
+ */
73
+ sound?: {
74
+ current(): Readonly<AppSound>;
75
+ onChanged(listener: (sound: Readonly<AppSound>) => void): () => void;
76
+ };
69
77
  /** 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
78
  onCapture?(handler: () => HTMLCanvasElement | string | null | Promise<HTMLCanvasElement | string | null>): () => void;
71
79
  destroy(): void;
@@ -81,4 +89,17 @@ export declare function parseAppEnvelope(input: unknown, session: string): {
81
89
  id: string;
82
90
  request: AppRequest | AppFrameRequest;
83
91
  };
92
+ /**
93
+ * The desktop's sound for this app (the `app.sound` event, any protocol): `muted` when the taskbar speaker (or the desktop's
94
+ * games sound) is off, `volume` the level games play at, from 0 to 1 (the website's desk sends master volume × its Games fader). The host is the one source of truth; an app follows it (`createAudio` from `@vibechain/os/audio` does). A host
95
+ * that predates it sends nothing, and the SDK reads that as audible at full volume.
96
+ */
97
+ export interface AppSound {
98
+ muted: boolean;
99
+ volume: number;
100
+ }
101
+ export declare const AUDIBLE: Readonly<AppSound>;
102
+ export declare function soundValue(input: unknown): Readonly<AppSound>;
103
+ /** Whether anything an app plays can be heard. */
104
+ export declare const audible: (sound: Readonly<AppSound>) => boolean;
84
105
  export declare function lifecycleValue(input: unknown): Readonly<AppLifecycle>;
@@ -117,6 +117,15 @@ export function parseAppEnvelope(input, session) {
117
117
  return { id: input.id, request: { method: request.method, value: checkpointValue(request.value) } };
118
118
  throw Error("This app has no permission for that method.");
119
119
  }
120
+ export const AUDIBLE = Object.freeze({ muted: false, volume: 1 });
121
+ export function soundValue(input) {
122
+ if (!plain(input) || !exact(input, ["muted", "volume"]) || typeof input.muted !== "boolean"
123
+ || typeof input.volume !== "number" || !Number.isFinite(input.volume) || input.volume < 0 || input.volume > 1)
124
+ throw Error("Invalid app sound.");
125
+ return Object.freeze({ muted: input.muted, volume: input.volume });
126
+ }
127
+ /** Whether anything an app plays can be heard. */
128
+ export const audible = (sound) => !sound.muted && sound.volume > 0;
120
129
  export function lifecycleValue(input) {
121
130
  if (!plain(input) || !exact(input, ["active", "width", "height"]) || typeof input.active !== "boolean"
122
131
  || typeof input.width !== "number" || !Number.isInteger(input.width) || input.width < 0 || input.width > 4096
@@ -0,0 +1,65 @@
1
+ /**
2
+ * `@vibechain/os/audio`: Web Audio that follows the desktop. `createAudio(app)` returns an AudioContext and a master GainNode
3
+ * that already obey the host's sound (the taskbar speaker and volume, `os.sound`), the window's lifecycle and the browser's
4
+ * gesture rule, and that recover from a context the browser stopped. An app connects what it plays to `master` and needs no
5
+ * other sound code.
6
+ *
7
+ * This is cooperative: a sandboxed frame cannot be muted from outside in a browser, so the host tells the app and the app
8
+ * obeys. VibeStore review requires every app that makes sound to follow the host's sound state; this helper is the easy way.
9
+ */
10
+ import { type AppSound } from "./app-protocol.ts";
11
+ import type { LifecycleSource, OsLifecycle } from "./loop.ts";
12
+ /** How long the master takes to reach a new level, in seconds: short enough to feel instant, long enough not to click. */
13
+ export declare const AUDIO_RAMP_SECONDS = 0.05;
14
+ /** The gestures that let a browser start audio in the frame; on each one a context that is not running is resumed. */
15
+ export declare const AUDIO_GESTURES: readonly string[];
16
+ /**
17
+ * Recovery bounds. A context still not running after this many gestures in a row (WebKit can leave one `suspended` or
18
+ * `interrupted` for the life of the page, after an audio interruption, sleep or an output change) is replaced by a new one,
19
+ * made inside the gesture so it may start; a context the browser closed is replaced at once. At most `remakes` times.
20
+ */
21
+ export declare const AUDIO_RECOVERY: Readonly<{
22
+ gestures: 3;
23
+ remakes: 3;
24
+ }>;
25
+ /** The 0.4 app object (`connectVibeMarketApp()`): lifecycle and, from 0.5.2, `sound`. */
26
+ export type AudioLegacySource = LifecycleSource & {
27
+ sound?: {
28
+ current(): Readonly<AppSound>;
29
+ onChanged(listener: (sound: Readonly<AppSound>) => void): () => void;
30
+ };
31
+ };
32
+ /** The 0.5 `Os` from `connect()`: lifecycle and, from 0.5.2, `sound`. */
33
+ export type AudioOsSource = OsLifecycle & {
34
+ readonly sound?: Readonly<AppSound>;
35
+ onSound?(listener: (sound: Readonly<AppSound>) => void): () => void;
36
+ };
37
+ export interface AudioOptions {
38
+ /** an AudioContext the app made itself; by default the helper makes one with `latencyHint` (and so does any replacement) */
39
+ context?: AudioContext;
40
+ /** for the helper's own contexts; default "interactive" */
41
+ latencyHint?: AudioContextLatencyCategory | number;
42
+ }
43
+ export interface AppAudio {
44
+ /** the current context. It is replaced if the browser closed it or it stayed stopped (see AUDIO_RECOVERY): read it again in `onChange` */
45
+ readonly context: AudioContext;
46
+ /** connect everything the app plays here; it follows the desktop, the app's own mute and the window, and is replaced with the context */
47
+ readonly master: GainNode;
48
+ /** the desktop's sound now */
49
+ readonly desktop: Readonly<AppSound>;
50
+ /** whether a player can hear the app: the desktop allows sound, the app's own mute is off, the window is active and the context runs */
51
+ readonly audible: boolean;
52
+ /** the app's own extra mute (a game's sound button). It can silence the app; it never overrides the desktop's mute. */
53
+ muted: boolean;
54
+ /** hold the context suspended (a pause menu, a lost GPU): neither the window coming back nor a click resumes it until false */
55
+ paused: boolean;
56
+ /** called after the desktop's sound, the app's mute, `paused`, the window, the context's state or the context itself changed */
57
+ onChange(listener: () => void): () => void;
58
+ /** stop following and close the context */
59
+ close(): void;
60
+ }
61
+ /**
62
+ * Web Audio for an app, following the desktop. Make it once, ideally in the first click (a context made then starts at
63
+ * once); a context made earlier starts on the frame's first click or key. Throws where the browser has no Web Audio.
64
+ */
65
+ export declare function createAudio(app: AudioLegacySource | AudioOsSource, options?: AudioOptions): AppAudio;
package/dist/audio.js ADDED
@@ -0,0 +1,162 @@
1
+ /**
2
+ * `@vibechain/os/audio`: Web Audio that follows the desktop. `createAudio(app)` returns an AudioContext and a master GainNode
3
+ * that already obey the host's sound (the taskbar speaker and volume, `os.sound`), the window's lifecycle and the browser's
4
+ * gesture rule, and that recover from a context the browser stopped. An app connects what it plays to `master` and needs no
5
+ * other sound code.
6
+ *
7
+ * This is cooperative: a sandboxed frame cannot be muted from outside in a browser, so the host tells the app and the app
8
+ * obeys. VibeStore review requires every app that makes sound to follow the host's sound state; this helper is the easy way.
9
+ */
10
+ import { AUDIBLE } from "./app-protocol.js";
11
+ /** How long the master takes to reach a new level, in seconds: short enough to feel instant, long enough not to click. */
12
+ export const AUDIO_RAMP_SECONDS = 0.05;
13
+ /** The gestures that let a browser start audio in the frame; on each one a context that is not running is resumed. */
14
+ export const AUDIO_GESTURES = Object.freeze(["pointerdown", "pointerup", "keydown", "touchend"]);
15
+ /**
16
+ * Recovery bounds. A context still not running after this many gestures in a row (WebKit can leave one `suspended` or
17
+ * `interrupted` for the life of the page, after an audio interruption, sleep or an output change) is replaced by a new one,
18
+ * made inside the gesture so it may start; a context the browser closed is replaced at once. At most `remakes` times.
19
+ */
20
+ export const AUDIO_RECOVERY = Object.freeze({ gestures: 3, remakes: 3 });
21
+ function follow(app) {
22
+ if ("lifecycle" in app) {
23
+ const sound = app.sound;
24
+ return {
25
+ active: () => app.lifecycle.current().active,
26
+ sound: () => sound?.current() ?? AUDIBLE,
27
+ onActive(listener) { let last = app.lifecycle.current().active; return app.lifecycle.onChanged(state => { if (state.active !== last) {
28
+ last = state.active;
29
+ listener(last);
30
+ } }); },
31
+ onSound: listener => sound ? sound.onChanged(listener) : () => { },
32
+ };
33
+ }
34
+ return {
35
+ active: () => app.active,
36
+ sound: () => app.sound ?? AUDIBLE,
37
+ onActive(listener) { const offs = [app.onPause(() => listener(false)), app.onResume(() => listener(true))]; return () => { for (const off of offs)
38
+ off(); }; },
39
+ onSound: listener => typeof app.onSound === "function" ? app.onSound(listener) : () => { },
40
+ };
41
+ }
42
+ /**
43
+ * Web Audio for an app, following the desktop. Make it once, ideally in the first click (a context made then starts at
44
+ * once); a context made earlier starts on the frame's first click or key. Throws where the browser has no Web Audio.
45
+ */
46
+ export function createAudio(app, options = {}) {
47
+ const host = follow(app);
48
+ const make = () => new AudioContext({ latencyHint: options.latencyHint ?? "interactive" });
49
+ let context = options.context ?? make(), master = context.createGain();
50
+ let own = false, paused = false, closed = false, active = host.active(), tries = 0, remakes = 0, suspendTimer;
51
+ const listeners = new Set();
52
+ const target = () => { const sound = host.sound(); return sound.muted || own || !active ? 0 : sound.volume; };
53
+ const changed = () => { for (const listener of [...listeners])
54
+ listener(); };
55
+ /** Move the master to where the desktop, the app and the window say, with a short ramp so nothing clicks. */
56
+ const apply = () => {
57
+ const now = context.currentTime, gain = master.gain;
58
+ gain.cancelScheduledValues(now);
59
+ gain.setValueAtTime(gain.value, now);
60
+ gain.linearRampToValueAtTime(target(), now + AUDIO_RAMP_SECONDS);
61
+ };
62
+ const wanted = () => !closed && !paused && active;
63
+ const start = () => { if (wanted() && context.state !== "running")
64
+ context.resume().catch(() => { }); };
65
+ const statechange = () => {
66
+ if (context.state === "running")
67
+ tries = 0;
68
+ if (context.state === "closed" && !closed) {
69
+ remake();
70
+ return;
71
+ }
72
+ changed();
73
+ };
74
+ const wire = () => {
75
+ master.gain.value = target();
76
+ master.connect(context.destination);
77
+ context.addEventListener("statechange", statechange);
78
+ };
79
+ /** A new context and master for one the browser closed or kept stopped; the app reconnects its nodes in `onChange`. */
80
+ function remake() {
81
+ if (remakes >= AUDIO_RECOVERY.remakes)
82
+ return;
83
+ remakes++;
84
+ tries = 0;
85
+ const old = context;
86
+ old.removeEventListener("statechange", statechange);
87
+ if (old.state !== "closed")
88
+ old.close().catch(() => { });
89
+ try {
90
+ context = make();
91
+ }
92
+ catch {
93
+ context = old;
94
+ return;
95
+ }
96
+ master = context.createGain();
97
+ wire();
98
+ start();
99
+ changed();
100
+ }
101
+ /** After the ramp down has played, stop the clock: a window behind another or a paused app costs nothing. */
102
+ const stop = () => {
103
+ clearTimeout(suspendTimer);
104
+ suspendTimer = setTimeout(() => { suspendTimer = undefined; if (!closed && !wanted() && context.state === "running")
105
+ context.suspend().catch(() => { }); }, AUDIO_RAMP_SECONDS * 1000 + 20);
106
+ };
107
+ const offs = [
108
+ host.onSound(() => { apply(); changed(); }),
109
+ host.onActive(next => { active = next; apply(); if (active) {
110
+ clearTimeout(suspendTimer);
111
+ start();
112
+ }
113
+ else
114
+ stop(); changed(); }),
115
+ ];
116
+ /** Every gesture while the context is not running resumes it; a context that ignores several in a row is replaced. */
117
+ const gesture = () => {
118
+ if (!wanted() || context.state === "running")
119
+ return;
120
+ if (++tries > AUDIO_RECOVERY.gestures)
121
+ remake();
122
+ else
123
+ start();
124
+ };
125
+ const visible = () => { if (document.visibilityState === "visible")
126
+ start(); };
127
+ for (const type of AUDIO_GESTURES)
128
+ window.addEventListener(type, gesture, { capture: true, passive: true });
129
+ document.addEventListener("visibilitychange", visible);
130
+ wire();
131
+ start();
132
+ return {
133
+ get context() { return context; },
134
+ get master() { return master; },
135
+ get desktop() { return host.sound(); },
136
+ get audible() { const sound = host.sound(); return !sound.muted && sound.volume > 0 && !own && active && context.state === "running"; },
137
+ get muted() { return own; },
138
+ set muted(value) { if (value === own)
139
+ return; own = value; apply(); changed(); },
140
+ get paused() { return paused; },
141
+ set paused(value) { if (value === paused)
142
+ return; paused = value; if (paused)
143
+ context.suspend().catch(() => { });
144
+ else
145
+ start(); changed(); },
146
+ onChange(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
147
+ close() {
148
+ if (closed)
149
+ return;
150
+ closed = true;
151
+ clearTimeout(suspendTimer);
152
+ for (const off of offs)
153
+ off();
154
+ for (const type of AUDIO_GESTURES)
155
+ window.removeEventListener(type, gesture, { capture: true });
156
+ document.removeEventListener("visibilitychange", visible);
157
+ context.removeEventListener("statechange", statechange);
158
+ listeners.clear();
159
+ context.close().catch(() => { });
160
+ },
161
+ };
162
+ }
package/dist/browser.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  /** The no-bundler build's entry: `dist/vibemarket-os.js` exposes exactly these as the global `VibemarketOS`. */
2
2
  export { connect, OsError } from "./os.ts";
3
3
  export { cardLink, packLink, parseVmosLink } from "./links.ts";
4
+ export { createAudio } from "./audio.ts";