@vibechain/os 0.5.0 → 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 (51) hide show
  1. package/AGENTS.md +22 -9
  2. package/README.md +53 -17
  3. package/SECURITY.md +6 -2
  4. package/dist/app-client.js +29 -5
  5. package/dist/app-host.d.ts +27 -4
  6. package/dist/app-host.js +76 -9
  7. package/dist/app-protocol.d.ts +36 -1
  8. package/dist/app-protocol.js +21 -0
  9. package/dist/app-wire.d.ts +24 -3
  10. package/dist/app-wire.js +19 -4
  11. package/dist/audio.d.ts +65 -0
  12. package/dist/audio.js +162 -0
  13. package/dist/browser.d.ts +2 -0
  14. package/dist/browser.js +2 -0
  15. package/dist/bundle.d.ts +2 -0
  16. package/dist/bundle.js +2 -0
  17. package/dist/capture.d.ts +22 -0
  18. package/dist/capture.js +99 -0
  19. package/dist/cli.js +3 -1
  20. package/dist/commands.d.ts +6 -0
  21. package/dist/commands.js +17 -0
  22. package/dist/index.d.ts +5 -2
  23. package/dist/index.js +1 -0
  24. package/dist/links.d.ts +21 -0
  25. package/dist/links.js +43 -0
  26. package/dist/os.d.ts +33 -8
  27. package/dist/os.js +68 -14
  28. package/dist/preview-parent.d.ts +8 -2
  29. package/dist/preview-parent.js +35 -10
  30. package/dist/preview-ui.js +1 -1
  31. package/dist/preview.js +1 -1
  32. package/dist/templates/plain/game.js +3 -1
  33. package/dist/testing.d.ts +15 -2
  34. package/dist/testing.js +64 -19
  35. package/dist/transport.d.ts +2 -0
  36. package/dist/transport.js +1 -1
  37. package/dist/vibemarket-os.js +1 -1
  38. package/examples/paw-beat/README.md +28 -9
  39. package/examples/paw-beat/game.ts +280 -123
  40. package/examples/paw-beat/index.html +18 -4
  41. package/examples/paw-beat/main.ts +101 -44
  42. package/examples/paw-beat/music.ts +72 -337
  43. package/examples/paw-beat/stage.ts +23 -9
  44. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  45. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  46. package/examples/paw-beat/synth.ts +477 -0
  47. package/examples/paw-beat/tracks.ts +286 -0
  48. package/examples/paw-beat/vibemarket.json +2 -2
  49. package/examples/vibexp-app/plain/game.ts +6 -2
  50. package/package.json +7 -1
  51. package/skill.md +399 -0
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,2 +1,4 @@
1
1
  /** The no-bundler build's entry: `dist/vibemarket-os.js` exposes exactly these as the global `VibemarketOS`. */
2
2
  export { connect, OsError } from "./os.ts";
3
+ export { cardLink, packLink, parseVmosLink } from "./links.ts";
4
+ export { createAudio } from "./audio.ts";
package/dist/browser.js CHANGED
@@ -1,2 +1,4 @@
1
1
  /** The no-bundler build's entry: `dist/vibemarket-os.js` exposes exactly these as the global `VibemarketOS`. */
2
2
  export { connect, OsError } from "./os.js";
3
+ export { cardLink, packLink, parseVmosLink } from "./links.js";
4
+ export { createAudio } from "./audio.js";
package/dist/bundle.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ /** The file extensions a bundle may contain (SVG is refused in schema 2 and 3 bundles by readBuiltBundle). */
2
+ export declare const ASSET_EXTENSIONS: readonly string[];
1
3
  export declare const assetType: (file: string) => string | undefined;
2
4
  export declare const compareAssetNames: (a: string, b: string) => number;
3
5
  /** Local authoring reader. Every allocation is bounded before reading; files cannot grow the budget. */
