ravensight-playtest 0.7.5 → 0.8.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 +57 -29
- package/docs/ADAPTERS.md +1 -1
- package/package.json +1 -1
- package/src/cli.js +25 -17
- package/src/commands/build.js +3 -1
- package/src/commands/hosted.js +100 -23
- package/src/commands/run.js +42 -10
- package/src/hosted/archivePreflight.js +112 -4
- package/src/hosted/buildStatus.js +2 -0
- package/src/hosted/buildUpload.js +22 -3
- package/src/hosted/recordedRun.js +272 -61
- package/src/hosted/status.js +26 -4
- package/src/run/comparison.js +7 -5
- package/src/run/controllers.js +14 -2
- package/src/run/drivers/web.js +45 -3
- package/src/run/personaLoop.js +89 -4
- package/src/run/resume.js +11 -1
- package/src/run/serveBuild.js +137 -0
package/src/run/drivers/web.js
CHANGED
|
@@ -1166,6 +1166,47 @@ export const CHECK_PLAYTEST_IDENTITY = Object.freeze({ token: 'check', runId: nu
|
|
|
1166
1166
|
* the one the platform implies
|
|
1167
1167
|
* @returns {Object} a driver
|
|
1168
1168
|
*/
|
|
1169
|
+
/**
|
|
1170
|
+
* The share of the viewport a visible canvas must cover for the persona to
|
|
1171
|
+
* need a picture of it. An engine's web page is often a canvas plus a little
|
|
1172
|
+
* text (love.js prints a title, a fullscreen button and a hint; Emscripten
|
|
1173
|
+
* and Unity pages a status line), and that text alone can pass the thin
|
|
1174
|
+
* observation bar, so the game itself, everything that happens in the canvas,
|
|
1175
|
+
* was never shown to the persona: a love.js run quit on "a blank canvas" that
|
|
1176
|
+
* was drawing the game the whole time.
|
|
1177
|
+
*/
|
|
1178
|
+
export const LARGE_CANVAS_SHARE = 0.15;
|
|
1179
|
+
|
|
1180
|
+
/**
|
|
1181
|
+
* Serialised by Playwright, so it must not close over anything. Whether a
|
|
1182
|
+
* visible canvas covers at least `share` of the viewport.
|
|
1183
|
+
* @param {number} share
|
|
1184
|
+
* @returns {boolean}
|
|
1185
|
+
*/
|
|
1186
|
+
/* c8 ignore start */
|
|
1187
|
+
export function pageHasLargeCanvas(share) {
|
|
1188
|
+
const area = window.innerWidth * window.innerHeight;
|
|
1189
|
+
if (!area) return false;
|
|
1190
|
+
for (const canvas of document.querySelectorAll('canvas')) {
|
|
1191
|
+
const box = canvas.getBoundingClientRect();
|
|
1192
|
+
const w = Math.max(0, Math.min(box.right, window.innerWidth) - Math.max(box.left, 0));
|
|
1193
|
+
const h = Math.max(0, Math.min(box.bottom, window.innerHeight) - Math.max(box.top, 0));
|
|
1194
|
+
const style = window.getComputedStyle(canvas);
|
|
1195
|
+
if (style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0 && (w * h) / area >= share) return true;
|
|
1196
|
+
}
|
|
1197
|
+
return false;
|
|
1198
|
+
}
|
|
1199
|
+
/* c8 ignore stop */
|
|
1200
|
+
|
|
1201
|
+
/**
|
|
1202
|
+
* Whether an observation needs a picture: a thin text observation, or a game
|
|
1203
|
+
* drawn in a large canvas. A page that cannot answer is treated as no canvas.
|
|
1204
|
+
*/
|
|
1205
|
+
export async function needsFrame(page, text) {
|
|
1206
|
+
if (String(text).trim().length < THIN_OBSERVATION_CHARS) return true;
|
|
1207
|
+
try { return (await page.evaluate(pageHasLargeCanvas, LARGE_CANVAS_SHARE)) === true; } catch { return false; }
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1169
1210
|
export function createWebDriver({ importer, headless = true, playtest = null, platform = process.platform, modifier = null, recording = {}, now = () => Date.now(), inspectVideo = probeVideo } = {}) {
|
|
1170
1211
|
const editModifier = modifier === 'Meta' || modifier === 'Control' ? modifier : platformModifier(platform);
|
|
1171
1212
|
let browser = null;
|
|
@@ -1454,7 +1495,7 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
|
|
|
1454
1495
|
async function currentHash(current) {
|
|
1455
1496
|
const snap = await snapshotText();
|
|
1456
1497
|
const after = { text: hashText(snap, shownText(snap)) };
|
|
1457
|
-
if (
|
|
1498
|
+
if (await needsFrame(current, snap.text)) {
|
|
1458
1499
|
const frame = await current.screenshot({ type: OBSERVATION_FRAME.type, quality: OBSERVATION_FRAME.quality, timeout: ACTION_TIMEOUT_MS });
|
|
1459
1500
|
after.screenshotBase64 = frame.toString('base64');
|
|
1460
1501
|
}
|
|
@@ -1864,8 +1905,9 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
|
|
|
1864
1905
|
}
|
|
1865
1906
|
// Canvas builds (a Godot or Unity web export is one <canvas> and
|
|
1866
1907
|
// nothing else) have no accessibility tree worth reading, so vision
|
|
1867
|
-
// is the only way to play them. Spend an image only then
|
|
1868
|
-
|
|
1908
|
+
// is the only way to play them. Spend an image only then: on a thin
|
|
1909
|
+
// page, or on any page whose game is a large canvas.
|
|
1910
|
+
if (await needsFrame(current, text)) {
|
|
1869
1911
|
try {
|
|
1870
1912
|
const buffer = await current.screenshot({ type: OBSERVATION_FRAME.type, quality: OBSERVATION_FRAME.quality, timeout: ACTION_TIMEOUT_MS });
|
|
1871
1913
|
observation.screenshotBase64 = buffer.toString('base64');
|
package/src/run/personaLoop.js
CHANGED
|
@@ -350,6 +350,18 @@ export async function runPersona(args) {
|
|
|
350
350
|
// worth keeping, by the same rule as a 402 during play.
|
|
351
351
|
const play = { actionsTaken: outcome.actionsTaken, quitReason: 'cost_cap', quitDetail: String(error.message || '') };
|
|
352
352
|
await writeSomeReport({ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt, endedAt: new Date().toISOString(), log, preservedMarkdown: error.completedReportMarkdown });
|
|
353
|
+
} else if (error && error.reportIncomplete && !args.signal?.aborted) {
|
|
354
|
+
// The run played; only the report step could not finish. Its notes are
|
|
355
|
+
// the report, by the same rule as a 402 in the report step. Under budget
|
|
356
|
+
// pressure that is a budget stop; otherwise the run is marked failed, so
|
|
357
|
+
// the unit is refunded, and the report still carries what it saw.
|
|
358
|
+
outcome.state = error.budgetPressure ? 'budget_exceeded' : 'failed';
|
|
359
|
+
outcome.quitReason = error.budgetPressure ? 'cost_cap' : 'error';
|
|
360
|
+
const actionsTaken = Math.max(outcome.actionsTaken || 0, actionLogFrom(actionRecords).length);
|
|
361
|
+
const play = { actionsTaken, quitReason: outcome.quitReason, quitDetail: safeErrorDetail(error, localBrief) };
|
|
362
|
+
await writeSomeReport({ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt,
|
|
363
|
+
endedAt: new Date().toISOString(), log, quitReason: outcome.quitReason, reason: REPORT_INCOMPLETE_REASON, bareReason: REPORT_INCOMPLETE_REASON,
|
|
364
|
+
preservedMarkdown: error.completedReportMarkdown });
|
|
353
365
|
} else if (error instanceof ProxyError && error.isClosed) {
|
|
354
366
|
outcome.state = 'canceled';
|
|
355
367
|
outcome.quitReason = 'error';
|
|
@@ -906,6 +918,11 @@ async function reportPhase({
|
|
|
906
918
|
let maxTokens = REPORT_MAX_TOKENS;
|
|
907
919
|
let shrunk = false;
|
|
908
920
|
let lastCandidate = null;
|
|
921
|
+
// The largest output ceiling a turn has already been cut off at. A retry
|
|
922
|
+
// below it is built to fail (pt_run_ed0941d6a976a93efa46: cut off at 4096,
|
|
923
|
+
// then asked again at 2326 and cut off again), so no retry goes below it.
|
|
924
|
+
let cutOffAt = 0;
|
|
925
|
+
let cutOffs = 0;
|
|
909
926
|
for (let attempt = 1; ; attempt += 1) {
|
|
910
927
|
let answer;
|
|
911
928
|
const askedAt = Date.now();
|
|
@@ -924,8 +941,14 @@ async function reportPhase({
|
|
|
924
941
|
} catch (error) {
|
|
925
942
|
if (!(error instanceof ProxyError && error.isBudget)) throw error;
|
|
926
943
|
const bodyChars = JSON.stringify({ messages, system, tools: REPORT_TOOLS, max_tokens: maxTokens, stream: true }).length;
|
|
927
|
-
const
|
|
928
|
-
|
|
944
|
+
const fits = shrunk ? null : reportTokensThatFit(error, maxTokens, bodyChars);
|
|
945
|
+
// After a cut-off, only a ceiling at least as large as the one that was
|
|
946
|
+
// cut off is worth paying for. Anything less goes to the step-log report.
|
|
947
|
+
const smaller = fits && fits >= cutOffAt ? fits : null;
|
|
948
|
+
if (fits && !smaller && !lastCandidate) {
|
|
949
|
+
log(`the report was cut off at ${cutOffAt} output tokens and the remaining model budget only fits ${fits}, which would be cut off too, so the report is written from the notes instead.`);
|
|
950
|
+
transcript.write({ kind: 'report_cut_off_no_room', cut_off_at: cutOffAt, fits });
|
|
951
|
+
} else if (!smaller && !shrunk && !lastCandidate) {
|
|
929
952
|
log(hasBudgetFigures(error)
|
|
930
953
|
? `even the smallest report (${REPORT_MIN_TOKENS} output tokens) does not fit the remaining model budget once the request itself is paid for, so the report is written from the notes instead.`
|
|
931
954
|
: 'the report turn was refused for budget with no budget figures in the refusal, so there is nothing to size a retry from; the report is written from the notes instead.');
|
|
@@ -935,6 +958,9 @@ async function reportPhase({
|
|
|
935
958
|
transcript.write({ kind: 'report_budget_retry', attempt, max_tokens: smaller, figures: error.figures || {} });
|
|
936
959
|
log(`the report turn did not fit the remaining model budget; asking again with an output ceiling of ${smaller} tokens.`);
|
|
937
960
|
maxTokens = smaller;
|
|
961
|
+
// A smaller ceiling needs a shorter report: say so, or the model
|
|
962
|
+
// writes the same length and is cut off.
|
|
963
|
+
askShorter(messages, smaller);
|
|
938
964
|
continue;
|
|
939
965
|
}
|
|
940
966
|
// A report already written on an earlier turn is the report, with its
|
|
@@ -1049,6 +1075,26 @@ async function reportPhase({
|
|
|
1049
1075
|
...missingSections.map(section => `report.md has no "${section}" section`)
|
|
1050
1076
|
];
|
|
1051
1077
|
|
|
1078
|
+
const cutOff = answer.stopReason === 'max_tokens';
|
|
1079
|
+
if (cutOff) {
|
|
1080
|
+
cutOffs += 1;
|
|
1081
|
+
cutOffAt = Math.max(cutOffAt, maxTokens);
|
|
1082
|
+
transcript.write({ kind: 'report_cut_off', attempt, max_tokens: maxTokens, cut_offs: cutOffs });
|
|
1083
|
+
// With its repair spent, a report.json already written beats another
|
|
1084
|
+
// metered turn; the server has the final word on it, as after a repair.
|
|
1085
|
+
if (lastCandidate && (repaired || cutOffs >= 2)) {
|
|
1086
|
+
report = lastCandidate;
|
|
1087
|
+
log(`the report turn was cut off at ${maxTokens} output tokens; keeping the report.json already written (${lint.length} problem(s)).`);
|
|
1088
|
+
break;
|
|
1089
|
+
}
|
|
1090
|
+
if (cutOffs >= 2) {
|
|
1091
|
+
log(`the report turn was cut off at its output limit twice (${maxTokens} tokens), so the report is written from the notes instead.`);
|
|
1092
|
+
throw reportIncomplete({ markdown, secrets, budgetPressure: shrunk || play.budgetWarned || play.budgetExceeded || play.reserveStopped,
|
|
1093
|
+
message: `The report step was cut off at its ${maxTokens} token output limit twice.` });
|
|
1094
|
+
}
|
|
1095
|
+
log(`the report turn was cut off at ${maxTokens} output tokens; asking once more for a shorter report with the same ceiling.`);
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1052
1098
|
// Every tool_use the next request echoes back needs its tool_result, or
|
|
1053
1099
|
// the API refuses the request. A write cut off at the token limit is
|
|
1054
1100
|
// malformed: it was not saved, and it is answered so.
|
|
@@ -1060,11 +1106,16 @@ async function reportPhase({
|
|
|
1060
1106
|
continued = true;
|
|
1061
1107
|
messages.push({ role: 'assistant', content: assistantContent(answer) });
|
|
1062
1108
|
messages.push({ role: 'user', content: toolResults.concat([{ type: 'text', text: CONTINUE_WITH_JSON }]) });
|
|
1109
|
+
if (cutOff) askShorter(messages, maxTokens);
|
|
1063
1110
|
continue;
|
|
1064
1111
|
}
|
|
1065
1112
|
|
|
1066
|
-
|
|
1067
|
-
|
|
1113
|
+
// A first cut-off on the repair turn still gets its one shorter retry.
|
|
1114
|
+
if (repaired && !(cutOff && cutOffs === 1)) {
|
|
1115
|
+
// No report.json after the repair: the run still played, so the notes
|
|
1116
|
+
// become the report rather than an empty one.
|
|
1117
|
+
if (!candidate) throw reportIncomplete({ markdown, secrets, budgetPressure: shrunk || play.budgetWarned || play.budgetExceeded || play.reserveStopped,
|
|
1118
|
+
message: `the report step did not produce a valid report.json: ${lint.join('; ')}` });
|
|
1068
1119
|
// Still imperfect after the repair: keep it, record the lint, and let
|
|
1069
1120
|
// the server have the final word. It validates the same schema and
|
|
1070
1121
|
// drops unevidenced findings itself, so this is a report with known
|
|
@@ -1082,6 +1133,7 @@ async function reportPhase({
|
|
|
1082
1133
|
role: 'user',
|
|
1083
1134
|
content: toolResults.concat([{ type: 'text', text: repairInstruction(validation.details, evidenceProblems, missingSections) }])
|
|
1084
1135
|
});
|
|
1136
|
+
if (cutOff) askShorter(messages, maxTokens);
|
|
1085
1137
|
}
|
|
1086
1138
|
|
|
1087
1139
|
// One bounded look at the evidence: each blocker or major (at most
|
|
@@ -1318,6 +1370,39 @@ export function buildReportRequest({ skill, persona, brief, localBrief = {}, int
|
|
|
1318
1370
|
return { system, messages: [{ role: 'user', content: [{ type: 'text', text: scrubSecrets(text, secrets) }] }] };
|
|
1319
1371
|
}
|
|
1320
1372
|
|
|
1373
|
+
/** What a report turn is told when its ceiling is tight or it was cut off. */
|
|
1374
|
+
export function shorterReportInstruction(maxTokens) {
|
|
1375
|
+
return `Your report has to fit in ${maxTokens} output tokens, and the last one did not. Write it much shorter: at most 5 findings, each description and repro step one or two short sentences, `
|
|
1376
|
+
+ 'and a report.md of about 250 words that keeps its four sections. Write the files in one turn and do not restate the notes.';
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
/** Add the shorter-report instruction to the last user message, which is the next request's question. */
|
|
1380
|
+
function askShorter(messages, maxTokens) {
|
|
1381
|
+
const last = messages[messages.length - 1];
|
|
1382
|
+
if (!last || last.role !== 'user') return;
|
|
1383
|
+
const text = shorterReportInstruction(maxTokens);
|
|
1384
|
+
const content = typeof last.content === 'string' ? [{ type: 'text', text: last.content }] : [...(last.content || [])];
|
|
1385
|
+
if (content.some(block => block && block.type === 'text' && block.text === text)) return;
|
|
1386
|
+
messages[messages.length - 1] = { ...last, content: [...content, { type: 'text', text }] };
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
/**
|
|
1390
|
+
* The report step could not finish: the caller writes the report from the
|
|
1391
|
+
* step log (notes, screenshots and actions), because a run that played never
|
|
1392
|
+
* comes back empty. A report.md completed on the way is kept as a draft.
|
|
1393
|
+
*/
|
|
1394
|
+
function reportIncomplete({ markdown, secrets, budgetPressure, message }) {
|
|
1395
|
+
const error = Object.assign(new Error(message), { reportIncomplete: true, budgetPressure: Boolean(budgetPressure) });
|
|
1396
|
+
if (typeof markdown === 'string' && markdown.trim()) {
|
|
1397
|
+
const safeMarkdown = scrubSecrets(markdown, secrets);
|
|
1398
|
+
if (Buffer.byteLength(safeMarkdown, 'utf8') <= 256 * 1024 && scanForSecrets(safeMarkdown).length === 0) error.completedReportMarkdown = safeMarkdown;
|
|
1399
|
+
}
|
|
1400
|
+
return error;
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
/** The reason a step-log report gives when the report step could not finish. */
|
|
1404
|
+
export const REPORT_INCOMPLETE_REASON = 'The report step could not finish within its output limit and the run\'s model budget. What the persona saw is below, and report.json carries the notes as unreviewed findings.';
|
|
1405
|
+
|
|
1321
1406
|
/** The smallest output ceiling worth retrying a report turn with. */
|
|
1322
1407
|
export const REPORT_MIN_TOKENS = 1536;
|
|
1323
1408
|
|
package/src/run/resume.js
CHANGED
|
@@ -9,6 +9,7 @@ import { reconcileDroppedFindings } from './dropped.js';
|
|
|
9
9
|
import { createReportValidator, writeReportFiles } from './report.js';
|
|
10
10
|
import * as stateFile from './state.js';
|
|
11
11
|
import { playJob, resolvePersonas } from '../commands/run.js';
|
|
12
|
+
import { serveBuildDir } from './serveBuild.js';
|
|
12
13
|
|
|
13
14
|
/** Server states that only a live process can be in, and this one is resuming it. */
|
|
14
15
|
const ABANDONED_MID_RUN = Object.freeze(['launching', 'playing']);
|
|
@@ -115,7 +116,16 @@ export async function resumeJob({ api, gameId, jobId, job, runs, state, repoRoot
|
|
|
115
116
|
}
|
|
116
117
|
|
|
117
118
|
const driverName = journal.driver || options.driver || 'playwright_web';
|
|
118
|
-
|
|
119
|
+
// A build served by `run --build-dir` lived on a port that died with that
|
|
120
|
+
// process: serve the same folder again (or the one passed now) and play there.
|
|
121
|
+
let servedTarget = null;
|
|
122
|
+
if (driverName === 'playwright_web' && (options.buildDir || journal.buildDir)) {
|
|
123
|
+
try { servedTarget = (await (injected.serveBuildDir || serveBuildDir)(options.buildDir || journal.buildDir)).url; } catch (error) {
|
|
124
|
+
log(`${error.message} Pass --build-dir with the build folder, or --build-url.`);
|
|
125
|
+
return EXIT.ENVIRONMENT;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const target = servedTarget || journal.target || options.buildUrl || options.godotProject;
|
|
119
129
|
if (!target) {
|
|
120
130
|
log('The journal does not say what this job was pointed at. Pass --build-url or --godot-project.');
|
|
121
131
|
return EXIT.ENVIRONMENT;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { CliError } from '../errors.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The local web server behind `run --build-dir`: an exported web build served
|
|
8
|
+
* from 127.0.0.1 on a free port, with the headers engines' web exports need
|
|
9
|
+
* and a static file server usually does not send.
|
|
10
|
+
*
|
|
11
|
+
* - `application/wasm` for `.wasm`, so the browser compiles while it downloads.
|
|
12
|
+
* - Content-Encoding for an engine's pre-compressed files (`x.wasm.br`,
|
|
13
|
+
* `x.framework.js.gz`), with the type of the file inside. Unity's Brotli and
|
|
14
|
+
* gzip builds refuse to start without it.
|
|
15
|
+
* - Cross-origin isolation on every response (COOP `same-origin`, COEP
|
|
16
|
+
* `credentialless`), so a threaded export (Godot with threads, love.js,
|
|
17
|
+
* Emscripten `-pthread`) gets SharedArrayBuffer. `credentialless` rather than
|
|
18
|
+
* `require-corp`: a local game may still load a font or image from another
|
|
19
|
+
* host, and that should keep working, without cookies.
|
|
20
|
+
* - `no-store`, so a rebuilt export is never played from a stale cache.
|
|
21
|
+
*
|
|
22
|
+
* It reads only files under the build folder (no symlink out of it), answers
|
|
23
|
+
* GET and HEAD only, and listens on the loopback address only.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export const CONTENT_TYPES = Object.freeze({
|
|
27
|
+
'.html': 'text/html; charset=utf-8', '.htm': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
|
|
28
|
+
'.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json',
|
|
29
|
+
'.map': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
30
|
+
'.gif': 'image/gif', '.svg': 'image/svg+xml', '.webp': 'image/webp', '.ico': 'image/x-icon', '.mp3': 'audio/mpeg',
|
|
31
|
+
'.ogg': 'audio/ogg', '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.mp4': 'video/mp4', '.webm': 'video/webm',
|
|
32
|
+
'.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.otf': 'font/otf', '.txt': 'text/plain; charset=utf-8',
|
|
33
|
+
'.xml': 'application/xml', '.pck': 'application/octet-stream', '.data': 'application/octet-stream',
|
|
34
|
+
'.mem': 'application/octet-stream', '.unityweb': 'application/octet-stream'
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const ENCODINGS = Object.freeze({ '.br': 'br', '.gz': 'gzip' });
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The type and encoding a file is served with. `.unityweb` is Unity's own
|
|
41
|
+
* fallback format, decoded by its loader, so it is sent as it is.
|
|
42
|
+
* @param {string} file
|
|
43
|
+
* @returns {Record<string, string>}
|
|
44
|
+
*/
|
|
45
|
+
export function contentHeaders(file) {
|
|
46
|
+
const ext = path.extname(file).toLowerCase();
|
|
47
|
+
const encoding = ENCODINGS[ext];
|
|
48
|
+
if (encoding) {
|
|
49
|
+
const inner = path.extname(file.slice(0, -ext.length)).toLowerCase();
|
|
50
|
+
if (inner && CONTENT_TYPES[inner]) return { 'content-type': CONTENT_TYPES[inner], 'content-encoding': encoding };
|
|
51
|
+
}
|
|
52
|
+
return { 'content-type': CONTENT_TYPES[ext] || 'application/octet-stream' };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Headers on every response. */
|
|
56
|
+
export const ISOLATION_HEADERS = Object.freeze({
|
|
57
|
+
'cache-control': 'no-store',
|
|
58
|
+
'cross-origin-opener-policy': 'same-origin',
|
|
59
|
+
'cross-origin-embedder-policy': 'credentialless',
|
|
60
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
61
|
+
'x-content-type-options': 'nosniff'
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The page to open in a build folder: `index.html` when there is one,
|
|
66
|
+
* otherwise the only `.html` file at the top (a Godot export keeps its
|
|
67
|
+
* project name, `jump-bunny.html`). Null when there is no single page.
|
|
68
|
+
* @param {string[]} names the folder's top-level file names
|
|
69
|
+
* @returns {string|null}
|
|
70
|
+
*/
|
|
71
|
+
export function pickEntry(names) {
|
|
72
|
+
if (names.includes('index.html')) return 'index.html';
|
|
73
|
+
const pages = names.filter(name => /\.html?$/i.test(name));
|
|
74
|
+
return pages.length === 1 ? pages[0] : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Start serving a build folder.
|
|
79
|
+
* @param {string} dir
|
|
80
|
+
* @param {{entry?: string|null, host?: string}} [options]
|
|
81
|
+
* @returns {Promise<{url: string, origin: string, entry: string, root: string, close: () => Promise<void>}>}
|
|
82
|
+
*/
|
|
83
|
+
export async function serveBuildDir(dir, { entry = null, host = '127.0.0.1' } = {}) {
|
|
84
|
+
let root;
|
|
85
|
+
try {
|
|
86
|
+
root = await realpath(path.resolve(dir));
|
|
87
|
+
if (!(await stat(root)).isDirectory()) throw new Error('not a directory');
|
|
88
|
+
} catch {
|
|
89
|
+
throw new CliError(`--build-dir ${dir} is not a folder. Point it at the folder your engine exported for the web (the one with the .html page).`);
|
|
90
|
+
}
|
|
91
|
+
const names = (await readdir(root, { withFileTypes: true })).filter(item => item.isFile()).map(item => item.name);
|
|
92
|
+
const page = entry || pickEntry(names);
|
|
93
|
+
if (!page) {
|
|
94
|
+
throw new CliError(`--build-dir ${dir} has no index.html and no single .html page. Export the game for the web, or name its page in the folder${names.some(name => /\.html?$/i.test(name)) ? ' (there is more than one .html file: open the right one with --build-url)' : ''}.`);
|
|
95
|
+
}
|
|
96
|
+
const server = createServer((req, res) => {
|
|
97
|
+
respond(root, req, res).catch(() => { if (!res.headersSent) res.writeHead(500, ISOLATION_HEADERS); res.end(); });
|
|
98
|
+
});
|
|
99
|
+
await new Promise((resolve, reject) => {
|
|
100
|
+
server.once('error', reject);
|
|
101
|
+
server.listen(0, host, resolve);
|
|
102
|
+
});
|
|
103
|
+
// The server lives as long as the run that started it, and never keeps the
|
|
104
|
+
// process alive on its own once the run is over.
|
|
105
|
+
server.unref();
|
|
106
|
+
const origin = `http://${host}:${server.address().port}`;
|
|
107
|
+
const url = `${origin}/${page.split('/').map(encodeURIComponent).join('/')}`;
|
|
108
|
+
return { url, origin, entry: page, root, close: () => new Promise(resolve => server.close(() => resolve())) };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function respond(root, req, res) {
|
|
112
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
113
|
+
res.writeHead(405, { ...ISOLATION_HEADERS, allow: 'GET, HEAD' });
|
|
114
|
+
return res.end();
|
|
115
|
+
}
|
|
116
|
+
let rel;
|
|
117
|
+
try { rel = decodeURIComponent(new URL(req.url, 'http://local').pathname); } catch {
|
|
118
|
+
res.writeHead(400, ISOLATION_HEADERS);
|
|
119
|
+
return res.end();
|
|
120
|
+
}
|
|
121
|
+
if (rel.includes('\0')) { res.writeHead(400, ISOLATION_HEADERS); return res.end(); }
|
|
122
|
+
if (rel.endsWith('/')) rel += 'index.html';
|
|
123
|
+
const file = path.resolve(root, '.' + rel);
|
|
124
|
+
if (file !== root && !file.startsWith(root + path.sep)) { res.writeHead(404, ISOLATION_HEADERS); return res.end(); }
|
|
125
|
+
let real;
|
|
126
|
+
try {
|
|
127
|
+
const info = await lstat(file);
|
|
128
|
+
real = await realpath(file);
|
|
129
|
+
if (!real.startsWith(root + path.sep) || !(await stat(real)).isFile() || (!info.isFile() && !info.isSymbolicLink())) throw new Error('outside');
|
|
130
|
+
} catch {
|
|
131
|
+
res.writeHead(404, ISOLATION_HEADERS);
|
|
132
|
+
return res.end();
|
|
133
|
+
}
|
|
134
|
+
const body = await readFile(real);
|
|
135
|
+
res.writeHead(200, { ...contentHeaders(real), ...ISOLATION_HEADERS, 'content-length': body.length });
|
|
136
|
+
res.end(req.method === 'HEAD' ? undefined : body);
|
|
137
|
+
}
|