# Build an app that keeps saves, a board and achievements (Preact, Svelte, Vue or React, with Vite)

You are building a small app for the phone inside Ibadan Life (https://ibadanlife.app), a life-simulation game set in Ibadan, Nigeria, as a developer OUTSIDE the city: it is submitted through an Arena54 developer account, and it keeps the player's progress, scores and achievements with Arena54, so the same player can meet them again outside this game. Build it in this folder.

Ask me what the app should do if I have not said; if you cannot ask, build the first of these. Good first apps: a habit tracker, a daily puzzle with a streak, a reading log.

THE FRAME. Your app is ONE HTML file, at most 200,000 characters (counted as JavaScript counts them, the file's length as a string), with its CSS in <style> and its JavaScript in <script>. It runs inside the player's phone in a locked frame:
- No network at all: no fetch, XMLHttpRequest, WebSocket, no scripts, stylesheets, fonts or images from any address. Pictures go in as data: URLs; the device's own fonts and emoji are fine, though emoji look different from phone to phone.
- No cookies, no localStorage or sessionStorage, no forms that submit (an <input> or a <button> outside a <form> is fine), no new windows, and it cannot move the page. It cannot send anything out. The only way to reach the game is the bridge below.
- Design for a screen about 360 px wide and 416 px tall. That is your app's own area: a strip above it always shows its name and its developer. Taller content scrolls.
- You may write it with Preact, Svelte, Vue or React, and Vite. What is submitted is still ONE file: build with vite-plugin-singlefile (or get the same result another way) so every script and style is inside the HTML. No code splitting, no dynamic import(), no web workers, no CDN, no web fonts, no pictures by address.
- The limit of 200,000 characters is on the BUILT file. React with react-dom is about 140,000 characters by itself once minified, so prefer Preact or Svelte, or keep a React app very small.
- A router that reads or changes the address will not work: the frame has no address. Keep screens in state.
- Vite itself adds a helper to the build that calls the network (its modulepreload polyfill), and check.mjs will refuse the file for it. Turn it off in the Vite config: build: { modulePreload: { polyfill: false } }.
- If check.mjs still finds one of its words, search the built file for the word to see whose code it is. If it is a library's, that library reaches for something the frame does not have: choose a lighter one.
- The build's one inline <script type="module"> is fine: ibadan is there before any script runs. JSX needs the framework's Vite plugin (for Preact, @preact/preset-vite); writing h() calls needs nothing.

THE BRIDGE. The phone adds a global object, ibadan, before your code runs. Every call returns a promise; a refusal rejects it with an Error whose message you can show the player. Use only these calls. There are no others. Your app has NO network: the game's own server makes each call to Arena54 for you, so there is no key or token in your file, and you must never put one there.
- ibadan.save.get(key) resolves with a string, or null if nothing is saved under that key. ibadan.save.set(key, value) keeps a string of at most 16,000 characters, in place of whatever was under that key, and resolves with nothing; to keep an object, use JSON.stringify and JSON.parse. ibadan.save.list() resolves with [{ key, bytes, updated_at }]. ibadan.save.remove(key) deletes one. A key is 1 to 40 letters, digits, _ or -.
- ibadan.board.post(board, score) puts a whole number from 0 to 1,000,000,000 on a board you name (1 to 40 letters, digits, _ or -) and resolves with { improved, best, rank }. A board keeps each player's highest score, so post the number itself; higher is better. ibadan.board.top(board) resolves with { top: [{ rank, name, score }], me }: the ten best, and me is { best, rank } or null if this player has no score there yet. A name can be null. You are never given another player's id.
- ibadan.achieve.list() resolves with [{ key, name, description, unlocked_at }], the achievements you defined at Arena54, with unlocked_at null until this player has one. ibadan.achieve.unlock(key) resolves with { key, name, new }, where new is true the first time. An achievement exists only once you have defined it for the app at Arena54 (its Leaderboards and achievements module); unlocking a key that is not defined there rejects. The stand-in below accepts any key, so list every key you used when you finish.
- ibadan.player() resolves with { name, id }: the player's username and an id made for your app alone. You are never told where a player is.
- ibadan.storage.get(key) and ibadan.storage.set(key, value) keep small strings inside the city only (keys up to 40 characters, values up to 2,000, 20 keys per player); get resolves with null for a key never set. Use save for anything that should follow the player outside Ibadan Life.
- ibadan.toast(text) shows a short message for 3 seconds; text past 120 characters is cut. ibadan.close() closes your app. Neither needs a permission.
At most 20 calls in any 10 seconds; past that a call rejects with "Too many requests. Slow down." So read once when the app opens and write when something changes, never on a repeating timer. Where changes come fast (a counter the player taps), hold the write and send the latest value at most once a second.
There is no clock in the bridge. For "today" use the device's own date, and know that a player can change it.

THE PLAYER MUST AGREE, AND MAY SAY NO. Every save call, every board call and every achieve call, reading included, needs the player's yes for its kind. The first call of a kind brings up the phone's own sheet: "Keep your progress outside the city?", "Put your scores on its board?" (it says the score goes under their username, where people outside the city can see it), or the same for achievements. A yes is remembered and that sheet does not come again. A no is NOT remembered: the call rejects with exactly "The player said no.", and the next call of that kind would bring the sheet up again. So when you see that message, stop making calls of that kind, keep the app working without them, say plainly on the page what is not being kept, and give one button that tries again. The three are separate: a no to the board does not stop saves.
Make one call that may ask at a time, and wait for it to settle before the next: the phone shows one sheet, so do not call board or achieve as the app opens alongside the first save. Call them when the player does the thing that needs them.
Other rejections are not a no and carry their own message to show: "Arena54 did not answer. Try again." (worth one more try later), "Keeping things with Arena54 is switched off in this city.", "This app's developer has not turned that on at Arena54." and "Too many requests. Slow down."

PERMISSIONS. Declare what the app uses, from "player", "storage", "saves", "boards" and "achievements", and at Arena54 turn on the matching modules (Saves; Leaderboards and achievements) for the app. A call whose permission was not declared is refused. An app from outside the city cannot charge a player.

WHAT GETS AN APP TURNED DOWN OR TAKEN DOWN. Pretending to be Ibadan Life. Asking for a password. Keeping anything about the player that the app does not need. Heavy work in the background.

A WORKING EXAMPLE, to copy the shape of:
```html
<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>body{font:16px system-ui;margin:16px;color:#2a1a12;background:#f4efe4}button{font:inherit;padding:10px 14px;border-radius:12px;border:0;background:#a44a1f;color:#fff}</style>
<h2>Visit counter</h2><p id="a">Reading…</p><p id="b"></p><button id="go">Count a visit</button>
<script>
  var a = document.getElementById("a"), b = document.getElementById("b"), n = 0, kept = true, board = true;
  function show() { a.textContent = "Visits: " + n + (kept ? "" : " (not being kept: you said no, or it is switched off)"); }
  ibadan.save.get("visits").then(function (v) { n = Number(v) || 0; show(); }, function (e) { kept = false; show(); b.textContent = e.message; });
  document.getElementById("go").onclick = function () {
    n++; show();
    // One call at a time, and each kind stops by itself once it has been refused.
    (kept ? ibadan.save.set("visits", String(n)).catch(function (e) { kept = false; show(); b.textContent = e.message; }) : Promise.resolve())
      .then(function () { return board ? ibadan.board.post("visits", n) : null; })
      .then(function (r) { if (r) b.textContent = "On the board: best " + r.best + ", rank " + r.rank + "."; }, function (e) { board = false; b.textContent = "Not on the board: " + e.message; });
  };
</script>
```

WHAT TO WRITE. A project and a checker:
1. The project: package.json, a Vite config with vite-plugin-singlefile, and src/. Vite needs an index.html at the top of the project as its entry. The build writes dist/index.html; have the build script copy that to app.html. app.html is the app that is checked and submitted: never edit it by hand, change the source or the config and build again. Handle every rejected promise: show the message, never leave a blank screen.
2. check.mjs: exactly the script below. Then run "node check.mjs" and fix the source or the Vite config, and build again, until its line starts with "ok:". It looks for these words anywhere in the file, comments and visible text included, so keep them out: fetch, XMLHttpRequest, WebSocket, EventSource, sendBeacon, importScripts, localStorage, sessionStorage, indexedDB, document.cookie. If you cannot open a browser, say so: "ok:" means the file may be submitted, not that you saw it run. It also writes harness.html, which runs the app in a frame like the phone's, with a stand-in for the bridge that keeps saves, one board and one achievement in memory and asks each of the three questions as the phone does (a browser box: OK is yes, Cancel is no, and a no is asked again on the next call); open that in a browser and try the app both ways. harness.html is for you alone and is never submitted.

```js
// check.mjs: run with  node check.mjs  beside app.html. It prints what the store would turn down, and writes
// harness.html: your app in the same kind of locked frame, with a stand-in for the phone's bridge. Open it in a browser.
import { readFileSync, writeFileSync } from "node:fs";
const src = readFileSync("app.html", "utf8"), bad = [];
if (src.length > 200000) bad.push("over 200000 characters: " + src.length);
if (/<script[^>]+\bsrc\s*=/i.test(src)) bad.push("a script loaded from another file");
if (/<link[^>]+\bhref\s*=\s*["']?(?!data:)/i.test(src)) bad.push("a linked stylesheet or font");
if (/\b(?:src|href|poster)\s*=\s*["']?\s*(?:https?:)?\/\//i.test(src) || /url\(\s*["']?\s*(?:https?:)?\/\//i.test(src)) bad.push("something loaded from another address");
if (/\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|sendBeacon|importScripts)\b/.test(src)) bad.push("a network call");
if (/\b(?:localStorage|sessionStorage|indexedDB|document\.cookie)\b/.test(src)) bad.push("the browser's own storage");
if (/<form\b/i.test(src)) bad.push("a <form>");
console.log(bad.length ? "WOULD BE TURNED DOWN: " + bad.join("; ") : "ok: " + src.length + " characters, one file, no network");
const MOCK = '<script>(function(){var kv={},sv={},best={},got={},yes={},g=function(k,q,o){Object.keys(o).forEach(function(n){var f=o[n];o[n]=function(){if(!yes[k]&&!(yes[k]=confirm(q)))return Promise.reject(new Error("The player said no."));return f.apply(null,arguments)}});return o},bad=function(k){return typeof k==="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(k)?null:Promise.reject(new Error("A key is 1 to 40 letters, digits, _ or -."))},ok=function(v){return new Promise(function(y){setTimeout(function(){y(v)},60)})};window.ibadan={player:function(){return ok({name:"ade",id:"0123456789abcdef0123456789abcdef"})},storage:{get:function(k){return ok(k in kv?kv[k]:null)},set:function(k,v){kv[k]=String(v);return ok()}},toast:function(t){console.log("toast:",t);return ok()},close:function(){console.log("close");return ok()},save:g("save","Keep your progress outside the city?",{list:function(){return ok(Object.keys(sv).map(function(k){return{key:k,bytes:sv[k].length,updated_at:new Date().toISOString()}}))},get:function(k){return bad(k)||ok(k in sv?sv[k]:null)},set:function(k,v){if(typeof v!=="string"||v.length>16000)return Promise.reject(new Error("A save is text of at most 16000 characters."));return bad(k)||(sv[k]=v,ok(null))},remove:function(k){return bad(k)||(delete sv[k],ok(null))}}),board:g("board","Put your scores on its board?",{post:function(b,n){if(bad(b))return bad(b);if(!Number.isInteger(n)||n<0||n>1e9)return Promise.reject(new Error("A score is a whole number from 0 to 1,000,000,000."));var w=best[b]||0;best[b]=Math.max(w,n);return ok({improved:n>w,best:best[b],rank:best[b]>=55?1:2})},top:function(b){return bad(b)||ok({top:[{rank:1,name:"kunle",score:55}].concat(best[b]?[{rank:2,name:"ade",score:best[b]}]:[]),me:best[b]?{best:best[b],rank:2}:null})}}),achieve:g("achieve","Keep your achievements outside the city?",{list:function(){return ok([{key:"first-visit",name:"First visit",description:"Open the app once",unlocked_at:got["first-visit"]||null}])},unlock:function(k){if(bad(k))return bad(k);var n=!got[k];got[k]=got[k]||new Date().toISOString();return ok({key:k,name:k,new:n})}})};})();<\/script>';
const policy = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:; media-src data:; connect-src 'none'; form-action 'none'";
const page = '<meta http-equiv="Content-Security-Policy" content="' + policy + '">' + MOCK + src;
// The real frame is sandbox="allow-scripts" only. allow-modals is added HERE alone, for a stand-in that asks a question with confirm().
writeFileSync("harness.html", '<!doctype html><title>harness</title><body style="margin:0;background:#222;display:grid;place-items:center;height:100vh"><iframe sandbox="allow-scripts allow-modals" style="width:360px;height:416px;border:0;border-radius:16px;background:#fff" srcdoc="' + page.replace(/&/g, "&amp;").replace(/"/g, "&quot;") + '"></iframe>');
process.exit(bad.length ? 1 : 0);
```

HOW IT IS SUBMITTED. Through an Arena54 developer account at developers.arena54.com, as kind "app" with the permissions it uses and no others. Only app.html is submitted. Ibadan Life's staff read and try every app before it is listed. Arena54's own guides and prompts are at https://developers.arena54.com/llms.txt.

When you finish, tell me: what the app does, which permissions it uses, what it does when the player says no, and what check.mjs printed.
