@vibechain/os 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -7,7 +7,10 @@
7
7
  bounded app-owned checkpoints and a score-only `game.finish({score})` signal; it has no profile, inventory, Steam/native,
8
8
  wallet, purchase or reward authority. The existing Market-game contract below
9
9
  continues to apply to collection games using `connectGameSdk()`; do not infer
10
- those permissions for an OS app. Public app publication remains disabled.
10
+ those permissions for an OS app. A VibeStore listing uses manifest schema version 2
11
+ (window size and a `store` object with icon, screenshots, description, category,
12
+ rating and support); the requirements are in README.md under "Listing in
13
+ VibeStore". Submit the packed ZIP from the VibeStore Submit tab in VibeMarket OS; every version is reviewed before listing, and an approved version is archived to public IPFS.
11
14
 
12
15
  This is the contract internal developers and agents test before public release.
13
16
  Build an ordinary static web game. Deliver a ZIP of **built output**, not source,
@@ -20,7 +23,7 @@ scripts, fonts, APIs, workers or wallet libraries. Bundle your dependencies/asse
20
23
  Install the published package in an independent game project:
21
24
 
22
25
  ```sh
23
- npm install @vibechain/os@0.2.1
26
+ npm install @vibechain/os@0.4.0
24
27
  ```
25
28
 
26
29
  To use a reviewed local SDK tarball instead, build it from the SDK package directory:
@@ -29,13 +32,13 @@ To use a reviewed local SDK tarball instead, build it from the SDK package direc
29
32
  pnpm install --frozen-lockfile
30
33
  pnpm review
31
34
  pnpm build
32
- pnpm pack --out /tmp/vibechain-os-0.2.1.tgz
35
+ pnpm pack --out /tmp/vibechain-os-0.4.0.tgz
33
36
  ```
34
37
 
35
38
  In an independent game project, install that tarball:
36
39
 
37
40
  ```sh
38
- npm install /tmp/vibechain-os-0.2.1.tgz
41
+ npm install /tmp/vibechain-os-0.4.0.tgz
39
42
  npm install --save-dev typescript esbuild
40
43
  ```
41
44
 
@@ -67,6 +70,8 @@ the bound calls `onError`, rather than presenting a partial collection as
67
70
  complete. Revoke cosmetic entitlements on error; retry with `observer.refresh()`.
68
71
  This helper adds no host permission and does not poll the chain by itself.
69
72
 
73
+ `examples/paw-beat` is a complete 3D rhythm game on the OS app facade (no permissions): Three.js, the `@vibechain/os/loop` and `@vibechain/os/canvas` helpers, synthesized audio, a checkpoint and `game.finish`; see its README.
74
+
70
75
  `examples/chonk-stack` is a complete game using this contract: vanilla
71
76
  TypeScript and Three.js, with all geometry and textures generated locally.
72
77
  Copy the folder into your game project, install the SDK tarball, run
@@ -128,7 +133,8 @@ operator approves the declared collection and permissions when publishing.
128
133
  Changing either requires a new version. Public developer ownership approval is
129
134
  not implemented in the local adapter.
130
135
 
131
- Supported assets: HTML, JS/MJS, CSS, JSON, PNG/JPEG/WebP/GIF/AVIF/SVG/ICO, WOFF/
136
+ Supported assets: HTML, JS/MJS, CSS, JSON, PNG/JPEG/WebP/GIF/AVIF/SVG/ICO (no SVG in
137
+ schema version 2 bundles), WOFF/
132
138
  WOFF2/TTF/OTF, MP3/OGG/WAV, MP4/WebM, WASM/BIN/TXT. Max 20 MiB compressed,
133
139
  64 MiB expanded, 16 MiB/file, 256 ZIP entries. No symlinks, encrypted files,
134
140
  traversal, duplicate/case-colliding names, absolute paths or hidden paths.
package/README.md CHANGED
@@ -5,7 +5,7 @@ Build games, tools and desktop apps for VibeMarket OS with TypeScript. Start wit
5
5
  ## Quickstart
6
6
 
7
7
  ```sh
8
- npx --yes @vibechain/os@0.2.1 init my-app
8
+ npx --yes @vibechain/os@0.4.0 init my-app
9
9
  cd my-app
10
10
  npm install
11
11
  npm run build
@@ -17,7 +17,7 @@ Open the printed `http://127.0.0.1:PORT` address. Stamp Club is a complete start
17
17
  The starter includes TypeScript and esbuild and pins your SDK version. To install from a downloaded SDK archive, supply its absolute path to npm and the initializer:
18
18
 
19
19
  ```sh
20
- npm exec --yes --package=/absolute/path/vibechain-os-0.2.1.tgz -- os init my-app /absolute/path/vibechain-os-0.2.1.tgz
20
+ npm exec --yes --package=/absolute/path/vibechain-os-0.4.0.tgz -- os init my-app /absolute/path/vibechain-os-0.4.0.tgz
21
21
  ```
22
22
 