package/dist/bundle.js CHANGED
@@ -11,6 +11,8 @@ const TYPES = {
11
11
  woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf", mp3: "audio/mpeg", ogg: "audio/ogg",
12
12
  wav: "audio/wav", mp4: "video/mp4", webm: "video/webm", wasm: "application/wasm", bin: "application/octet-stream", txt: "text/plain; charset=utf-8",
13
13
  };
14
+ /** The file extensions a bundle may contain (SVG is refused in schema 2 and 3 bundles by readBuiltBundle). */
15
+ export const ASSET_EXTENSIONS = Object.freeze(Object.keys(TYPES));
14
16
  export const assetType = (file) => TYPES[file.slice(file.lastIndexOf(".") + 1).toLowerCase()];
15
17
  export const compareAssetNames = (a, b) => a < b ? -1 : a > b ? 1 : 0;
16
18
  /** Local authoring reader. Every allocation is bounded before reading; files cannot grow the budget. */
@@ -0,0 +1,22 @@
1
+ /** The longest side of a captured frame, in pixels. */
2
+ export declare const CAPTURE_MAX_SIDE = 1280;
3
+ /** The visible canvas with the largest on-screen area, or null. */
4
+ export declare function largestCanvas(doc: Pick<Document, "querySelectorAll">): HTMLCanvasElement | null;
5
+ /** Draw `source` downscaled to at most 1280 pixels on its longest side and encode it (WebP, else JPEG) under 1,000,000 characters; null if it cannot. */
6
+ export declare function encodeCanvas(source: HTMLCanvasElement, doc: Pick<Document, "createElement">): string | null;
7
+ /** What an `os.onCapture` handler may answer. */
8
+ export type CaptureResult = HTMLCanvasElement | string | null;
9
+ /** The picture for a handler's answer: a canvas is downscaled and encoded, a data URL is kept if it is a valid one. */
10
+ export declare function frameFrom(result: unknown, doc: Pick<Document, "createElement">): string | null;
11
+ /**
12
+ * The client half of one capture exchange, shared by `connect()` and the 0.4 client. `send` posts the `app.frame`; `closed`
13
+ * says the session is over. With no handler the answer is the largest visible canvas on the NEXT animation frame, so a
14
+ * continuously rendering WebGL game's drawing buffer still holds the frame it just drew. Nothing here ever throws.
15
+ */
16
+ export declare function createCapturer(send: (id: string, image: string | null) => void, closed: () => boolean): {
17
+ /** the latest handler wins; the returned function removes this one only if it is still the latest */
18
+ on(next: () => CaptureResult | Promise<CaptureResult>): () => void;
19
+ clear(): void;
20
+ /** the host's `app.capture` event */
21
+ event(id: unknown): void;
22
+ };
@@ -0,0 +1,99 @@
1
+ /**
2
+ * The app side of the desktop camera: turn a canvas into the data URL an `app.frame` carries. The browser objects are passed
3
+ * in, so the helpers run (and test) without a global `document`.
4
+ */
5
+ import { captureId, frameImage } from "./app-protocol.js";
6
+ /** The longest side of a captured frame, in pixels. */
7
+ export const CAPTURE_MAX_SIDE = 1280;
8
+ const QUALITIES = [0.85, 0.6, 0.4];
9
+ /** The visible canvas with the largest on-screen area, or null. */
10
+ export function largestCanvas(doc) {
11
+ let best = null, area = 0;
12
+ for (const canvas of Array.from(doc.querySelectorAll("canvas"))) {
13
+ const box = canvas.getBoundingClientRect(), size = box.width * box.height;
14
+ if (size > area && canvas.width > 0 && canvas.height > 0) {
15
+ best = canvas;
16
+ area = size;
17
+ }
18
+ }
19
+ return best;
20
+ }
21
+ /** Draw `source` downscaled to at most 1280 pixels on its longest side and encode it (WebP, else JPEG) under 1,000,000 characters; null if it cannot. */
22
+ export function encodeCanvas(source, doc) {
23
+ try {
24
+ const width = source.width, height = source.height;
25
+ if (!(width > 0 && height > 0))
26
+ return null;
27
+ const scale = Math.min(1, CAPTURE_MAX_SIDE / Math.max(width, height));
28
+ const target = doc.createElement("canvas");
29
+ target.width = Math.max(1, Math.round(width * scale));
30
+ target.height = Math.max(1, Math.round(height * scale));
31
+ const context = target.getContext("2d");
32
+ if (!context)
33
+ return null;
34
+ context.drawImage(source, 0, 0, target.width, target.height);
35
+ for (const quality of QUALITIES) {
36
+ let url = target.toDataURL("image/webp", quality);
37
+ if (!url.startsWith("data:image/webp"))
38
+ url = target.toDataURL("image/jpeg", quality);
39
+ if (frameImage(url))
40
+ return url;
41
+ }
42
+ return null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ /** The picture for a handler's answer: a canvas is downscaled and encoded, a data URL is kept if it is a valid one. */
49
+ export function frameFrom(result, doc) {
50
+ if (typeof result === "string")
51
+ return frameImage(result) ? result : null;
52
+ if (result !== null && typeof result === "object" && "getContext" in result && "toDataURL" in result)
53
+ return encodeCanvas(result, doc);
54
+ return null;
55
+ }
56
+ /**
57
+ * The client half of one capture exchange, shared by `connect()` and the 0.4 client. `send` posts the `app.frame`; `closed`
58
+ * says the session is over. With no handler the answer is the largest visible canvas on the NEXT animation frame, so a
59
+ * continuously rendering WebGL game's drawing buffer still holds the frame it just drew. Nothing here ever throws.
60
+ */
61
+ export function createCapturer(send, closed) {
62
+ let handler = null;
63
+ const page = () => globalThis.document;
64
+ const answer = (id, image) => { if (closed())
65
+ return; try {
66
+ send(id, image);
67
+ }
68
+ catch { /* capture never breaks the app */ } };
69
+ return {
70
+ /** the latest handler wins; the returned function removes this one only if it is still the latest */
71
+ on(next) { handler = next; return () => { if (handler === next)
72
+ handler = null; }; },
73
+ clear() { handler = null; },
74
+ /** the host's `app.capture` event */
75
+ event(id) {
76
+ if (closed() || !captureId(id))
77
+ return;
78
+ try {
79
+ const custom = handler;
80
+ if (custom) {
81
+ Promise.resolve().then(custom).then(result => frameFrom(result, page()), () => null).then(image => answer(id, image), () => { });
82
+ return;
83
+ }
84
+ requestAnimationFrame(() => {
85
+ let image = null;
86
+ try {
87
+ const canvas = largestCanvas(page());
88
+ image = canvas ? frameFrom(canvas, page()) : null;
89
+ }
90
+ catch {
91
+ image = null;
92
+ }
93
+ answer(id, image);
94
+ });
95
+ }
96
+ catch { /* no document or animation frames: the host's timeout answers */ }
97
+ },
98
+ };
99
+ }
package/dist/cli.js CHANGED
@@ -4,6 +4,7 @@ import { APP_BUNDLE_LIMITS, GAME_LIMITS } from "./manifest.js";
4
4
  import { readBuiltBundle } from "./bundle.js";
5
5
  import { APP_TEMPLATES, appTemplate, createApp, stageAppAssets } from "./scaffold.js";
6
6
  import { checkApp } from "./check.js";
7
+ import { APP_CLI_COMMANDS } from "./commands.js";
7
8
  import { startAppPreview } from "./preview.js";
8
9
  import { redact } from "./redact.js";
9
10
  const MiB = 1024 * 1024;
@@ -84,7 +85,8 @@ export async function runCli(argv, runtime = createCliRuntime()) {
84
85
  return;
85
86
  }
86
87
  if (!["upload", "list", "publish", "rollback"].includes(command ?? "")) {
87
- runtime.log("os init <empty-directory> [sdk.tgz] [--template plain|canvas|three]\nos assets\nos check [directory]\nos preview <dist> [port]\nos pack <dist> <game.zip>\n\nSubmit to VibeStore (sign in with Steam in your browser):\nos login [--no-browser] [--device <name>]\nos whoami\nos submit <dist> [--yes]\nos status [app-id]\nos logout\n\nInternal publisher (local operators only):\nos upload <game.zip>\nos list\nos publish <game-id> <version> <registry-revision>\nos rollback <game-id> <version> <registry-revision>\n\nSet VIBEMARKET_PUBLISH_URL=http://127.0.0.1:8888 and VIBEMARKET_PUBLISH_TOKEN (local operator credential). Upload returns a draft preview URL. Publish and rollback only update the active version pointer.");
88
+ const usage = (group) => APP_CLI_COMMANDS.filter(command => command.group === group).map(command => command.usage).join("\n");
89
+ runtime.log(usage("build") + "\n\nSubmit to VibeStore (sign in with Steam in your browser):\n" + usage("publish") + "\n\nInternal publisher (local operators only):\nos upload <game.zip>\nos list\nos publish <game-id> <version> <registry-revision>\nos rollback <game-id> <version> <registry-revision>\n\nSet VIBEMARKET_PUBLISH_URL=http://127.0.0.1:8888 and VIBEMARKET_PUBLISH_TOKEN (local operator credential). Upload returns a draft preview URL. Publish and rollback only update the active version pointer.");
88
90
  return;
89
91
  }
90
92
  const base = new URL(runtime.env.VIBEMARKET_PUBLISH_URL ?? "http://127.0.0.1:8888");
@@ -0,0 +1,6 @@
1
+ export interface AppCliCommand {
2
+ usage: string;
3
+ does: string;
4
+ group: "build" | "publish";
5
+ }
6
+ export declare const APP_CLI_COMMANDS: readonly AppCliCommand[];
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The `os` commands an app developer uses, in the order `os` prints them: one list for the CLI's help and the agent skill
3
+ * (https://vibechain.com/os/skill.md), so the two cannot drift. The internal Market-game publisher commands are not here.
4
+ */
5
+ import { APP_TEMPLATES } from "./scaffold.js";
6
+ export const APP_CLI_COMMANDS = Object.freeze([
7
+ { group: "build", usage: `os init <empty-directory> [sdk.tgz] [--template ${APP_TEMPLATES.join("|")}]`, does: "create an app from a template (canvas when no template is given)" },
8
+ { group: "build", usage: "os assets", does: "copy index.html, vibemarket.json, the listed store images and the whole public/ folder into dist/" },
9
+ { group: "build", usage: "os check [directory]", does: "print every problem with the manifest and the built folder, one per line; exits 1 on any" },
10
+ { group: "build", usage: "os preview <dist> [port]", does: "run the built app locally in a sandboxed window with the production policy and stand-in cards, saves and player" },
11
+ { group: "build", usage: "os pack <dist> <game.zip>", does: "check the build and write the ZIP to submit" },
12
+ { group: "publish", usage: "os login [--no-browser] [--device <name>]", does: "sign this computer in: prints a code the human approves at https://vibechain.com/os/cli" },
13
+ { group: "publish", usage: "os whoami", does: "show the signed-in account and computer" },
14
+ { group: "publish", usage: "os submit <dist> [--yes]", does: "check, pack and upload the build for review after showing a summary and asking" },
15
+ { group: "publish", usage: "os status [app-id]", does: "list your submissions and their review state" },
16
+ { group: "publish", usage: "os logout", does: "revoke this computer's sign-in, then delete it" },
17
+ ]);
package/dist/index.d.ts CHANGED
@@ -2,13 +2,16 @@ export { connectGameSdk, createPortSdk } from "./client.ts";
2
2
  export { CHANNEL } from "./channel.ts";
3
3
  export { watchInventory } from "./inventory.ts";
4
4
  export { connect, OsError, OS_ERROR_CODES, OS_SDK_VERSION } from "./os.ts";
5
- export type { Card, Os, OsErrorCode, OsSize, Pack, PackCard, PackSummary, Player, Rarity, SignedInPlayer } from "./os.ts";
5
+ export type { Card, Os, OsErrorCode, OsSize, OsSound, Pack, PackCard, PackSummary, Player, Rarity, SignedInPlayer } from "./os.ts";
6
+ export type { CaptureResult } from "./capture.ts";
6
7
  export { spawnWorker } from "./worker.ts";
8
+ export { cardLink, packLink, parseVmosLink, VMOS_LINK_MAX } from "./links.ts";
9
+ export type { VmosLink } from "./links.ts";
7
10
  export type { SpawnedWorker, WorkerHost } from "./worker.ts";
8
11
  /** @deprecated Use `connect()`: the same readiness, lifecycle and score, plus saves that outlive the window, cards and more. */
9
12
  export { connectVibeMarketApp } from "./app-client.ts";
10
13
  export { GAME_SCORE_LIMIT } from "./completion.ts";
11
14
  export type { GameFinishInput } from "./completion.ts";
12
- export type { AppValue, AppLifecycle, VibeMarketAppSdk } from "./app-protocol.ts";
15
+ export type { AppValue, AppLifecycle, AppSound, VibeMarketAppSdk } from "./app-protocol.ts";
13
16
  export type { InventoryObserver } from "./inventory.ts";
14
17
  export type * from "./types.ts";
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ export { CHANNEL } from "./channel.js";
3
3
  export { watchInventory } from "./inventory.js";
4
4
  export { connect, OsError, OS_ERROR_CODES, OS_SDK_VERSION } from "./os.js";
5
5
  export { spawnWorker } from "./worker.js";
6
+ export { cardLink, packLink, parseVmosLink, VMOS_LINK_MAX } from "./links.js";
6
7
  /** @deprecated Use `connect()`: the same readiness, lifecycle and score, plus saves that outlive the window, cards and more. */
7
8
  export { connectVibeMarketApp } from "./app-client.js";
8
9
  export { GAME_SCORE_LIMIT } from "./completion.js";
@@ -0,0 +1,21 @@
1
+ export type VmosLink = {
2
+ kind: "pack";
3
+ pack: string;
4
+ } | {
5
+ kind: "card";
6
+ pack: string;
7
+ card: string;
8
+ };
9
+ export declare const VMOS_LINK_MAX = 200;
10
+ /** The three accepted forms, exactly as parseVmosLink matches them (the agent skill prints these). */
11
+ export declare const VMOS_LINK_PATTERNS: Readonly<{
12
+ pack: RegExp;
13
+ card: RegExp;
14
+ web: RegExp;
15
+ }>;
16
+ /** The target a link names, or null when it is not exactly one of the three forms. */
17
+ export declare function parseVmosLink(text: unknown): VmosLink | null;
18
+ /** `vmos://pack/<slug>`; throws an OsError `invalid` for a value that is not a pack slug. */
19
+ export declare function packLink(slug: string): string;
20
+ /** `vmos://card/<slug>/<cardId>`; throws an OsError `invalid` for a value that is not a pack slug or a card id. */
21
+ export declare function cardLink(slug: string, cardId: string): string;
package/dist/links.js ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * App links (VM_OS_APPS_3.md, link-out): one string form an app can show, store or receive from its server for a vmOS pack or
3
+ * card, opened with `os.open(link)`. Pure functions, no DOM: the SDK parses a link and sends the host only the parsed target;
4
+ * nothing here, nor the host, ever navigates to the string.
5
+ *
6
+ * vmos://pack/<slug>
7
+ * vmos://card/<slug>/<cardId>
8
+ * https://vibechain.com/os/pack/<slug> (and https://www.vibechain.com/...; one optional trailing "/")
9
+ *
10
+ * Exact and anchored: lowercase scheme and host, at most 200 characters, no percent-encoding, query, fragment, user, port,
11
+ * other host or other path. `<slug>` is a pack slug (at most 56 characters), `<cardId>` a creator card id.
12
+ */
13
+ import { CARD_ID, OsError } from "./app-wire.js";
14
+ import { packSlug } from "./manifest.js";
15
+ export const VMOS_LINK_MAX = 200;
16
+ const SLUG = "[a-z0-9]+(?:-[a-z0-9]+)*", CARD = "[A-Za-z0-9_-]{1,64}";
17
+ const PACK_LINK = new RegExp(`^vmos://pack/(${SLUG})$`);
18
+ const CARD_LINK = new RegExp(`^vmos://card/(${SLUG})/(${CARD})$`);
19
+ const WEB_PACK = new RegExp(`^https://(?:www\\.)?vibechain\\.com/os/pack/(${SLUG})/?$`);
20
+ /** The three accepted forms, exactly as parseVmosLink matches them (the agent skill prints these). */
21
+ export const VMOS_LINK_PATTERNS = Object.freeze({ pack: PACK_LINK, card: CARD_LINK, web: WEB_PACK });
22
+ /** The target a link names, or null when it is not exactly one of the three forms. */
23
+ export function parseVmosLink(text) {
24
+ if (typeof text !== "string" || text.length > VMOS_LINK_MAX)
25
+ return null;
26
+ const card = CARD_LINK.exec(text);
27
+ if (card)
28
+ return packSlug(card[1]) ? { kind: "card", pack: card[1], card: card[2] } : null;
29
+ const pack = PACK_LINK.exec(text) ?? WEB_PACK.exec(text);
30
+ return pack && packSlug(pack[1]) ? { kind: "pack", pack: pack[1] } : null;
31
+ }
32
+ /** `vmos://pack/<slug>`; throws an OsError `invalid` for a value that is not a pack slug. */
33
+ export function packLink(slug) {
34
+ if (!packSlug(slug))
35
+ throw new OsError("invalid", "That is not a pack slug.");
36
+ return `vmos://pack/${slug}`;
37
+ }
38
+ /** `vmos://card/<slug>/<cardId>`; throws an OsError `invalid` for a value that is not a pack slug or a card id. */
39
+ export function cardLink(slug, cardId) {
40
+ if (!packSlug(slug) || typeof cardId !== "string" || !CARD_ID.test(cardId))
41
+ throw new OsError("invalid", "That is not a pack slug and a card id.");
42
+ return `vmos://card/${slug}/${cardId}`;
43
+ }
package/dist/os.d.ts CHANGED
@@ -1,23 +1,34 @@
1
+ /**
2
+ * `connect()`: the one app API of @vibechain/os 0.5 (VM_OS_APPS_3.md section 11). On a host that advertises protocol 2 it
3
+ * says hello and every method works; on an older host `ready`, `finish`, lifecycle, `load` and `save` work (saves use the
4
+ * window-only checkpoint) and the rest reject with `unsupported`. Every rejection is an OsError with a stable code.
5
+ */
6
+ import { type AppSound } from "./app-protocol.ts";
1
7
  import { type Card, type OsErrorCode, type Pack, type PackSummary, type Player } from "./app-wire.ts";
8
+ import { type CaptureResult } from "./capture.ts";
2
9
  export type { Card, OsErrorCode, Pack, PackCard, PackSummary, Player, Rarity, SignedInPlayer } from "./app-wire.ts";
3
10
  export { OS_ERROR_CODES } from "./app-wire.ts";
4
11
  /** The SDK version a 0.5 client reports in `host.hello`. */
5
- export declare const OS_SDK_VERSION = "0.5.0";
6
- /** Every rejection of the app API. Branch on `code`; `message` is a plain sentence that may change. */
7
- export declare class OsError extends Error {
8
- readonly code: OsErrorCode;
9
- constructor(code: OsErrorCode, message: string);
10
- }
12
+ export declare const OS_SDK_VERSION = "0.5.2";
13
+ export { OsError } from "./app-wire.ts";
11
14
  export type OsSize = Readonly<{
12
15
  width: number;
13
16
  height: number;
14
17
  }>;
18
+ /** The desktop's sound for games: `muted` (the taskbar speaker, or games sound off) and the level games play at, from 0 to 1. */
19
+ export type OsSound = Readonly<AppSound>;
15
20
  export interface Os {
16
21
  /** false while the window is minimized or behind another window */
17
22
  readonly active: boolean;
18
23
  readonly size: OsSize;
19
24
  /** a guest's save lives only while the window is open */
20
25
  readonly guest: boolean;
26
+ /**
27
+ * The desktop's sound, which the app must follow: silent while `muted`, scaled by `volume` (0 to 1). Set before `connect()`
28
+ * resolves on a host that controls sound; `{ muted: false, volume: 1 }` on an older host. `createAudio(os)` from
29
+ * `@vibechain/os/audio` follows it for you.
30
+ */
31
+ readonly sound: OsSound;
21
32
  /** hide the host's loading screen */
22
33
  ready(): Promise<void>;
23
34
  /** 0 to 1 while loading; keeps a long load inside the host's readiness rule */
@@ -31,10 +42,14 @@ export interface Os {
31
42
  /** called with the whole current list whenever it changes; returns unsubscribe */
32
43
  onCards(listener: (cards: Card[]) => void): () => void;
33
44
  packs(): Promise<PackSummary[]>;
34
- /** a pack's full public card list, in pack order */
45
+ /** any public pack's face (name, cover, cards with art), in pack order; holdings only come from `cards()` */
35
46
  pack(id: string): Promise<Pack>;
36
- /** the host opens the pack in the market window; needs a click in the app */
47
+ /** the host opens any public pack in VibeMarket; needs a click in the app */
37
48
  showPack(id: string): Promise<void>;
49
+ /** the host opens that card in its pack's page; needs a click in the app (0.5.1 hosts) */
50
+ showCard(pack: string, cardId: string): Promise<void>;
51
+ /** open an app link (`vmos://pack/<slug>`, `vmos://card/<slug>/<cardId>`, `https://vibechain.com/os/pack/<slug>`); needs a click */
52
+ open(link: string): Promise<void>;
38
53
  /** who is playing: handle, name and picture, or `{ guest: true }`; plus a 5-minute token for your own server with `network` */
39
54
  player(): Promise<Player>;
40
55
  finish(result: {
@@ -45,9 +60,19 @@ export interface Os {
45
60
  onPause(listener: () => void): () => void;
46
61
  onResume(listener: () => void): () => void;
47
62
  onResize(listener: (size: OsSize) => void): () => void;
63
+ /** called with the new state whenever the desktop's sound changes; returns unsubscribe */
64
+ onSound(listener: (sound: OsSound) => void): () => void;
65
+ /**
66
+ * The desktop camera asks for a picture of the app. By default the SDK sends the largest visible canvas; register a handler
67
+ * to draw one yourself (DOM apps, a custom view). It may return a canvas, a PNG/JPEG/WebP data URL (at most 1,000,000
68
+ * characters) or null, now or as a promise. The latest handler wins; returns unsubscribe.
69
+ */
70
+ onCapture?(handler: () => CaptureResult | Promise<CaptureResult>): () => void;
48
71
  /** release the port */
49
72
  close(): void;
50
73
  }
74
+ /** What each code means, as the SDK's own rejections say it (also the agent skill's error table). */
75
+ export declare const OS_ERROR_MESSAGES: Readonly<Record<OsErrorCode, string>>;
51
76
  /** Connect to the host: the handshake, then hello on a protocol 2 host. Call once, early. */
52
77
  export declare function connect(options?: {
53
78
  signal?: AbortSignal;