@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.
- package/AGENTS.md +15 -6
- package/README.md +35 -10
- package/SECURITY.md +3 -1
- package/dist/app-client.js +20 -4
- package/dist/app-host.d.ts +12 -2
- package/dist/app-host.js +12 -2
- package/dist/app-protocol.d.ts +21 -0
- package/dist/app-protocol.js +9 -0
- package/dist/audio.d.ts +65 -0
- package/dist/audio.js +162 -0
- package/dist/browser.d.ts +1 -0
- package/dist/browser.js +1 -0
- package/dist/bundle.d.ts +2 -0
- package/dist/bundle.js +2 -0
- package/dist/cli.js +3 -1
- package/dist/commands.d.ts +6 -0
- package/dist/commands.js +17 -0
- package/dist/index.d.ts +2 -2
- package/dist/links.d.ts +6 -0
- package/dist/links.js +2 -0
- package/dist/os.d.ts +20 -2
- package/dist/os.js +30 -5
- package/dist/preview-parent.js +15 -2
- package/dist/preview-ui.js +1 -1
- package/dist/preview.js +1 -1
- package/dist/templates/plain/game.js +3 -1
- package/dist/testing.d.ts +9 -1
- package/dist/testing.js +27 -6
- package/dist/vibemarket-os.js +1 -1
- package/examples/paw-beat/README.md +28 -9
- package/examples/paw-beat/game.ts +280 -123
- package/examples/paw-beat/index.html +18 -4
- package/examples/paw-beat/main.ts +101 -44
- package/examples/paw-beat/music.ts +72 -337
- package/examples/paw-beat/stage.ts +23 -9
- package/examples/paw-beat/store/screenshot-1.webp +0 -0
- package/examples/paw-beat/store/screenshot-2.webp +0 -0
- package/examples/paw-beat/synth.ts +477 -0
- package/examples/paw-beat/tracks.ts +286 -0
- package/examples/paw-beat/vibemarket.json +2 -2
- package/examples/vibexp-app/plain/game.ts +6 -2
- package/package.json +7 -1
- package/skill.md +399 -0
package/dist/browser.js
CHANGED
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. */
|
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
|
-
|
|
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");
|
package/dist/commands.js
ADDED
|
@@ -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,7 +2,7 @@ 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
6
|
export type { CaptureResult } from "./capture.ts";
|
|
7
7
|
export { spawnWorker } from "./worker.ts";
|
|
8
8
|
export { cardLink, packLink, parseVmosLink, VMOS_LINK_MAX } from "./links.ts";
|
|
@@ -12,6 +12,6 @@ export type { SpawnedWorker, WorkerHost } from "./worker.ts";
|
|
|
12
12
|
export { connectVibeMarketApp } from "./app-client.ts";
|
|
13
13
|
export { GAME_SCORE_LIMIT } from "./completion.ts";
|
|
14
14
|
export type { GameFinishInput } from "./completion.ts";
|
|
15
|
-
export type { AppValue, AppLifecycle, VibeMarketAppSdk } from "./app-protocol.ts";
|
|
15
|
+
export type { AppValue, AppLifecycle, AppSound, VibeMarketAppSdk } from "./app-protocol.ts";
|
|
16
16
|
export type { InventoryObserver } from "./inventory.ts";
|
|
17
17
|
export type * from "./types.ts";
|
package/dist/links.d.ts
CHANGED
|
@@ -7,6 +7,12 @@ export type VmosLink = {
|
|
|
7
7
|
card: string;
|
|
8
8
|
};
|
|
9
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
|
+
}>;
|
|
10
16
|
/** The target a link names, or null when it is not exactly one of the three forms. */
|
|
11
17
|
export declare function parseVmosLink(text: unknown): VmosLink | null;
|
|
12
18
|
/** `vmos://pack/<slug>`; throws an OsError `invalid` for a value that is not a pack slug. */
|
package/dist/links.js
CHANGED
|
@@ -17,6 +17,8 @@ const SLUG = "[a-z0-9]+(?:-[a-z0-9]+)*", CARD = "[A-Za-z0-9_-]{1,64}";
|
|
|
17
17
|
const PACK_LINK = new RegExp(`^vmos://pack/(${SLUG})$`);
|
|
18
18
|
const CARD_LINK = new RegExp(`^vmos://card/(${SLUG})/(${CARD})$`);
|
|
19
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 });
|
|
20
22
|
/** The target a link names, or null when it is not exactly one of the three forms. */
|
|
21
23
|
export function parseVmosLink(text) {
|
|
22
24
|
if (typeof text !== "string" || text.length > VMOS_LINK_MAX)
|
package/dist/os.d.ts
CHANGED
|
@@ -1,20 +1,34 @@
|
|
|
1
|
-
|
|
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";
|
|
7
|
+
import { type Card, type OsErrorCode, type Pack, type PackSummary, type Player } from "./app-wire.ts";
|
|
2
8
|
import { type CaptureResult } from "./capture.ts";
|
|
3
9
|
export type { Card, OsErrorCode, Pack, PackCard, PackSummary, Player, Rarity, SignedInPlayer } from "./app-wire.ts";
|
|
4
10
|
export { OS_ERROR_CODES } from "./app-wire.ts";
|
|
5
11
|
/** The SDK version a 0.5 client reports in `host.hello`. */
|
|
6
|
-
export declare const OS_SDK_VERSION = "0.5.
|
|
12
|
+
export declare const OS_SDK_VERSION = "0.5.2";
|
|
7
13
|
export { OsError } from "./app-wire.ts";
|
|
8
14
|
export type OsSize = Readonly<{
|
|
9
15
|
width: number;
|
|
10
16
|
height: number;
|
|
11
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>;
|
|
12
20
|
export interface Os {
|
|
13
21
|
/** false while the window is minimized or behind another window */
|
|
14
22
|
readonly active: boolean;
|
|
15
23
|
readonly size: OsSize;
|
|
16
24
|
/** a guest's save lives only while the window is open */
|
|
17
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;
|
|
18
32
|
/** hide the host's loading screen */
|
|
19
33
|
ready(): Promise<void>;
|
|
20
34
|
/** 0 to 1 while loading; keeps a long load inside the host's readiness rule */
|
|
@@ -46,6 +60,8 @@ export interface Os {
|
|
|
46
60
|
onPause(listener: () => void): () => void;
|
|
47
61
|
onResume(listener: () => void): () => void;
|
|
48
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;
|
|
49
65
|
/**
|
|
50
66
|
* The desktop camera asks for a picture of the app. By default the SDK sends the largest visible canvas; register a handler
|
|
51
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
|
|
@@ -55,6 +71,8 @@ export interface Os {
|
|
|
55
71
|
/** release the port */
|
|
56
72
|
close(): void;
|
|
57
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>>;
|
|
58
76
|
/** Connect to the host: the handshake, then hello on a protocol 2 host. Call once, early. */
|
|
59
77
|
export declare function connect(options?: {
|
|
60
78
|
signal?: AbortSignal;
|
package/dist/os.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* says hello and every method works; on an older host `ready`, `finish`, lifecycle, `load` and `save` work (saves use the
|
|
4
4
|
* window-only checkpoint) and the rest reject with `unsupported`. Every rejection is an OsError with a stable code.
|
|
5
5
|
*/
|
|
6
|
-
import { APP_FRAGMENT, APP_LIMITS, appNonce, checkpointJson, lifecycleValue } from "./app-protocol.js";
|
|
6
|
+
import { APP_FRAGMENT, APP_LIMITS, AUDIBLE, appNonce, checkpointJson, lifecycleValue, soundValue } from "./app-protocol.js";
|
|
7
7
|
import { APP_SESSION_LIMITS, AppHostError, CARD_ID, OsError, osErrorCode, saveJson, saveValue, wireCard, wireCardsEvent, wireHello, wirePack, wirePackSummary, wirePlayer, } from "./app-wire.js";
|
|
8
8
|
import { createCapturer } from "./capture.js";
|
|
9
9
|
import { gameFinishInput } from "./completion.js";
|
|
@@ -12,9 +12,10 @@ import { connectHostPort, createRpcTransport } from "./transport.js";
|
|
|
12
12
|
import { parseVmosLink } from "./links.js";
|
|
13
13
|
export { OS_ERROR_CODES } from "./app-wire.js";
|
|
14
14
|
/** The SDK version a 0.5 client reports in `host.hello`. */
|
|
15
|
-
export const OS_SDK_VERSION = "0.5.
|
|
15
|
+
export const OS_SDK_VERSION = "0.5.2";
|
|
16
16
|
export { OsError } from "./app-wire.js";
|
|
17
|
-
|
|
17
|
+
/** What each code means, as the SDK's own rejections say it (also the agent skill's error table). */
|
|
18
|
+
export const OS_ERROR_MESSAGES = Object.freeze({
|
|
18
19
|
unsupported: "This host is older than this SDK and has no such feature.",
|
|
19
20
|
"not-permitted": "The manifest does not declare that, or the app is behind another window.",
|
|
20
21
|
invalid: "That argument is not valid.",
|
|
@@ -24,7 +25,8 @@ const MESSAGES = {
|
|
|
24
25
|
unavailable: "The host could not answer now; try again.",
|
|
25
26
|
timeout: "The host did not answer in 10 seconds.",
|
|
26
27
|
closed: "The session ended. Reopen the app.",
|
|
27
|
-
};
|
|
28
|
+
});
|
|
29
|
+
const MESSAGES = OS_ERROR_MESSAGES;
|
|
28
30
|
const fail = (code, message = MESSAGES[code]) => new OsError(code, message);
|
|
29
31
|
/** Errors the SDK raises itself keep their code; anything else is `invalid` (an argument) unless said otherwise. */
|
|
30
32
|
const asOsError = (error, fallback) => error instanceof OsError ? error
|
|
@@ -50,8 +52,9 @@ export async function connect(options = {}) {
|
|
|
50
52
|
export async function createOs(port, session, protocol, href) {
|
|
51
53
|
if (!appNonce(session))
|
|
52
54
|
throw fail("unavailable", "Invalid app session.");
|
|
53
|
-
let state = Object.freeze({ active: true, width: 0, height: 0 }), closed = false;
|
|
55
|
+
let state = Object.freeze({ active: true, width: 0, height: 0 }), closed = false, sound = AUDIBLE;
|
|
54
56
|
const pause = new Set(), resume = new Set(), resize = new Set(), watchers = new Set();
|
|
57
|
+
const sounds = new Set();
|
|
55
58
|
const transport = createRpcTransport(port, {
|
|
56
59
|
session, timeoutMs: APP_LIMITS.requestTimeoutMs,
|
|
57
60
|
maxPending: protocol === 2 ? 64 : APP_LIMITS.inFlight, jsonBytes: protocol === 2 ? APP_SESSION_LIMITS.messageBytes : APP_LIMITS.responseBytes,
|
|
@@ -69,6 +72,10 @@ export async function createOs(port, session, protocol, href) {
|
|
|
69
72
|
capturer.event(value.id);
|
|
70
73
|
return;
|
|
71
74
|
}
|
|
75
|
+
if (value.event === "app.sound") {
|
|
76
|
+
soundEvent(value.state);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
72
79
|
if (value.event !== "app.lifecycle")
|
|
73
80
|
return;
|
|
74
81
|
let next;
|
|
@@ -100,6 +107,21 @@ export async function createOs(port, session, protocol, href) {
|
|
|
100
107
|
throw fail("unavailable", "Invalid host response.");
|
|
101
108
|
return result;
|
|
102
109
|
};
|
|
110
|
+
/** Declared ahead so the transport can call it: a valid, changed state is kept and told to every listener. */
|
|
111
|
+
function soundEvent(value) {
|
|
112
|
+
let next;
|
|
113
|
+
try {
|
|
114
|
+
next = soundValue(value);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (next.muted === sound.muted && next.volume === sound.volume)
|
|
120
|
+
return;
|
|
121
|
+
sound = next;
|
|
122
|
+
for (const listener of [...sounds])
|
|
123
|
+
listener(sound);
|
|
124
|
+
}
|
|
103
125
|
const completed = (result) => { if (result.completed !== true)
|
|
104
126
|
throw fail("unavailable", "Invalid host acknowledgement."); };
|
|
105
127
|
let hello = null;
|
|
@@ -225,6 +247,7 @@ export async function createOs(port, session, protocol, href) {
|
|
|
225
247
|
get active() { return state.active; },
|
|
226
248
|
get size() { return Object.freeze({ width: state.width, height: state.height }); },
|
|
227
249
|
get guest() { return hello?.guest ?? false; },
|
|
250
|
+
get sound() { return sound; },
|
|
228
251
|
async ready() { completed(await call({ method: "ui.ready" })); },
|
|
229
252
|
progress(fraction) {
|
|
230
253
|
if (typeof fraction !== "number" || !Number.isFinite(fraction) || fraction < 0 || fraction > 1)
|
|
@@ -346,6 +369,7 @@ export async function createOs(port, session, protocol, href) {
|
|
|
346
369
|
return capturer.on(handler);
|
|
347
370
|
},
|
|
348
371
|
onResize(listener) { resize.add(listener); return () => { resize.delete(listener); }; },
|
|
372
|
+
onSound(listener) { sounds.add(listener); return () => { sounds.delete(listener); }; },
|
|
349
373
|
close() {
|
|
350
374
|
if (closed)
|
|
351
375
|
return;
|
|
@@ -360,6 +384,7 @@ export async function createOs(port, session, protocol, href) {
|
|
|
360
384
|
pause.clear();
|
|
361
385
|
resume.clear();
|
|
362
386
|
resize.clear();
|
|
387
|
+
sounds.clear();
|
|
363
388
|
watchers.clear();
|
|
364
389
|
transport.destroy();
|
|
365
390
|
},
|
package/dist/preview-parent.js
CHANGED
|
@@ -90,8 +90,10 @@ export async function startPreviewParent() {
|
|
|
90
90
|
if (refusal)
|
|
91
91
|
throw Error(refusal);
|
|
92
92
|
const surface = document.getElementById("surface"), status = document.getElementById("status"), toggle = document.getElementById("toggle"), reset = document.getElementById("reset"), pull = document.getElementById("pull");
|
|
93
|
+
const speaker = document.getElementById("sound"), volume = document.getElementById("volume");
|
|
93
94
|
const result = document.getElementById("result"), score = document.getElementById("score");
|
|
94
|
-
if (!surface || !status || !result || !score || !(toggle instanceof HTMLButtonElement) || !(reset instanceof HTMLButtonElement) || !(pull instanceof HTMLButtonElement)
|
|
95
|
+
if (!surface || !status || !result || !score || !(toggle instanceof HTMLButtonElement) || !(reset instanceof HTMLButtonElement) || !(pull instanceof HTMLButtonElement)
|
|
96
|
+
|| !(speaker instanceof HTMLButtonElement) || !(volume instanceof HTMLInputElement))
|
|
95
97
|
throw Error("Preview controls are missing.");
|
|
96
98
|
const meta = previewMetadata(await (await fetch("/preview.json", { credentials: "omit" })).json());
|
|
97
99
|
const runtime = new URL(meta.runtime);
|
|
@@ -129,6 +131,8 @@ export async function startPreviewParent() {
|
|
|
129
131
|
let controller = owner(), frame = null;
|
|
130
132
|
let mounted = null, observer = null, minimized = false;
|
|
131
133
|
let completion = null;
|
|
134
|
+
// the desktop's sound, as the taskbar speaker and volume would set it: the app must follow it (createAudio does)
|
|
135
|
+
let sound = { muted: false, volume: 1 };
|
|
132
136
|
const detach = () => { mounted?.dispose(); mounted = null; controller.suspend(); observer?.disconnect(); observer = null; frame?.remove(); frame = null; };
|
|
133
137
|
const draw = () => {
|
|
134
138
|
detach();
|
|
@@ -155,7 +159,7 @@ export async function startPreviewParent() {
|
|
|
155
159
|
frame.referrerPolicy = "no-referrer";
|
|
156
160
|
frame.src = source.href;
|
|
157
161
|
surface.appendChild(frame);
|
|
158
|
-
mounted = mountAppFrame(frame, { controller, challenge, current: () => !minimized && !document.hidden,
|
|
162
|
+
mounted = mountAppFrame(frame, { controller, challenge, sound, current: () => !minimized && !document.hidden,
|
|
159
163
|
ready: () => { status.textContent = "App ready · Minimize and restore to check its saved work."; },
|
|
160
164
|
progress: fraction => { status.textContent = `Loading the isolated app… ${Math.round(fraction * 100)}%`; },
|
|
161
165
|
finish: value => { completion = value; reset.textContent = "Play again"; draw(); },
|
|
@@ -168,6 +172,15 @@ export async function startPreviewParent() {
|
|
|
168
172
|
};
|
|
169
173
|
toggle.onclick = () => { minimized = !minimized; toggle.textContent = minimized ? "Restore" : "Minimize"; draw(); };
|
|
170
174
|
reset.onclick = () => { detach(); controller.dispose(); controller = owner(); completion = null; minimized = false; toggle.textContent = "Minimize"; reset.textContent = "Close / reset"; draw(); };
|
|
175
|
+
const setSound = (next) => {
|
|
176
|
+
sound = next;
|
|
177
|
+
mounted?.setSound(sound);
|
|
178
|
+
speaker.textContent = sound.muted ? "Sound off" : "Sound on";
|
|
179
|
+
speaker.setAttribute("aria-pressed", String(!sound.muted));
|
|
180
|
+
status.textContent = sound.muted ? "Desktop sound off: the app must be silent." : `Desktop sound on at ${Math.round(sound.volume * 100)}%: the app follows this volume.`;
|
|
181
|
+
};
|
|
182
|
+
speaker.onclick = () => setSound({ muted: !sound.muted, volume: sound.volume });
|
|
183
|
+
volume.oninput = () => setSound({ muted: sound.muted, volume: Math.min(1, Math.max(0, Number(volume.value) / 100)) });
|
|
171
184
|
pull.onclick = () => {
|
|
172
185
|
const name = catalog.pull();
|
|
173
186
|
status.textContent = name ? `Pulled ${name}. The app hears about it through onCards.` : "This app links no packs and does not read all cards, so there is nothing to pull.";
|
package/dist/preview-ui.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Me="vibemarket.game.v1";var gt=["127.0.0.1","localhost"],ft=["vibechain.com","www.vibechain.com"],yt=["__VM_STEAM__","__TAURI_INTERNALS__"],Je=["__TAURI__","vibeNative","ReactNativeWebView"],wt=/\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i,kt="Third-party apps are available only on vibechain.com and in the local browser developer preview.",bt="Third-party apps require a top-level browser host.",At="Third-party apps are disabled in native shells until their IPC isolation is verified.";function vt({protocol:e,hostname:t,port:r}){return e==="http:"?gt.includes(t)?"local":null:e==="https:"&&ft.includes(t)&&r===""?"production":null}function Ke(e,t){let r=Object.getOwnPropertyDescriptor(e,t);return r&&"value"in r?r.value:void 0}var Et=Object.freeze({windows:1,macos:1,linux:1}),xt=[["windows",/^Mozilla\/5\.0 \(Windows NT \d+\.\d+; Win64; x64\) AppleWebKit\/537\.36 \(KHTML, like Gecko\) Chrome\/\d+(?:\.\d+){3} Safari\/537\.36 Edg\/\d+(?:\.\d+){3}$/],["macos",/^Mozilla\/5\.0 \(Macintosh; Intel Mac OS X \d+(?:_\d+){1,2}\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)$/],["linux",/^Mozilla\/5\.0 \(X11; Linux (?:x86_64|aarch64)\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)(?: Version\/\d+(?:\.\d+){0,3} Safari\/\d+(?:\.\d+){0,3})?$/]];function St(e){return xt.find(([,t])=>t.test(e))?.[0]??null}function Pt(e,t,r){let n=Ke(e,"__VM_STEAM__");if(typeof n!="object"||n===null)return!1;let s=Object.getPrototypeOf(n);if(s!==Object.prototype&&s!==null)return!1;if(Ke(n,"appFrames")===1)return!0;let o=St(t);return o!==null&&r[o]===1}function le(e,t=Et){let r=vt(e.location);if(r===null)return kt;if(e.top!==e.self)return bt;let n=e.navigator.userAgent;return(r==="production"&&Pt(e,n,t)?Je:[...yt,...Je]).some(o=>o in e)||wt.test(n)?At:null}function pe(e){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw Error("Invalid game completion.");let t=Object.getOwnPropertyDescriptor(e,"score");if(Reflect.ownKeys(e).length!==1||!t||!("value"in t)||!t.enumerable||typeof t.value!="number"||!Number.isInteger(t.value)||t.value<0||t.value>1e9)throw Error("Score must be an integer from 0 to 1,000,000,000.");return Object.freeze({score:t.value})}var ue="vibexp";var A=Object.freeze({checkpointBytes:32*1024,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34*1024,responseBytes:34*1024,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:900*1e3,requestTimeoutMs:1e4}),Re=1e6,Ue=1101024,_e=e=>typeof e=="string"&&/^[1-9]\d{0,15}$/.test(e),Ce=e=>typeof e=="string"&&e.length<=Re&&/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(e);function Ie(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function me(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,"0")).join("")}function K(e,t){let r=JSON.stringify(e);if(typeof r!="string"||r.length>t||new TextEncoder().encode(r).length>t)throw Error("App message exceeds limit.");return r}function he(e,t){if(typeof e!="string"||e.length>t||new TextEncoder().encode(e).length>t)throw Error("Invalid app message size or encoding.");return JSON.parse(e)}var de=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Z=(e,t)=>{let r=Object.keys(e);return r.length===t.length&&Reflect.ownKeys(e).length===r.length&&r.every(n=>t.includes(n)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,n)??{},"value"))};function Oe(e){let t=0,r=0,n=(o,l)=>{if(++t>A.checkpointNodes||l>A.checkpointDepth)throw Error("App checkpoint is too complex.");if(o===null||typeof o=="boolean")return;if(typeof o=="number"){if(!Number.isFinite(o))throw Error("Checkpoint numbers must be finite.");return}if(typeof o=="string"){if(o.length>A.stringBytes)throw Error("App checkpoint string is too large.");let a=new TextEncoder().encode(o).byteLength;if(a>A.stringBytes||(r+=a)>A.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(o)){if(o.length>A.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(o).length!==o.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let a=0;a<o.length;a++){let p=Object.getOwnPropertyDescriptor(o,a);if(!p||!("value"in p))throw Error("Sparse/accessor checkpoints are unsupported.");n(p.value,l+1)}return}if(!de(o))throw Error("App checkpoint must contain only JSON values.");let y=Object.keys(o);if(Reflect.ownKeys(o).length!==y.length)throw Error("Checkpoint properties must be enumerable strings.");if(y.length>A.objectKeys)throw Error("App checkpoint has too many keys.");for(let a of y){if(["__proto__","constructor","prototype"].includes(a)||a.length>128)throw Error("Invalid app checkpoint key.");if(r+=new TextEncoder().encode(a).byteLength,r>A.checkpointBytes)throw Error("App checkpoint keys are too large.");let p=Object.getOwnPropertyDescriptor(o,a);if(!p||!("value"in p))throw Error("App checkpoint accessors are unsupported.");n(p.value,l+1)}};n(e,0);let s=JSON.stringify(e);if(new TextEncoder().encode(s).byteLength>A.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return s}function Te(e){return JSON.parse(Oe(e))}function qe(e,t){if(!de(e)||!Z(e,["id","session","request"])||e.session!==t||typeof e.id!="string"||e.id.length>80||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!de(e.request))throw Error("Invalid app session request.");let r=e.request;if(r.method==="app.frame"){if(!Z(r,["method","id","image"])||!_e(r.id)||r.image!==null&&typeof r.image!="string")throw Error("Invalid app frame.");return{id:e.id,request:{method:"app.frame",id:r.id,image:r.image}}}if(K(e,A.requestBytes),r.method==="game.finish"&&Z(r,["method","score"]))return{id:e.id,request:{method:"game.finish",...pe({score:r.score})}};if((r.method==="ui.ready"||r.method==="app.checkpoint.get")&&Z(r,["method"]))return{id:e.id,request:{method:r.method}};if(r.method==="app.checkpoint.set"&&Z(r,["method","value"]))return{id:e.id,request:{method:r.method,value:Te(r.value)}};throw Error("This app has no permission for that method.")}function ee(e){if(!de(e)||!Z(e,["active","width","height"])||typeof e.active!="boolean"||typeof e.width!="number"||!Number.isInteger(e.width)||e.width<0||e.width>4096||typeof e.height!="number"||!Number.isInteger(e.height)||e.height<0||e.height>4096)throw Error("Invalid app lifecycle.");return Object.freeze({active:e.active,width:e.width,height:e.height})}var Gt={descriptionMin:40,descriptionMax:2e3,supportMax:200,screenshotsMin:1,screenshotsMax:4,iconSize:256,iconBytes:256*1024,screenshotBytes:1024*1024};var Ht={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},Jt={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},Mt={packs:3,network:8,packSlugMax:56},Rt=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,V=e=>typeof e=="string"&&e.length<=Mt.packSlugMax&&Rt.test(e);function Ze(e){return e.length>0&&e.length<=200&&e.split("/").every(t=>/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(t)&&!t.endsWith("."))}var v=Object.freeze({idleMs:900*1e3,sessionMs:14400*1e3,requestsPerSecond:10,requestsPerMinute:120,lifetimeRequests:3e4,inFlight:8,readyMs:15e3,progressReadyMs:12e4,saveBytes:1048576,saveDepth:64,saveIntervalMs:1e4,messageBytes:1101024,frameChars:Re,captureMs:1200,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4}),ge=["common","rare","epic","legendary","mythic"],Le=/^[A-Za-z0-9_-]{1,64}$/,re=Object.freeze({handle:/^[a-z0-9_]{3,15}$/,nameMax:64,token:/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,tokenMin:20,tokenMax:1500}),te=1024,ne=Object.freeze({"host.hello":{request:256,response:te,states:"LFB"},"ui.progress":{request:64,response:64,rate:[4,1e3],states:"LFB"},"app.frame":{request:1000256,response:64,rate:[4,1e3],states:"LFB"},"app.save.get":{request:64,response:11e5,rate:[6,6e4],states:"LFB"},"app.save.set":{request:11e5,response:256,rate:[1,1e4],states:"LFB"},"cards.list":{request:256,response:256*te,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*te,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*te,rate:[30,6e4],states:"LFB"},"cards.watch":{request:64,response:64,rate:[30,6e4],states:"LFB"},"pack.show":{request:128,response:64,rate:[1,1e4],bucket:"show",states:"F"},"card.show":{request:192,response:64,rate:[1,1e4],bucket:"show",states:"F"},"player.get":{request:64,response:2*te,rate:[10,6e4],states:"LFB"},"display.maximize":{request:64,response:64,rate:[2,1e3],states:"F"},"display.fullscreen":{request:64,response:64,rate:[1,1e3],states:"F"}}),Ye=Object.freeze(Object.keys(ne).filter(e=>e!=="host.hello"&&e!=="card.show")),_t=new TextEncoder,se=e=>_t.encode(e).byteLength,X=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),U=(e,t,r=[])=>Reflect.ownKeys(e).every(s=>typeof s=="string"&&(t.includes(s)||r.includes(s))&&"value"in Object.getOwnPropertyDescriptor(e,s))&&t.every(s=>Object.hasOwn(e,s));var w=class extends Error{code;constructor(t,r){super(r),this.name="AppHostError",this.code=t}};function Ne(e){let t=s=>new w("invalid",s),r=(s,o)=>{if(!(s===null||typeof s=="boolean"||typeof s=="string")){if(typeof s=="number"){if(!Number.isFinite(s))throw t("A save's numbers must be finite.");return}if(typeof s!="object")throw t("A save must contain only JSON values.");if(o>v.saveDepth)throw t(`A save nests at most ${v.saveDepth} levels deep.`);if(Array.isArray(s)){if(Reflect.ownKeys(s).length!==s.length+1)throw t("A save's arrays cannot have extra properties.");for(let l=0;l<s.length;l++){let y=Object.getOwnPropertyDescriptor(s,l);if(!y||!("value"in y))throw t("A save's arrays cannot be sparse or have accessors.");r(y.value,o+1)}return}if(!X(s))throw t("A save must contain only plain objects, arrays and JSON values.");for(let l of Reflect.ownKeys(s)){let y=Object.getOwnPropertyDescriptor(s,l);if(typeof l!="string"||!y||!("value"in y)||!y.enumerable)throw t("A save's properties must be plain enumerable data.");r(y.value,o+1)}}};r(e,1);let n=JSON.stringify(e);if(se(n)>v.saveBytes)throw new w("too-large",`A save is at most ${v.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return n}function Qe(e){let t;try{t=JSON.parse(e)}catch{throw new w("invalid","The saved data is not JSON.")}return Ne(t),t}var I=(e,t,r=0)=>typeof e=="string"&&e.length>=r&&e.length<=t,fe=(e,t,r)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=r,Ct=e=>typeof e=="string"&&ge.includes(e),$e=".bin",ye=(e,t)=>`-/card/${e}/${t}${$e}`,we=e=>`-/cover/${e}${$e}`,It=e=>`-/player/${e}${$e}`;function et(e,t){if(!X(e)||!U(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:r,pack:n,name:s,art:o}=e,l=typeof r=="string"?r.slice(r.indexOf("/")+1):"";if(!V(n)||r!==`${n}/${l}`||!Le.test(l)||!I(s,120)||!Ct(e.rarity)||t&&!fe(e.count,1,1e6)||o!==null&&o!==ye(n,l))throw Error("Invalid card.");return{id:r,pack:n,name:s,rarity:e.rarity,...t?{count:e.count}:{},art:o}}function ze(e){return et(e,!0)}function Ot(e){return et(e,!1)}function tt(e){let{id:t,name:r,creator:n,art:s,total:o}=e;if(!V(t)||!I(r,120,1)||n!==null&&!I(n,64,1)||s!==null&&s!==we(t)||!fe(o,0,1e4))throw Error("Invalid pack.");return{id:t,name:r,creator:n,art:s,total:o}}function rt(e){if(!X(e)||!U(e,["id","name","creator","art","held","total"])||!fe(e.held,0,1e4))throw Error("Invalid pack.");let t=tt(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function nt(e){if(!X(e)||!U(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=tt(e),r=e.cards.map(Ot);if(r.some(n=>n.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:r}}var Tt=/[\u0000-\u001F\u007F-\u009F]/,Xe=e=>typeof e=="string"&&re.handle.test(e);function st(e){if(X(e)&&U(e,["guest"])&&e.guest===!0)return{guest:!0};if(!X(e)||!U(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:r,name:n,picture:s,token:o,expiresAt:l}=e;if(!Xe(t)||!I(n,re.nameMax,1)||Tt.test(n)||r!==void 0&&(!Xe(r)||r===t)||s!==null&&s!==It(t)||"token"in e!="expiresAt"in e||o!==void 0&&(!I(o,re.tokenMax,re.tokenMin)||!re.token.test(o)||!fe(l,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...r===void 0?{}:{username:r},name:n,picture:s,...o===void 0?{}:{token:o,expiresAt:l}}}var Fe=e=>I(e,64,1);var ot=e=>e.includes("/")?"../".repeat(e.split("/").length-1):"./";function it(e){let t=e.method,r=(...n)=>U(e,["method",...n]);switch(t){case"ui.ready":case"app.checkpoint.get":return r()?{method:t}:null;case"game.finish":return r("score")?{method:t,...pe({score:e.score})}:null;case"app.checkpoint.set":return r("value")?{method:t,value:Te(e.value)}:null;case"host.hello":return r("protocol","sdk")&&e.protocol===2&&I(e.sdk,20,1)&&/^[\x20-\x7e]+$/.test(e.sdk)?{method:t,protocol:2,sdk:e.sdk}:null;case"ui.progress":return r("value")&&typeof e.value=="number"&&Number.isFinite(e.value)?{method:t,value:e.value}:null;case"app.frame":return r("id","image")&&_e(e.id)&&(e.image===null||typeof e.image=="string")?{method:t,id:e.id,image:e.image}:null;case"app.save.get":case"cards.packs":case"player.get":return r()?{method:t}:null;case"app.save.set":return r("value")?{method:t,value:e.value}:null;case"cards.list":return!U(e,["method"],["pack","after"])||"pack"in e&&!I(e.pack,64,1)||"after"in e&&!I(e.after,64,1)?null:{method:t,..."pack"in e?{pack:e.pack}:{},..."after"in e?{after:e.after}:{}};case"cards.pack":case"pack.show":return r("pack")&&I(e.pack,64,1)?{method:t,pack:e.pack}:null;case"card.show":return r("pack","card")&&I(e.pack,64,1)&&I(e.card,64,1)?{method:t,pack:e.pack,card:e.card}:null;case"display.maximize":case"display.fullscreen":case"cards.watch":return r("on")&&typeof e.on=="boolean"?{method:t,on:e.on}:null;default:return null}}function Ve(e){return Object.hasOwn(ne,e)?ne[e]:{request:A.requestBytes,response:A.responseBytes,states:"LFB"}}function Lt(e,t,r){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype||Object.keys(e).length!==3||!("session"in e)||e.session!==t||!("id"in e)||typeof e.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!("request"in e)||!e.request||typeof e.request!="object"||Array.isArray(e.request))throw Error("Invalid app session request.");let n=it(e.request),s=n!==null&&!Object.hasOwn(ne,n.method);if(!n||!r&&!s&&n.method!=="host.hello"&&n.method!=="app.frame")throw Error("This app has no permission for that method.");if(se(JSON.stringify(e.request))>Ve(n.method).request)throw Error("App request exceeds its bound.");return{id:e.id,request:n}}function at(e,t){let r=[];return n=>(r=r.filter(s=>n-s<t),r.length>=e?!1:(r.push(n),!0))}var G={states:"That is not available while the app is loading or behind another window.",rate:"Too many requests of that kind; try again later.",slug:"That is not a pack slug.",after:"That page cursor is not valid.",unavailable:"The host could not answer that now; try again."};function ct(e=()=>performance.now(),t={}){let r=t.services,n=r!==void 0,s="null",o=!1,l,y,a=!1,p=e();if(!Number.isFinite(p))throw Error("App clock is invalid.");let d=p,O=p,W=0,N=0,j=p,P,b,R,E=!1,k,_=at(v.requestsPerMinute,6e4),$=n?v.sessionMs:A.sessionMs,z=n?v.lifetimeRequests:A.lifetimeRequests,oe=n?"App session reached its 4-hour limit. Reopen the app to keep playing.":"App session expired. Reopen the app.",g=h=>{if(o||P)return;P=h,clearTimeout(B),clearTimeout(R),s="null";let M=b;l?.close(),M?.(h)},B=setTimeout(()=>g(oe),$),C=()=>{let h;try{h=e()}catch{g("App clock changed. Reopen the app.");return}if(!Number.isFinite(h)||h<d){g("App clock changed. Reopen the app.");return}if(d=h,h-p>=$){g(oe);return}return h},ke=h=>{clearTimeout(R),R=setTimeout(()=>{let M=C();if(M===void 0)return;let F=M-j;if(F<v.idleMs){ke(v.idleMs-F);return}E||(E=!0,t.idle?.())},h)},We=h=>{j=h,E&&(E=!1,ke(v.idleMs))};n&&ke(v.idleMs);let be={protocol:n?2:1,attach(h,M,F){if(o||P||!Ie(M))throw h.close(),Error(P??"App controller is closed.");if(C()===void 0)throw h.close(),Error(P);l?.close();let Y=!1,Ae=0,ie=!1,ve=!1,je=0,Ee=!1,xe=!1,H,Be=new Set,De=new Map,ut=0,Q,q=c=>{let i=Q;Q=void 0,i&&(clearTimeout(i.timer),i.resolve(c))},Se=()=>{q(null),!Y&&(Y=!0,h.onmessage=null,h.onmessageerror=null,h.close(),l===Pe&&(l=void 0,b=void 0,k=void 0))},J=c=>{Y||(Se(),F.fault(c))},T=()=>!Y&&!o&&F.current(),Ge=F.foreground??(()=>!0),ae=(c,i)=>{T()&&h.postMessage(K(c,i))},Pe={lifecycle(c){T()&&h.postMessage(K({session:M,event:"app.lifecycle",state:ee(c)},A.responseBytes))},close:Se,capture(c=v.captureMs){if(q(null),!T())return Promise.resolve(null);let i=String(++ut),f=typeof c=="number"&&Number.isFinite(c)?Math.max(0,c):v.captureMs;return new Promise(u=>{Q={id:i,resolve:u,timer:setTimeout(()=>{Q?.id===i&&q(null)},f)};try{ae({session:M,event:"app.capture",id:i},256)}catch{q(null)}})}};l=Pe,b=F.fault,r&&(k=async()=>{if(!xe||!H||!T())return;let c=await r.cards();if(!T()||!xe||!H||!Fe(c.revision)||c.revision===H.revision)return;let i=new Map(c.cards.map(S=>{let x=ze(S);return[x.id,x]})),f=[...i.values()].filter(S=>JSON.stringify(H.cards.get(S.id))!==JSON.stringify(S)),u=[...H.cards.keys()].filter(S=>!i.has(S)),m={changed:f,removed:u,revision:c.revision};se(JSON.stringify(m))>v.cardsEventBytes&&(m={reset:!0,revision:c.revision}),H={revision:c.revision,cards:i},ae({session:M,event:"app.cards",state:m},v.cardsEventBytes+1024)});let He=c=>{let i=Q?.id===c.id;if(c.image!==null&&!Ce(c.image))throw i&&q(null),new w("invalid","That is not a PNG, JPEG or WebP data URL of at most 1,000,000 characters.");return i&&q(c.image),{completed:!0}},mt=async(c,i)=>{let f=(u,m)=>{try{return m(u)}catch{throw new w("unavailable",G.unavailable)}};switch(i.method){case"host.hello":return{protocol:2,guest:c.guest,features:[...Ye,...c.showCard?["card.show"]:[]],root:ot(c.entry)};case"ui.progress":if(!ve){if(i.value<0||i.value>1)throw new w("invalid","Progress is a number from 0 to 1.");F.progress?.(i.value)}return{completed:!0};case"app.frame":return He(i);case"app.save.get":{let u=await c.saveGet();return{value:u.value===null?null:f(u.value,Qe),savedAt:u.savedAt===null?null:f(u.savedAt,m=>{if(typeof m!="string"||m.length>30)throw Error();return m})}}case"app.save.set":{let u=Ne(i.value);if(Ee)throw new w("rate-limited","A save is already being written.");Ee=!0;try{let{savedAt:m}=await c.saveSet(u);return{savedAt:f(m,S=>{if(typeof S!="string"||S.length>30)throw Error();return S})}}finally{Ee=!1}}case"cards.list":{if(i.pack!==void 0&&!V(i.pack))throw new w("invalid",G.slug);let u=i.after===void 0?0:/^(?:0|[1-9]\d{0,5})$/.test(i.after)?Number(i.after):-1;if(u<0)throw new w("invalid",G.after);let m=await c.cards(),S=f(m,L=>{if(!Fe(L.revision)||!Array.isArray(L.cards))throw Error();return L.cards.map(ze)});i.pack===void 0&&u===0&&(H={revision:m.revision,cards:new Map(S.map(L=>[L.id,L]))});let x=i.pack===void 0?S:S.filter(L=>L.pack===i.pack),D=u+v.cardsPage;return{cards:x.slice(u,D),after:D<x.length?String(D):null,revision:m.revision}}case"cards.packs":return{packs:f(await c.packs(),u=>{if(!Array.isArray(u)||u.length>200)throw Error();return u.map(rt)})};case"cards.pack":if(!V(i.pack))throw new w("invalid",G.slug);return{pack:f(await c.pack(i.pack),u=>{let m=nt(u);if(m.id!==i.pack)throw Error();return m})};case"cards.watch":return xe=i.on,{completed:!0};case"pack.show":if(!V(i.pack))throw new w("invalid",G.slug);return await c.showPack(i.pack),{shown:!0};case"card.show":if(!c.showCard)throw new w("unsupported","This host cannot show a card.");if(!V(i.pack)||!Le.test(i.card))throw new w("invalid","That is not a pack slug and a card id.");return await c.showCard(i.pack,i.card),{shown:!0};case"player.get":return f(await c.player(),st);case"display.maximize":return await c.maximize(i.on),{completed:!0};case"display.fullscreen":return await c.fullscreen(i.on),{completed:!0}}};h.onmessage=c=>{if(!T()){Se();return}let i=C();if(i===void 0)return;if(i-O>=1e3&&(O=i,W=0),++W>A.requestsPerSecond||++N>z||Ae>=(ie?v.inFlight:A.inFlight)||n&&!_(i)){J("App request limit exceeded.");return}let f,u;try{n?{id:f,request:u}=Lt(he(c.data,v.messageBytes),M,ie):{id:f,request:u}=qe(he(c.data,Ue),M)}catch{J("Invalid or unpermitted app request.");return}if(n){if(!/^[1-9]\d{0,15}$/.test(f)||Number(f)<=je){J("App request was replayed.");return}je=Number(f)}else{if(Be.has(f)){J("App request was replayed.");return}Be.add(f)}if(u.method==="host.hello"){if(ie){J("App said hello twice.");return}ie=!0}Ae++,n&&We(i);let m=u.method,S=m==="ui.ready"||m==="game.finish"||m==="app.checkpoint.get"||m==="app.checkpoint.set";Promise.resolve().then(()=>{if(T()&&!(!Ge()&&(m==="game.finish"||m==="app.checkpoint.set"))){if(u.method==="app.frame"&&!n){try{let x=He(u);T()&&h.postMessage(K({session:M,id:f,result:x},A.responseBytes))}catch(x){T()&&h.postMessage(K({session:M,id:f,error:x.message,code:"invalid"},A.responseBytes))}return}if(S){let x;switch(u.method){case"ui.ready":ve=!0,F.ready(),x={completed:!0};break;case"game.finish":if(y&&y.score!==u.score){if(!n)throw Error("This game has already finished.");ae({session:M,id:f,error:"This game has already finished.",code:"invalid"},A.responseBytes);return}y??=Object.freeze({score:u.score}),x={completed:!0};break;case"app.checkpoint.get":x={checkpoint:JSON.parse(s)};break;default:s=Oe(u.value),x={completed:!0};break}T()&&(h.postMessage(K({session:M,id:f,result:x},A.responseBytes)),m==="game.finish"&&y&&!a&&T()&&(a=!0,F.finish?.(y)));return}return ht(f,u,m,i)}}).catch(()=>{Y||J("App request could not complete.")}).finally(()=>{Ae--})};let ht=async(c,i,f,u)=>{let m=Ve(f),S;try{let x=ve?Ge()?"F":"B":"L";if(!m.states.includes(x))throw new w("not-permitted",G.states);if(m.rate&&!(i.method==="display.fullscreen"&&!i.on)){let L=m.bucket??f,ce=De.get(L);if(ce||(ce=at(m.rate[0],m.rate[1]),De.set(L,ce)),!ce(u))throw new w("rate-limited",G.rate)}let D=await mt(r,i);if(se(JSON.stringify(D))>m.response)throw new w("unavailable","The answer is larger than this request may return.");S={session:M,id:c,result:D}}catch(x){let D=x instanceof w?x.code:"unavailable";S={session:M,id:c,error:x instanceof w?x.message.slice(0,300):G.unavailable,code:D}}ae(S,v.messageBytes)};return h.onmessageerror=()=>J("App message could not be decoded."),h.start(),Pe},suspend(){l?.close()},dispose(){o||(o=!0,clearTimeout(B),clearTimeout(R),l?.close(),s="null")}};return n&&(be.activity=()=>{let h=C();h!==void 0&&We(h)},be.cardsChanged=async()=>{try{await k?.()}catch{}}),be}function lt(e,t){let r=le(window);if(r)throw Error(r);if(!Ie(t.challenge)||new URL(e.src).hash!==`#${ue}=${t.challenge}`)throw Error("Invalid app frame challenge.");let n=t.controller.protocol===2,s=!1,o=!1,l=!1,y=0,a,p=!1,d=ee({active:!0,width:0,height:0}),O=()=>N("App took too long to become ready."),W=()=>{s||(s=!0,clearTimeout(b),clearTimeout(R),e.removeEventListener("load",j),window.removeEventListener("message",P),a?.close())},N=E=>{s||(W(),t.fault(E))},j=()=>{o?N("App navigation ended this session."):o=!0},P=E=>{if(s||l||!t.current()||E.source!==e.contentWindow)return;if(++y>32){N("App connection limit exceeded.");return}if(!o||E.origin!=="null")return;let k;try{k=he(E.data,256)}catch{N("Invalid app connection message.");return}if(!k||typeof k!="object"||Array.isArray(k)||!("channel"in k)||k.channel!==Me||!("type"in k)||k.type!=="connect"||!("challenge"in k)||k.challenge!==t.challenge||Object.keys(k).length!==3)return;l=!0,window.removeEventListener("message",P);let _=new MessageChannel,$=me();try{if(a=t.controller.attach(_.port1,$,{current:t.current,foreground:t.foreground,ready(){p=!0,clearTimeout(b),clearTimeout(R),t.ready()},finish:t.finish,fault:N,progress(z){p||s||(clearTimeout(b),b=setTimeout(O,v.readyMs),t.progress?.(z))}}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:Me,challenge:t.challenge,session:$,...n?{protocol:2}:{}},"*",[_.port2]),a.lifecycle(d)}catch{_.port1.close(),_.port2.close(),N("App connection could not complete.")}},b=setTimeout(O,v.readyMs),R=n?setTimeout(O,v.progressReadyMs):void 0;return e.addEventListener("load",j),window.addEventListener("message",P),{resize(E,k){d=ee({active:d.active,width:Math.min(4096,Math.max(0,Math.floor(E))),height:Math.min(4096,Math.max(0,Math.floor(k)))}),a?.lifecycle(d)},setActive(E){E!==d.active&&(d=ee({...d,active:E}),a?.lifecycle(d))},dispose:W,capture(E){return s||!a?Promise.resolve(null):a.capture(E)}}}function Nt(e){if(!e||typeof e!="object"||!("runtime"in e)||typeof e.runtime!="string")throw Error("Invalid preview metadata.");let t=e,r=(o,l)=>Array.isArray(o)&&o.length<=8&&o.every(l)?o:null,n=r(t.packs,V),s=r(t.network,o=>typeof o=="string");if(typeof t.name!="string"||typeof t.id!="string"||typeof t.entry!="string"||!Ze(t.entry)||!n||!s||!(t.cards==="none"||t.cards==="linked"||t.cards==="all"))throw Error("Invalid preview metadata.");return{name:t.name,runtime:e.runtime,id:t.id,entry:t.entry,packs:n,cards:t.cards,network:s}}var pt=e=>e.split("-").map(t=>t[0].toUpperCase()+t.slice(1)).join(" "),dt="preview-public";function $t(e,t=Math.random){let r=e.packs.length?e.packs:e.cards==="all"?["preview-pack"]:[],n=a=>({id:a,name:pt(a),creator:"Preview",art:we(a),total:6,cards:Array.from({length:6},(p,d)=>({id:`${a}/c${d+1}`,pack:a,name:`${pt(a)} #${d+1}`,rarity:ge[d%ge.length],art:ye(a,`c${d+1}`)}))}),s=r.map(n),o=[...s,...r.includes(dt)?[]:[n(dt)]],l=new Map(s.flatMap(a=>a.cards.slice(0,3).map(p=>[p.id,1]))),y=1;return{pack(a){let p=o.find(d=>d.id===a);if(!p)throw new w("invalid","There is no such public pack.");return p},card(a,p){let d=this.pack(a).cards.find(O=>O.id===`${a}/${p}`);if(!d)throw new w("invalid","That card is not in that pack.");return d},cards(){if(e.cards==="none")throw new w("not-permitted","The manifest does not declare cards.");return{cards:s.flatMap(p=>p.cards.filter(d=>l.has(d.id)).map(d=>({...d,count:l.get(d.id)}))),revision:String(y)}},packs(){return s.map(({cards:a,...p})=>({...p,held:e.cards==="none"?0:a.filter(d=>l.has(d.id)).length}))},pull(){let a=s.flatMap(d=>d.cards);if(!a.length)return null;let p=a[Math.min(a.length-1,Math.floor(t()*a.length))];return l.set(p.id,(l.get(p.id)??0)+1),y++,p.name}}}function zt(e,t){let r=`vmos-preview-save:${e}`,n={value:null,savedAt:null};return{get(){try{let s=t().getItem(r);if(s)return JSON.parse(s)}catch{}return n},set(s){n={value:s,savedAt:new Date().toISOString()};try{t().setItem(r,JSON.stringify(n))}catch{}return{savedAt:n.savedAt}}}}async function Ft(){let e=le(window);if(e)throw Error(e);let t=document.getElementById("surface"),r=document.getElementById("status"),n=document.getElementById("toggle"),s=document.getElementById("reset"),o=document.getElementById("pull"),l=document.getElementById("result"),y=document.getElementById("score");if(!t||!r||!l||!y||!(n instanceof HTMLButtonElement)||!(s instanceof HTMLButtonElement)||!(o instanceof HTMLButtonElement))throw Error("Preview controls are missing.");let a=Nt(await(await fetch("/preview.json",{credentials:"omit"})).json()),p=new URL(a.runtime);if(p.origin!==`http://localhost:${window.location.port}`||!/^\/game-assets\/[a-f0-9]{64}\//.test(p.pathname)||p.search||p.hash)throw Error("Invalid preview runtime.");let d=$t(a),O=zt(a.id,()=>window.localStorage),W=()=>{if(!navigator.userActivation?.isActive)throw new w("needs-click","That needs a fresh click in the app.")},N={guest:!1,entry:a.entry,async saveGet(){return O.get()},async saveSet(g){return O.set(g)},async cards(){return d.cards()},async packs(){return d.packs()},async pack(g){return d.pack(g)},async showPack(g){d.pack(g),W(),r.textContent=`VibeMarket would open the pack ${g} in its market window here.`},async showCard(g,B){let C=d.card(g,B);W(),r.textContent=`VibeMarket would open the card ${C.name} (${B}) on the pack ${g}'s page here.`},async player(){let g={guest:!1,handle:"preview_player",username:"preview",name:"Preview Player",picture:null};return a.network.length?{...g,token:"preview.not-a-real-token.unsigned",expiresAt:Date.now()+3e5}:g},async maximize(g){t.classList.toggle("maximized",g)},async fullscreen(g){if(!g){document.fullscreenElement&&await document.exitFullscreen();return}W(),await t.requestFullscreen()}},j=()=>ct(void 0,{services:N,idle:()=>{r.textContent="Still playing? VibeMarket asks here after 15 minutes without input."}}),P=j(),b=null,R=null,E=null,k=!1,_=null,$=()=>{R?.dispose(),R=null,P.suspend(),E?.disconnect(),E=null,b?.remove(),b=null},z=()=>{if($(),t.hidden=k||document.hidden||_!==null,l.hidden=!0,k||document.hidden){r.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}if(_){l.hidden=!1,y.textContent=String(_.score),r.textContent="Round complete. No Cash reward for this preview.";return}let g=me(),B=new URL(p);B.hash=`${ue}=${g}`,b=document.createElement("iframe"),b.title="VibeMarket OS app",b.sandbox.add("allow-scripts","allow-pointer-lock"),b.allow="autoplay; gamepad",b.setAttribute("credentialless",""),b.referrerPolicy="no-referrer",b.src=B.href,t.appendChild(b),R=lt(b,{controller:P,challenge:g,current:()=>!k&&!document.hidden,ready:()=>{r.textContent="App ready \xB7 Minimize and restore to check its saved work."},progress:C=>{r.textContent=`Loading the isolated app\u2026 ${Math.round(C*100)}%`},finish:C=>{_=C,s.textContent="Play again",z()},fault:C=>{$(),P.dispose(),P=j(),r.textContent=C}}),E=new ResizeObserver(()=>{b&&R?.resize(b.clientWidth,b.clientHeight)}),E.observe(b),r.textContent="Loading the isolated app\u2026"};n.onclick=()=>{k=!k,n.textContent=k?"Restore":"Minimize",z()},s.onclick=()=>{$(),P.dispose(),P=j(),_=null,k=!1,n.textContent="Minimize",s.textContent="Close / reset",z()},o.onclick=()=>{let g=d.pull();r.textContent=g?`Pulled ${g}. The app hears about it through onCards.`:"This app links no packs and does not read all cards, so there is nothing to pull.",P.cardsChanged?.()};let oe=window.setInterval(()=>{navigator.userActivation?.isActive&&P.activity?.()},1e4);document.addEventListener("visibilitychange",z),window.addEventListener("pagehide",()=>{window.clearInterval(oe),$(),P.dispose(),document.removeEventListener("visibilitychange",z)},{once:!0}),z()}typeof window<"u"&&typeof document<"u"&&Ft().catch(e=>{let t=document.getElementById("status");t&&(t.textContent=e instanceof Error?e.message:"Preview failed.")});export{dt as PREVIEW_PUBLIC_PACK,$t as previewCatalog,Nt as previewMetadata,zt as previewSaves,Ft as startPreviewParent};
|
|
1
|
+
var _e="vibemarket.game.v1";var gt=["127.0.0.1","localhost"],yt=["vibechain.com","www.vibechain.com"],wt=["__VM_STEAM__","__TAURI_INTERNALS__"],Ke=["__TAURI__","vibeNative","ReactNativeWebView"],kt=/\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i,bt="Third-party apps are available only on vibechain.com and in the local browser developer preview.",At="Third-party apps require a top-level browser host.",vt="Third-party apps are disabled in native shells until their IPC isolation is verified.";function Et({protocol:e,hostname:t,port:r}){return e==="http:"?gt.includes(t)?"local":null:e==="https:"&&yt.includes(t)&&r===""?"production":null}function Ue(e,t){let r=Object.getOwnPropertyDescriptor(e,t);return r&&"value"in r?r.value:void 0}var xt=Object.freeze({windows:1,macos:1,linux:1}),St=[["windows",/^Mozilla\/5\.0 \(Windows NT \d+\.\d+; Win64; x64\) AppleWebKit\/537\.36 \(KHTML, like Gecko\) Chrome\/\d+(?:\.\d+){3} Safari\/537\.36 Edg\/\d+(?:\.\d+){3}$/],["macos",/^Mozilla\/5\.0 \(Macintosh; Intel Mac OS X \d+(?:_\d+){1,2}\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)$/],["linux",/^Mozilla\/5\.0 \(X11; Linux (?:x86_64|aarch64)\) AppleWebKit\/\d+(?:\.\d+){0,3} \(KHTML, like Gecko\)(?: Version\/\d+(?:\.\d+){0,3} Safari\/\d+(?:\.\d+){0,3})?$/]];function Pt(e){return St.find(([,t])=>t.test(e))?.[0]??null}function Mt(e,t,r){let n=Ue(e,"__VM_STEAM__");if(typeof n!="object"||n===null)return!1;let o=Object.getPrototypeOf(n);if(o!==Object.prototype&&o!==null)return!1;if(Ue(n,"appFrames")===1)return!0;let s=Pt(t);return s!==null&&r[s]===1}function me(e,t=xt){let r=Et(e.location);if(r===null)return bt;if(e.top!==e.self)return At;let n=e.navigator.userAgent;return(r==="production"&&Mt(e,n,t)?Ke:[...wt,...Ke]).some(s=>s in e)||kt.test(n)?vt:null}function he(e){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw Error("Invalid game completion.");let t=Object.getOwnPropertyDescriptor(e,"score");if(Reflect.ownKeys(e).length!==1||!t||!("value"in t)||!t.enumerable||typeof t.value!="number"||!Number.isInteger(t.value)||t.value<0||t.value>1e9)throw Error("Score must be an integer from 0 to 1,000,000,000.");return Object.freeze({score:t.value})}var fe="vibexp";var v=Object.freeze({checkpointBytes:32*1024,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34*1024,responseBytes:34*1024,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:900*1e3,requestTimeoutMs:1e4}),Ce=1e6,qe=1101024,Ie=e=>typeof e=="string"&&/^[1-9]\d{0,15}$/.test(e),Oe=e=>typeof e=="string"&&e.length<=Ce&&/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(e);function Te(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function ge(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,"0")).join("")}function X(e,t){let r=JSON.stringify(e);if(typeof r!="string"||r.length>t||new TextEncoder().encode(r).length>t)throw Error("App message exceeds limit.");return r}function ye(e,t){if(typeof e!="string"||e.length>t||new TextEncoder().encode(e).length>t)throw Error("Invalid app message size or encoding.");return JSON.parse(e)}var se=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Z=(e,t)=>{let r=Object.keys(e);return r.length===t.length&&Reflect.ownKeys(e).length===r.length&&r.every(n=>t.includes(n)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,n)??{},"value"))};function Le(e){let t=0,r=0,n=(s,l)=>{if(++t>v.checkpointNodes||l>v.checkpointDepth)throw Error("App checkpoint is too complex.");if(s===null||typeof s=="boolean")return;if(typeof s=="number"){if(!Number.isFinite(s))throw Error("Checkpoint numbers must be finite.");return}if(typeof s=="string"){if(s.length>v.stringBytes)throw Error("App checkpoint string is too large.");let a=new TextEncoder().encode(s).byteLength;if(a>v.stringBytes||(r+=a)>v.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(s)){if(s.length>v.arrayItems)throw Error("App checkpoint array is too large.");if(Reflect.ownKeys(s).length!==s.length+1)throw Error("Array checkpoints cannot have extra properties.");for(let a=0;a<s.length;a++){let m=Object.getOwnPropertyDescriptor(s,a);if(!m||!("value"in m))throw Error("Sparse/accessor checkpoints are unsupported.");n(m.value,l+1)}return}if(!se(s))throw Error("App checkpoint must contain only JSON values.");let f=Object.keys(s);if(Reflect.ownKeys(s).length!==f.length)throw Error("Checkpoint properties must be enumerable strings.");if(f.length>v.objectKeys)throw Error("App checkpoint has too many keys.");for(let a of f){if(["__proto__","constructor","prototype"].includes(a)||a.length>128)throw Error("Invalid app checkpoint key.");if(r+=new TextEncoder().encode(a).byteLength,r>v.checkpointBytes)throw Error("App checkpoint keys are too large.");let m=Object.getOwnPropertyDescriptor(s,a);if(!m||!("value"in m))throw Error("App checkpoint accessors are unsupported.");n(m.value,l+1)}};n(e,0);let o=JSON.stringify(e);if(new TextEncoder().encode(o).byteLength>v.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return o}function Ne(e){return JSON.parse(Le(e))}function Ze(e,t){if(!se(e)||!Z(e,["id","session","request"])||e.session!==t||typeof e.id!="string"||e.id.length>80||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!se(e.request))throw Error("Invalid app session request.");let r=e.request;if(r.method==="app.frame"){if(!Z(r,["method","id","image"])||!Ie(r.id)||r.image!==null&&typeof r.image!="string")throw Error("Invalid app frame.");return{id:e.id,request:{method:"app.frame",id:r.id,image:r.image}}}if(X(e,v.requestBytes),r.method==="game.finish"&&Z(r,["method","score"]))return{id:e.id,request:{method:"game.finish",...he({score:r.score})}};if((r.method==="ui.ready"||r.method==="app.checkpoint.get")&&Z(r,["method"]))return{id:e.id,request:{method:r.method}};if(r.method==="app.checkpoint.set"&&Z(r,["method","value"]))return{id:e.id,request:{method:r.method,value:Ne(r.value)}};throw Error("This app has no permission for that method.")}var Gt=Object.freeze({muted:!1,volume:1});function we(e){if(!se(e)||!Z(e,["muted","volume"])||typeof e.muted!="boolean"||typeof e.volume!="number"||!Number.isFinite(e.volume)||e.volume<0||e.volume>1)throw Error("Invalid app sound.");return Object.freeze({muted:e.muted,volume:e.volume})}function ie(e){if(!se(e)||!Z(e,["active","width","height"])||typeof e.active!="boolean"||typeof e.width!="number"||!Number.isInteger(e.width)||e.width<0||e.width>4096||typeof e.height!="number"||!Number.isInteger(e.height)||e.height<0||e.height>4096)throw Error("Invalid app lifecycle.");return Object.freeze({active:e.active,width:e.width,height:e.height})}var Jt={descriptionMin:40,descriptionMax:2e3,supportMax:200,screenshotsMin:1,screenshotsMax:4,iconSize:256,iconBytes:256*1024,screenshotBytes:1024*1024};var Kt={archive:20*1024*1024,expanded:64*1024*1024,file:16*1024*1024,files:256,versions:100,games:40},Ut={archive:50*1024*1024,expanded:128*1024*1024,file:32*1024*1024,files:2e3},Rt={packs:3,network:8,packSlugMax:56},_t=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,j=e=>typeof e=="string"&&e.length<=Rt.packSlugMax&&_t.test(e);function Xe(e){return e.length>0&&e.length<=200&&e.split("/").every(t=>/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(t)&&!t.endsWith("."))}var E=Object.freeze({idleMs:900*1e3,sessionMs:14400*1e3,requestsPerSecond:10,requestsPerMinute:120,lifetimeRequests:3e4,inFlight:8,readyMs:15e3,progressReadyMs:12e4,saveBytes:1048576,saveDepth:64,saveIntervalMs:1e4,messageBytes:1101024,frameChars:Ce,captureMs:1200,cardsPage:500,cardsEventBytes:256*1024,clientPerSecond:8,clientPerMinute:100,tokenReuseMs:6e4}),ke=["common","rare","epic","legendary","mythic"],$e=/^[A-Za-z0-9_-]{1,64}$/,ce=Object.freeze({handle:/^[a-z0-9_]{3,15}$/,nameMax:64,token:/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,tokenMin:20,tokenMax:1500}),ae=1024,le=Object.freeze({"host.hello":{request:256,response:ae,states:"LFB"},"ui.progress":{request:64,response:64,rate:[4,1e3],states:"LFB"},"app.frame":{request:1000256,response:64,rate:[4,1e3],states:"LFB"},"app.save.get":{request:64,response:11e5,rate:[6,6e4],states:"LFB"},"app.save.set":{request:11e5,response:256,rate:[1,1e4],states:"LFB"},"cards.list":{request:256,response:256*ae,rate:[30,6e4],states:"LFB"},"cards.packs":{request:64,response:64*ae,rate:[30,6e4],states:"LFB"},"cards.pack":{request:128,response:64*ae,rate:[30,6e4],states:"LFB"},"cards.watch":{request:64,response:64,rate:[30,6e4],states:"LFB"},"pack.show":{request:128,response:64,rate:[1,1e4],bucket:"show",states:"F"},"card.show":{request:192,response:64,rate:[1,1e4],bucket:"show",states:"F"},"player.get":{request:64,response:2*ae,rate:[10,6e4],states:"LFB"},"display.maximize":{request:64,response:64,rate:[2,1e3],states:"F"},"display.fullscreen":{request:64,response:64,rate:[1,1e3],states:"F"}}),Qe=Object.freeze(Object.keys(le).filter(e=>e!=="host.hello"&&e!=="card.show")),Ct=new TextEncoder,pe=e=>Ct.encode(e).byteLength,ee=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Y=(e,t,r=[])=>Reflect.ownKeys(e).every(o=>typeof o=="string"&&(t.includes(o)||r.includes(o))&&"value"in Object.getOwnPropertyDescriptor(e,o))&&t.every(o=>Object.hasOwn(e,o));var w=class extends Error{code;constructor(t,r){super(r),this.name="AppHostError",this.code=t}};function ze(e){let t=o=>new w("invalid",o),r=(o,s)=>{if(!(o===null||typeof o=="boolean"||typeof o=="string")){if(typeof o=="number"){if(!Number.isFinite(o))throw t("A save's numbers must be finite.");return}if(typeof o!="object")throw t("A save must contain only JSON values.");if(s>E.saveDepth)throw t(`A save nests at most ${E.saveDepth} levels deep.`);if(Array.isArray(o)){if(Reflect.ownKeys(o).length!==o.length+1)throw t("A save's arrays cannot have extra properties.");for(let l=0;l<o.length;l++){let f=Object.getOwnPropertyDescriptor(o,l);if(!f||!("value"in f))throw t("A save's arrays cannot be sparse or have accessors.");r(f.value,s+1)}return}if(!ee(o))throw t("A save must contain only plain objects, arrays and JSON values.");for(let l of Reflect.ownKeys(o)){let f=Object.getOwnPropertyDescriptor(o,l);if(typeof l!="string"||!f||!("value"in f)||!f.enumerable)throw t("A save's properties must be plain enumerable data.");r(f.value,s+1)}}};r(e,1);let n=JSON.stringify(e);if(pe(n)>E.saveBytes)throw new w("too-large",`A save is at most ${E.saveBytes.toLocaleString("en-US")} bytes of JSON.`);return n}function et(e){let t;try{t=JSON.parse(e)}catch{throw new w("invalid","The saved data is not JSON.")}return ze(t),t}var T=(e,t,r=0)=>typeof e=="string"&&e.length>=r&&e.length<=t,be=(e,t,r)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=r,It=e=>typeof e=="string"&&ke.includes(e),Fe=".bin",Ae=(e,t)=>`-/card/${e}/${t}${Fe}`,ve=e=>`-/cover/${e}${Fe}`,Ot=e=>`-/player/${e}${Fe}`;function tt(e,t){if(!ee(e)||!Y(e,t?["id","pack","name","rarity","count","art"]:["id","pack","name","rarity","art"]))throw Error("Invalid card.");let{id:r,pack:n,name:o,art:s}=e,l=typeof r=="string"?r.slice(r.indexOf("/")+1):"";if(!j(n)||r!==`${n}/${l}`||!$e.test(l)||!T(o,120)||!It(e.rarity)||t&&!be(e.count,1,1e6)||s!==null&&s!==Ae(n,l))throw Error("Invalid card.");return{id:r,pack:n,name:o,rarity:e.rarity,...t?{count:e.count}:{},art:s}}function Ve(e){return tt(e,!0)}function Tt(e){return tt(e,!1)}function rt(e){let{id:t,name:r,creator:n,art:o,total:s}=e;if(!j(t)||!T(r,120,1)||n!==null&&!T(n,64,1)||o!==null&&o!==ve(t)||!be(s,0,1e4))throw Error("Invalid pack.");return{id:t,name:r,creator:n,art:o,total:s}}function nt(e){if(!ee(e)||!Y(e,["id","name","creator","art","held","total"])||!be(e.held,0,1e4))throw Error("Invalid pack.");let t=rt(e);return{id:t.id,name:t.name,creator:t.creator,art:t.art,held:e.held,total:t.total}}function ot(e){if(!ee(e)||!Y(e,["id","name","creator","art","total","cards"])||!Array.isArray(e.cards)||e.cards.length>1e4)throw Error("Invalid pack.");let t=rt(e),r=e.cards.map(Tt);if(r.some(n=>n.pack!==t.id))throw Error("Invalid pack.");return{...t,cards:r}}var Lt=/[\u0000-\u001F\u007F-\u009F]/,Ye=e=>typeof e=="string"&&ce.handle.test(e);function st(e){if(ee(e)&&Y(e,["guest"])&&e.guest===!0)return{guest:!0};if(!ee(e)||!Y(e,["guest","handle","name","picture"],["username","token","expiresAt"])||e.guest!==!1)throw Error("Invalid player.");let{handle:t,username:r,name:n,picture:o,token:s,expiresAt:l}=e;if(!Ye(t)||!T(n,ce.nameMax,1)||Lt.test(n)||r!==void 0&&(!Ye(r)||r===t)||o!==null&&o!==Ot(t)||"token"in e!="expiresAt"in e||s!==void 0&&(!T(s,ce.tokenMax,ce.tokenMin)||!ce.token.test(s)||!be(l,0,Number.MAX_SAFE_INTEGER)))throw Error("Invalid player.");return{guest:!1,handle:t,...r===void 0?{}:{username:r},name:n,picture:o,...s===void 0?{}:{token:s,expiresAt:l}}}var je=e=>T(e,64,1);var it=e=>e.includes("/")?"../".repeat(e.split("/").length-1):"./";function at(e){let t=e.method,r=(...n)=>Y(e,["method",...n]);switch(t){case"ui.ready":case"app.checkpoint.get":return r()?{method:t}:null;case"game.finish":return r("score")?{method:t,...he({score:e.score})}:null;case"app.checkpoint.set":return r("value")?{method:t,value:Ne(e.value)}:null;case"host.hello":return r("protocol","sdk")&&e.protocol===2&&T(e.sdk,20,1)&&/^[\x20-\x7e]+$/.test(e.sdk)?{method:t,protocol:2,sdk:e.sdk}:null;case"ui.progress":return r("value")&&typeof e.value=="number"&&Number.isFinite(e.value)?{method:t,value:e.value}:null;case"app.frame":return r("id","image")&&Ie(e.id)&&(e.image===null||typeof e.image=="string")?{method:t,id:e.id,image:e.image}:null;case"app.save.get":case"cards.packs":case"player.get":return r()?{method:t}:null;case"app.save.set":return r("value")?{method:t,value:e.value}:null;case"cards.list":return!Y(e,["method"],["pack","after"])||"pack"in e&&!T(e.pack,64,1)||"after"in e&&!T(e.after,64,1)?null:{method:t,..."pack"in e?{pack:e.pack}:{},..."after"in e?{after:e.after}:{}};case"cards.pack":case"pack.show":return r("pack")&&T(e.pack,64,1)?{method:t,pack:e.pack}:null;case"card.show":return r("pack","card")&&T(e.pack,64,1)&&T(e.card,64,1)?{method:t,pack:e.pack,card:e.card}:null;case"display.maximize":case"display.fullscreen":case"cards.watch":return r("on")&&typeof e.on=="boolean"?{method:t,on:e.on}:null;default:return null}}function We(e){return Object.hasOwn(le,e)?le[e]:{request:v.requestBytes,response:v.responseBytes,states:"LFB"}}function Nt(e,t,r){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype||Object.keys(e).length!==3||!("session"in e)||e.session!==t||!("id"in e)||typeof e.id!="string"||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!("request"in e)||!e.request||typeof e.request!="object"||Array.isArray(e.request))throw Error("Invalid app session request.");let n=at(e.request),o=n!==null&&!Object.hasOwn(le,n.method);if(!n||!r&&!o&&n.method!=="host.hello"&&n.method!=="app.frame")throw Error("This app has no permission for that method.");if(pe(JSON.stringify(e.request))>We(n.method).request)throw Error("App request exceeds its bound.");return{id:e.id,request:n}}function ct(e,t){let r=[];return n=>(r=r.filter(o=>n-o<t),r.length>=e?!1:(r.push(n),!0))}var H={states:"That is not available while the app is loading or behind another window.",rate:"Too many requests of that kind; try again later.",slug:"That is not a pack slug.",after:"That page cursor is not valid.",unavailable:"The host could not answer that now; try again."};function lt(e=()=>performance.now(),t={}){let r=t.services,n=r!==void 0,o="null",s=!1,l,f,a=!1,m=e();if(!Number.isFinite(m))throw Error("App clock is invalid.");let d=m,R=m,I=0,J=0,O=m,z,L,P,A=!1,b,k=ct(E.requestsPerMinute,6e4),_=n?E.sessionMs:v.sessionMs,F=n?E.lifetimeRequests:v.lifetimeRequests,C=n?"App session reached its 4-hour limit. Reopen the app to keep playing.":"App session expired. Reopen the app.",W=p=>{if(s||z)return;z=p,clearTimeout(B),clearTimeout(P),o="null";let M=L;l?.close(),M?.(p)},B=setTimeout(()=>W(C),_),K=()=>{let p;try{p=e()}catch{W("App clock changed. Reopen the app.");return}if(!Number.isFinite(p)||p<d){W("App clock changed. Reopen the app.");return}if(d=p,p-m>=_){W(C);return}return p},te=p=>{clearTimeout(P),P=setTimeout(()=>{let M=K();if(M===void 0)return;let V=M-O;if(V<E.idleMs){te(E.idleMs-V);return}A||(A=!0,t.idle?.())},p)},g=p=>{O=p,A&&(A=!1,te(E.idleMs))};n&&te(E.idleMs);let D={protocol:n?2:1,attach(p,M,V){if(s||z||!Te(M))throw p.close(),Error(z??"App controller is closed.");if(K()===void 0)throw p.close(),Error(z);l?.close();let re=!1,Ee=0,ue=!1,xe=!1,Be=0,Se=!1,Pe=!1,U,De=new Set,Ge=new Map,mt=0,ne,Q=c=>{let i=ne;ne=void 0,i&&(clearTimeout(i.timer),i.resolve(c))},Me=()=>{Q(null),!re&&(re=!0,p.onmessage=null,p.onmessageerror=null,p.close(),l===Re&&(l=void 0,L=void 0,b=void 0))},q=c=>{re||(Me(),V.fault(c))},N=()=>!re&&!s&&V.current(),He=V.foreground??(()=>!0),oe=(c,i)=>{N()&&p.postMessage(X(c,i))},Re={lifecycle(c){N()&&p.postMessage(X({session:M,event:"app.lifecycle",state:ie(c)},v.responseBytes))},sound(c){oe({session:M,event:"app.sound",state:we(c)},256)},close:Me,capture(c=E.captureMs){if(Q(null),!N())return Promise.resolve(null);let i=String(++mt),y=typeof c=="number"&&Number.isFinite(c)?Math.max(0,c):E.captureMs;return new Promise(u=>{ne={id:i,resolve:u,timer:setTimeout(()=>{ne?.id===i&&Q(null)},y)};try{oe({session:M,event:"app.capture",id:i},256)}catch{Q(null)}})}};l=Re,L=V.fault,r&&(b=async()=>{if(!Pe||!U||!N())return;let c=await r.cards();if(!N()||!Pe||!U||!je(c.revision)||c.revision===U.revision)return;let i=new Map(c.cards.map(S=>{let x=Ve(S);return[x.id,x]})),y=[...i.values()].filter(S=>JSON.stringify(U.cards.get(S.id))!==JSON.stringify(S)),u=[...U.cards.keys()].filter(S=>!i.has(S)),h={changed:y,removed:u,revision:c.revision};pe(JSON.stringify(h))>E.cardsEventBytes&&(h={reset:!0,revision:c.revision}),U={revision:c.revision,cards:i},oe({session:M,event:"app.cards",state:h},E.cardsEventBytes+1024)});let Je=c=>{let i=ne?.id===c.id;if(c.image!==null&&!Oe(c.image))throw i&&Q(null),new w("invalid","That is not a PNG, JPEG or WebP data URL of at most 1,000,000 characters.");return i&&Q(c.image),{completed:!0}},ht=async(c,i)=>{let y=(u,h)=>{try{return h(u)}catch{throw new w("unavailable",H.unavailable)}};switch(i.method){case"host.hello":return{protocol:2,guest:c.guest,features:[...Qe,...c.showCard?["card.show"]:[]],root:it(c.entry)};case"ui.progress":if(!xe){if(i.value<0||i.value>1)throw new w("invalid","Progress is a number from 0 to 1.");V.progress?.(i.value)}return{completed:!0};case"app.frame":return Je(i);case"app.save.get":{let u=await c.saveGet();return{value:u.value===null?null:y(u.value,et),savedAt:u.savedAt===null?null:y(u.savedAt,h=>{if(typeof h!="string"||h.length>30)throw Error();return h})}}case"app.save.set":{let u=ze(i.value);if(Se)throw new w("rate-limited","A save is already being written.");Se=!0;try{let{savedAt:h}=await c.saveSet(u);return{savedAt:y(h,S=>{if(typeof S!="string"||S.length>30)throw Error();return S})}}finally{Se=!1}}case"cards.list":{if(i.pack!==void 0&&!j(i.pack))throw new w("invalid",H.slug);let u=i.after===void 0?0:/^(?:0|[1-9]\d{0,5})$/.test(i.after)?Number(i.after):-1;if(u<0)throw new w("invalid",H.after);let h=await c.cards(),S=y(h,$=>{if(!je($.revision)||!Array.isArray($.cards))throw Error();return $.cards.map(Ve)});i.pack===void 0&&u===0&&(U={revision:h.revision,cards:new Map(S.map($=>[$.id,$]))});let x=i.pack===void 0?S:S.filter($=>$.pack===i.pack),G=u+E.cardsPage;return{cards:x.slice(u,G),after:G<x.length?String(G):null,revision:h.revision}}case"cards.packs":return{packs:y(await c.packs(),u=>{if(!Array.isArray(u)||u.length>200)throw Error();return u.map(nt)})};case"cards.pack":if(!j(i.pack))throw new w("invalid",H.slug);return{pack:y(await c.pack(i.pack),u=>{let h=ot(u);if(h.id!==i.pack)throw Error();return h})};case"cards.watch":return Pe=i.on,{completed:!0};case"pack.show":if(!j(i.pack))throw new w("invalid",H.slug);return await c.showPack(i.pack),{shown:!0};case"card.show":if(!c.showCard)throw new w("unsupported","This host cannot show a card.");if(!j(i.pack)||!$e.test(i.card))throw new w("invalid","That is not a pack slug and a card id.");return await c.showCard(i.pack,i.card),{shown:!0};case"player.get":return y(await c.player(),st);case"display.maximize":return await c.maximize(i.on),{completed:!0};case"display.fullscreen":return await c.fullscreen(i.on),{completed:!0}}};p.onmessage=c=>{if(!N()){Me();return}let i=K();if(i===void 0)return;if(i-R>=1e3&&(R=i,I=0),++I>v.requestsPerSecond||++J>F||Ee>=(ue?E.inFlight:v.inFlight)||n&&!k(i)){q("App request limit exceeded.");return}let y,u;try{n?{id:y,request:u}=Nt(ye(c.data,E.messageBytes),M,ue):{id:y,request:u}=Ze(ye(c.data,qe),M)}catch{q("Invalid or unpermitted app request.");return}if(n){if(!/^[1-9]\d{0,15}$/.test(y)||Number(y)<=Be){q("App request was replayed.");return}Be=Number(y)}else{if(De.has(y)){q("App request was replayed.");return}De.add(y)}if(u.method==="host.hello"){if(ue){q("App said hello twice.");return}ue=!0}Ee++,n&&g(i);let h=u.method,S=h==="ui.ready"||h==="game.finish"||h==="app.checkpoint.get"||h==="app.checkpoint.set";Promise.resolve().then(()=>{if(N()&&!(!He()&&(h==="game.finish"||h==="app.checkpoint.set"))){if(u.method==="app.frame"&&!n){try{let x=Je(u);N()&&p.postMessage(X({session:M,id:y,result:x},v.responseBytes))}catch(x){N()&&p.postMessage(X({session:M,id:y,error:x.message,code:"invalid"},v.responseBytes))}return}if(S){let x;switch(u.method){case"ui.ready":xe=!0,V.ready(),x={completed:!0};break;case"game.finish":if(f&&f.score!==u.score){if(!n)throw Error("This game has already finished.");oe({session:M,id:y,error:"This game has already finished.",code:"invalid"},v.responseBytes);return}f??=Object.freeze({score:u.score}),x={completed:!0};break;case"app.checkpoint.get":x={checkpoint:JSON.parse(o)};break;default:o=Le(u.value),x={completed:!0};break}N()&&(p.postMessage(X({session:M,id:y,result:x},v.responseBytes)),h==="game.finish"&&f&&!a&&N()&&(a=!0,V.finish?.(f)));return}return ft(y,u,h,i)}}).catch(()=>{re||q("App request could not complete.")}).finally(()=>{Ee--})};let ft=async(c,i,y,u)=>{let h=We(y),S;try{let x=xe?He()?"F":"B":"L";if(!h.states.includes(x))throw new w("not-permitted",H.states);if(h.rate&&!(i.method==="display.fullscreen"&&!i.on)){let $=h.bucket??y,de=Ge.get($);if(de||(de=ct(h.rate[0],h.rate[1]),Ge.set($,de)),!de(u))throw new w("rate-limited",H.rate)}let G=await ht(r,i);if(pe(JSON.stringify(G))>h.response)throw new w("unavailable","The answer is larger than this request may return.");S={session:M,id:c,result:G}}catch(x){let G=x instanceof w?x.code:"unavailable";S={session:M,id:c,error:x instanceof w?x.message.slice(0,300):H.unavailable,code:G}}oe(S,E.messageBytes)};return p.onmessageerror=()=>q("App message could not be decoded."),p.start(),Re},suspend(){l?.close()},dispose(){s||(s=!0,clearTimeout(B),clearTimeout(P),l?.close(),o="null")}};return n&&(D.activity=()=>{let p=K();p!==void 0&&g(p)},D.cardsChanged=async()=>{try{await b?.()}catch{}}),D}function pt(e,t){let r=me(window);if(r)throw Error(r);if(!Te(t.challenge)||new URL(e.src).hash!==`#${fe}=${t.challenge}`)throw Error("Invalid app frame challenge.");let n=t.controller.protocol===2,o=!1,s=!1,l=!1,f=0,a,m=!1,d=ie({active:!0,width:0,height:0}),R=t.sound===void 0?null:we(t.sound),I=()=>O("App took too long to become ready."),J=()=>{o||(o=!0,clearTimeout(P),clearTimeout(A),e.removeEventListener("load",z),window.removeEventListener("message",L),a?.close())},O=b=>{o||(J(),t.fault(b))},z=()=>{s?O("App navigation ended this session."):s=!0},L=b=>{if(o||l||!t.current()||b.source!==e.contentWindow)return;if(++f>32){O("App connection limit exceeded.");return}if(!s||b.origin!=="null")return;let k;try{k=ye(b.data,256)}catch{O("Invalid app connection message.");return}if(!k||typeof k!="object"||Array.isArray(k)||!("channel"in k)||k.channel!==_e||!("type"in k)||k.type!=="connect"||!("challenge"in k)||k.challenge!==t.challenge||Object.keys(k).length!==3)return;l=!0,window.removeEventListener("message",L);let _=new MessageChannel,F=ge();try{if(a=t.controller.attach(_.port1,F,{current:t.current,foreground:t.foreground,ready(){m=!0,clearTimeout(P),clearTimeout(A),t.ready()},finish:t.finish,fault:O,progress(C){m||o||(clearTimeout(P),P=setTimeout(I,E.readyMs),t.progress?.(C))}}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:_e,challenge:t.challenge,session:F,...n?{protocol:2}:{}},"*",[_.port2]),a.lifecycle(d),R&&a.sound(R)}catch{_.port1.close(),_.port2.close(),O("App connection could not complete.")}},P=setTimeout(I,E.readyMs),A=n?setTimeout(I,E.progressReadyMs):void 0;return e.addEventListener("load",z),window.addEventListener("message",L),{resize(b,k){d=ie({active:d.active,width:Math.min(4096,Math.max(0,Math.floor(b))),height:Math.min(4096,Math.max(0,Math.floor(k)))}),a?.lifecycle(d)},setActive(b){b!==d.active&&(d=ie({...d,active:b}),a?.lifecycle(d))},setSound(b){let k=we(b);R&&R.muted===k.muted&&R.volume===k.volume||(R=k,a?.sound(k))},dispose:J,capture(b){return o||!a?Promise.resolve(null):a.capture(b)}}}function $t(e){if(!e||typeof e!="object"||!("runtime"in e)||typeof e.runtime!="string")throw Error("Invalid preview metadata.");let t=e,r=(s,l)=>Array.isArray(s)&&s.length<=8&&s.every(l)?s:null,n=r(t.packs,j),o=r(t.network,s=>typeof s=="string");if(typeof t.name!="string"||typeof t.id!="string"||typeof t.entry!="string"||!Xe(t.entry)||!n||!o||!(t.cards==="none"||t.cards==="linked"||t.cards==="all"))throw Error("Invalid preview metadata.");return{name:t.name,runtime:e.runtime,id:t.id,entry:t.entry,packs:n,cards:t.cards,network:o}}var ut=e=>e.split("-").map(t=>t[0].toUpperCase()+t.slice(1)).join(" "),dt="preview-public";function zt(e,t=Math.random){let r=e.packs.length?e.packs:e.cards==="all"?["preview-pack"]:[],n=a=>({id:a,name:ut(a),creator:"Preview",art:ve(a),total:6,cards:Array.from({length:6},(m,d)=>({id:`${a}/c${d+1}`,pack:a,name:`${ut(a)} #${d+1}`,rarity:ke[d%ke.length],art:Ae(a,`c${d+1}`)}))}),o=r.map(n),s=[...o,...r.includes(dt)?[]:[n(dt)]],l=new Map(o.flatMap(a=>a.cards.slice(0,3).map(m=>[m.id,1]))),f=1;return{pack(a){let m=s.find(d=>d.id===a);if(!m)throw new w("invalid","There is no such public pack.");return m},card(a,m){let d=this.pack(a).cards.find(R=>R.id===`${a}/${m}`);if(!d)throw new w("invalid","That card is not in that pack.");return d},cards(){if(e.cards==="none")throw new w("not-permitted","The manifest does not declare cards.");return{cards:o.flatMap(m=>m.cards.filter(d=>l.has(d.id)).map(d=>({...d,count:l.get(d.id)}))),revision:String(f)}},packs(){return o.map(({cards:a,...m})=>({...m,held:e.cards==="none"?0:a.filter(d=>l.has(d.id)).length}))},pull(){let a=o.flatMap(d=>d.cards);if(!a.length)return null;let m=a[Math.min(a.length-1,Math.floor(t()*a.length))];return l.set(m.id,(l.get(m.id)??0)+1),f++,m.name}}}function Ft(e,t){let r=`vmos-preview-save:${e}`,n={value:null,savedAt:null};return{get(){try{let o=t().getItem(r);if(o)return JSON.parse(o)}catch{}return n},set(o){n={value:o,savedAt:new Date().toISOString()};try{t().setItem(r,JSON.stringify(n))}catch{}return{savedAt:n.savedAt}}}}async function Vt(){let e=me(window);if(e)throw Error(e);let t=document.getElementById("surface"),r=document.getElementById("status"),n=document.getElementById("toggle"),o=document.getElementById("reset"),s=document.getElementById("pull"),l=document.getElementById("sound"),f=document.getElementById("volume"),a=document.getElementById("result"),m=document.getElementById("score");if(!t||!r||!a||!m||!(n instanceof HTMLButtonElement)||!(o instanceof HTMLButtonElement)||!(s instanceof HTMLButtonElement)||!(l instanceof HTMLButtonElement)||!(f instanceof HTMLInputElement))throw Error("Preview controls are missing.");let d=$t(await(await fetch("/preview.json",{credentials:"omit"})).json()),R=new URL(d.runtime);if(R.origin!==`http://localhost:${window.location.port}`||!/^\/game-assets\/[a-f0-9]{64}\//.test(R.pathname)||R.search||R.hash)throw Error("Invalid preview runtime.");let I=zt(d),J=Ft(d.id,()=>window.localStorage),O=()=>{if(!navigator.userActivation?.isActive)throw new w("needs-click","That needs a fresh click in the app.")},z={guest:!1,entry:d.entry,async saveGet(){return J.get()},async saveSet(g){return J.set(g)},async cards(){return I.cards()},async packs(){return I.packs()},async pack(g){return I.pack(g)},async showPack(g){I.pack(g),O(),r.textContent=`VibeMarket would open the pack ${g} in its market window here.`},async showCard(g,D){let p=I.card(g,D);O(),r.textContent=`VibeMarket would open the card ${p.name} (${D}) on the pack ${g}'s page here.`},async player(){let g={guest:!1,handle:"preview_player",username:"preview",name:"Preview Player",picture:null};return d.network.length?{...g,token:"preview.not-a-real-token.unsigned",expiresAt:Date.now()+3e5}:g},async maximize(g){t.classList.toggle("maximized",g)},async fullscreen(g){if(!g){document.fullscreenElement&&await document.exitFullscreen();return}O(),await t.requestFullscreen()}},L=()=>lt(void 0,{services:z,idle:()=>{r.textContent="Still playing? VibeMarket asks here after 15 minutes without input."}}),P=L(),A=null,b=null,k=null,_=!1,F=null,C={muted:!1,volume:1},W=()=>{b?.dispose(),b=null,P.suspend(),k?.disconnect(),k=null,A?.remove(),A=null},B=()=>{if(W(),t.hidden=_||document.hidden||F!==null,a.hidden=!0,_||document.hidden){r.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}if(F){a.hidden=!1,m.textContent=String(F.score),r.textContent="Round complete. No Cash reward for this preview.";return}let g=ge(),D=new URL(R);D.hash=`${fe}=${g}`,A=document.createElement("iframe"),A.title="VibeMarket OS app",A.sandbox.add("allow-scripts","allow-pointer-lock"),A.allow="autoplay; gamepad",A.setAttribute("credentialless",""),A.referrerPolicy="no-referrer",A.src=D.href,t.appendChild(A),b=pt(A,{controller:P,challenge:g,sound:C,current:()=>!_&&!document.hidden,ready:()=>{r.textContent="App ready \xB7 Minimize and restore to check its saved work."},progress:p=>{r.textContent=`Loading the isolated app\u2026 ${Math.round(p*100)}%`},finish:p=>{F=p,o.textContent="Play again",B()},fault:p=>{W(),P.dispose(),P=L(),r.textContent=p}}),k=new ResizeObserver(()=>{A&&b?.resize(A.clientWidth,A.clientHeight)}),k.observe(A),r.textContent="Loading the isolated app\u2026"};n.onclick=()=>{_=!_,n.textContent=_?"Restore":"Minimize",B()},o.onclick=()=>{W(),P.dispose(),P=L(),F=null,_=!1,n.textContent="Minimize",o.textContent="Close / reset",B()};let K=g=>{C=g,b?.setSound(C),l.textContent=C.muted?"Sound off":"Sound on",l.setAttribute("aria-pressed",String(!C.muted)),r.textContent=C.muted?"Desktop sound off: the app must be silent.":`Desktop sound on at ${Math.round(C.volume*100)}%: the app follows this volume.`};l.onclick=()=>K({muted:!C.muted,volume:C.volume}),f.oninput=()=>K({muted:C.muted,volume:Math.min(1,Math.max(0,Number(f.value)/100))}),s.onclick=()=>{let g=I.pull();r.textContent=g?`Pulled ${g}. The app hears about it through onCards.`:"This app links no packs and does not read all cards, so there is nothing to pull.",P.cardsChanged?.()};let te=window.setInterval(()=>{navigator.userActivation?.isActive&&P.activity?.()},1e4);document.addEventListener("visibilitychange",B),window.addEventListener("pagehide",()=>{window.clearInterval(te),W(),P.dispose(),document.removeEventListener("visibilitychange",B)},{once:!0}),B()}typeof window<"u"&&typeof document<"u"&&Vt().catch(e=>{let t=document.getElementById("status");t&&(t.textContent=e instanceof Error?e.message:"Preview failed.")});export{dt as PREVIEW_PUBLIC_PACK,zt as previewCatalog,$t as previewMetadata,Ft as previewSaves,Vt as startPreviewParent};
|
package/dist/preview.js
CHANGED
|
@@ -6,7 +6,7 @@ import { appRuntimeCsp, appRuntimeHeaders } from "./runtime-policy.js";
|
|
|
6
6
|
import { CARD_ID } from "./app-wire.js";
|
|
7
7
|
import { packSlug } from "./manifest.js";
|
|
8
8
|
const CSS = `body{margin:0;background:#387bd8;font:14px Arial;color:#17233a}main{max-width:1000px;margin:40px auto}header{display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:space-between;background:linear-gradient(#1684ff,#0049d9);color:white;padding:8px;border-radius:8px 8px 0 0}h1{font-size:15px;margin:0}.frame{background:#ece9d8;border:3px solid #0059e9;min-height:520px}iframe{border:0;width:100%;height:540px;display:block}button{padding:6px 12px}#status{padding:10px;background:#ece9d8;margin:0}small{display:block;padding:12px;color:#fff}#result{background:#ece9d8;border:3px solid #0059e9;text-align:center;padding:48px 24px;min-height:300px}#result h2{font-size:32px;margin:0 0 24px}#score{display:block;font-size:clamp(32px,10vw,72px);overflow-wrap:anywhere;max-width:100%;color:#176844;margin:16px}.maximized iframe{height:calc(100vh - 140px)}#surface:fullscreen iframe{height:100vh}`;
|
|
9
|
-
const HTML = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>VibeMarket OS App Preview</title><link rel="stylesheet" href="/preview.css"></head><body><main><header><h1>VibeMarket OS · App Preview</h1><div><button id="toggle" type="button">Minimize</button> <button id="pull" type="button">Pull a card</button> <button id="reset" type="button">Close / reset</button></div></header><div id="surface" class="frame"></div><section id="result" hidden aria-label="Game results"><h2>Round complete</h2><p>Your score: <strong id="score"></strong></p><p>No Cash reward for this preview.</p></section><p id="status" role="status">Loading the isolated app…</p><small>Local development only · fake cards, a fake player token and a save kept in this browser; no account, Cash, Steam or wallet. Build again and restart this preview to load changed files.</small></main><script type="module" src="/sdk/preview-ui.js"></script></body></html>`;
|
|
9
|
+
const HTML = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>VibeMarket OS App Preview</title><link rel="stylesheet" href="/preview.css"></head><body><main><header><h1>VibeMarket OS · App Preview</h1><div><button id="toggle" type="button">Minimize</button> <button id="pull" type="button">Pull a card</button> <button id="sound" type="button" aria-pressed="true">Sound on</button> <input id="volume" type="range" min="0" max="100" value="100" aria-label="Desktop volume"> <button id="reset" type="button">Close / reset</button></div></header><div id="surface" class="frame"></div><section id="result" hidden aria-label="Game results"><h2>Round complete</h2><p>Your score: <strong id="score"></strong></p><p>No Cash reward for this preview.</p></section><p id="status" role="status">Loading the isolated app…</p><small>Local development only · fake cards, a fake player token and a save kept in this browser; no account, Cash, Steam or wallet. Build again and restart this preview to load changed files.</small></main><script type="module" src="/sdk/preview-ui.js"></script></body></html>`;
|
|
10
10
|
const MODULES = new Set(["preview-ui.js"]);
|
|
11
11
|
/** One immutable in-memory bundle. No file serving by arbitrary URL, proxy, credential or write endpoint. */
|
|
12
12
|
export async function startAppPreview(directory, port = 0) {
|
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
(() => {
|
|
3
3
|
VibemarketOS.connect().then(async (os) => {
|
|
4
4
|
const cat = document.getElementById("cat");
|
|
5
|
-
|
|
5
|
+
if (!(cat instanceof HTMLButtonElement)) return;
|
|
6
|
+
const saved = await os.load();
|
|
7
|
+
const best = saved !== null && typeof saved === "object" && "best" in saved && typeof saved.best === "number" ? saved.best : 0;
|
|
6
8
|
let taps = 0;
|
|
7
9
|
cat.onclick = () => {
|
|
8
10
|
taps++;
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type AppLifecycle, type AppValue, type VibeMarketAppSdk } from "./app-protocol.ts";
|
|
1
|
+
import { type AppLifecycle, type AppSound, type AppValue, type VibeMarketAppSdk } from "./app-protocol.ts";
|
|
2
2
|
import { type Card, type Pack } from "./app-wire.ts";
|
|
3
3
|
import { type GameFinishInput } from "./completion.ts";
|
|
4
4
|
import { type Os } from "./os.ts";
|
|
@@ -7,12 +7,16 @@ export interface FakeAppOptions {
|
|
|
7
7
|
checkpoint?: AppValue;
|
|
8
8
|
/** Starting lifecycle. Default: active, 800 x 600. */
|
|
9
9
|
lifecycle?: Partial<AppLifecycle>;
|
|
10
|
+
/** The desktop's sound at the start. Default: audible at full volume, as on a host that does not control sound. */
|
|
11
|
+
sound?: Partial<AppSound>;
|
|
10
12
|
}
|
|
11
13
|
export interface FakeApp {
|
|
12
14
|
/** Pass this wherever your game expects the result of `connectVibeMarketApp()`. */
|
|
13
15
|
readonly app: VibeMarketAppSdk;
|
|
14
16
|
/** Change the lifecycle as the host would (minimize, restore, resize) and notify listeners. */
|
|
15
17
|
setLifecycle(next: Partial<AppLifecycle>): void;
|
|
18
|
+
/** Change the desktop's sound as the taskbar speaker or volume would, and notify `sound.onChanged` listeners. */
|
|
19
|
+
setSound(next: Partial<AppSound>): void;
|
|
16
20
|
/** True once the game called `ready()`. */
|
|
17
21
|
readonly ready: boolean;
|
|
18
22
|
/** The score the game finished with, or null. */
|
|
@@ -54,6 +58,8 @@ export interface FakeOsOptions {
|
|
|
54
58
|
};
|
|
55
59
|
/** Starting lifecycle. Default: active, 800 x 600. */
|
|
56
60
|
lifecycle?: Partial<AppLifecycle>;
|
|
61
|
+
/** The desktop's sound at the start. Default: audible at full volume, as on a host that does not control sound. */
|
|
62
|
+
sound?: Partial<AppSound>;
|
|
57
63
|
/** 1 behaves like a host older than 0.5: saves are the 32 KiB checkpoint and the rest is `unsupported`. Default 2. */
|
|
58
64
|
protocol?: 1 | 2;
|
|
59
65
|
/** The clock `player()` stamps expiry with. Default `Date.now`. */
|
|
@@ -66,6 +72,8 @@ export interface FakeOs {
|
|
|
66
72
|
setCards(cards: readonly Card[]): void;
|
|
67
73
|
/** Change the lifecycle as the host would (minimize, restore, resize) and call the pause, resume and resize listeners. */
|
|
68
74
|
setLifecycle(next: Partial<AppLifecycle>): void;
|
|
75
|
+
/** Change the desktop's sound as the taskbar speaker or volume would, and call the `onSound` listeners. */
|
|
76
|
+
setSound(next: Partial<AppSound>): void;
|
|
69
77
|
/** The next `showPack` or `fullscreen` call counts as following a click in the app. */
|
|
70
78
|
click(): void;
|
|
71
79
|
readonly ready: boolean;
|