firstbyte 0.0.0-stage → 0.1.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.
@@ -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,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);
@@ -0,0 +1,157 @@
1
+ /*
2
+ * First Byte SDK. Load it with
3
+ * <script src="https://firstbyte.games/sdk.js"></script>
4
+ * and call window.FirstByte. Every call also works when the game runs on its own
5
+ * (no First Byte page around it), so a game never needs a special case.
6
+ *
7
+ * It talks to the page around it with postMessage: { firstbyte: 1, type, data, id }.
8
+ * The other side of that conversation is sdk/host.js.
9
+ */
10
+ (function (w) {
11
+ 'use strict';
12
+ if (w.FirstByte) return;
13
+
14
+ var VERSION = '0.1.0';
15
+ var REPLY_MS = 3000;
16
+ var SAVE_BYTES = 1024 * 1024;
17
+ var ACHIEVEMENT_ID = /^[a-z][a-z0-9-]{0,31}$/;
18
+ var host = w.parent && w.parent !== w ? w.parent : null;
19
+ var key = 'firstbyte:' + (w.location ? w.location.pathname : 'game');
20
+ var pending = {};
21
+ var nextId = 1;
22
+ var listeners = {};
23
+ var state = { ready: false, playing: false, muted: false };
24
+
25
+ function warn(msg) { try { console.warn('[FirstByte] ' + msg); } catch (e) {} }
26
+ function send(type, data) { if (host) host.postMessage({ firstbyte: 1, type: type, data: data }, '*'); }
27
+
28
+ function ask(type, data, alone) {
29
+ return new Promise(function (done) {
30
+ if (!host) return done(alone());
31
+ var id = nextId++;
32
+ var timer = setTimeout(function () { delete pending[id]; done(alone()); }, REPLY_MS);
33
+ pending[id] = function (m) { clearTimeout(timer); done(m.ok ? m.data : alone()); };
34
+ host.postMessage({ firstbyte: 1, type: type, data: data, id: id }, '*');
35
+ });
36
+ }
37
+
38
+ function emit(name) {
39
+ var list = (listeners[name] || []).slice();
40
+ for (var i = 0; i < list.length; i++) {
41
+ try { list[i](); } catch (e) { try { console.error(e); } catch (e2) {} }
42
+ }
43
+ }
44
+
45
+ w.addEventListener('message', function (e) {
46
+ var m = e.data;
47
+ if (!m || m.firstbyte !== 1 || !host || e.source !== host) return;
48
+ if (m.type === 'reply' && pending[m.id]) {
49
+ var f = pending[m.id];
50
+ delete pending[m.id];
51
+ f(m);
52
+ } else if (m.type === 'event') {
53
+ if (m.name === 'mute') state.muted = true;
54
+ if (m.name === 'unmute') state.muted = false;
55
+ emit(m.name);
56
+ }
57
+ });
58
+
59
+ function store(get, value) {
60
+ try {
61
+ if (get) return w.localStorage.getItem(key);
62
+ w.localStorage.setItem(key, value);
63
+ } catch (e) {}
64
+ return get ? null : true;
65
+ }
66
+
67
+ /* On its own, unlocks are kept in this browser; any well-formed id unlocks, since only the page knows the list. */
68
+ function unlockAlone(id) {
69
+ var kept = [];
70
+ try { kept = JSON.parse(w.localStorage.getItem(key + ':achievements')) || []; } catch (e) { kept = []; }
71
+ if (!Array.isArray(kept)) kept = [];
72
+ for (var i = 0; i < kept.length; i++) if (kept[i] && kept[i].id === id) return { unlocked: true, new: false };
73
+ kept.push({ id: id, at: Date.now() });
74
+ try { w.localStorage.setItem(key + ':achievements', JSON.stringify(kept)); } catch (e) {}
75
+ return { unlocked: true, new: true };
76
+ }
77
+
78
+ var api = {
79
+ version: VERSION,
80
+
81
+ /* Once, when the first frame is on screen. */
82
+ ready: function () {
83
+ if (state.ready) return;
84
+ state.ready = true;
85
+ send('ready');
86
+ },
87
+
88
+ /* true when a round starts, false when it ends (game over, between levels, a menu). */
89
+ playing: function (on) {
90
+ on = !!on;
91
+ if (on === state.playing) return;
92
+ state.playing = on;
93
+ send('playing', { on: on });
94
+ },
95
+
96
+ /* An ad, only at a break. Resolves { shown: true|false }. Never rejects. */
97
+ breakTime: function () {
98
+ if (state.playing) {
99
+ warn('breakTime() was called while playing, so no ad was shown. Call FirstByte.playing(false) first.');
100
+ send('break-refused', { reason: 'playing' });
101
+ return Promise.resolve({ shown: false, reason: 'playing' });
102
+ }
103
+ return ask('break', null, function () { return { shown: false, reason: 'no-site' }; });
104
+ },
105
+
106
+ /* Progress: anything JSON can store, up to 1 MB. */
107
+ save: function (data) {
108
+ var text;
109
+ try { text = JSON.stringify(data); } catch (e) { text = undefined; }
110
+ if (text === undefined) return Promise.reject(new Error('FirstByte.save() takes data that JSON can store.'));
111
+ if (text.length > SAVE_BYTES) return Promise.reject(new Error('FirstByte.save() is limited to 1 MB.'));
112
+ return ask('save', text, function () { return store(false, text); }).then(function () {});
113
+ },
114
+
115
+ /* The saved progress, or null. */
116
+ load: function () {
117
+ return ask('load', null, function () { return store(true); }).then(function (text) {
118
+ if (text == null) return null;
119
+ try { return JSON.parse(text); } catch (e) { return null; }
120
+ });
121
+ },
122
+
123
+ /* An optional score board. */
124
+ score: function (n) {
125
+ if (typeof n !== 'number' || !isFinite(n)) { warn('score() takes a number.'); return; }
126
+ send('score', { value: n });
127
+ },
128
+
129
+ /* An achievement earned, by its id in achievements.json. Only the first time is new. Never rejects. */
130
+ achieve: function (id) {
131
+ if (typeof id !== 'string' || !ACHIEVEMENT_ID.test(id)) {
132
+ warn('achieve() takes an id from achievements.json: lowercase letters, digits and hyphens, starting with a letter, like "first-win".');
133
+ return Promise.resolve({ unlocked: false, new: false, reason: 'bad-id' });
134
+ }
135
+ return ask('achieve', { id: id }, function () { return unlockAlone(id); });
136
+ },
137
+
138
+ /* 'mute', 'unmute', 'pause' (before an ad), 'resume'. Returns a function that stops listening. */
139
+ on: function (name, fn) {
140
+ if (typeof fn !== 'function') { warn('on() takes a name and a function.'); return function () {}; }
141
+ (listeners[name] = listeners[name] || []).push(fn);
142
+ send('listen', { event: name });
143
+ return function () {
144
+ var list = listeners[name] || [];
145
+ var i = list.indexOf(fn);
146
+ if (i >= 0) list.splice(i, 1);
147
+ };
148
+ },
149
+
150
+ get muted() { return state.muted; },
151
+ get isPlaying() { return state.playing; },
152
+ get onSite() { return !!host; },
153
+ };
154
+
155
+ w.FirstByte = api;
156
+ send('hello', { version: VERSION });
157
+ })(typeof window !== 'undefined' ? window : globalThis);
package/index.js ADDED
@@ -0,0 +1,7 @@
1
+ /* The public API: what a script or another tool imports from 'firstbyte'. Every export is a block's entry. */
2
+ export { check, report } from './blocks/check/Checker/Checker.js';
3
+ export { formatReport, summary } from './blocks/check/ReportText/ReportText.js';
4
+ export { brief } from './blocks/rules/Brief/Brief.js';
5
+ export { RULES, LIMITS, ALLOWED, ruleById } from './blocks/rules/Rulebook/Rulebook.js';
6
+ export { CATEGORIES } from './blocks/catalog/Kinds/Kinds.js';
7
+ export { needs, shortlist } from './blocks/catalog/Needs/Needs.js';
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "firstbyte",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "First Byte: the game SDK, the checker that tells a developer exactly what to fix, and the site.",
5
+ "type": "module",
6
+ "license": "UNLICENSED",
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
10
+ "bin": {
11
+ "firstbyte": "bin/firstbyte.js"
12
+ },
13
+ "files": [
14
+ "bin/",
15
+ "index.js",
16
+ "blocks/achievements/Achievements/",
17
+ "blocks/catalog/Kinds/",
18
+ "blocks/catalog/Needs/",
19
+ "blocks/check/",
20
+ "blocks/dev/Levels/",
21
+ "blocks/load/",
22
+ "blocks/metrics/Rollup/",
23
+ "blocks/rules/",
24
+ "blocks/sdk/",
25
+ "site/data/games.json",
26
+ "site/data/demo-sessions.json",
27
+ "!**/*.test.js",
28
+ "!**/*.spec.md"
29
+ ],
30
+ "exports": {
31
+ ".": "./index.js",
32
+ "./sdk": "./blocks/sdk/Sdk/Sdk.js",
33
+ "./host": "./blocks/sdk/Host/Host.js"
34
+ },
35
+ "scripts": {
36
+ "check": "node node_modules/blockkit/bin/blockkit.js check",
37
+ "build": "node scripts/build-site.js",
38
+ "test": "node --test --test-concurrency=1 \"blocks/**/*.test.js\" \"test/**/*.test.js\"",
39
+ "verify": "npm run check && node scripts/build-site.js --check && npm test",
40
+ "site": "node scripts/serve-site.js"
41
+ },
42
+ "peerDependencies": {
43
+ "playwright": "1.63.0"
44
+ },
45
+ "peerDependenciesMeta": {
46
+ "playwright": {
47
+ "optional": true
48
+ }
49
+ },
50
+ "devDependencies": {
51
+ "blockkit": "github:jacksonkvandyke/Blockkit#7eb509eb2213fd73575dd22816550ab26d72304b"
52
+ }
53
+ }