firstbyte 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +94 -2
  2. package/bin/firstbyte.js +32 -0
  3. package/blocks/achievements/Achievements/Achievements.js +102 -0
  4. package/blocks/catalog/Kinds/Kinds.js +18 -0
  5. package/blocks/catalog/Listing/Listing.js +178 -0
  6. package/blocks/catalog/Needs/Needs.js +68 -0
  7. package/blocks/check/Checker/Checker.js +63 -0
  8. package/blocks/check/FileChecks/FileChecks.js +228 -0
  9. package/blocks/check/PlayChecks/PlayChecks.js +289 -0
  10. package/blocks/check/PlayChecks/harness.html +21 -0
  11. package/blocks/check/PlayChecks/png.js +70 -0
  12. package/blocks/check/PlayChecks/serve.js +50 -0
  13. package/blocks/check/ReportText/ReportText.js +57 -0
  14. package/blocks/dev/Levels/Levels.js +47 -0
  15. package/blocks/load/Build/Build.js +45 -0
  16. package/blocks/load/Served/Served.js +27 -0
  17. package/blocks/load/Zip/Zip.js +141 -0
  18. package/blocks/metrics/Rollup/Rollup.js +79 -0
  19. package/blocks/rules/Brief/Brief.js +168 -0
  20. package/blocks/rules/Rulebook/Rulebook.js +214 -0
  21. package/blocks/rules/Starter/Starter.js +22 -0
  22. package/blocks/rules/Starter/game/README.txt +11 -0
  23. package/blocks/rules/Starter/game/achievements.json +6 -0
  24. package/blocks/rules/Starter/game/cover.jpg +0 -0
  25. package/blocks/rules/Starter/game/game.js +147 -0
  26. package/blocks/rules/Starter/game/game.json +9 -0
  27. package/blocks/rules/Starter/game/index.html +14 -0
  28. package/blocks/rules/Starter/game/style.css +3 -0
  29. package/blocks/sdk/Host/Host.js +123 -0
  30. package/blocks/sdk/Sdk/Sdk.js +157 -0
  31. package/index.js +7 -0
  32. package/package.json +52 -4
  33. package/site/data/demo-sessions.json +1 -0
  34. package/site/data/games.json +9 -0