23
23
  That explicit fallback 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`.
@@ -41,7 +41,47 @@ window.addEventListener("pagehide", () => app.destroy(), { once: true });
41
41
 
42
42
  Checkpoint is a base app capability, separate from Market permissions. It accepts only the same app's bounded JSON: ≤32 KiB UTF-8, depth8, ≤2,048 nodes, ≤64 keys/object, ≤256 items/array and ≤8KiB/string. State lives in trusted host memory, scoped to the open installation/version/identity/window; it is cleared on close, revoke, package/identity change or the controller's absolute 15-minute expiry. Suspension does not extend that lifetime. There is no arbitrary namespace, disk storage, account data or browser-restart guarantee. `write()` resolves after acknowledgement; an accepted snapshot can be restored even if that acknowledgement was interrupted.
43
43
 
44
- Manifest: use schema/sdkVersion1, `permissions: []` and `collectionId: null`. App methods are deliberately limited to readiness, checkpoints and the score-only completion signal. Raw requests for profile, inventory, rewards, purchases, Steam, native IPC or wallet operations terminate this app session. Existing Market games continue using `connectGameSdk()` with their existing permissions and host transaction review.
44
+ Manifest: use `sdkVersion: 1`, category `vibexp-app`, `permissions: []` and `collectionId: null`, with `schemaVersion: 1`, or `schemaVersion: 2` to add a store listing (below). App methods are deliberately limited to readiness, checkpoints and the score-only completion signal. Raw requests for profile, inventory, rewards, purchases, Steam, native IPC or wallet operations terminate this app session. Existing Market games continue using `connectGameSdk()` with their existing permissions and host transaction review.
45
+
46
+ ## Game helpers (since 0.3.0)
47
+
48
+ Two optional imports for canvas, WebGL and engine-based games. Both follow the host lifecycle, so a game stops drawing when its window is not active.
49
+
50
+ ```ts
51
+ import { connectVibeMarketApp } from "@vibechain/os";
52
+ import { createLoop } from "@vibechain/os/loop";
53
+ import { fitCanvas } from "@vibechain/os/canvas";
54
+
55
+ const app = await connectVibeMarketApp();
56
+ const canvas = document.querySelector("canvas")!;
57
+ fitCanvas(app, canvas, { onResize: ({ width, height }) => renderer.setSize(width, height, false) });
58
+ const loop = createLoop(app, { update: stepMs => world.step(stepMs), render: alpha => renderer.draw(alpha) });
59
+ await app.ready();
60
+ window.addEventListener("pagehide", () => { loop.stop(); app.destroy(); }, { once: true });
61
+ ```
62
+
63
+ `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`.
64
+
65
+ ### Testing your game
66
+
67
+ `@vibechain/os/testing` is an in-memory stand-in for the host, so game logic can be unit-tested without a browser:
68
+
69
+ ```ts
70
+ import { createFakeApp } from "@vibechain/os/testing";
71
+
72
+ const host = createFakeApp({ checkpoint: { stamps: 3 } });
73
+ const game = await startGame(host.app); // your code, given the app instead of connecting
74
+ host.setLifecycle({ active: false }); // as if the window was minimized
75
+ expect(game.paused).toBe(true);
76
+ await game.end();
77
+ expect(host.finished).toEqual({ score: 3 });
78
+ ```
79
+
80
+ It applies the real checkpoint, score and lifecycle validation and the single-shot completion rule. It has no time limit or request budget, so still run the preview before you ship.
81
+
82
+ ### A complete 3D example
83
+
84
+ `examples/paw-beat` in this package is a small 3D rhythm game built on these helpers with Three.js: a procedural dancing cat, a synthesized song, a saved personal best and a reported score. Its README has the build commands.
45
85
 
46
86
  ## Intro, loading and results
47
87
 
@@ -57,9 +97,40 @@ await app.game.finish({ score: 42 });
57
97
 
58
98
  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.
59
99
 
100
+ ## Listing in VibeStore
101
+
102
+ VibeStore is the app store inside VibeMarket OS. You submit from its **Submit** tab, and every version is reviewed by a person before it is listed. The requirements below are checked at submission. An app is listed with manifest schema version 2: version 1 plus two required objects.
103
+
104
+ ```json
105
+ {
106
+ "schemaVersion": 2, "sdkVersion": 1, "id": "my-app", "version": "1.0.0", "name": "My App", "tagline": "One line about it.",
107
+ "category": "vibexp-app", "entry": "index.html", "permissions": [], "collectionId": null,
108
+ "window": { "width": 960, "height": 600, "resizable": true },
109
+ "store": {
110
+ "icon": "store/icon.png", "screenshots": ["store/screenshot-1.webp"],
111
+ "description": "At least forty characters of plain text about the app.", "category": "game",
112
+ "rating": { "violence": "none", "language": "none", "mature": false }, "support": "https://example.com/help"
113
+ }
114
+ }
115
+ ```
116
+
117
+ | Field | Requirement |
118
+ |---|---|
119
+ | `window` | `width` 320 to 1600 and `height` 200 to 1200 whole CSS pixels, `resizable` true or false. The window opens at this size. |
120
+ | `store.icon` | A `.png` file in the bundle, exactly 256 x 256 pixels and at most 256 KiB. |
121
+ | `store.screenshots` | 1 to 4 different `.png`, `.jpg`, `.jpeg` or `.webp` files in the bundle, none of them the icon, each at most 1 MiB, with contents that match the extension. |
122
+ | `store.description` | Plain text, 40 to 2,000 characters after trimming. Line breaks are allowed; other control characters are not. Shown as text, never as HTML. |
123
+ | `store.category` | `game`, `tool` or `toy`. |
124
+ | `store.rating` | `violence` and `language` each `none`, `mild` or `strong`, and `mature` true or false. Rate honestly. |
125
+ | `store.support` | An `https://` URL without a user name or password, or an email address, at most 200 characters. Players and reviewers see it. |
126
+
127
+ A version 2 bundle may not contain SVG files anywhere, because SVG is a document format that can carry script; use PNG or WebP. The bundle limits in [SECURITY.md](SECURITY.md) still apply, and the submitted ZIP is at most 20 MiB. Unknown fields are refused at every level. `os pack` and `os preview` run the same manifest and image checks, so a listing problem shows up locally first. To validate in your own tools, `@vibechain/os/manifest` exports `parseManifest` and the bounds, and `@vibechain/os/listing` exports `checkListing`, `pngSize` and `imageKind`, which work on plain `Uint8Array` bytes in Node or a browser.
128
+
129
+ `examples/paw-beat` is a complete version 2 listing.
130
+
60
131
  ## Publishing status
