@vibechain/os 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +11 -5
- package/README.md +76 -5
- package/SECURITY.md +22 -3
- package/dist/app-runtime.d.ts +1 -1
- package/dist/app-runtime.js +11 -3
- package/dist/bundle.js +10 -0
- package/dist/canvas.d.ts +40 -0
- package/dist/canvas.js +41 -0
- package/dist/listing.d.ts +35 -0
- package/dist/listing.js +56 -0
- package/dist/loop.d.ts +34 -0
- package/dist/loop.js +47 -0
- package/dist/manifest.d.ts +70 -1
- package/dist/manifest.js +117 -9
- package/dist/preview-ui.js +1 -1
- package/dist/scaffold.js +10 -3
- package/dist/testing.d.ts +29 -0
- package/dist/testing.js +49 -0
- package/examples/paw-beat/README.md +50 -0
- package/examples/paw-beat/cat.ts +129 -0
- package/examples/paw-beat/game.ts +151 -0
- package/examples/paw-beat/index.html +65 -0
- package/examples/paw-beat/main.ts +243 -0
- package/examples/paw-beat/music.ts +123 -0
- package/examples/paw-beat/store/icon.png +0 -0
- package/examples/paw-beat/store/screenshot-1.webp +0 -0
- package/examples/paw-beat/store/screenshot-2.webp +0 -0
- package/examples/paw-beat/vibemarket.json +21 -0
- package/examples/tsconfig.json +2 -2
- package/package.json +17 -1
package/dist/manifest.js
CHANGED
|
@@ -1,19 +1,32 @@
|
|
|
1
1
|
export const GAME_PERMISSIONS = ["profile.get", "catalog.list", "inventory.get", "packs.buy", "packs.sell", "packs.open", "cards.reveal", "cards.sell", "cards.collect"];
|
|
2
|
+
/** VibeStore listing categories. */
|
|
3
|
+
export const APP_STORE_CATEGORIES = ["game", "tool", "toy"];
|
|
4
|
+
/** Content rating levels for `store.rating.violence` and `store.rating.language`. */
|
|
5
|
+
export const APP_CONTENT_RATINGS = ["none", "mild", "strong"];
|
|
6
|
+
/** Screenshot file extensions a listing may name (lowercase). */
|
|
7
|
+
export const APP_SCREENSHOT_EXTENSIONS = ["png", "jpg", "jpeg", "webp"];
|
|
8
|
+
/** Window size bounds in CSS pixels, inclusive. */
|
|
9
|
+
export const APP_WINDOW_LIMITS = { minWidth: 320, maxWidth: 1600, minHeight: 200, maxHeight: 1200 };
|
|
10
|
+
/**
|
|
11
|
+
* Listing bounds, inclusive. Description length counts Unicode code points after trimming.
|
|
12
|
+
* The icon and screenshot byte limits are checked on bundle bytes by `checkListing` in `@vibechain/os/listing`.
|
|
13
|
+
*/
|
|
14
|
+
export const APP_STORE_LIMITS = {
|
|
15
|
+
descriptionMin: 40, descriptionMax: 2000, supportMax: 200, screenshotsMin: 1, screenshotsMax: 4,
|
|
16
|
+
iconSize: 256, iconBytes: 256 * 1024, screenshotBytes: 1024 * 1024,
|
|
17
|
+
};
|
|
2
18
|
export const GAME_LIMITS = { archive: 20 * 1024 * 1024, expanded: 64 * 1024 * 1024, file: 16 * 1024 * 1024, files: 256, versions: 100, games: 40 };
|
|
3
19
|
export function assetPath(value) {
|
|
4
20
|
return value.length > 0 && value.length <= 200 && value.split("/").every(part => /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(part) && !part.endsWith("."));
|
|
5
21
|
}
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
throw Error("Manifest fields must match schema version 1 exactly.");
|
|
22
|
+
const V1_FIELDS = ["schemaVersion", "sdkVersion", "id", "version", "name", "tagline", "category", "entry", "permissions", "collectionId"];
|
|
23
|
+
const record = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
24
|
+
const exactFields = (data, fields) => !Object.keys(data).some(key => !fields.includes(key)) && fields.every(key => key in data);
|
|
25
|
+
const extension = (file) => file.slice(file.lastIndexOf(".") + 1);
|
|
26
|
+
/** The rules both schema versions share; field set and version checks stay with the caller. */
|
|
27
|
+
function common(data) {
|
|
13
28
|
const str = (key, max) => { const value = data[key]; if (typeof value !== "string" || !value.trim() || value !== value.trim() || value.length > max)
|
|
14
29
|
throw Error(`Invalid manifest ${key}.`); return value; };
|
|
15
|
-
if (data.schemaVersion !== 1 || data.sdkVersion !== 1)
|
|
16
|
-
throw Error("Only manifest and SDK version 1 are supported.");
|
|
17
30
|
const id = str("id", 60), version = str("version", 50), entry = str("entry", 200);
|
|
18
31
|
if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(id) || id === "chonk-club")
|
|
19
32
|
throw Error("Choose a lowercase game slug; chonk-club is reserved for the built-in game.");
|
|
@@ -21,6 +34,14 @@ export function parseManifest(input) {
|
|
|
21
34
|
throw Error("Version must be semver, for example 1.0.0 or 1.0.0-test.1.");
|
|
22
35
|
if (!assetPath(entry) || !entry.endsWith(".html"))
|
|
23
36
|
throw Error("Entry must be a relative .html asset path.");
|
|
37
|
+
return { str, id, version, entry };
|
|
38
|
+
}
|
|
39
|
+
function parseV1(data) {
|
|
40
|
+
if (!exactFields(data, V1_FIELDS))
|
|
41
|
+
throw Error("Manifest fields must match schema version 1 exactly.");
|
|
42
|
+
if (data.schemaVersion !== 1 || data.sdkVersion !== 1)
|
|
43
|
+
throw Error("Only manifest and SDK version 1 are supported.");
|
|
44
|
+
const { str, id, version, entry } = common(data);
|
|
24
45
|
if (!Array.isArray(data.permissions) || data.permissions.some(value => typeof value !== "string" || !GAME_PERMISSIONS.includes(value)) || new Set(data.permissions).size !== data.permissions.length)
|
|
25
46
|
throw Error("Permissions must be a unique list of supported SDK methods.");
|
|
26
47
|
const permissions = data.permissions;
|
|
@@ -30,3 +51,90 @@ export function parseManifest(input) {
|
|
|
30
51
|
throw Error("Trading permissions require a collectionId.");
|
|
31
52
|
return { schemaVersion: 1, sdkVersion: 1, id, version, name: str("name", 60), tagline: str("tagline", 160), category: str("category", 80), entry, permissions: [...permissions].sort(), collectionId: data.collectionId };
|
|
32
53
|
}
|
|
54
|
+
function parseWindow(input) {
|
|
55
|
+
if (!record(input) || !exactFields(input, ["width", "height", "resizable"]))
|
|
56
|
+
throw Error("window must be an object with exactly width, height and resizable.");
|
|
57
|
+
const { width, height, resizable } = input, limits = APP_WINDOW_LIMITS;
|
|
58
|
+
if (!Number.isInteger(width) || width < limits.minWidth || width > limits.maxWidth)
|
|
59
|
+
throw Error(`window.width must be an integer from ${limits.minWidth} to ${limits.maxWidth}.`);
|
|
60
|
+
if (!Number.isInteger(height) || height < limits.minHeight || height > limits.maxHeight)
|
|
61
|
+
throw Error(`window.height must be an integer from ${limits.minHeight} to ${limits.maxHeight}.`);
|
|
62
|
+
if (typeof resizable !== "boolean")
|
|
63
|
+
throw Error("window.resizable must be true or false.");
|
|
64
|
+
return { width: width, height: height, resizable };
|
|
65
|
+
}
|
|
66
|
+
// Controls other than newline: C0 (tab and carriage return included), DEL and C1.
|
|
67
|
+
const CONTROL = /[\u0000-\u0009\u000B-\u001F\u007F-\u009F]/;
|
|
68
|
+
const EMAIL = /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*\.[A-Za-z]{2,63}$/;
|
|
69
|
+
/** An `https://` URL without credentials, or a plausible email address. Exported for forms that validate as the parser does. */
|
|
70
|
+
export function supportContact(value) {
|
|
71
|
+
if (value.length > APP_STORE_LIMITS.supportMax || value !== value.trim() || /\s/.test(value) || CONTROL.test(value))
|
|
72
|
+
return false;
|
|
73
|
+
if (!value.startsWith("https://"))
|
|
74
|
+
return EMAIL.test(value);
|
|
75
|
+
let url;
|
|
76
|
+
try {
|
|
77
|
+
url = new URL(value);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
return url.protocol === "https:" && !url.username && !url.password && /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]+)$/.test(url.hostname);
|
|
83
|
+
}
|
|
84
|
+
function parseStore(input) {
|
|
85
|
+
if (!record(input) || !exactFields(input, ["icon", "screenshots", "description", "category", "rating", "support"]))
|
|
86
|
+
throw Error("store must be an object with exactly icon, screenshots, description, category, rating and support.");
|
|
87
|
+
const limits = APP_STORE_LIMITS, { icon, screenshots, description, category, rating, support } = input;
|
|
88
|
+
if (typeof icon !== "string" || !assetPath(icon) || !icon.endsWith(".png"))
|
|
89
|
+
throw Error("store.icon must be a relative asset path ending in .png.");
|
|
90
|
+
if (!Array.isArray(screenshots) || screenshots.length < limits.screenshotsMin || screenshots.length > limits.screenshotsMax)
|
|
91
|
+
throw Error(`store.screenshots must list ${limits.screenshotsMin} to ${limits.screenshotsMax} images.`);
|
|
92
|
+
const shots = screenshots, paths = [], seen = new Set([icon.toLowerCase()]);
|
|
93
|
+
for (const shot of shots) {
|
|
94
|
+
if (typeof shot !== "string" || !assetPath(shot) || !APP_SCREENSHOT_EXTENSIONS.includes(extension(shot)))
|
|
95
|
+
throw Error("Each store screenshot must be a relative asset path ending in .png, .jpg, .jpeg or .webp.");
|
|
96
|
+
if (seen.has(shot.toLowerCase()))
|
|
97
|
+
throw Error("store.screenshots must be distinct files, none of them the icon.");
|
|
98
|
+
seen.add(shot.toLowerCase());
|
|
99
|
+
paths.push(shot);
|
|
100
|
+
}
|
|
101
|
+
if (typeof description !== "string" || CONTROL.test(description))
|
|
102
|
+
throw Error("store.description must be plain text; newlines are the only control characters allowed.");
|
|
103
|
+
const text = description.trim(), length = [...text].length;
|
|
104
|
+
if (length < limits.descriptionMin || length > limits.descriptionMax)
|
|
105
|
+
throw Error(`store.description must be ${limits.descriptionMin} to ${limits.descriptionMax} characters.`);
|
|
106
|
+
if (typeof category !== "string" || !APP_STORE_CATEGORIES.includes(category))
|
|
107
|
+
throw Error(`store.category must be one of ${APP_STORE_CATEGORIES.join(", ")}.`);
|
|
108
|
+
if (!record(rating) || !exactFields(rating, ["violence", "language", "mature"]))
|
|
109
|
+
throw Error("store.rating must be an object with exactly violence, language and mature.");
|
|
110
|
+
const levels = APP_CONTENT_RATINGS;
|
|
111
|
+
if (typeof rating.violence !== "string" || !levels.includes(rating.violence) || typeof rating.language !== "string" || !levels.includes(rating.language))
|
|
112
|
+
throw Error(`store.rating.violence and store.rating.language must each be one of ${APP_CONTENT_RATINGS.join(", ")}.`);
|
|
113
|
+
if (typeof rating.mature !== "boolean")
|
|
114
|
+
throw Error("store.rating.mature must be true or false.");
|
|
115
|
+
if (typeof support !== "string" || !supportContact(support))
|
|
116
|
+
throw Error(`store.support must be an https:// URL or an email address of at most ${limits.supportMax} characters.`);
|
|
117
|
+
return {
|
|
118
|
+
icon, screenshots: paths, description: text, category: category,
|
|
119
|
+
rating: { violence: rating.violence, language: rating.language, mature: rating.mature }, support,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function parseV2(data) {
|
|
123
|
+
if (!exactFields(data, [...V1_FIELDS, "window", "store"]))
|
|
124
|
+
throw Error("Manifest fields must match schema version 2 exactly.");
|
|
125
|
+
if (data.sdkVersion !== 1)
|
|
126
|
+
throw Error("Only SDK version 1 is supported.");
|
|
127
|
+
const { str, id, version, entry } = common(data);
|
|
128
|
+
if (data.category !== "vibexp-app" || !Array.isArray(data.permissions) || data.permissions.length || data.collectionId !== null)
|
|
129
|
+
throw Error("Schema version 2 apps must declare category vibexp-app, permissions [] and collectionId null.");
|
|
130
|
+
return {
|
|
131
|
+
schemaVersion: 2, sdkVersion: 1, id, version, name: str("name", 60), tagline: str("tagline", 160), category: "vibexp-app", entry,
|
|
132
|
+
permissions: [], collectionId: null, window: parseWindow(data.window), store: parseStore(data.store),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** Accepts schema version 1 exactly as before and schema version 2 with its window and store listing. Unknown fields are rejected at every level. */
|
|
136
|
+
export function parseManifest(input) {
|
|
137
|
+
if (!record(input))
|
|
138
|
+
throw Error("vibemarket.json must be an object.");
|
|
139
|
+
return input.schemaVersion === 2 ? parseV2(input) : parseV1(input);
|
|
140
|
+
}
|
package/dist/preview-ui.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var S="vibemarket.game.v1";function O(e){return e.location.protocol!=="http:"||!["127.0.0.1","localhost"].includes(e.location.hostname)?"Third-party apps are available only in the local browser developer preview.":e.top!==e.self?"Third-party apps require a top-level browser host.":["__VM_STEAM__","__TAURI_INTERNALS__","__TAURI__","vibeNative","ReactNativeWebView"].some(t=>t in e)||/\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i.test(e.navigator.userAgent)?"Third-party apps are disabled in native shells until their IPC isolation is verified.":null}function J(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 P="vibexp";var l=Object.freeze({checkpointBytes:32*1024,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34*1024,responseBytes:34*1024,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:900*1e3,requestTimeoutMs:1e4});function j(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function T(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,"0")).join("")}function B(e,t){let n=JSON.stringify(e);if(typeof n!="string"||n.length>t||new TextEncoder().encode(n).length>t)throw Error("App message exceeds limit.");return n}function V(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 M=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),I=(e,t)=>{let n=Object.keys(e);return n.length===t.length&&Reflect.ownKeys(e).length===n.length&&n.every(i=>t.includes(i)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,i)??{},"value"))};function G(e){let t=0,n=0,i=(o,m)=>{if(++t>l.checkpointNodes||m>l.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>l.stringBytes)throw Error("App checkpoint string is too large.");let s=new TextEncoder().encode(o).byteLength;if(s>l.stringBytes||(n+=s)>l.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(o)){if(o.length>l.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 s=0;s<o.length;s++){let p=Object.getOwnPropertyDescriptor(o,s);if(!p||!("value"in p))throw Error("Sparse/accessor checkpoints are unsupported.");i(p.value,m+1)}return}if(!M(o))throw Error("App checkpoint must contain only JSON values.");let u=Object.keys(o);if(Reflect.ownKeys(o).length!==u.length)throw Error("Checkpoint properties must be enumerable strings.");if(u.length>l.objectKeys)throw Error("App checkpoint has too many keys.");for(let s of u){if(["__proto__","constructor","prototype"].includes(s)||s.length>128)throw Error("Invalid app checkpoint key.");if(n+=new TextEncoder().encode(s).byteLength,n>l.checkpointBytes)throw Error("App checkpoint keys are too large.");let p=Object.getOwnPropertyDescriptor(o,s);if(!p||!("value"in p))throw Error("App checkpoint accessors are unsupported.");i(p.value,m+1)}};i(e,0);let d=JSON.stringify(e);if(new TextEncoder().encode(d).byteLength>l.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return d}function $(e){return JSON.parse(G(e))}function D(e,t){if(!M(e)||!I(e,["id","session","request"])||e.session!==t||typeof e.id!="string"||e.id.length>80||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!M(e.request))throw Error("Invalid app session request.");let n=e.request;if(n.method==="game.finish"&&I(n,["method","score"]))return{id:e.id,request:{method:"game.finish",...J({score:n.score})}};if((n.method==="ui.ready"||n.method==="app.checkpoint.get")&&I(n,["method"]))return{id:e.id,request:{method:n.method}};if(n.method==="app.checkpoint.set"&&I(n,["method","value"]))return{id:e.id,request:{method:n.method,value:$(n.value)}};throw Error("This app has no permission for that method.")}function _(e){if(!M(e)||!I(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})}function L(e=()=>performance.now()){let t="null",n=!1,i,d,o=!1,m=e();if(!Number.isFinite(m))throw Error("App clock is invalid.");let u=m,s=m,p=0,c=0,g,y,f=r=>{if(n||g)return;g=r,clearTimeout(h),t="null";let w=y;i?.close(),w?.(r)},h=setTimeout(()=>f("App session expired. Reopen the app."),l.sessionMs),a=()=>{let r;try{r=e()}catch{f("App clock changed. Reopen the app.");return}if(!Number.isFinite(r)||r<u){f("App clock changed. Reopen the app.");return}if(u=r,r-m>=l.sessionMs){f("App session expired. Reopen the app.");return}return r};return{attach(r,w,b){if(n||g||!j(w))throw r.close(),Error(g??"App controller is closed.");if(a()===void 0)throw r.close(),Error(g);i?.close();let A=!1,N=0,z=new Set,C=()=>{A||(A=!0,r.onmessage=null,r.onmessageerror=null,r.close(),i===F&&(i=void 0,y=void 0))},k=x=>{A||(C(),b.fault(x))},E=()=>!A&&!n&&b.current(),F={lifecycle(x){E()&&r.postMessage(B({session:w,event:"app.lifecycle",state:_(x)},l.responseBytes))},close:C};return i=F,y=b.fault,r.onmessage=x=>{if(!E()){C();return}let q=a();if(q===void 0)return;if(q-s>=1e3&&(s=q,p=0),++p>l.requestsPerSecond||++c>l.lifetimeRequests||N>=l.inFlight){k("App request limit exceeded.");return}let v;try{v=D(V(x.data,l.requestBytes),w)}catch{k("Invalid or unpermitted app request.");return}if(z.has(v.id)){k("App request was replayed.");return}z.add(v.id),N++,Promise.resolve().then(()=>{if(!E())return;let R;switch(v.request.method){case"ui.ready":b.ready(),R={completed:!0};break;case"game.finish":if(d&&d.score!==v.request.score)throw Error("This game has already finished.");d??=Object.freeze({score:v.request.score}),R={completed:!0};break;case"app.checkpoint.get":R={checkpoint:JSON.parse(t)};break;case"app.checkpoint.set":t=G(v.request.value),R={completed:!0};break}let K={session:w,id:v.id,result:R};E()&&(r.postMessage(B(K,l.responseBytes)),v.request.method==="game.finish"&&d&&!o&&E()&&(o=!0,b.finish?.(d)))}).catch(()=>{A||k("App request could not complete.")}).finally(()=>{N--})},r.onmessageerror=()=>k("App message could not be decoded."),r.start(),F},suspend(){i?.close()},dispose(){n||(n=!0,clearTimeout(h),i?.close(),t="null")}}}function H(e,t){let n=O(window);if(n)throw Error(n);if(!j(t.challenge)||new URL(e.src).hash!==`#${P}=${t.challenge}`)throw Error("Invalid app frame challenge.");let i=!1,d=!1,o=!1,m=0,u,s=_({active:!0,width:0,height:0}),p=()=>{i||(i=!0,clearTimeout(f),e.removeEventListener("load",g),window.removeEventListener("message",y),u?.close())},c=h=>{i||(p(),t.fault(h))},g=()=>{d?c("App navigation ended this session."):d=!0},y=h=>{if(i||o||!t.current()||h.source!==e.contentWindow)return;if(++m>32){c("App connection limit exceeded.");return}if(!d||h.origin!=="null")return;let a;try{a=V(h.data,256)}catch{c("Invalid app connection message.");return}if(!a||typeof a!="object"||Array.isArray(a)||!("channel"in a)||a.channel!==S||!("type"in a)||a.type!=="connect"||!("challenge"in a)||a.challenge!==t.challenge||Object.keys(a).length!==3)return;o=!0,window.removeEventListener("message",y);let r=new MessageChannel,w=T();try{if(u=t.controller.attach(r.port1,w,{current:t.current,ready(){clearTimeout(f),t.ready()},finish:t.finish,fault:c}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:S,challenge:t.challenge,session:w},"*",[r.port2]),u.lifecycle(s)}catch{r.port1.close(),r.port2.close(),c("App connection could not complete.")}},f=setTimeout(()=>c("App took too long to become ready."),15e3);return e.addEventListener("load",g),window.addEventListener("message",y),{resize(h,a){s=_({active:!0,width:Math.min(4096,Math.max(0,Math.floor(h))),height:Math.min(4096,Math.max(0,Math.floor(a)))}),u?.lifecycle(s)},dispose:p}}async function U(){let e=O(window);if(e)throw Error(e);let t=document.getElementById("surface"),n=document.getElementById("status"),i=document.getElementById("toggle"),d=document.getElementById("reset"),o=document.getElementById("result"),m=document.getElementById("score");if(!t||!n||!o||!m||!(i instanceof HTMLButtonElement)||!(d instanceof HTMLButtonElement))throw Error("Preview controls are missing.");let u=await(await fetch("/preview.json",{credentials:"omit"})).json();if(!u||typeof u!="object"||!("runtime"in u)||typeof u.runtime!="string")throw Error("Invalid preview metadata.");let s=new URL(u.runtime);if(s.origin!==`http://localhost:${window.location.port}`||!/^\/game-assets\/[a-f0-9]{64}\//.test(s.pathname)||s.search||s.hash)throw Error("Invalid preview runtime.");let p=L(),c=null,g=null,y=null,f=!1,h=null,a=()=>{g?.dispose(),g=null,p.suspend(),y?.disconnect(),y=null,c?.remove(),c=null},r=()=>{if(a(),t.hidden=f||document.hidden||h!==null,o.hidden=!0,f||document.hidden){n.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}if(h){o.hidden=!1,m.textContent=String(h.score),n.textContent="Round complete. No Cash reward for this preview.";return}let w=T(),b=new URL(s);b.hash=`${P}=${w}`,c=document.createElement("iframe"),c.title="VibeMarket OS app",c.sandbox.add("allow-scripts"),c.referrerPolicy="no-referrer",c.src=b.href,t.appendChild(c),g=H(c,{controller:p,challenge:w,current:()=>!f&&!document.hidden,ready:()=>{n.textContent="App ready \xB7 Minimize and restore to check its saved work."},finish:A=>{h=A,d.textContent="Play again",r()},fault:A=>{a(),p.dispose(),p=L(),n.textContent=A}}),y=new ResizeObserver(()=>{c&&g?.resize(c.clientWidth,c.clientHeight)}),y.observe(c),n.textContent="Loading the isolated app\u2026"};i.onclick=()=>{f=!f,i.textContent=f?"Restore":"Minimize",r()},d.onclick=()=>{a(),p.dispose(),p=L(),h=null,f=!1,i.textContent="Minimize",d.textContent="Close / reset",r()},document.addEventListener("visibilitychange",r),window.addEventListener("pagehide",()=>{a(),p.dispose(),document.removeEventListener("visibilitychange",r)},{once:!0}),r()}typeof window<"u"&&typeof document<"u"&&U().catch(e=>{let t=document.getElementById("status");t&&(t.textContent=e instanceof Error?e.message:"Preview failed.")});export{U as startPreviewParent};
|
|
1
|
+
var q="vibemarket.game.v1";var U=["127.0.0.1","localhost"],$=["vibechain.com","www.vibechain.com"];function W({protocol:e,hostname:t,port:n}){return e==="http:"?U.includes(t):e==="https:"&&$.includes(t)&&n===""}function O(e){return W(e.location)?e.top!==e.self?"Third-party apps require a top-level browser host.":["__VM_STEAM__","__TAURI_INTERNALS__","__TAURI__","vibeNative","ReactNativeWebView"].some(t=>t in e)||/\b(Tauri|Electron|VibeSteam|VibeMarketDesktop|wv)\b/i.test(e.navigator.userAgent)?"Third-party apps are disabled in native shells until their IPC isolation is verified.":null:"Third-party apps are available only on vibechain.com and in the local browser developer preview."}function J(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 P="vibexp";var l=Object.freeze({checkpointBytes:32*1024,checkpointDepth:8,checkpointNodes:2048,objectKeys:64,arrayItems:256,stringBytes:8192,requestBytes:34*1024,responseBytes:34*1024,requestsPerSecond:10,inFlight:4,lifetimeRequests:5e3,sessionMs:900*1e3,requestTimeoutMs:1e4});function j(e){return typeof e=="string"&&/^[a-f0-9]{32}$/.test(e)}function M(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,"0")).join("")}function B(e,t){let n=JSON.stringify(e);if(typeof n!="string"||n.length>t||new TextEncoder().encode(n).length>t)throw Error("App message exceeds limit.");return n}function V(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 T=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),I=(e,t)=>{let n=Object.keys(e);return n.length===t.length&&Reflect.ownKeys(e).length===n.length&&n.every(i=>t.includes(i)&&Object.hasOwn(Object.getOwnPropertyDescriptor(e,i)??{},"value"))};function G(e){let t=0,n=0,i=(o,m)=>{if(++t>l.checkpointNodes||m>l.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>l.stringBytes)throw Error("App checkpoint string is too large.");let s=new TextEncoder().encode(o).byteLength;if(s>l.stringBytes||(n+=s)>l.checkpointBytes)throw Error("App checkpoint strings are too large.");return}if(Array.isArray(o)){if(o.length>l.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 s=0;s<o.length;s++){let a=Object.getOwnPropertyDescriptor(o,s);if(!a||!("value"in a))throw Error("Sparse/accessor checkpoints are unsupported.");i(a.value,m+1)}return}if(!T(o))throw Error("App checkpoint must contain only JSON values.");let u=Object.keys(o);if(Reflect.ownKeys(o).length!==u.length)throw Error("Checkpoint properties must be enumerable strings.");if(u.length>l.objectKeys)throw Error("App checkpoint has too many keys.");for(let s of u){if(["__proto__","constructor","prototype"].includes(s)||s.length>128)throw Error("Invalid app checkpoint key.");if(n+=new TextEncoder().encode(s).byteLength,n>l.checkpointBytes)throw Error("App checkpoint keys are too large.");let a=Object.getOwnPropertyDescriptor(o,s);if(!a||!("value"in a))throw Error("App checkpoint accessors are unsupported.");i(a.value,m+1)}};i(e,0);let d=JSON.stringify(e);if(new TextEncoder().encode(d).byteLength>l.checkpointBytes)throw Error("App checkpoint exceeds32KiB.");return d}function Y(e){return JSON.parse(G(e))}function H(e,t){if(!T(e)||!I(e,["id","session","request"])||e.session!==t||typeof e.id!="string"||e.id.length>80||!/^[A-Za-z0-9_-]{1,80}$/.test(e.id)||!T(e.request))throw Error("Invalid app session request.");let n=e.request;if(n.method==="game.finish"&&I(n,["method","score"]))return{id:e.id,request:{method:"game.finish",...J({score:n.score})}};if((n.method==="ui.ready"||n.method==="app.checkpoint.get")&&I(n,["method"]))return{id:e.id,request:{method:n.method}};if(n.method==="app.checkpoint.set"&&I(n,["method","value"]))return{id:e.id,request:{method:n.method,value:Y(n.value)}};throw Error("This app has no permission for that method.")}function _(e){if(!T(e)||!I(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})}function L(e=()=>performance.now()){let t="null",n=!1,i,d,o=!1,m=e();if(!Number.isFinite(m))throw Error("App clock is invalid.");let u=m,s=m,a=0,c=0,g,y,f=r=>{if(n||g)return;g=r,clearTimeout(h),t="null";let w=y;i?.close(),w?.(r)},h=setTimeout(()=>f("App session expired. Reopen the app."),l.sessionMs),p=()=>{let r;try{r=e()}catch{f("App clock changed. Reopen the app.");return}if(!Number.isFinite(r)||r<u){f("App clock changed. Reopen the app.");return}if(u=r,r-m>=l.sessionMs){f("App session expired. Reopen the app.");return}return r};return{attach(r,w,b){if(n||g||!j(w))throw r.close(),Error(g??"App controller is closed.");if(p()===void 0)throw r.close(),Error(g);i?.close();let A=!1,C=0,z=new Set,N=()=>{A||(A=!0,r.onmessage=null,r.onmessageerror=null,r.close(),i===S&&(i=void 0,y=void 0))},k=x=>{A||(N(),b.fault(x))},E=()=>!A&&!n&&b.current(),S={lifecycle(x){E()&&r.postMessage(B({session:w,event:"app.lifecycle",state:_(x)},l.responseBytes))},close:N};return i=S,y=b.fault,r.onmessage=x=>{if(!E()){N();return}let F=p();if(F===void 0)return;if(F-s>=1e3&&(s=F,a=0),++a>l.requestsPerSecond||++c>l.lifetimeRequests||C>=l.inFlight){k("App request limit exceeded.");return}let v;try{v=H(V(x.data,l.requestBytes),w)}catch{k("Invalid or unpermitted app request.");return}if(z.has(v.id)){k("App request was replayed.");return}z.add(v.id),C++,Promise.resolve().then(()=>{if(!E())return;let R;switch(v.request.method){case"ui.ready":b.ready(),R={completed:!0};break;case"game.finish":if(d&&d.score!==v.request.score)throw Error("This game has already finished.");d??=Object.freeze({score:v.request.score}),R={completed:!0};break;case"app.checkpoint.get":R={checkpoint:JSON.parse(t)};break;case"app.checkpoint.set":t=G(v.request.value),R={completed:!0};break}let K={session:w,id:v.id,result:R};E()&&(r.postMessage(B(K,l.responseBytes)),v.request.method==="game.finish"&&d&&!o&&E()&&(o=!0,b.finish?.(d)))}).catch(()=>{A||k("App request could not complete.")}).finally(()=>{C--})},r.onmessageerror=()=>k("App message could not be decoded."),r.start(),S},suspend(){i?.close()},dispose(){n||(n=!0,clearTimeout(h),i?.close(),t="null")}}}function D(e,t){let n=O(window);if(n)throw Error(n);if(!j(t.challenge)||new URL(e.src).hash!==`#${P}=${t.challenge}`)throw Error("Invalid app frame challenge.");let i=!1,d=!1,o=!1,m=0,u,s=_({active:!0,width:0,height:0}),a=()=>{i||(i=!0,clearTimeout(f),e.removeEventListener("load",g),window.removeEventListener("message",y),u?.close())},c=h=>{i||(a(),t.fault(h))},g=()=>{d?c("App navigation ended this session."):d=!0},y=h=>{if(i||o||!t.current()||h.source!==e.contentWindow)return;if(++m>32){c("App connection limit exceeded.");return}if(!d||h.origin!=="null")return;let p;try{p=V(h.data,256)}catch{c("Invalid app connection message.");return}if(!p||typeof p!="object"||Array.isArray(p)||!("channel"in p)||p.channel!==q||!("type"in p)||p.type!=="connect"||!("challenge"in p)||p.challenge!==t.challenge||Object.keys(p).length!==3)return;o=!0,window.removeEventListener("message",y);let r=new MessageChannel,w=M();try{if(u=t.controller.attach(r.port1,w,{current:t.current,ready(){clearTimeout(f),t.ready()},finish:t.finish,fault:c}),!e.contentWindow)throw Error("App frame is unavailable.");e.contentWindow.postMessage({channel:q,challenge:t.challenge,session:w},"*",[r.port2]),u.lifecycle(s)}catch{r.port1.close(),r.port2.close(),c("App connection could not complete.")}},f=setTimeout(()=>c("App took too long to become ready."),15e3);return e.addEventListener("load",g),window.addEventListener("message",y),{resize(h,p){s=_({active:!0,width:Math.min(4096,Math.max(0,Math.floor(h))),height:Math.min(4096,Math.max(0,Math.floor(p)))}),u?.lifecycle(s)},dispose:a}}async function Z(){let e=O(window);if(e)throw Error(e);let t=document.getElementById("surface"),n=document.getElementById("status"),i=document.getElementById("toggle"),d=document.getElementById("reset"),o=document.getElementById("result"),m=document.getElementById("score");if(!t||!n||!o||!m||!(i instanceof HTMLButtonElement)||!(d instanceof HTMLButtonElement))throw Error("Preview controls are missing.");let u=await(await fetch("/preview.json",{credentials:"omit"})).json();if(!u||typeof u!="object"||!("runtime"in u)||typeof u.runtime!="string")throw Error("Invalid preview metadata.");let s=new URL(u.runtime);if(s.origin!==`http://localhost:${window.location.port}`||!/^\/game-assets\/[a-f0-9]{64}\//.test(s.pathname)||s.search||s.hash)throw Error("Invalid preview runtime.");let a=L(),c=null,g=null,y=null,f=!1,h=null,p=()=>{g?.dispose(),g=null,a.suspend(),y?.disconnect(),y=null,c?.remove(),c=null},r=()=>{if(p(),t.hidden=f||document.hidden||h!==null,o.hidden=!0,f||document.hidden){n.textContent="App suspended. Its host-accepted checkpoint stays in this window.";return}if(h){o.hidden=!1,m.textContent=String(h.score),n.textContent="Round complete. No Cash reward for this preview.";return}let w=M(),b=new URL(s);b.hash=`${P}=${w}`,c=document.createElement("iframe"),c.title="VibeMarket OS app",c.sandbox.add("allow-scripts"),c.referrerPolicy="no-referrer",c.src=b.href,t.appendChild(c),g=D(c,{controller:a,challenge:w,current:()=>!f&&!document.hidden,ready:()=>{n.textContent="App ready \xB7 Minimize and restore to check its saved work."},finish:A=>{h=A,d.textContent="Play again",r()},fault:A=>{p(),a.dispose(),a=L(),n.textContent=A}}),y=new ResizeObserver(()=>{c&&g?.resize(c.clientWidth,c.clientHeight)}),y.observe(c),n.textContent="Loading the isolated app\u2026"};i.onclick=()=>{f=!f,i.textContent=f?"Restore":"Minimize",r()},d.onclick=()=>{p(),a.dispose(),a=L(),h=null,f=!1,i.textContent="Minimize",d.textContent="Close / reset",r()},document.addEventListener("visibilitychange",r),window.addEventListener("pagehide",()=>{p(),a.dispose(),document.removeEventListener("visibilitychange",r)},{once:!0}),r()}typeof window<"u"&&typeof document<"u"&&Z().catch(e=>{let t=document.getElementById("status");t&&(t.textContent=e instanceof Error?e.message:"Preview failed.")});export{Z as startPreviewParent};
|
package/dist/scaffold.js
CHANGED
|
@@ -45,12 +45,19 @@ export async function createApp(directory, sdkTarball) {
|
|
|
45
45
|
}
|
|
46
46
|
export async function stageAppAssets(root) {
|
|
47
47
|
const directory = await realpath(root), output = path.join(directory, "dist");
|
|
48
|
-
parseManifest(JSON.parse(new TextDecoder().decode(await readBoundedAsset(path.join(directory, "vibemarket.json"), 16 * 1024))));
|
|
48
|
+
const manifest = parseManifest(JSON.parse(new TextDecoder().decode(await readBoundedAsset(path.join(directory, "vibemarket.json"), 16 * 1024))));
|
|
49
49
|
await mkdir(output, { recursive: true });
|
|
50
50
|
if (await realpath(output) !== output)
|
|
51
51
|
throw Error("App output cannot be a symlink.");
|
|
52
|
-
|
|
53
|
-
|
|
52
|
+
// A schema version 2 listing also needs its store images next to the built app.
|
|
53
|
+
const names = ["index.html", "vibemarket.json", ...(manifest.schemaVersion === 2 ? [manifest.store.icon, ...manifest.store.screenshots] : [])];
|
|
54
|
+
for (const name of names) {
|
|
55
|
+
const destination = path.join(output, name), parent = path.dirname(destination);
|
|
56
|
+
if (parent !== output) {
|
|
57
|
+
await mkdir(parent, { recursive: true });
|
|
58
|
+
if (await realpath(parent) !== parent)
|
|
59
|
+
throw Error("App output cannot be a symlink.");
|
|
60
|
+
}
|
|
54
61
|
try {
|
|
55
62
|
if ((await lstat(destination)).isSymbolicLink())
|
|
56
63
|
throw Error("App output cannot contain symlinked files.");
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type AppLifecycle, type AppValue, type VibeMarketAppSdk } from "./app-protocol.ts";
|
|
2
|
+
import { type GameFinishInput } from "./completion.ts";
|
|
3
|
+
export interface FakeAppOptions {
|
|
4
|
+
/** What `checkpoint.read()` returns first. Default: `null`, as on a first open. */
|
|
5
|
+
checkpoint?: AppValue;
|
|
6
|
+
/** Starting lifecycle. Default: active, 800 x 600. */
|
|
7
|
+
lifecycle?: Partial<AppLifecycle>;
|
|
8
|
+
}
|
|
9
|
+
export interface FakeApp {
|
|
10
|
+
/** Pass this wherever your game expects the result of `connectVibeMarketApp()`. */
|
|
11
|
+
readonly app: VibeMarketAppSdk;
|
|
12
|
+
/** Change the lifecycle as the host would (minimize, restore, resize) and notify listeners. */
|
|
13
|
+
setLifecycle(next: Partial<AppLifecycle>): void;
|
|
14
|
+
/** True once the game called `ready()`. */
|
|
15
|
+
readonly ready: boolean;
|
|
16
|
+
/** The score the game finished with, or null. */
|
|
17
|
+
readonly finished: Readonly<GameFinishInput> | null;
|
|
18
|
+
/** The last checkpoint the fake host accepted. */
|
|
19
|
+
readonly checkpoint: AppValue;
|
|
20
|
+
/** True once the game called `destroy()`. */
|
|
21
|
+
readonly destroyed: boolean;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* An in-memory stand-in for the VibeMarket OS host, for unit tests. It applies the same
|
|
25
|
+
* checkpoint, score and lifecycle validation as the real host and the same single-shot
|
|
26
|
+
* completion rule, but has no window, no port, no time limit and no request budget.
|
|
27
|
+
* Passing here does not replace a run in the preview.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createFakeApp(options?: FakeAppOptions): FakeApp;
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { checkpointValue, lifecycleValue } from "./app-protocol.js";
|
|
2
|
+
import { gameFinishInput } from "./completion.js";
|
|
3
|
+
/**
|
|
4
|
+
* An in-memory stand-in for the VibeMarket OS host, for unit tests. It applies the same
|
|
5
|
+
* checkpoint, score and lifecycle validation as the real host and the same single-shot
|
|
6
|
+
* completion rule, but has no window, no port, no time limit and no request budget.
|
|
7
|
+
* Passing here does not replace a run in the preview.
|
|
8
|
+
*/
|
|
9
|
+
export function createFakeApp(options = {}) {
|
|
10
|
+
let checkpoint = checkpointValue(options.checkpoint ?? null);
|
|
11
|
+
let state = lifecycleValue({ active: true, width: 800, height: 600, ...options.lifecycle });
|
|
12
|
+
let ready = false, destroyed = false, finished = null;
|
|
13
|
+
const listeners = new Set();
|
|
14
|
+
const open = () => { if (destroyed)
|
|
15
|
+
throw Error("Game session ended."); };
|
|
16
|
+
const app = Object.freeze({
|
|
17
|
+
game: Object.freeze({
|
|
18
|
+
async finish(input) {
|
|
19
|
+
open();
|
|
20
|
+
const result = gameFinishInput(input);
|
|
21
|
+
if (finished && finished.score !== result.score)
|
|
22
|
+
throw Error("This game has already finished.");
|
|
23
|
+
finished ??= result;
|
|
24
|
+
},
|
|
25
|
+
}),
|
|
26
|
+
async ready() { open(); ready = true; },
|
|
27
|
+
checkpoint: Object.freeze({
|
|
28
|
+
async read() { open(); return checkpointValue(checkpoint); },
|
|
29
|
+
async write(value) { open(); checkpoint = checkpointValue(value); },
|
|
30
|
+
}),
|
|
31
|
+
lifecycle: Object.freeze({
|
|
32
|
+
current: () => state,
|
|
33
|
+
onChanged(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
34
|
+
}),
|
|
35
|
+
destroy() { destroyed = true; listeners.clear(); },
|
|
36
|
+
});
|
|
37
|
+
return {
|
|
38
|
+
app,
|
|
39
|
+
setLifecycle(next) {
|
|
40
|
+
state = lifecycleValue({ ...state, ...next });
|
|
41
|
+
for (const listener of [...listeners])
|
|
42
|
+
listener(state);
|
|
43
|
+
},
|
|
44
|
+
get ready() { return ready; },
|
|
45
|
+
get finished() { return finished; },
|
|
46
|
+
get checkpoint() { return checkpointValue(checkpoint); },
|
|
47
|
+
get destroyed() { return destroyed; },
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# Paw Beat
|
|
2
|
+
|
|
3
|
+
A 3D rhythm game for VibeMarket OS, written in TypeScript with Three.js. Arrows slide down four lanes toward their targets. Press the matching key as each one lands (arrow keys, WASD or the on-screen pads) and Biscuit the cat dances the step. Timing is judged perfect, great or good; every ten steps in a row adds 10% to each step, up to double. One song lasts about a minute.
|
|
4
|
+
|
|
5
|
+
It is a complete example of the app API:
|
|
6
|
+
|
|
7
|
+
| File | What it shows |
|
|
8
|
+
|---|---|
|
|
9
|
+
| `game.ts` | The chart generator and judging as pure TypeScript with no DOM, renderer or audio, so they can be unit-tested |
|
|
10
|
+
| `cat.ts` | A procedural 3D cat built from primitives at runtime; no model or texture files |
|
|
11
|
+
| `music.ts` | The whole song synthesized with Web Audio and scheduled on the audio clock, which also times the steps |
|
|
12
|
+
| `main.ts` | `connectVibeMarketApp()`, `fitCanvas` and `createLoop` from the SDK helpers, a checkpoint for the personal best, and `game.finish({ score })` |
|
|
13
|
+
|
|
14
|
+
Everything in the game is generated in code, so the bundle is `index.html`, one script, the manifest and the three store images in `store/`. The steps and the lead melody come from a seed, so each round is a little different and any round can be replayed in a test.
|
|
15
|
+
|
|
16
|
+
## Build and run
|
|
17
|
+
|
|
18
|
+
In your own project, with `@vibechain/os`, `three`, `@types/three`, `esbuild` and `typescript` installed:
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npx esbuild main.ts --bundle --minify --format=esm --target=es2022 --outfile=dist/game.js
|
|
22
|
+
cp index.html vibemarket.json dist/
|
|
23
|
+
cp -R store dist/
|
|
24
|
+
npx os preview dist
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Open the printed `http://127.0.0.1:PORT` address. Use a unique `id` and `version` in `vibemarket.json` before packaging your own game.
|
|
28
|
+
|
|
29
|
+
## Listing in VibeStore
|
|
30
|
+
|
|
31
|
+
`vibemarket.json` uses manifest schema version 2, so it carries a complete VibeStore listing: a `window` of 960 x 600 that can be resized, and a `store` object with the icon, two screenshots, a plain-text description, the `game` category, a content rating (violence `none`, language `none`, not mature) and a support link.
|
|
32
|
+
|
|
33
|
+
The requirements are checked when you submit from the VibeStore **Submit** tab, and `os pack` and `os preview` check the same things locally:
|
|
34
|
+
|
|
35
|
+
- the icon is a PNG of exactly 256 x 256 pixels, at most 256 KiB;
|
|
36
|
+
- there are 1 to 4 screenshots, PNG, JPEG or WebP, each at most 1 MiB, with contents that match the extension;
|
|
37
|
+
- the description is 40 to 2,000 characters of plain text;
|
|
38
|
+
- the support contact is an `https://` URL or an email address;
|
|
39
|
+
- the window is 320 to 1600 by 200 to 1200 pixels;
|
|
40
|
+
- there is no SVG anywhere in the bundle.
|
|
41
|
+
|
|
42
|
+
`store/icon.png` is Biscuit drawn by `cat.ts` itself, and the screenshots are captures of this game running in the SDK preview. Replace all three, and the listing text, with your own before submitting a game of your own.
|
|
43
|
+
|
|
44
|
+
## What the score means
|
|
45
|
+
|
|
46
|
+
The score is reported to the host with `game.finish`. It is display data. The game cannot grant Cash, XP or items, and the preview awards nothing.
|
|
47
|
+
|
|
48
|
+
## License
|
|
49
|
+
|
|
50
|
+
MIT, with the rest of the `@vibechain/os` package. Biscuit, the song and all of the code here are original to this example.
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import * as THREE from "three";
|
|
2
|
+
import type { Lane } from "./game";
|
|
3
|
+
|
|
4
|
+
export interface Cat {
|
|
5
|
+
readonly root: THREE.Group;
|
|
6
|
+
/** Play the move for a step that landed. */
|
|
7
|
+
dance(lane: Lane): void;
|
|
8
|
+
/** A missed step: ears back, a wobble. */
|
|
9
|
+
stumble(): void;
|
|
10
|
+
/** `beatPhase` runs 0 to 1 across each beat, so the idle bounce lands on the music. */
|
|
11
|
+
animate(seconds: number, beatPhase: number): void;
|
|
12
|
+
dispose(): void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const FUR = "#e8944a", FUR_DARK = "#b9652a", CREAM = "#fff1dc", PINK = "#ff9db5", INK = "#2a1a2e";
|
|
16
|
+
type Triple = [number, number, number];
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Biscuit, a procedural dancing cat. Everything is built from primitives at runtime:
|
|
20
|
+
* there is no model file, texture or other downloaded asset.
|
|
21
|
+
*/
|
|
22
|
+
export function createCat(): Cat {
|
|
23
|
+
const root = new THREE.Group(), figure = new THREE.Group(), head = new THREE.Group();
|
|
24
|
+
root.add(figure);
|
|
25
|
+
const geometries: THREE.BufferGeometry[] = [], materials: THREE.Material[] = [];
|
|
26
|
+
const sphere = new THREE.SphereGeometry(1, 28, 20), cone = new THREE.ConeGeometry(0.3, 0.52, 4);
|
|
27
|
+
geometries.push(sphere, cone);
|
|
28
|
+
const paint = (color: string, roughness = 0.85) => {
|
|
29
|
+
const material = new THREE.MeshStandardMaterial({ color, roughness });
|
|
30
|
+
materials.push(material);
|
|
31
|
+
return material;
|
|
32
|
+
};
|
|
33
|
+
const fur = paint(FUR), dark = paint(FUR_DARK), cream = paint(CREAM), pink = paint(PINK, 0.6), ink = paint(INK, 0.3);
|
|
34
|
+
const part = (parent: THREE.Object3D, geometry: THREE.BufferGeometry, material: THREE.Material, position: Triple, scale: Triple) => {
|
|
35
|
+
const mesh = new THREE.Mesh(geometry, material);
|
|
36
|
+
mesh.position.set(position[0], position[1], position[2]);
|
|
37
|
+
mesh.scale.set(scale[0], scale[1], scale[2]);
|
|
38
|
+
parent.add(mesh);
|
|
39
|
+
return mesh;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// Upright body with a cream tummy and two stripes.
|
|
43
|
+
part(figure, sphere, fur, [0, 1.0, 0], [0.78, 0.95, 0.7]);
|
|
44
|
+
part(figure, sphere, cream, [0, 0.92, 0.36], [0.5, 0.62, 0.42]);
|
|
45
|
+
for (const y of [1.25, 1.0]) part(figure, sphere, dark, [0, y, -0.62], [0.42, 0.06, 0.08]);
|
|
46
|
+
|
|
47
|
+
// Feet stay planted; front paws are the arms that do the dancing.
|
|
48
|
+
for (const side of [-1, 1]) part(figure, sphere, cream, [side * 0.36, 0.14, 0.2], [0.26, 0.15, 0.36]);
|
|
49
|
+
const leftPaw = part(figure, sphere, cream, [-0.74, 1.05, 0.25], [0.2, 0.2, 0.2]);
|
|
50
|
+
const rightPaw = part(figure, sphere, cream, [0.74, 1.05, 0.25], [0.2, 0.2, 0.2]);
|
|
51
|
+
|
|
52
|
+
const tail: THREE.Mesh[] = [];
|
|
53
|
+
for (let i = 0; i < 7; i++) {
|
|
54
|
+
const size = 0.17 - i * 0.01;
|
|
55
|
+
tail.push(part(figure, sphere, dark, [0, 0.45 + i * 0.17, -0.7 - i * 0.1], [size, size, size]));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
head.position.set(0, 2.2, 0.08);
|
|
59
|
+
figure.add(head);
|
|
60
|
+
part(head, sphere, fur, [0, 0, 0], [0.74, 0.64, 0.66]);
|
|
61
|
+
const ears = [-1, 1].map(side => {
|
|
62
|
+
const ear = part(head, cone, fur, [side * 0.44, 0.58, -0.02], [1, 1, 0.6]);
|
|
63
|
+
ear.rotation.z = side * -0.3;
|
|
64
|
+
part(ear, cone, pink, [0, -0.04, 0.12], [0.6, 0.7, 0.5]);
|
|
65
|
+
return { ear, side };
|
|
66
|
+
});
|
|
67
|
+
for (const side of [-1, 1]) part(head, sphere, cream, [side * 0.26, -0.2, 0.5], [0.24, 0.18, 0.2]);
|
|
68
|
+
part(head, sphere, pink, [0, -0.1, 0.66], [0.07, 0.05, 0.05]);
|
|
69
|
+
const eyes = [-1, 1].map(side => part(head, sphere, ink, [side * 0.27, 0.1, 0.57], [0.09, 0.13, 0.05]));
|
|
70
|
+
const whiskers = new THREE.LineBasicMaterial({ color: "#ffffff", transparent: true, opacity: 0.7 });
|
|
71
|
+
materials.push(whiskers);
|
|
72
|
+
for (const side of [-1, 1]) {
|
|
73
|
+
for (let i = 0; i < 3; i++) {
|
|
74
|
+
const geometry = new THREE.BufferGeometry().setFromPoints([
|
|
75
|
+
new THREE.Vector3(side * 0.34, -0.16 - i * 0.05, 0.6),
|
|
76
|
+
new THREE.Vector3(side * 0.95, -0.1 - i * 0.13, 0.5),
|
|
77
|
+
]);
|
|
78
|
+
geometries.push(geometry);
|
|
79
|
+
head.add(new THREE.Line(geometry, whiskers));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Each move is a short pulse (1 fading to 0) that the pose below reads.
|
|
84
|
+
const pulse = { left: 0, right: 0, up: 0, down: 0, stumble: 0 };
|
|
85
|
+
let clock = 0;
|
|
86
|
+
return {
|
|
87
|
+
root,
|
|
88
|
+
dance(lane) {
|
|
89
|
+
pulse[lane] = 1;
|
|
90
|
+
},
|
|
91
|
+
stumble() {
|
|
92
|
+
pulse.stumble = 1;
|
|
93
|
+
},
|
|
94
|
+
animate(seconds, beatPhase) {
|
|
95
|
+
clock += seconds;
|
|
96
|
+
for (const key of Object.keys(pulse) as (keyof typeof pulse)[]) pulse[key] = Math.max(0, pulse[key] - seconds * 3.2);
|
|
97
|
+
const ease = (value: number) => Math.sin(value * Math.PI); // up and back down over one pulse
|
|
98
|
+
const side = ease(pulse.right) - ease(pulse.left), jump = ease(pulse.up), crouch = ease(pulse.down), wobble = pulse.stumble;
|
|
99
|
+
// The idle bounce: a quick dip right on the beat that relaxes before the next one.
|
|
100
|
+
const bounce = Math.pow(1 - beatPhase, 3);
|
|
101
|
+
|
|
102
|
+
figure.position.x = side * 0.75;
|
|
103
|
+
figure.position.y = jump * 1.1;
|
|
104
|
+
figure.rotation.z = -side * 0.28 + Math.sin(clock * 38) * 0.07 * wobble;
|
|
105
|
+
figure.rotation.y = side * 0.35;
|
|
106
|
+
figure.scale.y = 1 - bounce * 0.07 - crouch * 0.38 + jump * 0.08;
|
|
107
|
+
figure.scale.x = figure.scale.z = 1 + bounce * 0.04 + crouch * 0.2;
|
|
108
|
+
|
|
109
|
+
head.rotation.x = bounce * 0.18 + crouch * 0.25 - jump * 0.2;
|
|
110
|
+
head.rotation.z = side * 0.2;
|
|
111
|
+
|
|
112
|
+
// Paws: the stepping side punches out, both go up for a jump, both drop for a crouch.
|
|
113
|
+
const leftUp = Math.max(ease(pulse.left), jump), rightUp = Math.max(ease(pulse.right), jump);
|
|
114
|
+
leftPaw.position.set(-0.74 - ease(pulse.left) * 0.45, 1.05 + leftUp * 0.85 - crouch * 0.4 + bounce * 0.06, 0.25);
|
|
115
|
+
rightPaw.position.set(0.74 + ease(pulse.right) * 0.45, 1.05 + rightUp * 0.85 - crouch * 0.4 + bounce * 0.06, 0.25);
|
|
116
|
+
|
|
117
|
+
// Eyes squeeze shut on a landed jump; ears go flat on a stumble.
|
|
118
|
+
for (const eye of eyes) eye.scale.y = 0.13 * (1 - jump * 0.7) * (1 - wobble * 0.5);
|
|
119
|
+
for (const { ear, side: earSide } of ears) ear.rotation.z = earSide * (-0.3 - wobble * 0.8);
|
|
120
|
+
tail.forEach((segment, index) => {
|
|
121
|
+
segment.position.x = Math.sin(clock * 6 + index * 0.55) * 0.05 * index + side * -0.06 * index;
|
|
122
|
+
});
|
|
123
|
+
},
|
|
124
|
+
dispose() {
|
|
125
|
+
for (const geometry of geometries) geometry.dispose();
|
|
126
|
+
for (const material of materials) material.dispose();
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paw Beat rules. Pure TypeScript: no DOM, no renderer, no audio, no SDK. main.ts feeds
|
|
3
|
+
* in the song clock and key presses and reads state out, so every rule is unit-testable.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export const LANES = ["left", "down", "up", "right"] as const;
|
|
7
|
+
export type Lane = typeof LANES[number];
|
|
8
|
+
|
|
9
|
+
export const BPM = 120;
|
|
10
|
+
export const BEAT_SECONDS = 60 / BPM;
|
|
11
|
+
/** Four silent beats to count in, then 112 beats of steps: one minute in all. */
|
|
12
|
+
export const COUNT_IN_BEATS = 4;
|
|
13
|
+
export const SONG_BEATS = 116;
|
|
14
|
+
export const SONG_SECONDS = SONG_BEATS * BEAT_SECONDS;
|
|
15
|
+
/** The host accepts integer scores up to this value. */
|
|
16
|
+
export const SCORE_LIMIT = 1_000_000_000;
|
|
17
|
+
|
|
18
|
+
/** How close to the beat a press must land, in seconds, and what it pays. */
|
|
19
|
+
const WINDOWS = [
|
|
20
|
+
{ judgement: "perfect", within: 0.05, points: 100 },
|
|
21
|
+
{ judgement: "great", within: 0.1, points: 60 },
|
|
22
|
+
{ judgement: "good", within: 0.16, points: 30 },
|
|
23
|
+
] as const;
|
|
24
|
+
const MISS_AFTER = WINDOWS[2].within;
|
|
25
|
+
|
|
26
|
+
export type Judgement = typeof WINDOWS[number]["judgement"] | "miss";
|
|
27
|
+
export interface Note { readonly time: number; readonly lane: Lane }
|
|
28
|
+
export interface NoteView extends Note { readonly index: number; readonly judged: Judgement | null }
|
|
29
|
+
|
|
30
|
+
export interface DanceState {
|
|
31
|
+
readonly time: number;
|
|
32
|
+
readonly score: number;
|
|
33
|
+
readonly combo: number;
|
|
34
|
+
readonly bestCombo: number;
|
|
35
|
+
readonly counts: Readonly<Record<Judgement, number>>;
|
|
36
|
+
readonly finished: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface DanceGame {
|
|
40
|
+
readonly notes: readonly NoteView[];
|
|
41
|
+
readonly state: DanceState;
|
|
42
|
+
/** Move the song clock to `time` seconds. Notes that scrolled past unhit become misses. */
|
|
43
|
+
advance(time: number): readonly NoteView[];
|
|
44
|
+
/** Visit every note timed from `from` to `to` seconds, in order, without allocating. For drawing. */
|
|
45
|
+
each(from: number, to: number, visit: (note: Note, judged: Judgement | null) => void): void;
|
|
46
|
+
/** A press in `lane` at the current clock. Returns the note it hit, or null for a stray press. */
|
|
47
|
+
press(lane: Lane): NoteView | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Small deterministic generator, so a seed replays the same steps. */
|
|
51
|
+
function random(seed: number): () => number {
|
|
52
|
+
let state = seed >>> 0;
|
|
53
|
+
return () => {
|
|
54
|
+
state = (state + 0x6d2b79f5) >>> 0;
|
|
55
|
+
let value = Math.imul(state ^ (state >>> 15), 1 | state);
|
|
56
|
+
value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value;
|
|
57
|
+
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Write the steps for one song. It warms up on the beat, adds off-beat steps in the
|
|
63
|
+
* middle and two-paw jumps near the end. The same lane never repeats on an off-beat,
|
|
64
|
+
* so every pattern is playable with four keys.
|
|
65
|
+
*/
|
|
66
|
+
export function createChart(seed: number): Note[] {
|
|
67
|
+
const next = random(seed), notes: Note[] = [];
|
|
68
|
+
const pick = (avoid?: Lane): Lane => {
|
|
69
|
+
const pool = LANES.filter(lane => lane !== avoid);
|
|
70
|
+
return pool[Math.floor(next() * pool.length)] ?? "left";
|
|
71
|
+
};
|
|
72
|
+
let previous: Lane | undefined;
|
|
73
|
+
for (let beat = COUNT_IN_BEATS; beat < SONG_BEATS - 2; beat++) {
|
|
74
|
+
const progress = (beat - COUNT_IN_BEATS) / (SONG_BEATS - COUNT_IN_BEATS);
|
|
75
|
+
// Leave a breath at the end of every eight-beat phrase.
|
|
76
|
+
if (beat % 8 === 7 && progress < 0.75) continue;
|
|
77
|
+
const lane = pick(previous);
|
|
78
|
+
notes.push({ time: beat * BEAT_SECONDS, lane });
|
|
79
|
+
previous = lane;
|
|
80
|
+
if (progress > 0.7 && next() < 0.3) {
|
|
81
|
+
// A jump: a second paw on the same beat.
|
|
82
|
+
notes.push({ time: beat * BEAT_SECONDS, lane: pick(lane) });
|
|
83
|
+
} else if (progress > 0.3 && next() < 0.4) {
|
|
84
|
+
const between = pick(previous);
|
|
85
|
+
notes.push({ time: (beat + 0.5) * BEAT_SECONDS, lane: between });
|
|
86
|
+
previous = between;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return notes;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function createGame(seed = 1): DanceGame {
|
|
93
|
+
const chart = createChart(seed);
|
|
94
|
+
const judged: (Judgement | null)[] = chart.map(() => null);
|
|
95
|
+
const counts: Record<Judgement, number> = { perfect: 0, great: 0, good: 0, miss: 0 };
|
|
96
|
+
let time = 0, score = 0, combo = 0, bestCombo = 0, firstOpen = 0;
|
|
97
|
+
const view = (index: number): NoteView => ({ ...chart[index]!, index, judged: judged[index] ?? null });
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
get notes() { return chart.map((_, index) => view(index)); },
|
|
101
|
+
get state(): DanceState {
|
|
102
|
+
return { time, score, combo, bestCombo, counts: { ...counts }, finished: time >= SONG_SECONDS };
|
|
103
|
+
},
|
|
104
|
+
advance(next) {
|
|
105
|
+
if (!Number.isFinite(next) || next <= time) return [];
|
|
106
|
+
time = Math.min(next, SONG_SECONDS);
|
|
107
|
+
const missed: NoteView[] = [];
|
|
108
|
+
for (let index = firstOpen; index < chart.length && chart[index]!.time < time - MISS_AFTER; index++) {
|
|
109
|
+
if (judged[index] === null) {
|
|
110
|
+
judged[index] = "miss";
|
|
111
|
+
counts.miss += 1;
|
|
112
|
+
combo = 0;
|
|
113
|
+
missed.push(view(index));
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
while (firstOpen < chart.length && judged[firstOpen] !== null) firstOpen++;
|
|
117
|
+
return missed;
|
|
118
|
+
},
|
|
119
|
+
each(from, to, visit) {
|
|
120
|
+
// Binary search for the first note at or after `from`.
|
|
121
|
+
let low = 0, high = chart.length;
|
|
122
|
+
while (low < high) {
|
|
123
|
+
const middle = (low + high) >> 1;
|
|
124
|
+
if (chart[middle]!.time < from) low = middle + 1;
|
|
125
|
+
else high = middle;
|
|
126
|
+
}
|
|
127
|
+
for (let index = low; index < chart.length && chart[index]!.time <= to; index++) visit(chart[index]!, judged[index] ?? null);
|
|
128
|
+
},
|
|
129
|
+
press(lane) {
|
|
130
|
+
if (time >= SONG_SECONDS) return null;
|
|
131
|
+
// The closest unjudged note in this lane, if it is inside the widest window.
|
|
132
|
+
let best = -1, bestOff = Infinity;
|
|
133
|
+
for (let index = firstOpen; index < chart.length && chart[index]!.time <= time + MISS_AFTER; index++) {
|
|
134
|
+
const off = Math.abs(chart[index]!.time - time);
|
|
135
|
+
if (judged[index] === null && chart[index]!.lane === lane && off < bestOff) {
|
|
136
|
+
best = index;
|
|
137
|
+
bestOff = off;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const window = WINDOWS.find(item => bestOff <= item.within);
|
|
141
|
+
if (best < 0 || !window) return null;
|
|
142
|
+
judged[best] = window.judgement;
|
|
143
|
+
counts[window.judgement] += 1;
|
|
144
|
+
combo += 1;
|
|
145
|
+
bestCombo = Math.max(bestCombo, combo);
|
|
146
|
+
// Every ten steps in a row adds 10%, up to double.
|
|
147
|
+
score = Math.min(SCORE_LIMIT, score + Math.round(window.points * Math.min(2, 1 + Math.floor(combo / 10) * 0.1)));
|
|
148
|
+
return view(best);
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|