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.
- package/README.md +94 -2
- package/bin/firstbyte.js +32 -0
- package/blocks/achievements/Achievements/Achievements.js +102 -0
- package/blocks/catalog/Kinds/Kinds.js +18 -0
- package/blocks/catalog/Listing/Listing.js +178 -0
- package/blocks/catalog/Needs/Needs.js +68 -0
- package/blocks/check/Checker/Checker.js +63 -0
- package/blocks/check/FileChecks/FileChecks.js +228 -0
- package/blocks/check/PlayChecks/PlayChecks.js +289 -0
- package/blocks/check/PlayChecks/harness.html +21 -0
- package/blocks/check/PlayChecks/png.js +70 -0
- package/blocks/check/PlayChecks/serve.js +50 -0
- package/blocks/check/ReportText/ReportText.js +57 -0
- package/blocks/dev/Levels/Levels.js +47 -0
- package/blocks/load/Build/Build.js +45 -0
- package/blocks/load/Served/Served.js +27 -0
- package/blocks/load/Zip/Zip.js +141 -0
- package/blocks/metrics/Rollup/Rollup.js +79 -0
- package/blocks/rules/Brief/Brief.js +168 -0
- package/blocks/rules/Rulebook/Rulebook.js +214 -0
- package/blocks/rules/Starter/Starter.js +22 -0
- package/blocks/rules/Starter/game/README.txt +11 -0
- package/blocks/rules/Starter/game/achievements.json +6 -0
- package/blocks/rules/Starter/game/cover.jpg +0 -0
- package/blocks/rules/Starter/game/game.js +147 -0
- package/blocks/rules/Starter/game/game.json +9 -0
- package/blocks/rules/Starter/game/index.html +14 -0
- package/blocks/rules/Starter/game/style.css +3 -0
- package/blocks/sdk/Host/Host.js +123 -0
- package/blocks/sdk/Sdk/Sdk.js +157 -0
- package/index.js +7 -0
- package/package.json +52 -4
- package/site/data/demo-sessions.json +1 -0
- package/site/data/games.json +9 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The 'files' rules (F1-F7): everything that can be checked by reading the build, without playing it.
|
|
3
|
+
* Spec: FileChecks.spec.md. Called by check/Checker; each rule's words and fix are in rules/Rulebook.
|
|
4
|
+
*/
|
|
5
|
+
import { readGameFile, checkCover, GAME_FILE, COVER_FILE } from '../../catalog/Listing/Listing.js';
|
|
6
|
+
import { LIMITS } from '../../rules/Rulebook/Rulebook.js';
|
|
7
|
+
import { FILE as ACHIEVEMENTS, readList } from '../../achievements/Achievements/Achievements.js';
|
|
8
|
+
|
|
9
|
+
const TEXT = /\.(html?|m?js|css|json|txt|xml|svg)$/i;
|
|
10
|
+
|
|
11
|
+
export const OTHER_PORTALS = [
|
|
12
|
+
{ name: 'CrazyGames', re: /sdk\.crazygames\.com|CrazyGames\.SDK|window\.CrazyGames\b/ },
|
|
13
|
+
{ name: 'Poki', re: /poki-sdk|game-cdn\.poki\.com|\bPokiSDK\b/ },
|
|
14
|
+
{ name: 'GameDistribution', re: /gamedistribution\.com|\bgdsdk\b/ },
|
|
15
|
+
{ name: 'Yandex Games', re: /yandex\.ru\/games\/sdk|\bYaGames\b/ },
|
|
16
|
+
{ name: 'Playgama', re: /playgama-bridge|playgama\.com/i },
|
|
17
|
+
{ name: 'GamePix', re: /gamepix\.com|\bGamePix\./ },
|
|
18
|
+
{ name: 'GameMonetize', re: /gamemonetize/i },
|
|
19
|
+
{ name: 'Y8', re: /api\.y8\.com|y8\.com\/api/ },
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
export const STORE_LINKS = [
|
|
23
|
+
'store.steampowered.com', 'patreon.com', 'ko-fi.com', 'buymeacoffee.com', 'paypal.com', 'paypal.me',
|
|
24
|
+
'apps.apple.com', 'play.google.com', 'itch.io', 'crazygames.com', 'poki.com', 'newgrounds.com',
|
|
25
|
+
'kongregate.com', 'armorgames.com', 'gamejolt.com',
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
/* The SDK's script tag: its src is the SDK's address, or a .js file with firstbyte in its name. Tested on one
|
|
29
|
+
tag at a time (scriptTags), never across a whole file, so no file can make the check slow. */
|
|
30
|
+
const SDK_SRC = /\ssrc\s*=\s*["']([^"']{1,500})["']/i;
|
|
31
|
+
const isSdkTag = (tag) => { const m = SDK_SRC.exec(tag); return !!m && (m[1] === 'https://firstbyte.games/sdk.js' || /firstbyte[^/]*\.js$/i.test(m[1])); };
|
|
32
|
+
/* Every <script ...> opening tag in a page, each at most 2000 characters, found in one pass. */
|
|
33
|
+
function scriptTags(src) {
|
|
34
|
+
const lower = src.toLowerCase();
|
|
35
|
+
const out = [];
|
|
36
|
+
for (let i = lower.indexOf('<script'); i !== -1 && out.length < 500; i = lower.indexOf('<script', i + 7)) {
|
|
37
|
+
const end = lower.indexOf('>', i);
|
|
38
|
+
out.push(src.slice(i, end === -1 ? i + 2000 : Math.min(end + 1, i + 2000)));
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
/* Strings inside the SDK itself, which survive bundling and minifying. */
|
|
43
|
+
const SDK_BUNDLED = /\[FirstByte\] |["']firstbyte:["']/;
|
|
44
|
+
const SDK_CALLS = /FirstByte\.(ready|playing|breakTime|save|load|score|achieve|on)\(/;
|
|
45
|
+
|
|
46
|
+
export function checkFiles(files, root) {
|
|
47
|
+
const text = new Map();
|
|
48
|
+
for (const [name, buf] of files) if (TEXT.test(name)) text.set(name, buf.toString('utf8'));
|
|
49
|
+
return [
|
|
50
|
+
indexTop(files, root),
|
|
51
|
+
relativePaths(files, text, root ?? ''),
|
|
52
|
+
size(files),
|
|
53
|
+
otherPortal(text),
|
|
54
|
+
storeLinks(text),
|
|
55
|
+
sdk(text),
|
|
56
|
+
achievements(files, text, root ?? ''),
|
|
57
|
+
gameFile(files, root ?? ''),
|
|
58
|
+
];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function indexTop(files, root) {
|
|
62
|
+
if (root === '') return { id: 'F1', status: 'pass' };
|
|
63
|
+
/* The whole game zipped inside one folder is the commonest way to zip a build, and plays the same:
|
|
64
|
+
the site and the checker both serve it from that folder (load/Build findRoot). */
|
|
65
|
+
if (root) return { id: 'F1', status: 'pass', detail: [`index.html is inside the folder "${root.slice(0, -1)}", which holds the whole game. That works.`] };
|
|
66
|
+
const names = [...files.keys()].filter((n) => !n.startsWith('__MACOSX/'));
|
|
67
|
+
const found = names.filter((n) => /(^|\/)index\.html$/.test(n));
|
|
68
|
+
/* Some engines name the page after the project ("my-game.html"): one page at the top is surely it. */
|
|
69
|
+
const pages = names.filter((n) => !n.includes('/') && /\.html?$/i.test(n));
|
|
70
|
+
const detail = found.length
|
|
71
|
+
? [`index.html is at ${found.map((f) => `"${f}"`).join(', ')}, with other files outside its folder. Put index.html at the top, next to them.`]
|
|
72
|
+
: names.some((n) => n.split('/').pop().toLowerCase() === 'index.html')
|
|
73
|
+
? ['The file must be called index.html, all lower case.']
|
|
74
|
+
: pages.length === 1
|
|
75
|
+
? [`There is no index.html. Rename "${pages[0]}" to index.html.`]
|
|
76
|
+
: ['There is no index.html in the build.'];
|
|
77
|
+
return { id: 'F1', status: 'fail', detail };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function refsIn(name, src) {
|
|
81
|
+
const out = [];
|
|
82
|
+
const add = (v) => out.push(v.trim());
|
|
83
|
+
if (/\.html?$/i.test(name)) {
|
|
84
|
+
for (const m of src.matchAll(/\s(?:src|href|data-src|poster)\s*=\s*["']([^"']{1,2000})["']/gi)) add(m[1]);
|
|
85
|
+
}
|
|
86
|
+
if (/\.(html?|css)$/i.test(name)) {
|
|
87
|
+
for (const m of src.matchAll(/url\(\s*["']?([^"')]{1,2000})["']?\s*\)/gi)) add(m[1]);
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function relativePaths(files, text, root) {
|
|
93
|
+
const detail = [];
|
|
94
|
+
let fail = false;
|
|
95
|
+
for (const name of files.keys()) {
|
|
96
|
+
if (name.includes('\\')) { fail = true; detail.push(`"${name}" has a backslash in its path. Zip it again on the command line or with 7-Zip.`); }
|
|
97
|
+
}
|
|
98
|
+
const lower = new Map([...files.keys()].map((n) => [n.toLowerCase(), n]));
|
|
99
|
+
for (const [name, src] of text) {
|
|
100
|
+
if (!name.startsWith(root)) continue;
|
|
101
|
+
const dir = name.slice(0, name.lastIndexOf('/') + 1);
|
|
102
|
+
for (const ref of refsIn(name, src)) {
|
|
103
|
+
if (/^(https?:|data:|blob:|mailto:|tel:|javascript:|#|about:|\/\/)/i.test(ref) || ref.includes('${') || ref === '') continue;
|
|
104
|
+
if (ref.startsWith('/')) { fail = true; detail.push(`${name}: "${ref}" starts with "/". Use "${ref.replace(/^\/+/, '')}".`); continue; }
|
|
105
|
+
if (/^(file:|[a-z]:\\)/i.test(ref)) { fail = true; detail.push(`${name}: "${ref}" points at a file on your computer.`); continue; }
|
|
106
|
+
const target = resolve(dir, ref.split(/[?#]/)[0]);
|
|
107
|
+
if (target === null || files.has(target)) continue;
|
|
108
|
+
const near = lower.get(target.toLowerCase());
|
|
109
|
+
if (near) { fail = true; detail.push(`${name}: "${ref}" is "${near.slice(root.length)}" in the build. Match the case exactly.`); }
|
|
110
|
+
else detail.push(`${name}: "${ref}" is not in the build.`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (fail) return { id: 'F2', status: 'fail', detail };
|
|
114
|
+
if (detail.length) return { id: 'F2', status: 'warn', detail: [...detail, 'These may be made by your code at run time. If not, the game will miss them.'] };
|
|
115
|
+
return { id: 'F2', status: 'pass' };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function resolve(dir, ref) {
|
|
119
|
+
let ref2;
|
|
120
|
+
try { ref2 = decodeURIComponent(ref); } catch { ref2 = ref; }
|
|
121
|
+
const parts = (dir + ref2).split('/');
|
|
122
|
+
const out = [];
|
|
123
|
+
for (const p of parts) {
|
|
124
|
+
if (p === '..') { if (!out.length) return null; out.pop(); }
|
|
125
|
+
else if (p !== '.' && p !== '') out.push(p);
|
|
126
|
+
}
|
|
127
|
+
return out.join('/');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function size(files) {
|
|
131
|
+
let total = 0;
|
|
132
|
+
for (const buf of files.values()) total += buf.length;
|
|
133
|
+
const mb = (n) => `${(n / 1024 / 1024).toFixed(1)} MB`;
|
|
134
|
+
if (total <= LIMITS.sizeBytes) return { id: 'F3', status: 'pass', detail: [`${mb(total)} unzipped.`] };
|
|
135
|
+
const biggest = [...files].sort((a, b) => b[1].length - a[1].length).slice(0, 5);
|
|
136
|
+
return { id: 'F3', status: 'fail', detail: [`${mb(total)} unzipped, over the 50 MB limit. Biggest files:`, ...biggest.map(([n, b]) => ` ${mb(b.length)} ${n}`)] };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function otherPortal(text) {
|
|
140
|
+
const loaded = [];
|
|
141
|
+
const inCode = [];
|
|
142
|
+
for (const { name, re } of OTHER_PORTALS) {
|
|
143
|
+
const tags = [...text].filter(([f, src]) => /\.html?$/i.test(f) && scriptTags(src).some((tag) => re.test(tag)));
|
|
144
|
+
const where = [...text].filter(([, src]) => re.test(src)).map(([f]) => f);
|
|
145
|
+
if (tags.length) loaded.push(`${name} SDK is loaded by ${tags.map(([f]) => f).join(', ')}.`);
|
|
146
|
+
else if (where.length) inCode.push(`${name} SDK code is in ${where.slice(0, 3).join(', ')}${where.length > 3 ? ` and ${where.length - 3} more` : ''}.`);
|
|
147
|
+
}
|
|
148
|
+
if (loaded.length) return { id: 'F4', status: 'fail', detail: [...loaded, ...inCode] };
|
|
149
|
+
if (inCode.length) return { id: 'F4', status: 'warn', detail: [...inCode, "It isn't loaded by the page, so it may be a multi-site adapter that stays quiet here. If it shows another site's ads or prompts on First Byte, make a build without it."] };
|
|
150
|
+
return { id: 'F4', status: 'pass' };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function storeLinks(text) {
|
|
154
|
+
const inHref = [];
|
|
155
|
+
const inCode = [];
|
|
156
|
+
for (const [name, src] of text) {
|
|
157
|
+
for (const host of STORE_LINKS) {
|
|
158
|
+
const re = new RegExp(`https?://(?:[\\w-]+\\.)*${host.replace(/\./g, '\\.')}[^\\s"'<>)]*`, 'gi');
|
|
159
|
+
for (const m of src.matchAll(re)) {
|
|
160
|
+
const before = src.slice(Math.max(0, m.index - 12), m.index);
|
|
161
|
+
(/\.html?$/i.test(name) && /href\s*=\s*["']?$/i.test(before) ? inHref : inCode).push(`${name}: ${m[0]}`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (inHref.length) return { id: 'F5', status: 'fail', detail: unique(inHref) };
|
|
166
|
+
if (inCode.length) return { id: 'F5', status: 'warn', detail: [...unique(inCode), 'Found in code, not as a link. If the game shows it to players, remove it.'] };
|
|
167
|
+
return { id: 'F5', status: 'pass' };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function sdk(text) {
|
|
171
|
+
for (const [name, src] of text) {
|
|
172
|
+
if (/\.html?$/i.test(name) && scriptTags(src).some(isSdkTag)) return { id: 'F6', status: 'pass' };
|
|
173
|
+
}
|
|
174
|
+
for (const src of text.values()) if (SDK_BUNDLED.test(src)) return { id: 'F6', status: 'pass', detail: ['The SDK is bundled into your code.'] };
|
|
175
|
+
const calls = [...text].find(([, src]) => SDK_CALLS.test(src));
|
|
176
|
+
if (calls) return { id: 'F6', status: 'fail', detail: [`${calls[0]} calls FirstByte, but the SDK is never loaded, so the game will stop with an error.`] };
|
|
177
|
+
return { id: 'F6', status: 'note', detail: ['No SDK found. That is allowed: the game will earn no ad share and keep no saves with us.'] };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const unique = (a) => [...new Set(a)].slice(0, 8);
|
|
181
|
+
|
|
182
|
+
/*
|
|
183
|
+
* F7: achievements.json, next to index.html, checked by achievements/Achievements. A listed id that
|
|
184
|
+
* is nowhere in the code is only LOOK: the code may build the id at run time, which reading can't see.
|
|
185
|
+
*/
|
|
186
|
+
function achievements(files, text, root) {
|
|
187
|
+
const at = root + ACHIEVEMENTS;
|
|
188
|
+
if (!files.has(at)) {
|
|
189
|
+
const elsewhere = [...files.keys()].find((n) => n === ACHIEVEMENTS || n.endsWith(`/${ACHIEVEMENTS}`));
|
|
190
|
+
if (elsewhere) return { id: 'F7', status: 'fail', detail: [`achievements.json is at "${elsewhere}". Move it next to index.html${root ? ` (into "${root.slice(0, -1)}")` : ''}.`] };
|
|
191
|
+
return { id: 'F7', status: 'note', detail: ['No achievements. You can add up to 30: see npx firstbyte brief.'] };
|
|
192
|
+
}
|
|
193
|
+
const { list, problems } = readList(files.get(at).toString('utf8'));
|
|
194
|
+
if (!list) return { id: 'F7', status: 'fail', detail: problems };
|
|
195
|
+
const code = [...text].filter(([n]) => n !== at && /\.(html?|m?js)$/i.test(n)).map(([, src]) => src);
|
|
196
|
+
const unseen = list.filter((a) => !code.some((src) => src.includes(a.id)));
|
|
197
|
+
const detail = [`${list.length} achievement${list.length === 1 ? '' : 's'}.`];
|
|
198
|
+
if (!unseen.length) return { id: 'F7', status: 'pass', detail };
|
|
199
|
+
return { id: 'F7', status: 'warn', detail: [...detail, ...unseen.map((a) => `"${a.id}" isn't written in your code. Fine if your code builds the id; otherwise it can never unlock.`)] };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/* F8: game.json and cover.jpg, the developer's part of the game's page, when the build carries them. */
|
|
203
|
+
function gameFile(files, root) {
|
|
204
|
+
const detail = [];
|
|
205
|
+
let bad = false;
|
|
206
|
+
const at = (name) => {
|
|
207
|
+
if (files.has(root + name)) return root + name;
|
|
208
|
+
const elsewhere = [...files.keys()].find((n) => n === name || n.endsWith(`/${name}`));
|
|
209
|
+
if (elsewhere && !elsewhere.startsWith('__MACOSX/')) { bad = true; detail.push(`${name} is at "${elsewhere}". Move it next to index.html${root ? ` (into "${root.slice(0, -1)}")` : ''}.`); }
|
|
210
|
+
return null;
|
|
211
|
+
};
|
|
212
|
+
const game = at(GAME_FILE);
|
|
213
|
+
if (game) {
|
|
214
|
+
const { details, problems } = readGameFile(files.get(game).toString('utf8'));
|
|
215
|
+
if (!details) { bad = true; detail.push(...problems.map((p) => `${GAME_FILE}: ${p}`)); } else {
|
|
216
|
+
const has = ['name', 'hook', 'controls', 'kinds'].filter((k) => details[k] !== undefined);
|
|
217
|
+
detail.push(`${GAME_FILE}: ${has.length ? `has ${has.join(', ')}.` : 'is empty, so it fills in nothing.'}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const cover = at(COVER_FILE);
|
|
221
|
+
if (cover) {
|
|
222
|
+
const c = checkCover(new Uint8Array(files.get(cover)));
|
|
223
|
+
if (c.problems.length) { bad = true; detail.push(...c.problems.map((p) => p.replace(/^Cover: /, `${COVER_FILE}: `))); } else detail.push(`${COVER_FILE}: ${c.width} × ${c.height}.`);
|
|
224
|
+
}
|
|
225
|
+
if (bad) return { id: 'F8', status: 'fail', detail };
|
|
226
|
+
if (!detail.length) return { id: 'F8', status: 'note', detail: [`No ${GAME_FILE} or ${COVER_FILE}. With them, the boxes fill themselves in when you send: see npx firstbyte brief.`] };
|
|
227
|
+
return { id: 'F8', status: 'pass', detail };
|
|
228
|
+
}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The 'play' rules (P1-P9): the build is served from memory and played in headless Chromium, inside
|
|
3
|
+
* the same page side (sdk/Host, in harness.html) the site puts around a game. Spec: PlayChecks.spec.md.
|
|
4
|
+
* Called by check/Checker. run() plays the game once and every rule below reads what it recorded.
|
|
5
|
+
*/
|
|
6
|
+
import { createRequire } from 'node:module';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { serve, SDK } from './serve.js';
|
|
9
|
+
import { decodePng, hasPicture, changed } from './png.js';
|
|
10
|
+
import { LIMITS, RULES } from '../../rules/Rulebook/Rulebook.js';
|
|
11
|
+
import { FILE as ACHIEVEMENTS, readList } from '../../achievements/Achievements/Achievements.js';
|
|
12
|
+
|
|
13
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
14
|
+
const secs = (ms) => `${(ms / 1000).toFixed(1)} s`;
|
|
15
|
+
const PLAY_IDS = RULES.filter((r) => r.check === 'play').map((r) => r.id);
|
|
16
|
+
|
|
17
|
+
/* Runs in every frame before the game's own code: records errors and sound, through __fbRecord, a binding
|
|
18
|
+
the checker keeps in Node; the game, on its own origin, can neither read nor rewrite what was recorded. */
|
|
19
|
+
const PROBE = `(() => {
|
|
20
|
+
const rec = (kind, msg) => { try { window.__fbRecord(kind, String(msg).slice(0, 300)); } catch (e) {} };
|
|
21
|
+
addEventListener('error', (e) => { if (e instanceof ErrorEvent) rec('error', e.message || 'Script error'); }, true);
|
|
22
|
+
addEventListener('unhandledrejection', (e) => rec('error', 'Unhandled promise rejection: ' + (e.reason && e.reason.message || e.reason)));
|
|
23
|
+
/* A sound file plays through AudioBufferSourceNode, which has its own start(); tones use the shared one. */
|
|
24
|
+
for (const P of [window.AudioScheduledSourceNode, window.AudioBufferSourceNode]) {
|
|
25
|
+
if (!P || !Object.prototype.hasOwnProperty.call(P.prototype, 'start')) continue;
|
|
26
|
+
const start = P.prototype.start;
|
|
27
|
+
P.prototype.start = function (...a) { rec('sound', 'Web Audio'); return start.apply(this, a); };
|
|
28
|
+
}
|
|
29
|
+
const M = window.HTMLMediaElement && HTMLMediaElement.prototype;
|
|
30
|
+
if (M) { const play = M.play; M.play = function (...a) { if (!this.muted && this.volume > 0) rec('sound', 'audio element'); return play.apply(this, a); }; }
|
|
31
|
+
if (window !== window.top) addEventListener('scroll', () => rec('scroll', 'page'), { capture: true, passive: true });
|
|
32
|
+
})();`;
|
|
33
|
+
|
|
34
|
+
/* The game froze the page, so nothing it did can be told: P1 fails saying so, the rest are skipped. */
|
|
35
|
+
function froze(ms) {
|
|
36
|
+
const why = `The game froze the page: it stopped answering for ${Math.round(ms / 1000)} s, so the checker stopped. Look for a loop that never ends.`;
|
|
37
|
+
return PLAY_IDS.map((id) => (id === 'P1' ? { id, status: 'fail', detail: [why] } : { id, status: 'skip', detail: ['The game froze the page, so this could not be checked.'] }));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function skipPlay(why) {
|
|
41
|
+
return PLAY_IDS.map((id) => ({ id, status: 'skip', detail: [why] }));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/*
|
|
45
|
+
* Where Playwright is looked for, in order:
|
|
46
|
+
* 1. next to the checker itself (a project that installed both, or this repo);
|
|
47
|
+
* 2. a global install, found through NODE_PATH, which only require() reads;
|
|
48
|
+
* 3. the folder the command is run from: `npx firstbyte check` runs the checker from npm's own
|
|
49
|
+
* cache, far from the developer's project, where they installed Playwright.
|
|
50
|
+
* `near: null` skips the first two (for the test of the third).
|
|
51
|
+
*/
|
|
52
|
+
export async function loadPlaywright(opts = {}, { cwd = process.cwd(), near = import.meta.url } = {}) {
|
|
53
|
+
if (opts.playwright) return opts.playwright;
|
|
54
|
+
if (near) {
|
|
55
|
+
try { return await import('playwright'); } catch {}
|
|
56
|
+
try { return createRequire(near)('playwright'); } catch {}
|
|
57
|
+
}
|
|
58
|
+
try { return createRequire(join(cwd, 'package.json'))('playwright'); } catch { return null; }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const isRoot = () => typeof process.getuid === 'function' && process.getuid() === 0;
|
|
62
|
+
|
|
63
|
+
/* The game is untrusted code: Chromium's own sandbox stays on, so a page that breaks out of the renderer
|
|
64
|
+
is still boxed in. Chromium can't sandbox itself as root, so as root it is off unless asked for. */
|
|
65
|
+
/* The browser it starts reaches nothing but this machine's own checker servers: every other name fails to
|
|
66
|
+
resolve, WebRTC can't open its own routes, and it inherits none of the worker's secrets. */
|
|
67
|
+
const LOCKED_ARGS = ['--autoplay-policy=no-user-gesture-required', '--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1',
|
|
68
|
+
'--force-webrtc-ip-handling-policy=disable_non_proxied_udp', '--webrtc-ip-handling-policy=disable_non_proxied_udp'];
|
|
69
|
+
const QUIET_ENV = () => ({ PATH: process.env.PATH || '/usr/bin:/bin', HOME: process.env.HOME || '/tmp', TMPDIR: process.env.TMPDIR || '/tmp', LANG: 'C.UTF-8' });
|
|
70
|
+
/* How long one play may take in all: a game that freezes the page is failed at this, never waited on forever. */
|
|
71
|
+
export const DEADLINE_MS = 180_000;
|
|
72
|
+
|
|
73
|
+
async function launch(pw, sandbox) {
|
|
74
|
+
try {
|
|
75
|
+
return await pw.chromium.launch({ chromiumSandbox: sandbox, args: LOCKED_ARGS, ...(process.platform === 'win32' ? {} : { env: QUIET_ENV() }) });
|
|
76
|
+
} catch (e) {
|
|
77
|
+
if (!sandbox) throw e;
|
|
78
|
+
throw new Error(`Chromium's sandbox could not start, so the game was not played: ${String(e.message).split('\n')[0]} Run the checker as a normal user, not root.`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function checkPlay(files, root, opts = {}) {
|
|
83
|
+
const readyMs = opts.readyMs ?? LIMITS.readyMs;
|
|
84
|
+
const pw = await loadPlaywright(opts);
|
|
85
|
+
if (!pw) return skipPlay('Playing the game needs a browser, which is not installed. In your game\'s folder run: npm i -D playwright@1.63.0 && npx playwright install chromium. Or install nothing: drop the zip at firstbyte.games/send and press "Just check it".');
|
|
86
|
+
|
|
87
|
+
const ownBrowser = !opts.browser;
|
|
88
|
+
const browser = opts.browser || await launch(pw, opts.sandbox ?? !isRoot());
|
|
89
|
+
/* Whatever fails, nothing is left running: the browser this started, the context, the file server. */
|
|
90
|
+
let server = null;
|
|
91
|
+
let context = null;
|
|
92
|
+
try {
|
|
93
|
+
server = await serve(files, root);
|
|
94
|
+
context = await browser.newContext({ viewport: { width: 960, height: 540 }, serviceWorkers: 'block' });
|
|
95
|
+
/* The game's achievement ids go to the harness's sdk/Host, so P9 can see an unlock that isn't listed. */
|
|
96
|
+
const raw = files.get(root + ACHIEVEMENTS);
|
|
97
|
+
const listed = raw ? readList(raw.toString('utf8')) : null;
|
|
98
|
+
await context.addInitScript((ids) => { window.__fbAchievements = ids; }, listed?.list?.map((a) => a.id) ?? []);
|
|
99
|
+
let timer;
|
|
100
|
+
const frozen = new Promise((r) => { timer = setTimeout(() => r(null), opts.deadlineMs ?? DEADLINE_MS); });
|
|
101
|
+
const results = await Promise.race([run(context, server, readyMs, opts.screenshotMs ?? 30_000, opts.soundMs ?? 15_000), frozen]);
|
|
102
|
+
clearTimeout(timer);
|
|
103
|
+
if (!results) return froze(opts.deadlineMs ?? DEADLINE_MS);
|
|
104
|
+
return [...results, achievementsKnown(results.h, { hasFile: !!raw, list: listed?.list ?? null })];
|
|
105
|
+
} finally {
|
|
106
|
+
/* A frozen page can stall closing too: never wait on it for long. */
|
|
107
|
+
const soon = (p) => Promise.race([p.catch(() => {}), new Promise((r) => setTimeout(r, 10_000))]);
|
|
108
|
+
await soon(context?.close() ?? Promise.resolve());
|
|
109
|
+
if (ownBrowser) await soon(browser.close());
|
|
110
|
+
await server?.close();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function run(context, { port, gamePort }, readyMs, shotMs, soundMs) {
|
|
115
|
+
const local = `127.0.0.1:${port}`;
|
|
116
|
+
const gameHost = `127.0.0.1:${gamePort}`;
|
|
117
|
+
const external = new Set();
|
|
118
|
+
const missing = new Set();
|
|
119
|
+
const errors = [];
|
|
120
|
+
const log = [];
|
|
121
|
+
|
|
122
|
+
await context.exposeBinding('__fbRecord', (_src, kind, msg) => { if (log.length < 2000) log.push({ kind: String(kind), msg: String(msg), at: Date.now() }); });
|
|
123
|
+
await context.addInitScript(PROBE);
|
|
124
|
+
await context.route('**/*', (route) => {
|
|
125
|
+
const url = new URL(route.request().url());
|
|
126
|
+
if (url.href === 'https://firstbyte.games/sdk.js') return route.fulfill({ body: SDK, contentType: 'text/javascript' });
|
|
127
|
+
if (url.host === local || url.host === gameHost) return route.continue();
|
|
128
|
+
external.add(url.host);
|
|
129
|
+
return route.abort();
|
|
130
|
+
});
|
|
131
|
+
/* A WebSocket isn't a request route() sees: catch it, name its host for P3, and never connect it. */
|
|
132
|
+
await context.routeWebSocket(/.*/, (ws) => { try { external.add(new URL(ws.url()).host); } catch {} ws.close(); });
|
|
133
|
+
|
|
134
|
+
const page = await context.newPage();
|
|
135
|
+
page.on('pageerror', (e) => errors.push(e.message));
|
|
136
|
+
page.on('console', (m) => {
|
|
137
|
+
if (m.type() === 'error' && !/Failed to load resource|net::ERR_/.test(m.text())) errors.push(m.text());
|
|
138
|
+
});
|
|
139
|
+
page.on('response', (r) => {
|
|
140
|
+
const url = new URL(r.url());
|
|
141
|
+
/* Any local miss counts, including a path that starts with "/" and so escapes the game's folder. */
|
|
142
|
+
if (url.host === gameHost && r.status() >= 400) missing.add(url.pathname.startsWith('/game/') ? url.pathname.slice(6) : `${url.pathname} (outside the game's folder: the path starts with "/")`);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
const start = Date.now();
|
|
146
|
+
let loadError = null;
|
|
147
|
+
await page.goto(`http://${local}/__fb/harness.html`, { waitUntil: 'load', timeout: readyMs + 10_000 }).catch((e) => { loadError = e.message.split('\n')[0]; });
|
|
148
|
+
|
|
149
|
+
const host = () => page.evaluate(() => ({ state: window.__fbHost.state, events: window.__fb.events, now: Date.now() - window.__fb.t0 })).then((h) => ({ ...h, log: log.slice() }), () => null);
|
|
150
|
+
const frame = page.locator('#game');
|
|
151
|
+
/* Without a graphics card one picture of a 3D game can take 10 s or more, so pictures get time. */
|
|
152
|
+
const shot = async () => { try { return decodePng(await frame.screenshot({ timeout: shotMs })); } catch { return null; } };
|
|
153
|
+
|
|
154
|
+
while (Date.now() - start < readyMs) {
|
|
155
|
+
const h = await host();
|
|
156
|
+
if (h && h.state.ready) break;
|
|
157
|
+
await sleep(150);
|
|
158
|
+
}
|
|
159
|
+
const first = await host();
|
|
160
|
+
const a = await shot();
|
|
161
|
+
await sleep(800);
|
|
162
|
+
const b = await shot();
|
|
163
|
+
|
|
164
|
+
const inputAt = (await host())?.now ?? 0;
|
|
165
|
+
await page.mouse.click(480, 270).catch(() => {});
|
|
166
|
+
for (const key of ['Space', 'Enter', 'ArrowRight', 'ArrowUp', 'KeyW', 'KeyD']) await page.keyboard.press(key).catch(() => {});
|
|
167
|
+
await sleep(1000);
|
|
168
|
+
const c = await shot();
|
|
169
|
+
for (let i = 0; i < 14; i++) {
|
|
170
|
+
await page.keyboard.press(['ArrowLeft', 'ArrowRight', 'Space', 'ArrowUp', 'ArrowDown'][i % 5]).catch(() => {});
|
|
171
|
+
if (i % 4 === 3) await page.mouse.click(300 + i * 20, 200 + i * 10).catch(() => {});
|
|
172
|
+
await sleep(250);
|
|
173
|
+
}
|
|
174
|
+
/* Many games load their sounds only once the first click allows audio; give them time to be heard. */
|
|
175
|
+
for (let waited = 0; waited < soundMs; waited += 600) {
|
|
176
|
+
const heard = log.some((l) => l.kind === 'sound');
|
|
177
|
+
if (heard) break;
|
|
178
|
+
await page.keyboard.press(['Space', 'ArrowRight', 'ArrowLeft'][(waited / 600) % 3]).catch(() => {});
|
|
179
|
+
if ((waited / 600) % 2) await page.mouse.click(480, 270).catch(() => {});
|
|
180
|
+
await sleep(600);
|
|
181
|
+
}
|
|
182
|
+
await page.evaluate(() => window.__fbHost.mute(true)).catch(() => {});
|
|
183
|
+
await sleep(300);
|
|
184
|
+
const end = await host();
|
|
185
|
+
|
|
186
|
+
const h = end || first || { state: {}, events: [], log: [] };
|
|
187
|
+
const errs = [...(loadError ? [`The page did not finish loading: ${loadError}`] : []), ...errors, ...h.log.filter((l) => l.kind === 'error').map((l) => l.msg)];
|
|
188
|
+
const results = [
|
|
189
|
+
loads(errs, missing),
|
|
190
|
+
onScreen(first, a, readyMs),
|
|
191
|
+
selfContained(external),
|
|
192
|
+
responds(h, inputAt, a, b, c),
|
|
193
|
+
sound(h.log),
|
|
194
|
+
adsAtBreaks(h),
|
|
195
|
+
noAdFirst(h, inputAt),
|
|
196
|
+
mute(h),
|
|
197
|
+
];
|
|
198
|
+
/* Not a result: what P9 reads, added by checkPlay, which knows the game's list. */
|
|
199
|
+
results.h = h;
|
|
200
|
+
return results;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function loads(errs, missing) {
|
|
204
|
+
const detail = [...new Set(errs)].slice(0, 6);
|
|
205
|
+
for (const m of missing) detail.push(`Missing file: ${m}`);
|
|
206
|
+
return detail.length ? { id: 'P1', status: 'fail', detail } : { id: 'P1', status: 'pass' };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function onScreen(h, img, readyMs) {
|
|
210
|
+
if (h?.state.ready) return { id: 'P2', status: 'pass', detail: [`FirstByte.ready() after ${secs(h.state.readyAt)}.`] };
|
|
211
|
+
if (h?.state.hello) return { id: 'P2', status: 'fail', detail: [`The SDK loaded, but FirstByte.ready() was not called within ${secs(readyMs)}.`] };
|
|
212
|
+
if (!img) return { id: 'P2', status: 'skip', detail: ['The checker could not take a picture of the game, so it could not tell. Call FirstByte.ready() and it can.'] };
|
|
213
|
+
if (hasPicture(img)) return { id: 'P2', status: 'pass', detail: [`A picture was on screen within ${secs(readyMs)}.`] };
|
|
214
|
+
return { id: 'P2', status: 'fail', detail: [`The screen was still blank after ${secs(readyMs)}.`] };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function selfContained(external) {
|
|
218
|
+
if (!external.size) return { id: 'P3', status: 'pass' };
|
|
219
|
+
return { id: 'P3', status: 'fail', detail: [`Tried to load from: ${[...external].join(', ')}.`] };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function responds(h, inputAt, a, b, c) {
|
|
223
|
+
const played = h.events.find((e) => e.type === 'playing' && e.data?.on && e.t >= inputAt);
|
|
224
|
+
const scrolled = h.log.some((l) => l.kind === 'scroll');
|
|
225
|
+
const SCROLL = 'The game page scrolled when Space or the arrow keys were pressed. Call event.preventDefault() for the keys your game uses, and give the page overflow: hidden.';
|
|
226
|
+
if (played && scrolled) return { id: 'P4', status: 'warn', detail: [`FirstByte.playing(true) ${secs(played.t - inputAt)} after the first input.`, SCROLL] };
|
|
227
|
+
if (played) return { id: 'P4', status: 'pass', detail: [`FirstByte.playing(true) ${secs(played.t - inputAt)} after the first input.`] };
|
|
228
|
+
if (scrolled) return { id: 'P4', status: 'fail', detail: [SCROLL] };
|
|
229
|
+
if (!a || !b || !c) return { id: 'P4', status: 'skip', detail: ['The checker could not take screenshots of the game.'] };
|
|
230
|
+
const idle = changed(a, b), after = changed(b, c);
|
|
231
|
+
if (after > 0.002 && after > idle * 1.5 + 0.001) return { id: 'P4', status: 'pass', detail: ['The screen changed after keys and a click.'] };
|
|
232
|
+
if (idle > 0.002) return { id: 'P4', status: 'warn', detail: ['The screen keeps moving on its own, so the checker could not tell whether input did anything. Call FirstByte.playing(true) when play starts and the checker can tell.'] };
|
|
233
|
+
/* Something changed, but too little to be sure it was the input (a small sprite that moved, or a
|
|
234
|
+
blinking cursor): that is not "nothing changed", so it is LOOK, never FAIL. */
|
|
235
|
+
if (after > 0) return { id: 'P4', status: 'warn', detail: ["Only a little of the screen changed after the keys and a click, so the checker could not tell whether the game answered them. If it did, there is nothing to fix. To make this a PASS, call FirstByte.playing(true) when the player's first key or click starts play."] };
|
|
236
|
+
return { id: 'P4', status: 'fail', detail: ['Nothing changed on screen after Space, Enter, the arrow keys, W, D and a click.'] };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function sound(log) {
|
|
240
|
+
const s = log.filter((l) => l.kind === 'sound');
|
|
241
|
+
if (s.length) return { id: 'P5', status: 'pass', detail: [`${s.length} sound${s.length === 1 ? '' : 's'} played.`] };
|
|
242
|
+
return { id: 'P5', status: 'fail', detail: ['No sound played during the test.'] };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function adsAtBreaks(h) {
|
|
246
|
+
if (!h.state.hello) return { id: 'P6', status: 'pass', detail: ['No SDK, so the game shows no ads here.'] };
|
|
247
|
+
const bad = h.events.filter((e) => e.type === 'break-refused' || (e.type === 'break' && e.refused === 'playing'));
|
|
248
|
+
const asked = h.events.filter((e) => e.type === 'break' || e.type === 'break-refused');
|
|
249
|
+
if (bad.length) return { id: 'P6', status: 'fail', detail: bad.map((e) => `breakTime() at ${secs(e.t)}, while playing.`) };
|
|
250
|
+
if (asked.length && !h.events.some((e) => e.type === 'playing')) {
|
|
251
|
+
return { id: 'P6', status: 'warn', detail: ['The game asks for ads but never calls FirstByte.playing(), so the site cannot tell a break from play. Call playing(true) when a round starts and playing(false) when it ends.'] };
|
|
252
|
+
}
|
|
253
|
+
if (asked.length) return { id: 'P6', status: 'pass', detail: [`${asked.length} ad${asked.length === 1 ? '' : 's'} asked for, each at a break.`] };
|
|
254
|
+
return { id: 'P6', status: 'pass', detail: ['No ad was asked for during the test.'] };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function noAdFirst(h, inputAt) {
|
|
258
|
+
const early = h.events.find((e) => (e.type === 'break' || e.type === 'break-refused') && (e.t < inputAt || (!e.everPlayed && h.events.some((x) => x.type === 'playing'))));
|
|
259
|
+
if (early) return { id: 'P7', status: 'fail', detail: [`An ad was asked for at ${secs(early.t)}, before the first play.`] };
|
|
260
|
+
return { id: 'P7', status: 'pass' };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function mute(h) {
|
|
264
|
+
if (!h.state.hello) return { id: 'P8', status: 'skip', detail: ['Needs the SDK: without it the site cannot ask the game to go quiet.'] };
|
|
265
|
+
if (h.state.listening?.mute) return { id: 'P8', status: 'pass' };
|
|
266
|
+
return { id: 'P8', status: 'fail', detail: ["The game does not listen for FirstByte.on('mute')."] };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/* A name for an id, for the line a developer can paste: 'night-owl' -> 'Night owl'. */
|
|
270
|
+
const nameOf = (id) => id.charAt(0).toUpperCase() + id.slice(1).replace(/-/g, ' ');
|
|
271
|
+
|
|
272
|
+
/*
|
|
273
|
+
* P9: every FirstByte.achieve() seen while playing, against the build's achievements.json. With a list
|
|
274
|
+
* and no unlock it is LOOK, never pass: the game was played too briefly to tell.
|
|
275
|
+
*/
|
|
276
|
+
function achievementsKnown(h, { hasFile, list }) {
|
|
277
|
+
const seen = h.events.filter((e) => e.type === 'achieve');
|
|
278
|
+
const ids = [...new Set(seen.map((e) => e.data?.id))];
|
|
279
|
+
const paste = (id) => `{ "id": "${id}", "name": "${nameOf(id)}", "about": "What the player did." }`;
|
|
280
|
+
if (!hasFile) {
|
|
281
|
+
if (!ids.length) return { id: 'P9', status: 'note', detail: ['No achievements.'] };
|
|
282
|
+
return { id: 'P9', status: 'fail', detail: [`The game unlocks ${ids.map((i) => `"${i}"`).join(', ')} but has no achievements.json. Add one next to index.html: { "achievements": [ ${ids.map(paste).join(', ')} ] }`] };
|
|
283
|
+
}
|
|
284
|
+
if (!list) return { id: 'P9', status: 'skip', detail: ['achievements.json has problems (see F7), so unlocks could not be checked.'] };
|
|
285
|
+
const unknown = [...new Set(seen.filter((e) => e.refused === 'unknown').map((e) => e.data?.id))];
|
|
286
|
+
if (unknown.length) return { id: 'P9', status: 'fail', detail: unknown.map((id) => `"${id}" isn't in achievements.json. Fix its spelling in your code, or add it: ${paste(id)}`) };
|
|
287
|
+
if (ids.length) return { id: 'P9', status: 'pass', detail: [`Unlocked while we played: ${ids.join(', ')}.`] };
|
|
288
|
+
return { id: 'P9', status: 'warn', detail: [`None of the ${list.length} achievements unlocked in the ${secs(h.now ?? 0)} we played. Check one can be earned early, so players see them working.`] };
|
|
289
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html>
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<title>First Byte check</title>
|
|
6
|
+
<style>html,body{margin:0;height:100%;background:#000}iframe{border:0;width:100%;height:100%;display:block}</style>
|
|
7
|
+
</head>
|
|
8
|
+
<body>
|
|
9
|
+
<iframe id="game" src="/game/index.html" allow="autoplay; fullscreen; gamepad"></iframe>
|
|
10
|
+
<script src="/__fb/host.js"></script>
|
|
11
|
+
<script>
|
|
12
|
+
window.__fb = { events: [], t0: Date.now() };
|
|
13
|
+
window.__fbHost = FirstByteHost.attach(document.getElementById('game'), {
|
|
14
|
+
key: 'check',
|
|
15
|
+
achievements: window.__fbAchievements || [],
|
|
16
|
+
onEvent: function (e) { window.__fb.events.push(e); },
|
|
17
|
+
showAd: function () { return new Promise(function (r) { setTimeout(function () { r(true); }, 50); }); }
|
|
18
|
+
});
|
|
19
|
+
</script>
|
|
20
|
+
</body>
|
|
21
|
+
</html>
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/* Just enough PNG to compare screenshots: 8-bit RGB or RGBA, not interlaced (what Chromium writes). */
|
|
2
|
+
import { inflateSync } from 'node:zlib';
|
|
3
|
+
|
|
4
|
+
export function decodePng(buf) {
|
|
5
|
+
let p = 8;
|
|
6
|
+
let width = 0, height = 0, channels = 0;
|
|
7
|
+
const idat = [];
|
|
8
|
+
while (p < buf.length) {
|
|
9
|
+
const len = buf.readUInt32BE(p);
|
|
10
|
+
const type = buf.toString('latin1', p + 4, p + 8);
|
|
11
|
+
const body = buf.subarray(p + 8, p + 8 + len);
|
|
12
|
+
if (type === 'IHDR') {
|
|
13
|
+
width = body.readUInt32BE(0);
|
|
14
|
+
height = body.readUInt32BE(4);
|
|
15
|
+
const depth = body[8], color = body[9], interlace = body[12];
|
|
16
|
+
if (depth !== 8 || interlace !== 0 || (color !== 2 && color !== 6)) throw new Error('Unsupported PNG');
|
|
17
|
+
channels = color === 6 ? 4 : 3;
|
|
18
|
+
} else if (type === 'IDAT') idat.push(body);
|
|
19
|
+
else if (type === 'IEND') break;
|
|
20
|
+
p += 12 + len;
|
|
21
|
+
}
|
|
22
|
+
const raw = inflateSync(Buffer.concat(idat));
|
|
23
|
+
const stride = width * channels;
|
|
24
|
+
const out = Buffer.alloc(height * stride);
|
|
25
|
+
for (let y = 0; y < height; y++) {
|
|
26
|
+
const f = raw[y * (stride + 1)];
|
|
27
|
+
const src = y * (stride + 1) + 1;
|
|
28
|
+
const dst = y * stride;
|
|
29
|
+
for (let x = 0; x < stride; x++) {
|
|
30
|
+
const a = x >= channels ? out[dst + x - channels] : 0;
|
|
31
|
+
const b = y > 0 ? out[dst + x - stride] : 0;
|
|
32
|
+
const c = y > 0 && x >= channels ? out[dst + x - stride - channels] : 0;
|
|
33
|
+
let v = raw[src + x];
|
|
34
|
+
if (f === 1) v += a;
|
|
35
|
+
else if (f === 2) v += b;
|
|
36
|
+
else if (f === 3) v += (a + b) >> 1;
|
|
37
|
+
else if (f === 4) {
|
|
38
|
+
const pa = Math.abs(b - c), pb = Math.abs(a - c), pc = Math.abs(a + b - 2 * c);
|
|
39
|
+
v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
|
|
40
|
+
}
|
|
41
|
+
out[dst + x] = v & 255;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return { width, height, channels, data: out };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/* True when the picture is more than one flat colour. */
|
|
48
|
+
export function hasPicture(img) {
|
|
49
|
+
const seen = new Set();
|
|
50
|
+
const { data, channels } = img;
|
|
51
|
+
for (let i = 0; i < data.length; i += channels * 37) {
|
|
52
|
+
seen.add(((data[i] >> 4) << 8) | ((data[i + 1] >> 4) << 4) | (data[i + 2] >> 4));
|
|
53
|
+
if (seen.size > 6) return true;
|
|
54
|
+
}
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/* The share of pixels (0..1) that changed noticeably between two screenshots. */
|
|
59
|
+
export function changed(a, b) {
|
|
60
|
+
if (a.width !== b.width || a.height !== b.height) return 1;
|
|
61
|
+
let n = 0, diff = 0;
|
|
62
|
+
const ch = a.channels, chb = b.channels;
|
|
63
|
+
for (let px = 0; px < a.width * a.height; px += 7) {
|
|
64
|
+
const i = px * ch, j = px * chb;
|
|
65
|
+
const d = Math.abs(a.data[i] - b.data[j]) + Math.abs(a.data[i + 1] - b.data[j + 1]) + Math.abs(a.data[i + 2] - b.data[j + 2]);
|
|
66
|
+
if (d > 30) diff++;
|
|
67
|
+
n++;
|
|
68
|
+
}
|
|
69
|
+
return diff / n;
|
|
70
|
+
}
|