61
132
 
62
- This release supports local browser previews. Production app submissions and approval are not available yet. Installing the SDK does not list your app in VibeMarket OS. The app API does not grant native, inventory, payment or reward access. Existing Market games continue to use their separate permissioned API.
133
+ Publish by submitting your packed ZIP from the VibeStore **Submit** tab in VibeMarket OS; 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 does not grant native, inventory, payment or reward access. Existing Market games continue to use their separate permissioned API.
63
134
 
64
135
  See the [SDK docs](https://vibechain.com/os/docs) for the app API and [SECURITY.md](SECURITY.md) for the sandbox and resource limits.
65
136
 
@@ -70,7 +141,7 @@ pnpm install --frozen-lockfile
70
141
  pnpm review
71
142
  pnpm build
72
143
  pnpm check:package
73
- pnpm release:preview --version 0.2.1
144
+ pnpm release:preview --version 0.4.0
74
145
  ```
75
146
 
76
147
  `pnpm build` emits JavaScript/declarations plus one bundled preview host UI. Production publishing still requires a separate reviewed service and explicit activation. The existing local upload/publish/rollback commands retain their operator-token and loopback gates. Read [SECURITY.md](SECURITY.md) before integrating any untrusted app.
package/SECURITY.md CHANGED
@@ -1,10 +1,28 @@
1
1
  # VibeMarket OS app security and resource contract
2
2
 
3
- This is a bounded local browser development adapter, not a certification that arbitrary web code is safe. It grants no host identity or economy access. Native support and public app publication remain disabled.
3
+ These are bounded browser host controls, not a certification that arbitrary web code is safe. They grant no host identity or economy access. Native shells are refused. Store submission and review are checked by the VibeStore service, not by this package, and are not described here as open.
4
+
5
+ ## Host admission
6
+
7
+ `appRuntimeRefusal` decides whether a window may mount an app frame at all; `mountAppFrame` refuses to start without it. It admits exactly two kinds of host, both as the top-level window:
8
+
9
+ | Host | Admitted |
10
+ |---|---|
11
+ | Local developer preview | `http://127.0.0.1` or `http://localhost`, any port |
12
+ | VibeMarket OS website | `https://vibechain.com` or `https://www.vibechain.com`, default port only |
13
+
14
+ Every other origin is refused, including other `https` hosts and subdomains, plain `http` to the production names and any explicit port on them. A framed host is refused. Known native bridge markers (`__VM_STEAM__`, `__TAURI_INTERNALS__`, `__TAURI__`, `vibeNative`, `ReactNativeWebView`) and embedded user agents (Tauri, Electron, VibeSteam, VibeMarketDesktop, Android `wv`) are refused on every host. Admission is a refusal policy: the absence of a marker does not certify an unknown webview.
15
+
16
+ ## Runtime origins
17
+
18
+ - **Local preview.** `os preview` serves the parent page from `127.0.0.1` and the app from a different host, `localhost`, on the same port.
19
+ - **vibechain.com.** Apps are served by the website on the same origin as the desktop, under `/os/runtime/external/<appId>/<versionKey>/<file>`, where `versionKey` names one immutable version. There is no separate app domain. On the same origin exactly one thing keeps an app's HTML from running as `vibechain.com` with the player's session: the sandbox, which gives the document an opaque origin. The website's runtime route is therefore required to send `Content-Security-Policy: sandbox allow-scripts` on every response under that path, to serve HTML only to frame requests, to answer errors as plain text, to use fixed content types with `nosniff`, and to ignore and never set cookies. Those controls live in the website, not in this package, and this package cannot enforce them. What remains after them: browsers may run an app in the same process as the desktop, and the protection depends on those headers being right on every response. A separate registrable domain would be stronger; moving to one later is a routing change.
20
+
21
+ `mountAppFrame` accepts the bootstrap only from its own frame's window with origin `null`, on both hosts. If a response ever arrived without the sandbox, the app would not be able to connect to the host, but its code would already have run with the site's origin; the connection check is not a substitute for the header.
4
22
 
5
23
  ## Boundary
6
24
 
7
- - App code executes in a distinct host's iframe, `sandbox="allow-scripts"`, without `allow-same-origin`, top navigation, popups, forms or downloads. Runtime HTTP CSP also carries `sandbox allow-scripts`, including direct visits. The host checks its browser/native policy before creating a frame. Never inject third-party JavaScript into the desktop React realm or a privileged native webview.
25
+ - App code executes in an iframe with `sandbox="allow-scripts"`, without `allow-same-origin`, top navigation, popups, forms or downloads. Runtime HTTP CSP also carries `sandbox allow-scripts`, including direct visits. The host checks its browser/native policy before creating a frame. Never inject third-party JavaScript into the desktop React realm or a privileged native webview.
8
26
  - Admission binds the exact iframe WindowProxy, opaque origin `null`, one unpredictable 128-bit URL challenge, then a private MessagePort with a fresh 128-bit session. `null` is not an identity by itself. Bootstrap is ≤256-byte JSON and ≤32 messages from that child; unrelated windows receive no port. The global listener is removed after connection.
9
27
  - 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.
10
28
  - Close, navigation, minimize, app focus loss, hidden document, identity or package change revoke the active generation. Minimize/focus loss preserves only the same app's host-accepted bounded checkpoint. Restore creates a fresh iframe, challenge and session. Host focus uses desktop policy, not the browser `blur` event caused by focusing the child itself.
@@ -23,6 +41,7 @@ This is a bounded local browser development adapter, not a certification that ar
23
41
  | Absolute controller lifetime / readiness | 15minutes across suspension and remounts /15seconds |
24
42
  | App-side request wait | 10seconds |
25
43
  | Built bundle | Existing256 total entries, 16MiB/file, 64MiB expanded; ZIP20MiB |
44
+ | Schema version 2 bundle | No SVG files; store icon a 256 x 256 PNG ≤256KiB; 1–4 screenshots ≤1MiB each, signature matching the extension |
26
45
  | First Desk adapter | One open third-party app controller and at most one untrusted iframe |
27
46
 
28
47
  The local preview snapshots admitted files once using bounded no-follow file-handle reads, then serves only that immutable in-memory map and exact fixed host assets. It has no URL proxy, arbitrary filesystem route, write route or credential. Local filesystem authoring is not the public upload trust boundary; the existing ZIP validator remains responsible for untrusted uploads. The preview requires `127.0.0.1` for the parent and a different `localhost` runtime host, validates Host headers, never auto-opens a browser, and closes owned connections on shutdown.
@@ -33,4 +52,4 @@ The browser allocates structured-clone data before host validation. Message byte
33
52
 
34
53
  CSP restricts fetches, assets, workers and embedding, but does not universally prevent a sandboxed app navigating its own frame to an external URL. Navigation revokes the session after load; a request may already have occurred. Do not describe this as a network firewall or supply secrets that require one. Known native bridge markers and embedded user agents are denied; their absence does not certify unknown webviews. Actual native IPC provenance tests are required before native admission.
35
54
 
36
- Public activation requires a separately controlled registrable runtime domain, immutable pinned package and asset digests, publisher authentication/review, explicit permissions, revocation/kill switch, atomic update/rollback, network/abuse budgets, account/install scope and adversarial tests. Scores/checkpoints are untrusted client claims. Rewards, inventory grants and payments require separate server-authoritative, replay-safe, idempotent and capped verification; they are not implemented by this app API.
55
+ Listing third-party apps relies on controls outside this package: publisher authentication, employee review of every version, immutable version digests, revocation, network and abuse budgets, install scope and adversarial tests. The listing checks in this package (`parseManifest`, `checkListing`, the SVG refusal) validate a bundle's shape; they do not review its behaviour. Scores/checkpoints are untrusted client claims. Rewards, inventory grants and payments require separate server-authoritative, replay-safe, idempotent and capped verification; they are not implemented by this app API.
@@ -1,2 +1,2 @@
1
- /** Admission policy for the local browser adapter; marker absence is not native certification. */
1
+ /** Admission policy for browser hosts; marker absence is not native certification. */
2
2
  export declare function appRuntimeRefusal(host: Window): string | null;
@@ -1,7 +1,15 @@
1
- /** Admission policy for the local browser adapter; marker absence is not native certification. */
1
+ const LOCAL_HOSTS = ["127.0.0.1", "localhost"];
2
+ const PRODUCTION_HOSTS = ["vibechain.com", "www.vibechain.com"];
3
+ /** The local developer preview over http on any port, or the VibeMarket OS website over https on its default port. */
4
+ function admittedHost({ protocol, hostname, port }) {
5
+ if (protocol === "http:")
6
+ return LOCAL_HOSTS.includes(hostname);
7
+ return protocol === "https:" && PRODUCTION_HOSTS.includes(hostname) && port === "";
8
+ }
9
+ /** Admission policy for browser hosts; marker absence is not native certification. */
2
10
  export function appRuntimeRefusal(host) {
3
- if (host.location.protocol !== "http:" || !["127.0.0.1", "localhost"].includes(host.location.hostname))
4
- return "Third-party apps are available only in the local browser developer preview.";
11
+ if (!admittedHost(host.location))
12
+ return "Third-party apps are available only on vibechain.com and in the local browser developer preview.";
5
13
  if (host.top !== host.self)
6
14
  return "Third-party apps require a top-level browser host.";
7
15
  if (["__VM_STEAM__", "__TAURI_INTERNALS__", "__TAURI__", "vibeNative", "ReactNativeWebView"].some(key => key in host)
package/dist/bundle.js CHANGED
@@ -3,6 +3,7 @@ import { lstat, open, opendir, realpath } from "node:fs/promises";
3
3
  import { constants } from "node:fs";
4
4
  import path from "node:path";
5
5
  import { assetPath, GAME_LIMITS, parseManifest } from "./manifest.js";
6
+ import { checkListing } from "./listing.js";
6
7
  const TYPES = {
7
8
  html: "text/html; charset=utf-8", js: "text/javascript; charset=utf-8", mjs: "text/javascript; charset=utf-8",
8
9
  css: "text/css; charset=utf-8", json: "application/json", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg",
@@ -74,6 +75,15 @@ export async function readBuiltBundle(directory) {
74
75
  const manifest = parseManifest(JSON.parse(new TextDecoder().decode(input)));
75
76
  if (!files[manifest.entry])
76
77
  throw Error("Manifest entry is missing from the app bundle.");
78
+ if (manifest.schemaVersion === 2) {
79
+ // SVG is a document format that can carry script; schema version 2 bundles are served by the store runtime.
80
+ const svg = Object.keys(files).sort(compareAssetNames).find(file => assetType(file) === TYPES.svg);
81
+ if (svg)
82
+ throw Error(`Schema version 2 apps cannot contain SVG files; convert ${svg} to PNG or WebP.`);
83
+ const listing = checkListing(manifest, files);
84
+ if (!listing.ok)
85
+ throw Error(`Store listing (${listing.code}): ${listing.message}`);
86
+ }
77
87
  files["vibemarket.json"] = new TextEncoder().encode(JSON.stringify(manifest));
78
88
  const digest = createHash("sha256");
79
89
  for (const [file, bytes] of Object.entries(files).sort(([a], [b]) => compareAssetNames(a, b)))
@@ -0,0 +1,40 @@
1
+ import type { LifecycleSource } from "./loop.ts";
2
+ export interface CanvasFit {
3
+ /** Backing-store size in device pixels. */
4
+ width: number;
5
+ height: number;
6
+ /** The pixel ratio actually applied, after both caps. */
7
+ pixelRatio: number;
8
+ }
9
+ export interface FitOptions {
10
+ /** Highest device pixel ratio to render at, 1 to 4. Default: 2. */
11
+ maxPixelRatio?: number;
12
+ /** Highest backing-store area in pixels; the ratio is lowered to fit. Default: 3840 x 2160. */
13
+ maxPixels?: number;
14
+ /** Called after the backing store changed size. Resize the viewport and camera here. */
15
+ onResize?(fit: Readonly<CanvasFit>): void;
16
+ /** WebGL context was lost. Stop drawing; GPU resources are gone. */
17
+ onContextLost?(): void;
18
+ /** WebGL context is back. Recreate GPU resources. */
19
+ onContextRestored?(): void;
20
+ }
21
+ export interface FitTarget {
22
+ width: number;
23
+ height: number;
24
+ addEventListener(type: string, listener: (event: Event) => void): void;
25
+ removeEventListener(type: string, listener: (event: Event) => void): void;
26
+ }
27
+ export interface FittedCanvas {
28
+ /** The last applied size, or null until the host has reported a surface size. */
29
+ current(): Readonly<CanvasFit> | null;
30
+ stop(): void;
31
+ }
32
+ /**
33
+ * Keep a canvas backing store matched to the host surface, with the pixel ratio capped
34
+ * so a high-density display cannot multiply the fill cost. The canvas is resized (and so
35
+ * cleared) only when the computed size actually changes. Style the canvas to fill the
36
+ * app; this sets only its `width` and `height`.
37
+ */
38
+ export declare function fitCanvas(app: LifecycleSource, canvas: FitTarget, options?: FitOptions, view?: {
39
+ devicePixelRatio: number;
40
+ }): FittedCanvas;
package/dist/canvas.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Keep a canvas backing store matched to the host surface, with the pixel ratio capped
3
+ * so a high-density display cannot multiply the fill cost. The canvas is resized (and so
4
+ * cleared) only when the computed size actually changes. Style the canvas to fill the
5
+ * app; this sets only its `width` and `height`.
6
+ */
7
+ export function fitCanvas(app, canvas, options = {}, view = window) {
8
+ const maxRatio = options.maxPixelRatio ?? 2, maxPixels = options.maxPixels ?? 3840 * 2160;
9
+ if (!Number.isFinite(maxRatio) || maxRatio < 1 || maxRatio > 4)
10
+ throw Error("maxPixelRatio must be from 1 to 4.");
11
+ if (!Number.isInteger(maxPixels) || maxPixels < 1)
12
+ throw Error("maxPixels must be a positive integer.");
13
+ let fit = null;
14
+ const apply = (state) => {
15
+ if (state.width < 1 || state.height < 1)
16
+ return;
17
+ const device = Number.isFinite(view.devicePixelRatio) && view.devicePixelRatio >= 1 ? view.devicePixelRatio : 1;
18
+ const pixelRatio = Math.min(device, maxRatio, Math.sqrt(maxPixels / (state.width * state.height)));
19
+ const width = Math.max(1, Math.floor(state.width * pixelRatio)), height = Math.max(1, Math.floor(state.height * pixelRatio));
20
+ if (fit && fit.width === width && fit.height === height)
21
+ return;
22
+ canvas.width = width;
23
+ canvas.height = height;
24
+ fit = Object.freeze({ width, height, pixelRatio });
25
+ options.onResize?.(fit);
26
+ };
27
+ const lost = (event) => { event.preventDefault(); options.onContextLost?.(); };
28
+ const restored = () => { options.onContextRestored?.(); };
29
+ canvas.addEventListener("webglcontextlost", lost);
30
+ canvas.addEventListener("webglcontextrestored", restored);
31
+ const unsubscribe = app.lifecycle.onChanged(apply);
32
+ apply(app.lifecycle.current());
33
+ return {
34
+ current: () => fit,
35
+ stop() {
36
+ unsubscribe();
37
+ canvas.removeEventListener("webglcontextlost", lost);
38
+ canvas.removeEventListener("webglcontextrestored", restored);
39
+ },
40
+ };
41
+ }
@@ -0,0 +1,35 @@
1
+ import { type AppManifestV2 } from "./manifest.ts";
2
+ /**
3
+ * Byte checks for a schema version 2 store listing. Pure functions over `Uint8Array` with no Node or DOM
4
+ * dependency, so the same rules run in the CLI, a server and a browser.
5
+ */
6
+ export type ImageKind = "png" | "jpeg" | "webp";
7
+ export interface ImageSize {
8
+ width: number;
9
+ height: number;
10
+ }
11
+ /** The `StoreSubmitCode` values a listing check can produce. */
12
+ export type ListingErrorCode = "missing-icon" | "bad-icon" | "bad-screenshot";
13
+ export interface ListingError {
14
+ ok: false;
15
+ code: ListingErrorCode;
16
+ message: string;
17
+ detail: string;
18
+ }
19
+ export type ListingResult = {
20
+ ok: true;
21
+ } | ListingError;
22
+ /**
23
+ * Width and height of a PNG from its first chunk, or null. Checks the 8-byte signature, that the first chunk is
24
+ * `IHDR` with length 13 and present in full, and that both dimensions are 1 to 2^31-1 as the PNG format requires.
25
+ * Nothing else in the file is read or trusted; this is not a decoder.
26
+ */
27
+ export declare function pngSize(bytes: Uint8Array): ImageSize | null;
28
+ /** The image format named by a file's magic bytes, or null. */
29
+ export declare function imageKind(bytes: Uint8Array): ImageKind | null;
30
+ /**
31
+ * Checks the icon and screenshots a v2 manifest names against the bundle's files: the icon exists, is a PNG of
32
+ * exactly 256 x 256 pixels and at most 256 KiB; each screenshot exists, is at most 1 MiB and its signature matches
33
+ * its extension. `detail` is the offending path. Assumes `manifest` came from `parseManifest`.
34
+ */
35
+ export declare function checkListing(manifest: AppManifestV2, files: Readonly<Record<string, Uint8Array>>): ListingResult;
@@ -0,0 +1,56 @@
1
+ import { APP_STORE_LIMITS } from "./manifest.js";
2
+ const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
3
+ const IHDR = [0x49, 0x48, 0x44, 0x52];
4
+ const startsWith = (bytes, prefix, offset = 0) => bytes.length >= offset + prefix.length && prefix.every((value, i) => bytes[offset + i] === value);
5
+ const uint32 = (bytes, offset) => ((bytes[offset] << 24) >>> 0) + (bytes[offset + 1] << 16) + (bytes[offset + 2] << 8) + bytes[offset + 3];
6
+ /**
7
+ * Width and height of a PNG from its first chunk, or null. Checks the 8-byte signature, that the first chunk is
8
+ * `IHDR` with length 13 and present in full, and that both dimensions are 1 to 2^31-1 as the PNG format requires.
9
+ * Nothing else in the file is read or trusted; this is not a decoder.
10
+ */
11
+ export function pngSize(bytes) {
12
+ if (bytes.length < 8 + 8 + 13 || !startsWith(bytes, PNG) || uint32(bytes, 8) !== 13 || !startsWith(bytes, IHDR, 12))
13
+ return null;
14
+ const width = uint32(bytes, 16), height = uint32(bytes, 20);
15
+ return width > 0 && height > 0 && width <= 0x7fffffff && height <= 0x7fffffff ? { width, height } : null;
16
+ }
17
+ /** The image format named by a file's magic bytes, or null. */
18
+ export function imageKind(bytes) {
19
+ if (startsWith(bytes, PNG))
20
+ return "png";
21
+ if (startsWith(bytes, [0xff, 0xd8, 0xff]))
22
+ return "jpeg";
23
+ if (startsWith(bytes, [0x52, 0x49, 0x46, 0x46]) && startsWith(bytes, [0x57, 0x45, 0x42, 0x50], 8))
24
+ return "webp";
25
+ return null;
26
+ }
27
+ const KIND_BY_EXTENSION = { png: "png", jpg: "jpeg", jpeg: "jpeg", webp: "webp" };
28
+ const fail = (code, message, detail) => ({ ok: false, code, message, detail });
29
+ const KiB = 1024;
30
+ /**
31
+ * Checks the icon and screenshots a v2 manifest names against the bundle's files: the icon exists, is a PNG of
32
+ * exactly 256 x 256 pixels and at most 256 KiB; each screenshot exists, is at most 1 MiB and its signature matches
33
+ * its extension. `detail` is the offending path. Assumes `manifest` came from `parseManifest`.
34
+ */
35
+ export function checkListing(manifest, files) {
36
+ const limits = APP_STORE_LIMITS, file = (name) => Object.hasOwn(files, name) ? files[name] : undefined;
37
+ const { icon, screenshots } = manifest.store, iconBytes = file(icon);
38
+ if (!iconBytes)
39
+ return fail("missing-icon", `The store icon ${icon} is not in the app bundle.`, icon);
40
+ if (iconBytes.byteLength > limits.iconBytes)
41
+ return fail("bad-icon", `The store icon ${icon} is larger than ${limits.iconBytes / KiB} KiB.`, icon);
42
+ const size = pngSize(iconBytes);
43
+ if (!size || size.width !== limits.iconSize || size.height !== limits.iconSize)
44
+ return fail("bad-icon", `The store icon ${icon} must be a PNG of exactly ${limits.iconSize} x ${limits.iconSize} pixels.`, icon);
45
+ for (const shot of screenshots) {
46
+ const bytes = file(shot);
47
+ if (!bytes)
48
+ return fail("bad-screenshot", `The screenshot ${shot} is not in the app bundle.`, shot);
49
+ if (bytes.byteLength > limits.screenshotBytes)
50
+ return fail("bad-screenshot", `The screenshot ${shot} is larger than ${limits.screenshotBytes / KiB / KiB} MiB.`, shot);
51
+ const expected = KIND_BY_EXTENSION[shot.slice(shot.lastIndexOf(".") + 1)];
52
+ if (!expected || imageKind(bytes) !== expected)
53
+ return fail("bad-screenshot", `The screenshot ${shot} is not a ${expected ?? "supported"} image, or its contents do not match its extension.`, shot);
54
+ }
55
+ return { ok: true };
56
+ }
package/dist/loop.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import type { AppLifecycle } from "./app-protocol.ts";
2
+ /** The part of the app SDK the game helpers read. `connectVibeMarketApp()` satisfies it. */
3
+ export interface LifecycleSource {
4
+ lifecycle: {
5
+ current(): Readonly<AppLifecycle>;
6
+ onChanged(listener: (state: Readonly<AppLifecycle>) => void): () => void;
7
+ };
8
+ }
9
+ export interface LoopOptions {
10
+ /** Fixed simulation step in milliseconds, above 0 and at most 1000. Default: 1000 / 60. */
11
+ stepMs?: number;
12
+ /** Most simulation steps run in one frame after a stall, 1 to 240. Extra time is dropped. Default: 5. */
13
+ maxSteps?: number;
14
+ /** Advance the simulation by exactly `stepMs`. */
15
+ update(stepMs: number): void;
16
+ /** Draw once per frame. `alpha` (0 to 1) is how far the frame sits between two simulation steps. */
17
+ render(alpha: number): void;
18
+ }
19
+ export interface Loop {
20
+ /** True while a frame is scheduled: the app is active and the loop was not stopped. */
21
+ readonly running: boolean;
22
+ /** Stop for good and release the lifecycle listener. */
23
+ stop(): void;
24
+ }
25
+ export interface FrameClock {
26
+ requestAnimationFrame(callback: (time: number) => void): number;
27
+ cancelAnimationFrame(handle: number): void;
28
+ }
29
+ /**
30
+ * A fixed-timestep game loop that runs only while the host reports the app active.
31
+ * Time spent inactive is discarded rather than simulated on return. If `update` or
32
+ * `render` throws, the error propagates and the loop stays stopped.
33
+ */
34
+ export declare function createLoop(app: LifecycleSource, options: LoopOptions, clock?: FrameClock): Loop;
package/dist/loop.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * A fixed-timestep game loop that runs only while the host reports the app active.
3
+ * Time spent inactive is discarded rather than simulated on return. If `update` or
4
+ * `render` throws, the error propagates and the loop stays stopped.
5
+ */
6
+ export function createLoop(app, options, clock = window) {
7
+ const step = options.stepMs ?? 1000 / 60, maxSteps = options.maxSteps ?? 5;
8
+ if (!Number.isFinite(step) || step <= 0 || step > 1000)
9
+ throw Error("stepMs must be above 0 and at most 1000.");
10
+ if (!Number.isInteger(maxSteps) || maxSteps < 1 || maxSteps > 240)
11
+ throw Error("maxSteps must be an integer from 1 to 240.");
12
+ let frame, previous, accumulator = 0, stopped = false;
13
+ const pause = () => {
14
+ if (frame !== undefined)
15
+ clock.cancelAnimationFrame(frame);
16
+ frame = undefined;
17
+ previous = undefined;
18
+ };
19
+ const schedule = () => {
20
+ if (frame === undefined && !stopped && app.lifecycle.current().active)
21
+ frame = clock.requestAnimationFrame(tick);
22
+ };
23
+ const tick = (time) => {
24
+ frame = undefined;
25
+ if (previous !== undefined)
26
+ accumulator += Math.min(Math.max(time - previous, 0), step * maxSteps);
27
+ previous = time;
28
+ while (accumulator >= step) {
29
+ options.update(step);
30
+ accumulator -= step;
31
+ if (stopped)
32
+ return;
33
+ }
34
+ options.render(accumulator / step);
35
+ schedule();
36
+ };
37
+ const unsubscribe = app.lifecycle.onChanged(state => { if (state.active)
38
+ schedule();
39
+ else
40
+ pause(); });
41
+ schedule();
42
+ return {
43
+ get running() { return frame !== undefined; },
44
+ stop() { if (stopped)
45
+ return; stopped = true; pause(); unsubscribe(); },
46
+ };
47
+ }
@@ -1,6 +1,7 @@
1
1
  export declare const GAME_PERMISSIONS: readonly ["profile.get", "catalog.list", "inventory.get", "packs.buy", "packs.sell", "packs.open", "cards.reveal", "cards.sell", "cards.collect"];
2
2
  export type GamePermission = typeof GAME_PERMISSIONS[number];
3
- export interface GameManifest {
3
+ /** Schema version 1: Market games and VibeMarket OS apps without a store listing. */
4
+ export interface GameManifestV1 {
4
5
  schemaVersion: 1;
5
6
  sdkVersion: 1;
6
7
  id: string;
@@ -12,6 +13,71 @@ export interface GameManifest {
12
13
  permissions: GamePermission[];
13
14
  collectionId: string | null;
14
15
  }
16
+ /** VibeStore listing categories. */
17
+ export declare const APP_STORE_CATEGORIES: readonly ["game", "tool", "toy"];
18
+ export type AppStoreCategory = typeof APP_STORE_CATEGORIES[number];
19
+ /** Content rating levels for `store.rating.violence` and `store.rating.language`. */
20
+ export declare const APP_CONTENT_RATINGS: readonly ["none", "mild", "strong"];
21
+ export type AppContentRating = typeof APP_CONTENT_RATINGS[number];
22
+ /** Screenshot file extensions a listing may name (lowercase). */
23
+ export declare const APP_SCREENSHOT_EXTENSIONS: readonly ["png", "jpg", "jpeg", "webp"];
24
+ export type AppScreenshotExtension = typeof APP_SCREENSHOT_EXTENSIONS[number];
25
+ /** Window size bounds in CSS pixels, inclusive. */
26
+ export declare const APP_WINDOW_LIMITS: {
27
+ readonly minWidth: 320;
28
+ readonly maxWidth: 1600;
29
+ readonly minHeight: 200;
30
+ readonly maxHeight: 1200;
31
+ };
32
+ /**
33
+ * Listing bounds, inclusive. Description length counts Unicode code points after trimming.
34
+ * The icon and screenshot byte limits are checked on bundle bytes by `checkListing` in `@vibechain/os/listing`.
35
+ */
36
+ export declare const APP_STORE_LIMITS: {
37
+ readonly descriptionMin: 40;
38
+ readonly descriptionMax: 2000;
39
+ readonly supportMax: 200;
40
+ readonly screenshotsMin: 1;
41
+ readonly screenshotsMax: 4;
42
+ readonly iconSize: 256;
43
+ readonly iconBytes: number;
44
+ readonly screenshotBytes: number;
45
+ };
46
+ export interface AppWindow {
47
+ width: number;
48
+ height: number;
49
+ resizable: boolean;
50
+ }
51
+ export interface AppContentRatingSet {
52
+ violence: AppContentRating;
53
+ language: AppContentRating;
54
+ mature: boolean;
55
+ }
56
+ export interface AppStoreListing {
57
+ icon: string;
58
+ screenshots: string[];
59
+ description: string;
60
+ category: AppStoreCategory;
61
+ rating: AppContentRatingSet;
62
+ support: string;
63
+ }
64
+ /** Schema version 2: a VibeMarket OS app with a VibeStore listing. */
65
+ export interface AppManifestV2 {
66
+ schemaVersion: 2;
67
+ sdkVersion: 1;
68
+ id: string;
69
+ version: string;
70
+ name: string;
71
+ tagline: string;
72
+ category: "vibexp-app";
73
+ entry: string;
74
+ permissions: [];
75
+ collectionId: null;
76
+ window: AppWindow;
77
+ store: AppStoreListing;
78
+ }
79
+ /** Every manifest `parseManifest` admits, discriminated on `schemaVersion`. */
80
+ export type GameManifest = GameManifestV1 | AppManifestV2;
15
81
  export declare const GAME_LIMITS: {
16
82
  readonly archive: number;
17
83
  readonly expanded: number;
@@ -21,4 +87,7 @@ export declare const GAME_LIMITS: {
21
87
  readonly games: 40;
22
88
  };
23
89
  export declare function assetPath(value: string): boolean;
90
+ /** An `https://` URL without credentials, or a plausible email address. Exported for forms that validate as the parser does. */
91
+ export declare function supportContact(value: string): boolean;
92
+ /** Accepts schema version 1 exactly as before and schema version 2 with its window and store listing. Unknown fields are rejected at every level. */
24
93
  export declare function parseManifest(input: unknown): GameManifest;