@@ -0,0 +1,214 @@
1
+ /*
2
+ * The rulebook. Everything First Byte expects from a game lives here and nowhere else:
3
+ * the checker runs these rules, and the AI brief (site/ai.txt) is written from them.
4
+ * Rule ids are never renumbered or reused. Add a new id instead.
5
+ *
6
+ * check: 'files' checked by reading the build } Ready to send: the checker, which the
7
+ * 'play' checked by playing the build } developer can run before sending
8
+ * 'person' the quality review: played by our team, graded good, needs work or must fix
9
+ * strict: a quality item that is only good or must fix (no 'needs work').
10
+ * test: how a person tests a quality item, in two short steps: shown in the walkthrough our team
11
+ * grades with, and to the developer playing their own game the same way.
12
+ */
13
+
14
+ export const LIMITS = {
15
+ sizeBytes: 50 * 1024 * 1024,
16
+ readyMs: 10_000,
17
+ saveBytes: 1024 * 1024,
18
+ };
19
+
20
+ export const RULES = [
21
+ {
22
+ id: 'F1', key: 'index-top', check: 'files',
23
+ title: 'index.html at the top, or in one folder',
24
+ brief: 'Ships as one zip with index.html at the top, or inside one folder that holds the whole game.',
25
+ fix: 'Zip your build folder. index.html goes at the top, or in the one folder that holds everything.',
26
+ },
27
+ {
28
+ id: 'F2', key: 'relative-paths', check: 'files',
29
+ title: 'Every path is relative',
30
+ brief: 'Every path in the build is relative ("img/hero.png", never "/img/hero.png"), and its case matches the file.',
31
+ fix: 'Remove the leading "/" (in Vite, set base: "./"), and match upper and lower case exactly.',
32
+ },
33
+ {
34
+ id: 'F3', key: 'size', check: 'files',
35
+ title: 'Under 50 MB',
36
+ brief: 'The whole build is under 50 MB unzipped.',
37
+ fix: 'Compress textures and audio, and leave source files, maps and unused assets out of the build.',
38
+ },
39
+ {
40
+ id: 'F4', key: 'no-other-portal', check: 'files',
41
+ title: "No other site's SDK",
42
+ brief: "Loads no other game site's SDK (CrazyGames, Poki, GameDistribution, Yandex, Playgama, GamePix, GameMonetize, Y8). Make a First Byte build without it.",
43
+ fix: "Make a First Byte build that leaves the other site's SDK out. Keep it in your builds for that site.",
44
+ },
45
+ {
46
+ id: 'F5', key: 'no-store-links', check: 'files',
47
+ title: 'No links to outside purchases or other game sites',
48
+ brief: 'Has no links to outside purchases (Steam, Patreon, Ko-fi, PayPal, app stores) or to other game sites.',
49
+ fix: 'Remove the link from the First Byte build. Credits can name you, without a link to buy.',
50
+ },
51
+ {
52
+ id: 'F6', key: 'sdk', check: 'files', optional: true,
53
+ title: 'Uses the First Byte SDK',
54
+ brief: 'Optional: loads the First Byte SDK. Without it the game earns no ad share and keeps no saves with us.',
55
+ fix: 'Add <script src="https://firstbyte.games/sdk.js"></script> to index.html, before your game\'s script.',
56
+ },
57
+ {
58
+ id: 'F7', key: 'achievements', check: 'files',
59
+ title: 'Achievements are listed right',
60
+ brief: 'If the game has achievements, lists them in achievements.json next to index.html: an id, a name, a line about it and an optional icon, up to 30. A game without achievements needs no file.',
61
+ fix: 'Fix each line above in achievements.json, or leave the file out.',
62
+ },
63
+ {
64
+ id: 'F8', key: 'game-file', check: 'files',
65
+ title: 'game.json and cover.jpg are right',
66
+ brief: "If the build carries game.json or cover.jpg next to index.html, they are right: game.json has any of the game's name, one line on what you do, its controls and its kinds, and cover.jpg is a 16:9 JPEG, at least 640 wide, under 1 MB. They fill in the boxes when the game is sent. A game without them needs neither.",
67
+ fix: 'Fix each line above, or leave the file out and fill in the boxes when you send.',
68
+ },
69
+ {
70
+ id: 'P1', key: 'loads', check: 'play',
71
+ title: 'Loads without errors',
72
+ brief: 'Loads with no errors in the console and no missing files.',
73
+ fix: 'Open the game with the browser console showing and fix the first error listed.',
74
+ },
75
+ {
76
+ id: 'P2', key: 'on-screen', check: 'play',
77
+ title: 'On screen within 10 seconds',
78
+ brief: 'Something is on screen within 10 seconds. With the SDK, call FirstByte.ready() once, when the first frame is drawn.',
79
+ fix: 'Show something right away and load the rest in the background. Call FirstByte.ready() once the first frame is drawn.',
80
+ },
81
+ {
82
+ id: 'P3', key: 'self-contained', check: 'play',
83
+ title: 'Loads nothing from the internet',
84
+ brief: 'Loads every file from the build itself, apart from the First Byte SDK. No CDNs, web fonts or trackers.',
85
+ fix: 'Download the file into your build and load it with a relative path.',
86
+ },
87
+ {
88
+ id: 'P4', key: 'responds', check: 'play',
89
+ title: 'Responds to keys or a click',
90
+ brief: 'Responds to the keyboard and the mouse straight away, with no sign-in or account first. Keys the game uses must not scroll the page: event.preventDefault(). With the SDK, call FirstByte.playing(true) on the first key or click that starts play.',
91
+ fix: 'Let the first key press or click start the game. Put sign-in, if any, after the first play.',
92
+ },
93
+ {
94
+ id: 'P5', key: 'sound', check: 'play',
95
+ title: 'Plays sound',
96
+ brief: 'Plays sound for actions and menus.',
97
+ fix: 'Add a sound to the first thing the player does. A placeholder is fine for a first build.',
98
+ },
99
+ {
100
+ id: 'P6', key: 'ads-at-breaks', check: 'play',
101
+ title: 'Ads only at breaks',
102
+ brief: 'Shows ads only at a natural break, such as a game over or between levels. With the SDK: FirstByte.playing(false) first, then FirstByte.breakTime().',
103
+ fix: 'Call FirstByte.playing(false) when the round ends, and only then FirstByte.breakTime().',
104
+ },
105
+ {
106
+ id: 'P7', key: 'no-ad-first', check: 'play',
107
+ title: 'No ad before the first play',
108
+ brief: 'Never shows an ad before the player has played.',
109
+ fix: 'Ask for an ad only after the first round has ended.',
110
+ },
111
+ {
112
+ id: 'P8', key: 'mute', check: 'play',
113
+ title: 'Mutes when the site asks',
114
+ brief: "Goes quiet when the site's mute button is pressed: FirstByte.on('mute', ...) and FirstByte.on('unmute', ...).",
115
+ fix: "Add FirstByte.on('mute', () => yourVolume(0)) and FirstByte.on('unmute', () => yourVolume(1)).",
116
+ },
117
+ {
118
+ id: 'P9', key: 'achievements-known', check: 'play',
119
+ title: 'Unlocks only listed achievements',
120
+ brief: 'Calls FirstByte.achieve(id) only with ids from achievements.json, when the player earns one.',
121
+ fix: 'Call FirstByte.achieve(id) with an id from achievements.json, spelled the same, when the player earns it.',
122
+ },
123
+ {
124
+ id: 'H1', key: 'new', check: 'person',
125
+ title: 'Something new',
126
+ brief: 'Brings something new: an idea, a look or a feeling we have not seen lately. A polished copy is not picked.',
127
+ test: ["Play one full round.", "Ask: what would you tell a friend is new about it? If it is only a well-made copy, it is not new."],
128
+ },
129
+ {
130
+ id: 'H2', key: 'fun-fast', check: 'person',
131
+ title: 'Fun in the first 10 seconds',
132
+ brief: 'The player is doing something fun within 10 seconds, with no long menu first.',
133
+ test: ["Restart it and count to 10 from the first screen.", "By 10 you should be playing, not reading or clicking through menus."],
134
+ },
135
+ {
136
+ id: 'H3', key: 'no-copy', check: 'person', strict: true,
137
+ title: 'Not a copy of another game',
138
+ brief: "Does not copy another game's name, characters, art, music or levels.",
139
+ test: ["Look at the name, the characters, the art and the music.", "If any of it is taken from a game you know, it is must fix."],
140
+ },
141
+ {
142
+ id: 'H4', key: 'yours', check: 'person', strict: true,
143
+ title: 'Yours to publish',
144
+ brief: 'The developer made the game, or has the right to publish it.',
145
+ test: ["Look for another studio's logo, credits or art.", "If you doubt it is theirs to publish, it is must fix: ask them in your feedback."],
146
+ },
147
+ {
148
+ id: 'H5', key: 'first-minute', check: 'person',
149
+ title: 'The first minute is clear',
150
+ brief: 'A new player knows what to do and what to aim for within the first minute, without reading instructions.',
151
+ test: ["Restart it and play one minute, reading nothing outside the game.", "Then say what you do and what you are aiming for. If you can't, it is not clear."],
152
+ },
153
+ {
154
+ id: 'H6', key: 'controls', check: 'person',
155
+ title: 'Controls feel good',
156
+ brief: 'The controls answer straight away, do what the player expects, and are shown on screen when they matter.',
157
+ test: ["Press every control and watch for a delay.", "Check the controls are shown on screen the first time you need them."],
158
+ },
159
+ {
160
+ id: 'H7', key: 'difficulty', check: 'person',
161
+ title: 'Difficulty is fair',
162
+ brief: 'It starts easy enough to learn, gets harder at a fair pace, and a loss feels like the player\'s own mistake.',
163
+ test: ["Play until you have lost twice.", "The start should be easy enough to learn, and each loss should feel like your own mistake."],
164
+ },
165
+ {
166
+ id: 'H8', key: 'smooth', check: 'person',
167
+ title: 'Runs smoothly',
168
+ brief: 'Plays without stutter or long pauses on an ordinary laptop, including when the most is happening.',
169
+ test: ["Play to the busiest moment you can reach.", "Watch for stutter, or a pause longer than a blink."],
170
+ },
171
+ {
172
+ id: 'H9', key: 'readable', check: 'person',
173
+ title: 'Easy to read',
174
+ brief: 'The player, the dangers and the goal stand out at a glance, and every word on screen is easy to read.',
175
+ test: ["Glance at the screen for one second: find the player, the danger and the goal.", "Read every word on screen without leaning in."],
176
+ },
177
+ {
178
+ id: 'H10', key: 'sound-feel', check: 'person',
179
+ title: 'Sounds good',
180
+ brief: 'Sounds fit the game, tell the player what just happened, and never grate on a long play.',
181
+ test: ["Play two minutes with the sound on.", "What you do should have a sound that fits, and nothing should grate by the end."],
182
+ },
183
+ {
184
+ id: 'H11', key: 'no-bugs', check: 'person',
185
+ title: 'No bugs found',
186
+ brief: 'Nothing broke while our team played it: no stuck states, glitches, lost progress or crashes.',
187
+ test: ["Try to break it: mash the keys, restart mid-round, lose, win, leave it idle.", "Anything stuck, glitched or lost is a bug."],
188
+ },
189
+ ];
190
+
191
+ export const ALLOWED = [
192
+ 'Publishing the same game anywhere else, before, during or after First Byte.',
193
+ 'Skipping the SDK. The game then earns no ad share and keeps no saves with us.',
194
+ ];
195
+
196
+ /* The two sections of the checklist. */
197
+ export const SECTIONS = {
198
+ ready: { title: 'Ready to send', about: 'Checked automatically. Run npx firstbyte check to see it before you send.' },
199
+ quality: { title: 'Quality review', about: 'Played by our team. Each is good, needs work, or must fix.' },
200
+ };
201
+ export const sectionOf = (rule) => (rule.check === 'person' ? 'quality' : 'ready');
202
+
203
+ /* How the team grades a quality item. Only must fix blocks a game from being picked. */
204
+ export const GRADES = {
205
+ good: { label: 'Good', blocks: false },
206
+ 'needs-work': { label: 'Needs work', blocks: false },
207
+ 'must-fix': { label: 'Must fix', blocks: true },
208
+ };
209
+
210
+ export function ruleById(id) {
211
+ const rule = RULES.find((r) => r.id === id);
212
+ if (!rule) throw new Error(`No rule ${id}`);
213
+ return rule;
214
+ }
@@ -0,0 +1,22 @@
1
+ /*
2
+ * The starter game: a tiny, complete game that passes every automatic check, for a developer or their
3
+ * AI to start from. The game itself is the files in ./game/ (edit them there). The site hands them
4
+ * out as starter.zip (scripts/build-site.js) and the AI brief shows them (rules/Brief).
5
+ */
6
+ import { readFileSync } from 'node:fs';
7
+ import { writeZip } from '../../load/Zip/Zip.js';
8
+
9
+ export const STARTER_URL = 'https://firstbyte.games/starter.zip';
10
+
11
+ /* In the order a person reads them. */
12
+ const FILES = ['index.html', 'game.js', 'style.css', 'achievements.json', 'game.json', 'cover.jpg', 'README.txt'];
13
+ /* The cover is a picture (scripts/make-starter-cover.js): bytes, where the rest is text. */
14
+ const BINARY = /\.jpg$/;
15
+
16
+ export function starterFiles() {
17
+ /* Line endings as in the repo's other text files, whatever the machine. */
18
+ const at = (name) => new URL(`./game/${name}`, import.meta.url);
19
+ return Object.fromEntries(FILES.map((name) => [name, BINARY.test(name) ? readFileSync(at(name)) : readFileSync(at(name), 'utf8').replace(/\r\n/g, '\n')]));
20
+ }
21
+
22
+ export const starterZip = () => writeZip(starterFiles());
@@ -0,0 +1,11 @@
1
+ First Byte starter game
2
+
3
+ A tiny game that passes every First Byte check. Make it yours: change game.js,
4
+ keep the lines marked with a rule id (P2, P4, P5...) and it keeps passing.
5
+
6
+ Check it: zip this folder and drop it at firstbyte.games/send (Just check it)
7
+ or run: npx firstbyte check .
8
+ For an AI: paste firstbyte.games/ai.txt into it first.
9
+
10
+ game.json and cover.jpg fill in the boxes when you send it (name, one line on
11
+ what you do, controls, kinds, cover). Change them to match your game.
@@ -0,0 +1,6 @@
1
+ {
2
+ "achievements": [
3
+ { "id": "first-round", "name": "First round", "about": "Start a round.", "icon": "flag" },
4
+ { "id": "ten-coins", "name": "Ten coins", "about": "Collect 10 coins in one round.", "icon": "coin" }
5
+ ]
6
+ }
@@ -0,0 +1,147 @@
1
+ /*
2
+ * First Byte starter game: collect coins before the time runs out. It passes every check.
3
+ * Change anything you like. The lines marked with a rule id (P2, P4...) are what the checker looks
4
+ * for: keep what they do and your game keeps passing.
5
+ */
6
+ const canvas = document.getElementById('game');
7
+ const g = canvas.getContext('2d');
8
+ const W = canvas.width;
9
+ const H = canvas.height;
10
+ const SPEED = 240;
11
+ const ROUND_SECONDS = 20;
12
+ const MOVES = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1], a: [-1, 0], d: [1, 0], w: [0, -1], s: [0, 1] };
13
+
14
+ const player = { x: W / 2, y: H / 2 };
15
+ const held = new Set();
16
+ let coin = spot();
17
+ let target = null;
18
+ let score = 0;
19
+ let best = 0;
20
+ let timeLeft = 0;
21
+ let last = 0;
22
+ let muted = false;
23
+ let audio = null;
24
+
25
+ function spot() {
26
+ return { x: 30 + Math.random() * (W - 60), y: 40 + Math.random() * (H - 70) };
27
+ }
28
+
29
+ /* P5: a sound for what the player does. P8: no sound while the site's mute button is on. */
30
+ function beep(freq) {
31
+ if (muted) return;
32
+ audio = audio || new AudioContext();
33
+ const osc = audio.createOscillator();
34
+ const gain = audio.createGain();
35
+ gain.gain.value = 0.05;
36
+ osc.frequency.value = freq;
37
+ osc.connect(gain).connect(audio.destination);
38
+ osc.start();
39
+ osc.stop(audio.currentTime + 0.06);
40
+ }
41
+ FirstByte.on('mute', () => { muted = true; });
42
+ FirstByte.on('unmute', () => { muted = false; });
43
+
44
+ /* P4: the first key or tap starts a round, and tells the site that play has begun. */
45
+ function start() {
46
+ if (FirstByte.isPlaying) return;
47
+ score = 0;
48
+ timeLeft = ROUND_SECONDS;
49
+ coin = spot();
50
+ FirstByte.playing(true);
51
+ /* P9: an id from achievements.json. Calling it again later is fine. */
52
+ FirstByte.achieve('first-round');
53
+ beep(660);
54
+ }
55
+
56
+ /* P6: an ad only at a break. playing(false) first, then breakTime(). */
57
+ async function gameOver() {
58
+ FirstByte.playing(false);
59
+ FirstByte.score(score);
60
+ if (score >= 10) FirstByte.achieve('ten-coins');
61
+ if (score > best) {
62
+ best = score;
63
+ await FirstByte.save({ best });
64
+ }
65
+ await FirstByte.breakTime();
66
+ }
67
+
68
+ addEventListener('keydown', (e) => {
69
+ /* P4: keys the game uses must not scroll the page. */
70
+ if (MOVES[e.key] || e.key === ' ' || e.key === 'Enter') e.preventDefault();
71
+ start();
72
+ held.add(e.key);
73
+ });
74
+ addEventListener('keyup', (e) => held.delete(e.key));
75
+
76
+ /* A tap or a click: the player walks to that spot, so the game works on a phone too. */
77
+ function toGame(e) {
78
+ const r = canvas.getBoundingClientRect();
79
+ const scale = Math.min(r.width / W, r.height / H);
80
+ return { x: (e.clientX - r.left - (r.width - W * scale) / 2) / scale, y: (e.clientY - r.top - (r.height - H * scale) / 2) / scale };
81
+ }
82
+ addEventListener('pointerdown', (e) => { start(); target = toGame(e); });
83
+ addEventListener('pointermove', (e) => { if (e.buttons) target = toGame(e); });
84
+
85
+ function update(dt) {
86
+ let dx = 0;
87
+ let dy = 0;
88
+ for (const key of held) if (MOVES[key]) { dx += MOVES[key][0]; dy += MOVES[key][1]; }
89
+ if (dx || dy) target = null;
90
+ if (target) {
91
+ dx = target.x - player.x;
92
+ dy = target.y - player.y;
93
+ if (Math.hypot(dx, dy) < 4) target = null;
94
+ }
95
+ const far = Math.hypot(dx, dy);
96
+ if (far) {
97
+ player.x = Math.max(12, Math.min(W - 12, player.x + (dx / far) * SPEED * dt));
98
+ player.y = Math.max(12, Math.min(H - 12, player.y + (dy / far) * SPEED * dt));
99
+ }
100
+ if (Math.hypot(player.x - coin.x, player.y - coin.y) < 20) {
101
+ score++;
102
+ coin = spot();
103
+ beep(880);
104
+ }
105
+ timeLeft -= dt;
106
+ if (timeLeft <= 0) gameOver();
107
+ }
108
+
109
+ function draw() {
110
+ g.fillStyle = '#14161f';
111
+ g.fillRect(0, 0, W, H);
112
+ g.fillStyle = '#ffd23f';
113
+ g.beginPath();
114
+ g.arc(coin.x, coin.y, 9, 0, Math.PI * 2);
115
+ g.fill();
116
+ g.fillStyle = '#7d8dff';
117
+ g.fillRect(player.x - 12, player.y - 12, 24, 24);
118
+ g.fillStyle = '#eef0f6';
119
+ g.font = '18px sans-serif';
120
+ g.textAlign = 'left';
121
+ g.fillText(`Coins ${score}`, 16, 28);
122
+ g.textAlign = 'right';
123
+ g.fillText(FirstByte.isPlaying ? `${Math.ceil(timeLeft)} s` : `Best ${best}`, W - 16, 28);
124
+ if (!FirstByte.isPlaying) {
125
+ g.textAlign = 'center';
126
+ g.font = '22px sans-serif';
127
+ g.fillText('Press any key or tap to play', W / 2, H / 2 + 60);
128
+ }
129
+ }
130
+
131
+ function frame(now) {
132
+ const dt = Math.min(0.05, (now - last) / 1000);
133
+ last = now;
134
+ if (FirstByte.isPlaying) update(dt);
135
+ draw();
136
+ requestAnimationFrame(frame);
137
+ }
138
+
139
+ /* The player's best score from last time, then the first frame. P2: ready() once it is on screen. */
140
+ FirstByte.load().then((saved) => {
141
+ best = (saved && saved.best) || 0;
142
+ requestAnimationFrame((t) => {
143
+ last = t;
144
+ frame(t);
145
+ FirstByte.ready();
146
+ });
147
+ });
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "My First Byte game",
3
+ "hook": "Collect coins before the time runs out.",
4
+ "controls": [
5
+ { "keys": ["arrows", "wasd"], "does": "Move" },
6
+ { "keys": ["tap"], "does": "Walk there" }
7
+ ],
8
+ "kinds": ["quick-runs"]
9
+ }
@@ -0,0 +1,14 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>My First Byte game</title>
7
+ <link rel="stylesheet" href="style.css">
8
+ </head>
9
+ <body>
10
+ <canvas id="game" width="640" height="360"></canvas>
11
+ <script src="https://firstbyte.games/sdk.js"></script>
12
+ <script src="game.js"></script>
13
+ </body>
14
+ </html>
@@ -0,0 +1,3 @@
1
+ /* The game fills its frame, whatever size that is, and the picture keeps its shape. */
2
+ html, body { margin: 0; height: 100%; background: #14161f; overflow: hidden; }
3
+ canvas { display: block; width: 100%; height: 100%; object-fit: contain; touch-action: none; }
@@ -0,0 +1,123 @@
1
+ /*
2
+ * The page side of the SDK: what the First Byte site (and the checker) runs around a game's iframe.
3
+ *
4
+ * var host = FirstByteHost.attach(iframe, {
5
+ * onEvent: function (e) {}, every message, with the time and whether the game was playing
6
+ * showAd: function () { return Promise }, runs an ad; default shows none
7
+ * storage: { get(key), set(key, value) }, default: memory
8
+ * key: 'game-id',
9
+ * achievements: ['first-win'] the game's achievement ids; unlocks kept in storage
10
+ * });
11
+ * host.mute(true); host.state; host.detach();
12
+ */
13
+ (function (w) {
14
+ 'use strict';
15
+
16
+ function memory() {
17
+ var m = {};
18
+ return { get: function (k) { return k in m ? m[k] : null; }, set: function (k, v) { m[k] = v; } };
19
+ }
20
+
21
+ /* The most a save may be, in characters: the SDK's 1 MB, kept here too. */
22
+ var SAVE_CHARS = 1024 * 1024;
23
+
24
+ function attach(frame, opts) {
25
+ opts = opts || {};
26
+ var storage = opts.storage || memory();
27
+ var key = opts.key || 'game';
28
+ var showAd = opts.showAd || function () { return Promise.resolve(false); };
29
+ var t0 = Date.now();
30
+ var listed = opts.achievements || [];
31
+ var akey = key + ':achievements';
32
+ var state = { hello: false, version: null, ready: false, readyAt: null, playing: false, everPlayed: false, listening: {}, score: null, inAd: false, achieved: [] };
33
+
34
+ /* Unlocks kept so far: { id, at }[], read fresh each time so another tab's are known. */
35
+ function kept() {
36
+ var list;
37
+ try { list = JSON.parse(storage.get(akey)); } catch (e) { list = null; }
38
+ if (!Array.isArray(list)) return [];
39
+ return list.filter(function (u) { return u && typeof u.id === 'string'; });
40
+ }
41
+ function ids(list) { return list.map(function (u) { return u.id; }); }
42
+ state.achieved = ids(kept());
43
+
44
+ function achieve(id, replyId) {
45
+ if (listed.indexOf(id) < 0) {
46
+ log('achieve', { id: id }, { new: false, refused: 'unknown' });
47
+ reply(replyId, true, { unlocked: false, new: false, reason: 'unknown' });
48
+ return;
49
+ }
50
+ var have = kept();
51
+ var isNew = ids(have).indexOf(id) < 0;
52
+ if (isNew) { have.push({ id: id, at: Date.now() }); storage.set(akey, JSON.stringify(have)); }
53
+ state.achieved = ids(have);
54
+ log('achieve', { id: id }, { new: isNew });
55
+ reply(replyId, true, { unlocked: true, new: isNew });
56
+ }
57
+
58
+ function to(msg) { if (frame.contentWindow) frame.contentWindow.postMessage(msg, '*'); }
59
+ function reply(id, ok, data) { to({ firstbyte: 1, type: 'reply', id: id, ok: ok, data: data }); }
60
+ function event(name) { to({ firstbyte: 1, type: 'event', name: name }); }
61
+ function log(type, data, extra) {
62
+ if (!opts.onEvent) return;
63
+ var e = { t: Date.now() - t0, type: type, data: data, playing: state.playing, everPlayed: state.everPlayed };
64
+ for (var k in extra || {}) e[k] = extra[k];
65
+ try { opts.onEvent(e); } catch (err) {}
66
+ }
67
+
68
+ function onMessage(e) {
69
+ var m = e.data;
70
+ if (!m || m.firstbyte !== 1 || e.source !== frame.contentWindow) return;
71
+ var d = m.data || {};
72
+ switch (m.type) {
73
+ case 'hello': state.hello = true; state.version = d.version; log('hello', d); break;
74
+ case 'ready':
75
+ if (!state.ready) { state.ready = true; state.readyAt = Date.now() - t0; }
76
+ log('ready'); break;
77
+ case 'playing':
78
+ state.playing = !!d.on;
79
+ if (state.playing) state.everPlayed = true;
80
+ log('playing', { on: state.playing }); break;
81
+ case 'break-refused': log('break-refused', d); break;
82
+ case 'break':
83
+ if (state.playing || state.inAd) {
84
+ log('break', null, { shown: false, refused: state.playing ? 'playing' : 'busy' });
85
+ reply(m.id, true, { shown: false, reason: state.playing ? 'playing' : 'busy' });
86
+ break;
87
+ }
88
+ log('break', null, { shown: true });
89
+ state.inAd = true;
90
+ event('pause');
91
+ Promise.resolve().then(showAd).then(function (shown) {
92
+ state.inAd = false; event('resume'); reply(m.id, true, { shown: !!shown });
93
+ }, function () {
94
+ state.inAd = false; event('resume'); reply(m.id, true, { shown: false });
95
+ });
96
+ break;
97
+ case 'save': {
98
+ /* The 1 MB limit is the page's to keep: a game can skip the SDK and post anything. */
99
+ const text = m.data;
100
+ if (typeof text !== 'string' || text.length > SAVE_CHARS) { log('save', null, { refused: 'too-big' }); reply(m.id, false, null); break; }
101
+ const kept = storage.set(key, text) !== false;
102
+ log('save', null, kept ? {} : { refused: 'storage' });
103
+ reply(m.id, kept, kept);
104
+ break;
105
+ }
106
+ case 'load': log('load'); reply(m.id, true, storage.get(key)); break;
107
+ case 'score': state.score = d.value; log('score', d); break;
108
+ case 'listen': state.listening[d.event] = true; log('listen', d); break;
109
+ case 'achieve': achieve(String(d.id), m.id); break;
110
+ default: log('unknown', { type: m.type });
111
+ }
112
+ }
113
+
114
+ w.addEventListener('message', onMessage);
115
+ return {
116
+ state: state,
117
+ mute: function (on) { event(on ? 'mute' : 'unmute'); log(on ? 'mute' : 'unmute'); },
118
+ detach: function () { w.removeEventListener('message', onMessage); },
119
+ };
120
+ }
121
+
122
+ w.FirstByteHost = { attach: attach };
123
+ })(typeof window !== 'undefined' ? window : globalThis);