ravensight-playtest 0.8.1 → 0.8.3

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 CHANGED
@@ -29,6 +29,8 @@ question, and nothing is charged.
29
29
  | `--video`, `--transcript` | Save video or transcripts of both sessions in their reports. Priced in the quote. |
30
30
  | `--wait` | Stay until the run finishes, printing each phase change and the queue place while it waits, then each mode's outcome. Works with a saved quote file too. |
31
31
  | `--game <id>` | Override the linked game. |
32
+ | `--even-if-unknown` | Buy a run even though an earlier admission for this game has no known outcome yet. Without it, `hosted run` refuses before quoting while such a record exists, because that earlier run may have been charged: ask with `hosted status` first. |
33
+ | `-y, --yes` | Answer the price confirmation with yes. Needed without a terminal and with `--json`. |
32
34
 
33
35
  `hosted run` prints the hosted run id and job id as soon as the run is admitted.
34
36
  A run waiting for a hosted machine shows its place, such as "Queued, position 2,
@@ -59,13 +61,22 @@ options, expiry and refund rules. It charges nothing. `hosted run` confirms
59
61
  that saved quote before one admission request. Its durable journal blocks an
60
62
  automatic second POST after an uncertain outcome; preserve it for reconciliation.
61
63
  Both forms of `hosted run` keep that journal under `.ravensight/hosted-runs/`.
62
- When the server refuses the run with its own reason (busy capacity, funding,
63
- an expired quote), no run was started, nothing was charged and the journal is
64
- cleared, so the same command can be run again; it sends the same idempotency
65
- key, so the server can never admit it twice. Only an answer that never arrived
66
- leaves the outcome unknown. Then `hosted status`, with no run id, asks the
67
- server what happened once the quote has expired (so asking cannot start the
68
- run), records the run if it was admitted, and clears the journal if it was not.
64
+ When the server refuses the run with a reason of its own that proves nothing
65
+ was admitted (busy capacity, funding, the daily allowance, an expired quote),
66
+ no run was started, nothing was charged and the journal is cleared. Whether the
67
+ same saved quote can be run again depends on when the server refused it. A
68
+ refusal before the server records the attempt leaves the key free, so the same
69
+ command can run again under the same idempotency key and the server can still
70
+ never admit it twice. A refusal from inside the admission is kept by the server
71
+ under that key, so the same saved quote is refused from then on, and the
72
+ message asks for a new quote; `hosted run` without a quote file always quotes
73
+ afresh. A 404, 403 or 409 can also come back for an attempt the server
74
+ already holds, possibly admitted and charged, so it leaves the outcome unknown, like an answer that never arrived. Then
75
+ `hosted status`, with no run id, asks the server what happened once the quote
76
+ has expired (so asking cannot start the run), records the run if it was
77
+ admitted, and clears the journal only when the server says for certain that it
78
+ was not. While any outcome for the game is unknown, `hosted run` refuses to buy
79
+ another run unless `--even-if-unknown` is passed.
69
80
  A charged-blocked acknowledgement does not prove gameplay or a report. This
70
81
  command does not top up funds, change local run/report files or ask for model
71
82
  proxy permission on the CLI credential.
@@ -504,7 +515,8 @@ splitting the job in two is what gets everything played.
504
515
  | `--upload-transcript` | Upload `transcript.jsonl` as well as the reports. |
505
516
  | `--dry-upload` | List every file and byte that would be sent, and send nothing. |
506
517
  | `--key-modifier <meta\|control>` | The modifier the browser driver uses for editing shortcuts such as select all. Defaults to this machine's own (Command on macOS, Control elsewhere); set it when the browser's platform is not this machine's. `RAVENSIGHT_KEY_MODIFIER` does the same. |
507
- | `--build-dir <dir>` | Serve an exported web build folder from this machine and play it: `index.html`, or the folder's one `.html` page (a Godot export named after the project). The local server sends `application/wasm`, Content-Encoding for Unity's Brotli and gzip files (`.br`, `.gz`), and cross-origin isolation, so threaded Godot, love.js and Emscripten builds get SharedArrayBuffer. `resume` serves the same folder again. Not with `--build-url`. |
518
+ | `--build-dir <dir>` | Serve an exported web build folder from this machine and play it: `index.html`, or the folder's one `.html` page (a Godot export named after the project). The local server sends `application/wasm`, Content-Encoding for Unity's Brotli and gzip files (`.br`, `.gz`), and cross-origin isolation, so threaded Godot, love.js and Emscripten builds get SharedArrayBuffer. `resume` serves the same folder again. Not with `--build-url`. The server answers only `127.0.0.1` or `localhost` on its own port and never serves dotfiles. |
519
+ | `--build-entry <file>` | The page to open inside `--build-dir` when the folder has more than one `.html` file, relative to it, such as `play.html`. |
508
520
  | `--headed`, `--headless` | Show or hide the browser. |
509
521
  | `--verbose` | Print each turn. |
510
522
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ravensight-playtest",
3
- "version": "0.8.1",
3
+ "version": "0.8.3",
4
4
  "description": "Local AI playtests and seeded game simulations with reports in Ravensight.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://ravensight.io/docs/#playtest",
package/src/cli.js CHANGED
@@ -61,6 +61,7 @@ Run options (parsed by the runner, see src/run/args.js):
61
61
  --build-url <url> the web build to play
62
62
  --build-dir <dir> a web export folder to serve from this machine and play: index.html or its one
63
63
  .html page, with wasm, Brotli and gzip engine files and threaded builds served right
64
+ --build-entry <file> the page to open inside --build-dir, when it has more than one .html file
64
65
  --godot-project <dir> the Godot project directory
65
66
  --driver-config <file> local WebDriver or JSON-RPC bridge configuration
66
67
  --max-actions <n> lower the actions one persona may take; it can only lower the persona's own patience, never raise it
@@ -181,6 +182,7 @@ export function buildProgram() {
181
182
  .option('--game <id>', 'game id, overriding this repo’s configuration')
182
183
  .option('--video', 'save video of both game sessions in their reports')
183
184
  .option('--wait', 'stay until the report is ready, printing each phase change (with or without a saved quote)')
185
+ .option('--even-if-unknown', 'buy a run even though an earlier admission for this game has no known outcome yet (it may have been charged; check it first with "hosted status")')
184
186
  // Hidden: the server now queues a funded run instead of refusing it for
185
187
  // capacity. Kept so an older server's busy answer can still be waited out.
186
188
  .addOption(new Option('--wait-for-capacity [minutes]', 'when hosted capacity is busy, ask again about once a minute and start when there is room, for up to this many minutes (default 60)').hideHelp())
@@ -189,10 +191,11 @@ export function buildProgram() {
189
191
  if (filename) {
190
192
  const extra = ['build', 'persona', 'game', 'video'].filter(name => options[name] !== undefined);
191
193
  if (extra.length) throw new CliError(`A saved quote already fixes its build, persona and options. Drop --${extra.join(', --')}, or run "hosted run" without a quote file.`);
192
- return hostedRun(filename, flagsFrom(command.optsWithGlobals(), { wait: options.wait, waitForCapacity: options.waitForCapacity }));
194
+ return hostedRun(filename, flagsFrom(command.optsWithGlobals(), { wait: options.wait, waitForCapacity: options.waitForCapacity,
195
+ evenIfUnknown: options.evenIfUnknown }));
193
196
  }
194
197
  return hostedRunDirect(flagsFrom(command.optsWithGlobals(), { build: options.build, persona: options.persona, game: options.game,
195
- video: options.video, wait: options.wait, waitForCapacity: options.waitForCapacity }));
198
+ video: options.video, wait: options.wait, waitForCapacity: options.waitForCapacity, evenIfUnknown: options.evenIfUnknown }));
196
199
  }));
197
200
  common(hosted.command('status [run-id]'))
198
201
  .description('show the phase of one hosted run (queued, provisioning, running, capturing, analyzing, report ready, failed or canceled), each mode and the report link; with no run id, ask the server about any admission whose outcome is not known yet')
@@ -5,7 +5,7 @@ import { CliError, ExitCode } from '../errors.js';
5
5
  import { ui } from '../ui/index.js';
6
6
  import { quoteHostedRun, runHostedQuote, hostedQuoteLines, prepareHostedRun, admitHostedOffer, confirmQuestion,
7
7
  hostedConsentLines, fundingShortfall, readHostedRun, cancelHostedRun, GERI_PROVIDERS, admitWithCapacityWait,
8
- resolveHostedIntents } from '../hosted/recordedRun.js';
8
+ resolveHostedIntents, assertNoUnknownAdmission } from '../hosted/recordedRun.js';
9
9
  import { hostedPlaytestStatus, modeOutcomes, modeLine, TERMINAL_PHASES, queueInfo, queueLine } from '../hosted/status.js';
10
10
  import { jobLink } from '../dashboard.js';
11
11
  import { DEFAULT_PERSONAS } from '../runDefaults.js';
@@ -35,10 +35,10 @@ export async function hostedRun(filename, flags = {}, deps = {}) {
35
35
  if (flags.json && !flags.yes && !deps.confirm) throw new CliError('Inspect the saved quote, then use --yes with --json. No admission was requested.');
36
36
  const maxWaitMs = capacityWaitMs(flags.waitForCapacity);
37
37
  const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
38
- const now = deps.now || Date.now, sleep = deps.sleep || (() => sleepFor(POLL_MS));
38
+ const now = deps.now || Date.now, sleep = poller(deps);
39
39
  return withAuthHandling(context, async () => {
40
40
  const api = context.api, apiUrl = api.apiUrl;
41
- const result = await runHostedQuote({ filename, api, apiUrl, repoRoot: context.repoRoot, now,
41
+ const result = await runHostedQuote({ filename, api, apiUrl, repoRoot: context.repoRoot, now, evenIfUnknown: Boolean(flags.evenIfUnknown),
42
42
  confirm: deps.confirm || (question => ui.confirm(question, { yes: Boolean(flags.yes) })),
43
43
  onPrepared: offer => { if (!flags.json) hostedQuoteLines(offer).forEach(line => ui.info(line)); },
44
44
  admit: admitter(flags, deps, maxWaitMs) });
@@ -54,7 +54,7 @@ export async function hostedRun(filename, flags = {}, deps = {}) {
54
54
  }
55
55
  if (!flags.wait) {
56
56
  if (flags.json) ui.json(admitted);
57
- else ui.info('The server acknowledged charged_blocked. This does not prove a worker started or produced gameplay or reports.');
57
+ else ui.info(`The server acknowledged the paid admission (${admitted.state}). This does not prove a worker started or produced gameplay or reports.`);
58
58
  return ExitCode.OK;
59
59
  }
60
60
  const view = await waitForRun({ api, gameId, admissionId: admitted.admissionId, apiUrl, sleep, now, onPhase: phaseLine(flags) });
@@ -94,7 +94,10 @@ function admitter(flags, deps, maxWaitMs) {
94
94
 
95
95
  const POLL_MS = 15000;
96
96
  const dollars = cents => `$${(cents / 100).toFixed(2)}`;
97
- const sleepFor = ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); if (timer.unref) timer.unref(); });
97
+ // Not unref'd: while --wait polls, this timer is the only thing keeping the
98
+ // process alive, and an unref'd one let it exit 0 after the first poll.
99
+ const sleepFor = ms => new Promise(resolve => setTimeout(resolve, ms));
100
+ const poller = deps => deps.sleep || (() => sleepFor(Number.isSafeInteger(deps.pollMs) && deps.pollMs > 0 ? deps.pollMs : POLL_MS));
98
101
 
99
102
  /** One status object for --json and for the printed lines. */
100
103
  function statusView(gameId, apiUrl, { admission, job, runs }, now = Date.now()) {
@@ -161,9 +164,10 @@ export async function hostedRunDirect(flags = {}, deps = {}) {
161
164
  if (flags.json && !flags.yes && !deps.confirm) throw new CliError('A hosted run charges prepaid funds. Use --yes with --json. Nothing was charged.');
162
165
  const maxWaitMs = capacityWaitMs(flags.waitForCapacity);
163
166
  const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
164
- const now = deps.now || Date.now, sleep = deps.sleep || (() => sleepFor(POLL_MS));
167
+ const now = deps.now || Date.now, sleep = poller(deps);
165
168
  return withAuthHandling(context, async () => {
166
169
  const api = context.api, apiUrl = api.apiUrl, gameId = resolveGameId(flags, context.config);
170
+ await assertNoUnknownAdmission({ repoRoot: context.repoRoot, apiUrl, gameId, evenIfUnknown: Boolean(flags.evenIfUnknown) });
167
171
  const { offer, build, funding } = await prepareHostedRun({ api, apiUrl, gameId, buildId: flags.build,
168
172
  persona: flags.persona || DEFAULT_PERSONAS[0], includeVideo: Boolean(flags.video), now });
169
173
  if (!flags.json) {
@@ -206,7 +210,7 @@ export async function hostedRunDirect(flags = {}, deps = {}) {
206
210
 
207
211
  export async function hostedStatus(admissionId, flags = {}, deps = {}) {
208
212
  const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
209
- const now = deps.now || Date.now, sleep = deps.sleep || (() => sleepFor(POLL_MS));
213
+ const now = deps.now || Date.now, sleep = poller(deps);
210
214
  if (!admissionId) {
211
215
  if (flags.wait) throw new CliError('Name the hosted run to wait for: hosted status <run-id> --wait.');
212
216
  return withAuthHandling(context, () => resolvePending(context, flags, now));
@@ -226,13 +230,41 @@ async function resolvePending(context, flags, now) {
226
230
  const results = await resolveHostedIntents({ api: context.api, apiUrl: context.api.apiUrl, repoRoot: context.repoRoot, now });
227
231
  if (flags.json) { ui.json({ intents: results.map(({ message, ...row }) => row) }); }
228
232
  else if (!results.length) ui.info('No hosted admission is waiting for an answer. Name a run to see it: ravensight-playtest hosted status <run-id>');
229
- else for (const row of results) {
230
- ui.info(row.message);
231
- if (row.state === 'admitted') ui.info(`Check on it with: ravensight-playtest hosted status ${row.admissionId}`);
232
- }
233
+ else pendingLines(results).forEach(line => ui.info(line));
233
234
  return results.some(row => ['unknown', 'unreadable', 'wait', 'other_api'].includes(row.state)) ? ExitCode.ENVIRONMENT : ExitCode.OK;
234
235
  }
235
236
 
237
+ const LISTED_QUOTES = 3;
238
+
239
+ /**
240
+ * The lines "hosted status" prints for resolved intents, in the resolver's
241
+ * order (admitted first, newest first). Several earlier attempts the server
242
+ * refused for one game collapse into one count line, because each charged
243
+ * nothing and a list of them beside a charged run reads as alarming.
244
+ */
245
+ export function pendingLines(results) {
246
+ const lines = [], refused = new Map();
247
+ for (const row of results) {
248
+ if (row.state === 'not_admitted') {
249
+ const key = row.gameId;
250
+ if (!refused.has(key)) refused.set(key, []);
251
+ refused.get(key).push(row);
252
+ continue;
253
+ }
254
+ lines.push(row.message);
255
+ if (row.state === 'admitted') lines.push(`Check on it with: ravensight-playtest hosted status ${row.admissionId}`);
256
+ }
257
+ for (const [gameId, rows] of refused) {
258
+ if (rows.length === 1) { lines.push(rows[0].message); continue; }
259
+ const times = rows.map(row => row.createdAt).filter(Boolean).sort();
260
+ const quotes = rows.map(row => row.quoteId).filter(Boolean);
261
+ const named = quotes.slice(0, LISTED_QUOTES).join(', ') + (quotes.length > LISTED_QUOTES ? `, and ${quotes.length - LISTED_QUOTES} more` : '');
262
+ const span = times.length ? `, saved from ${times[0]} to ${times.at(-1)},` : '';
263
+ lines.push(`Game ${gameId}: ${rows.length} earlier attempts${span} were refused by the server before admission${named ? ` (quotes ${named})` : ''}. Those attempts started no run and charged nothing; they say nothing about any other run. Their records are cleared.`);
264
+ }
265
+ return lines;
266
+ }
267
+
236
268
  export async function hostedCancel(admissionId, flags = {}, deps = {}) {
237
269
  if (flags.json && !flags.yes && !deps.confirm) throw new CliError('Use --yes with --json to cancel a hosted run. Nothing was canceled.');
238
270
  const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
@@ -313,7 +313,7 @@ async function run(flags, injected, deps, log) {
313
313
  modules,
314
314
  driver: driverName,
315
315
  target,
316
- ...(served ? { buildDir: served.root } : {}),
316
+ ...(served ? { buildDir: served.root, ...(options.buildEntry !== undefined ? { buildEntry: served.entry } : {}) } : {}),
317
317
  priceCents: registered.price && registered.price.price_cents,
318
318
  options: {
319
319
  maxActions: options.maxActions ?? null,
@@ -487,7 +487,13 @@ export function unusedFlagWarnings(options) {
487
487
  * @returns {Promise<{url: string, root: string, entry: string}|null|false>}
488
488
  */
489
489
  export async function serveBuildDirOption({ options, driverName, log, serve = serveBuildDir }) {
490
- if (options.buildDir === undefined) return null;
490
+ if (options.buildDir === undefined) {
491
+ if (options.buildEntry !== undefined) {
492
+ log('--build-entry names the page inside --build-dir. Pass --build-dir too. Nothing was registered or charged.');
493
+ return false;
494
+ }
495
+ return null;
496
+ }
491
497
  if (driverName !== 'playwright_web') {
492
498
  log(`--build-dir serves a web build, and this run uses ${driverName}. Nothing was registered or charged.`);
493
499
  return false;
@@ -497,7 +503,7 @@ export async function serveBuildDirOption({ options, driverName, log, serve = se
497
503
  return false;
498
504
  }
499
505
  try {
500
- const served = await serve(options.buildDir);
506
+ const served = await serve(options.buildDir, options.buildEntry === undefined ? {} : { entry: options.buildEntry });
501
507
  options.buildUrl = served.url;
502
508
  log(`Serving ${served.root} at ${served.url} (wasm, compressed engine files and cross-origin isolation for threaded builds).`);
503
509
  return served;
@@ -312,10 +312,18 @@ const MAX_LISTED = 10;
312
312
  * person can choose: nothing is guessed.
313
313
  * @returns {Promise<{entrypoint: string, reason: 'root'|'only-top-level'|'wrapped-folder'|'only-one'}>}
314
314
  */
315
+ // What macOS Finder adds to a ZIP it makes: the __MACOSX/ resource-fork tree,
316
+ // AppleDouble ._ files beside each file, and .DS_Store. None is ever the entry,
317
+ // and counting them would hide the one folder that holds the build.
318
+ const finderMetadata = name => {
319
+ const parts = name.split('/'), last = parts.at(-1);
320
+ return parts[0] === '__MACOSX' || last.startsWith('._') || last === '.DS_Store';
321
+ };
322
+
315
323
  export async function chooseEntrypoint(archive, { limits: supplied, format } = {}) {
316
324
  const kind = ENTRY_KINDS[format];
317
325
  if (!kind) throw new CliError('Choose the entry file inside the ZIP with --entrypoint. No upload reservation was requested.');
318
- const names = await archiveFileNames(archive, buildLimits(supplied));
326
+ const names = (await archiveFileNames(archive, buildLimits(supplied))).filter(name => !finderMetadata(name));
319
327
  const tops = new Set(names.map(name => name.split('/')[0]));
320
328
  const wrapped = names.length > 0 && names.every(name => name.includes('/')) && tops.size === 1;
321
329
  const base = wrapped ? `${[...tops][0]}/` : '';
@@ -182,13 +182,14 @@ async function clearIntent(journal) {
182
182
 
183
183
  // A saved durable intent whose outcome is unknown is never retried here; only
184
184
  // "hosted status" asks the server about it. The server receives a stable key.
185
- export async function runHostedQuote({ filename, api, apiUrl, repoRoot, confirm, onPrepared = () => {}, now = Date.now, admit = admitHostedOffer }) {
185
+ export async function runHostedQuote({ filename, api, apiUrl, repoRoot, confirm, onPrepared = () => {}, now = Date.now, admit = admitHostedOffer, evenIfUnknown = false }) {
186
186
  const offer = validateHostedOffer(await readHostedQuote(filename), apiUrl, now());
187
187
  const journal = offerJournal(repoRoot, offer), prior = await readJournal(journal);
188
188
  if (prior?.phase === 'charged_blocked' && admissionPattern.test(prior.admission?.admissionId || '')) {
189
189
  fail(`This quote already started hosted run ${prior.admission.admissionId}. Check it with: ravensight-playtest hosted status ${prior.admission.admissionId}`);
190
190
  }
191
191
  if (prior) fail(`This quote's earlier admission has no known outcome yet (${journal}). Ask the server what happened with: ravensight-playtest hosted status. No request was repeated.`);
192
+ await assertNoUnknownAdmission({ repoRoot, apiUrl, gameId: offer.gameId, evenIfUnknown });
192
193
  const { profile, funding } = await available(api, offer.gameId, offer.request.profileVersion, offer.request.standardProvider);
193
194
  if (profile.driver !== offer.request.driver || funding?.eligible === false || offer.quote.funding?.eligible === false) fail('The server no longer advertises this profile or sufficient prepaid funding. Nothing was charged.');
194
195
  await onPrepared(offer);
@@ -199,23 +200,43 @@ export async function runHostedQuote({ filename, api, apiUrl, repoRoot, confirm,
199
200
 
200
201
  export const confirmQuestion = offer => `Pay ${money(offer.quote.dueNowCents)} now (${money(offer.quote.totalPriceCents)} total) for the quoted Geri then Freki runs and the evidence options shown?`;
201
202
 
202
- // Refusals the server makes with its own code, before any charge: the request
203
- // failed inside the admission's transaction, which rolled back, or before it.
204
- // These are certain, so the local intent is cleared and the same quote can be
205
- // tried again. A 5xx or a status the server did not explain is not certain.
206
- const CERTAIN_REFUSALS = new Set(['hosted_funding_required', 'quote_not_accepted', 'not_found',
207
- 'recorded_setup_required', 'hosted_global_capacity', 'too_many_active_hosted_runs', 'hosted_daily_capacity',
208
- 'hosted_build_too_large', 'hosted_build_safety_hold', 'quote_expired', 'recorded_quote_changed',
209
- 'hosted_game_unavailable', 'hosted_studio_unavailable']);
210
- // Refused by the server with its own code, but a 5xx: reported plainly, intent kept for "hosted status".
211
- const EXPLAINED_UNAVAILABLE = new Set(['recorded_unavailable', 'hosted_execution_budget_unconfigured']);
203
+ // Refusals the server makes with its own code that prove nothing was admitted
204
+ // under this key. Each one is thrown only before the server records an
205
+ // admission intent for the key, or from inside the admission transaction it
206
+ // then aborted (game_tracker hostedPlaytest/customer.js create,
207
+ // recordedCustomer.js create, recordedAdmission.js admit). A key the server
208
+ // already holds an intent for is answered by reconcile instead, and reconcile
209
+ // can throw none of these. So the answer is certain on the first POST and on a
210
+ // replay alike: the local intent is cleared. A 5xx or a status the server did
211
+ // not explain is not certain.
212
+ const CERTAIN_REFUSALS = new Set(['hosted_funding_required', 'recorded_setup_required', 'hosted_global_capacity',
213
+ 'too_many_active_hosted_runs', 'hosted_daily_capacity', 'hosted_build_too_large', 'hosted_build_safety_hold',
214
+ 'quote_expired', 'hosted_game_unavailable', 'hosted_studio_unavailable',
215
+ // The two explained 5xx: thrown before the intent exists, or inside a transaction that aborted.
216
+ 'recorded_unavailable', 'hosted_execution_budget_unconfigured']);
212
217
  export const CAPACITY_CODES = Object.freeze(['hosted_global_capacity', 'too_many_active_hosted_runs']);
213
218
  // The server keeps an attempt it refused under the plan's key and answers a
214
- // repeat with this, so that quote cannot start a run. Nothing was charged.
219
+ // repeat with { state: 'failed', dispatchAllowed: false }, so that quote cannot
220
+ // start a run. Nothing was charged.
215
221
  export const REFUSED_EARLIER = 'hosted_quote_refused_earlier';
216
222
 
217
223
  export const certainRefusal = error => error instanceof ApiError
218
- && (error.status === 401 || error.status >= 400 && error.status < 500 && CERTAIN_REFUSALS.has(error.code));
224
+ && (error.status === 401 || error.status >= 400 && error.status < 600 && CERTAIN_REFUSALS.has(error.code));
225
+
226
+ /**
227
+ * Why an explained 4xx says nothing certain. These answers (a 404 from the game
228
+ * route or from the admission's own access check, a 403 for the role, a 409
229
+ * from the stored consent or plan check) also come back for a key the server
230
+ * already holds, possibly admitted and charged: a game deleted or retired,
231
+ * membership removed, or another account signed in. Null when not a 4xx.
232
+ */
233
+ export function unclearRefusalReason(error) {
234
+ if (!(error instanceof ApiError) || error.status < 400 || error.status >= 500) return null;
235
+ if (error.status === 404 || error.code === 'not_found') return 'the server would not answer for this game or account (the game may have been deleted or retired, your membership removed, or another account is signed in)';
236
+ if (error.status === 403) return 'the signed-in account is not allowed to run hosted playtests for this game';
237
+ if (['quote_not_accepted', 'recorded_quote_changed', 'recorded_admission_conflict'].includes(error.code)) return 'the server\'s record for this quote does not match this request';
238
+ return `the server answered ${error.status}${error.code ? ` (${error.code})` : ''}`;
239
+ }
219
240
 
220
241
  export function hostedRefusalMessage(error) {
221
242
  const code = error?.code;
@@ -224,12 +245,10 @@ export function hostedRefusalMessage(error) {
224
245
  const topUp = Number.isSafeInteger(f?.requiredTopUpCents) && f.requiredTopUpCents > 0 ? ` Add at least ${money(f.requiredTopUpCents)} of prepaid funds, then request a new quote.` : ' Add prepaid funds, then request a new quote.';
225
246
  return `The server refused the run for funding. No run was started and nothing was charged.${topUp}`;
226
247
  }
227
- if (code === 'quote_not_accepted') return 'The server did not accept this consent for the quote. Nothing was charged; request a new quote.';
228
248
  if (CAPACITY_CODES.includes(code)) return 'Hosted capacity is busy, so no run was started and nothing was charged. Run the same command again with --wait-for-capacity to wait for room and start then; it never charges twice. Adding funds does not increase capacity.';
229
249
  if (code === 'hosted_daily_capacity') return 'Today\'s hosted run allowance is used up. No run was started and nothing was charged. Try again after the daily limit resets at 00:00 UTC.';
230
250
  if (code === 'recorded_setup_required') return `${error.message || 'Complete the playtest brief and choose an available persona.'} Nothing was charged.`;
231
- if (code === 'not_found') return 'The quote is no longer available. Nothing was charged; request a new quote.';
232
- if (code === 'quote_expired' || code === 'recorded_quote_changed') return 'The quote expired before the run was admitted. No run was started and nothing was charged; request a new quote.';
251
+ if (code === 'quote_expired') return 'The quote expired before the run was admitted. No run was started and nothing was charged; request a new quote.';
233
252
  if (code === 'hosted_build_too_large') return 'This build is too large to play on a hosted machine: hosted playtests play builds up to 300 MiB unpacked. Make the build smaller and upload it again. Nothing was charged.';
234
253
  if (code === 'hosted_build_safety_hold') return 'This build was stopped for safety during a hosted playtest and cannot run again until an admin reviews and clears it in the dashboard. Nothing was charged.';
235
254
  if (code === REFUSED_EARLIER) return 'The server already refused an earlier attempt with this quote, so it will not start a run from it. No run was started and nothing was charged; request a new quote, or use "hosted run" without a quote file.';
@@ -239,24 +258,51 @@ export function hostedRefusalMessage(error) {
239
258
  const refusalError = (code, error = { code }) => Object.assign(new CliError(hostedRefusalMessage(error), ExitCode.ENVIRONMENT),
240
259
  { refusal: { code, certain: true, retryAfter: Number.isFinite(error.retryAfter) ? error.retryAfter : null } });
241
260
 
261
+ // The states a replayed key can report for an admission it made. The first
262
+ // answer is charged_blocked; a replay after the direct queue moved the run on
263
+ // reports where it is now (game_tracker recordedAdmission REPLAY_STATE). Every
264
+ // one of them means the run was admitted and charged once.
265
+ export const ADMITTED_STATES = Object.freeze(['charged_blocked', 'dispatched', 'running', 'review', 'closed', 'settled', 'canceled']);
266
+ const ACK_KEYS = ['admissionId', 'dispatchAllowed', 'jobId', 'state', 'totalPriceCents'];
267
+ const wholeOrNull = value => value === null || value === undefined || Number.isSafeInteger(value) && value >= 0;
268
+ const timeOrNull = value => value === null || value === undefined || typeof value === 'string' && value.length <= 64 && Number.isFinite(Date.parse(value));
269
+ // The queue place (directQueue.forAdmission). It is information only, never
270
+ // money, but each field it names must still have its own type.
271
+ export function validQueue(q) {
272
+ return Boolean(q) && typeof q === 'object' && !Array.isArray(q) && Number.isSafeInteger(q.position) && q.position >= 0
273
+ && ['ahead', 'running', 'ceiling', 'expectedStartMinutes', 'latestStartMinutes'].every(key => wholeOrNull(q[key]))
274
+ && ['estimatedStartAt', 'expectedStartAt', 'latestStartAt'].every(key => timeOrNull(q[key]))
275
+ && (q.startsNow === undefined || typeof q.startsNow === 'boolean')
276
+ && (q.message === undefined || typeof q.message === 'string' && q.message.length <= 500);
277
+ }
278
+
242
279
  // What a 202 from POST /runs says: the acknowledgement of a new or replayed
243
280
  // admission, the server's record that this key's attempt was refused, or an
244
- // outcome the server itself cannot yet state.
281
+ // outcome the server itself cannot yet state. The keys are checked exactly,
282
+ // because this answer is the record of money taken: a queued admission adds
283
+ // `queued: true` with its `queue` place, and nothing else is accepted.
245
284
  function readAdmissionAnswer(answer, totalPriceCents) {
246
285
  if (answer.status !== 202 || answer.headers.get('content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json'
247
286
  || typeof answer.body !== 'string' || Buffer.byteLength(answer.body) > MAX_QUOTE_BYTES) return { kind: 'unknown' };
248
287
  let ack;
249
288
  try { ack = JSON.parse(answer.body); } catch { return { kind: 'unknown' }; }
250
- if (ack && same(ack, { state: 'failed', dispatchAllowed: false })) return { kind: 'refused_earlier' };
251
- // A queued admission also carries its queue place; it is read through queueInfo, never trusted as money.
252
- const keys = ack && typeof ack === 'object' ? Object.keys(ack).filter(key => key !== 'queue').sort() : [];
253
- if (Object.hasOwn(ack || {}, 'queue') && !queueInfo(ack)) return { kind: 'unknown' };
254
- if (!ack || !same(keys, ['admissionId', 'dispatchAllowed', 'jobId', 'state', 'totalPriceCents'])
255
- || ack.state !== 'charged_blocked' || ack.dispatchAllowed !== false || ack.totalPriceCents !== totalPriceCents
256
- || !admissionPattern.test(ack.admissionId || '') || !/^pt_job_[a-f0-9]{20}$/.test(ack.jobId || '')) return { kind: 'unknown' };
257
- return { kind: 'admitted', ack };
289
+ if (!ack || typeof ack !== 'object' || Array.isArray(ack)) return { kind: 'unknown' };
290
+ if (same(ack, { state: 'failed', dispatchAllowed: false })) return { kind: 'refused_earlier' };
291
+ // Whatever else is wrong, an admission id the server named is kept so the person can find the run.
292
+ const named = { admissionId: admissionPattern.test(ack.admissionId || '') ? ack.admissionId : null,
293
+ jobId: /^pt_job_[a-f0-9]{20}$/.test(ack.jobId || '') ? ack.jobId : null };
294
+ const unknown = { kind: 'unknown', ...named };
295
+ const keys = Object.keys(ack).filter(key => key !== 'queue' && key !== 'queued').sort();
296
+ if (Object.hasOwn(ack, 'queue') && !validQueue(ack.queue)) return unknown;
297
+ if (Object.hasOwn(ack, 'queued') && (ack.queued !== true || !Object.hasOwn(ack, 'queue'))) return unknown;
298
+ if (!same(keys, ACK_KEYS) || !ADMITTED_STATES.includes(ack.state) || ack.dispatchAllowed !== false
299
+ || ack.totalPriceCents !== totalPriceCents || !named.admissionId || !named.jobId) return unknown;
300
+ const { queued, ...rest } = ack;
301
+ return { kind: 'admitted', ack: rest };
258
302
  }
259
303
 
304
+ const namedRun = read => read.admissionId ? ` The server named hosted run ${read.admissionId}${read.jobId ? ` (job ${read.jobId})` : ''}; check it with: ravensight-playtest hosted status ${read.admissionId}` : '';
305
+
260
306
  async function postAdmission(api, { gameId, consent, idempotencyKey }, captureFile) {
261
307
  let responseCaptured = false;
262
308
  const answer = await api.request('POST', `${base(gameId)}/runs`, { body: consent,
@@ -296,26 +342,34 @@ export async function admitHostedOffer({ offer, api, apiUrl, repoRoot, now = Dat
296
342
  if (error.status === 401) throw error;
297
343
  throw refusalError(error.code, error);
298
344
  }
299
- if (error instanceof ApiError && EXPLAINED_UNAVAILABLE.has(error.code)) {
300
- throw new CliError(`${hostedRefusalMessage(error)} To confirm and free this quote, run: ravensight-playtest hosted status`, ExitCode.ENVIRONMENT);
301
- }
302
- fail(`The admission's outcome is not known: ${unknownAdvice(journal)}`);
345
+ // Any other explained answer may follow an ambiguous commit the server
346
+ // then reconciled, so it is kept for "hosted status" like a lost reply.
347
+ const reason = unclearRefusalReason(error);
348
+ fail(`The admission's outcome is not known${reason ? `, because ${reason}` : ''}: ${unknownAdvice(journal)}`);
303
349
  }
304
350
  const read = answer ? readAdmissionAnswer(answer, offer.quote.totalPriceCents) : { kind: 'unknown' };
305
351
  if (read.kind === 'refused_earlier') { await clearIntent(journal); throw refusalError(REFUSED_EARLIER); }
306
- if (read.kind !== 'admitted') fail(`The admission acknowledgement needs reconciliation: ${unknownAdvice(journal)}`);
352
+ if (read.kind !== 'admitted') fail(`The admission acknowledgement needs reconciliation: ${unknownAdvice(journal)}.${namedRun(read)}`);
307
353
  await recordAdmitted(journal, state, read.ack);
308
354
  return { state: 'charged_blocked', ...read.ack, queue: queueInfo(read.ack), journal, replayAuthorized: false, gameplayProven: false };
309
355
  }
310
356
 
311
357
  const unknownAdvice = journal => `the run may or may not have started. Preserve ${journal}; nothing was retried. Ask the server what happened with: ravensight-playtest hosted status`;
312
358
 
359
+ const createdTime = state => (Number.isFinite(Date.parse(state?.createdAt)) ? new Date(Date.parse(state.createdAt)).toISOString() : null);
360
+ const attemptName = state => `quote ${state.quoteId || 'unnamed'}${createdTime(state) ? `, attempt saved ${createdTime(state)}` : ''}`;
361
+ const newestFirst = (a, b) => (Date.parse(b.createdAt) || 0) - (Date.parse(a.createdAt) || 0);
362
+
313
363
  /**
314
364
  * Settle every saved admission intent whose outcome is unknown by asking the
315
365
  * server, which answers from its own record under the same idempotency key.
316
366
  * The question is only sent once the quote has expired, so it can report an
317
- * admission but never start one. A certain answer that nothing was admitted
318
- * clears the intent; an admission is recorded; anything else is kept.
367
+ * admission but never start one. Only a certain answer that nothing was
368
+ * admitted clears the intent: { state: 'failed', dispatchAllowed: false }, or
369
+ * a refusal code the server throws only when it holds no intent for the key.
370
+ * A 404, 403 or 409 can come back for a key that was admitted, so it is kept.
371
+ * An admission is recorded; anything else is kept. Admitted rows come first,
372
+ * then the rest, each newest first.
319
373
  */
320
374
  export async function resolveHostedIntents({ api, apiUrl, repoRoot, now = Date.now }) {
321
375
  const dir = journalDir(repoRoot), here = origin(apiUrl), results = [];
@@ -331,47 +385,83 @@ export async function resolveHostedIntents({ api, apiUrl, repoRoot, now = Date.n
331
385
  results.push({ journal, state: 'unreadable', message: `${journal} is not a hosted admission record this version can read. Nothing was sent.` });
332
386
  continue;
333
387
  }
388
+ const row = { journal, gameId: state.gameId, quoteId: state.quoteId || null, createdAt: createdTime(state) };
389
+ const game = `Game ${state.gameId}, ${attemptName(state)}`;
334
390
  if (state.apiUrl !== here) {
335
- results.push({ journal, gameId: state.gameId, state: 'other_api', message: `${journal} belongs to ${state.apiUrl}. Run this with --api-url ${state.apiUrl} to resolve it.` });
391
+ results.push({ ...row, state: 'other_api', message: `${journal} belongs to ${state.apiUrl}. Run this with --api-url ${state.apiUrl} to resolve it.` });
336
392
  continue;
337
393
  }
338
394
  const created = Date.parse(state.createdAt);
339
395
  const expiresAt = Number.isSafeInteger(state.quoteExpiresAt) ? state.quoteExpiresAt : (Number.isFinite(created) ? created + QUOTE_LIFETIME_MS : null);
340
396
  const askAt = expiresAt === null ? null : expiresAt + SERVER_CLOCK_MARGIN_MS;
341
397
  if (askAt === null || now() < askAt) {
342
- results.push({ journal, gameId: state.gameId, state: 'wait', askAt,
398
+ results.push({ ...row, state: 'wait', askAt,
343
399
  message: askAt === null ? `${journal} has no readable time. Nothing was sent.`
344
- : `Game ${state.gameId}: asking before ${new Date(askAt).toISOString()} could still start the run, so nothing was sent. Run "hosted status" again after that time.` });
400
+ : `${game}: asking before ${new Date(askAt).toISOString()} could still start the run, so nothing was sent. Run "hosted status" again after that time.` });
345
401
  continue;
346
402
  }
347
403
  let answer;
348
404
  try { answer = await postAdmission(api, state, `${journal}.reconcile-${now()}-${randomUUID().slice(0, 8)}.json`); }
349
405
  catch (error) {
350
- if (certainRefusal(error) && error.status !== 401) {
406
+ if (error instanceof ApiError && error.status === 401) throw error;
407
+ if (certainRefusal(error)) {
351
408
  await clearIntent(journal);
352
- results.push({ journal, gameId: state.gameId, state: 'not_admitted', code: error.code,
353
- message: `Game ${state.gameId}: the server has no run for this quote. No run was started and nothing was charged. The record is cleared.` });
409
+ results.push({ ...row, state: 'not_admitted', code: error.code,
410
+ message: `${game}: the server refused that earlier attempt before admitting it (${error.code}). That attempt started no run and charged nothing; it says nothing about any other run. The record is cleared.` });
354
411
  continue;
355
412
  }
356
- if (error instanceof ApiError && error.status === 401) throw error;
357
- results.push({ journal, gameId: state.gameId, state: 'unknown', message: `Game ${state.gameId}: the server did not answer clearly (${error.code || error.message}). The record is kept; try again later.` });
413
+ const reason = unclearRefusalReason(error);
414
+ results.push({ ...row, state: 'unknown', ...(error instanceof ApiError ? { code: error.code || null, status: error.status } : {}),
415
+ message: reason
416
+ ? `${game}: the outcome is still unknown, because ${reason}. It may have been admitted and charged. The record is kept and nothing was retried. Check the account you are signed in with and the game, then run "hosted status" again; if it persists, write to support@realityse.com with ${path.basename(journal)}.`
417
+ : `${game}: the server did not answer clearly (${error.code || error.message}). The record is kept; try again later.` });
358
418
  continue;
359
419
  }
360
420
  const read = answer ? readAdmissionAnswer(answer, state.consent.totalPriceCents) : { kind: 'unknown' };
361
421
  if (read.kind === 'refused_earlier') {
362
422
  await clearIntent(journal);
363
- results.push({ journal, gameId: state.gameId, state: 'not_admitted', code: REFUSED_EARLIER,
364
- message: `Game ${state.gameId}: the server refused that attempt. No run was started and nothing was charged. The record is cleared.` });
423
+ results.push({ ...row, state: 'not_admitted', code: REFUSED_EARLIER,
424
+ message: `${game}: the server refused that earlier attempt. That attempt started no run and charged nothing; it says nothing about any other run. The record is cleared.` });
365
425
  } else if (read.kind === 'admitted') {
366
426
  await recordAdmitted(journal, state, read.ack);
367
- results.push({ journal, gameId: state.gameId, state: 'admitted', admissionId: read.ack.admissionId, jobId: read.ack.jobId,
368
- totalPriceCents: read.ack.totalPriceCents, message: `Game ${state.gameId}: the run was admitted as ${read.ack.admissionId} and charged ${money(read.ack.totalPriceCents)}.` });
427
+ results.push({ ...row, state: 'admitted', admissionId: read.ack.admissionId, jobId: read.ack.jobId,
428
+ totalPriceCents: read.ack.totalPriceCents, runState: read.ack.state,
429
+ message: `${game}: the run was admitted as ${read.ack.admissionId} (job ${read.ack.jobId}) and charged ${money(read.ack.totalPriceCents)}.` });
369
430
  } else {
370
- results.push({ journal, gameId: state.gameId, state: 'unknown',
371
- message: `Game ${state.gameId}: the server cannot state the outcome yet. The record is kept; nothing was retried. If this persists, write to support@realityse.com with ${path.basename(journal)}.` });
431
+ results.push({ ...row, state: 'unknown', ...(read.admissionId ? { admissionId: read.admissionId } : {}), ...(read.jobId ? { jobId: read.jobId } : {}),
432
+ message: `${game}: the server cannot state the outcome yet. The record is kept; nothing was retried.${namedRun(read)} If this persists, write to support@realityse.com with ${path.basename(journal)}.` });
372
433
  }
373
434
  }
374
- return results;
435
+ const admitted = results.filter(r => r.state === 'admitted').sort(newestFirst);
436
+ return [...admitted, ...results.filter(r => r.state !== 'admitted').sort(newestFirst)];
437
+ }
438
+
439
+ /**
440
+ * Saved admissions for this API and game whose outcome is still unknown. A new
441
+ * purchase is refused while any exists, because the earlier one may have been
442
+ * charged and only "hosted status" can say.
443
+ */
444
+ export async function unknownAdmissions({ repoRoot, apiUrl, gameId }) {
445
+ const dir = journalDir(repoRoot), here = origin(apiUrl), rows = [];
446
+ let names = [];
447
+ try { names = (await readdir(dir)).filter(name => /^[a-f0-9]{64}\.json$/.test(name)).sort(); }
448
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
449
+ for (const name of names) {
450
+ const state = await readJournal(path.join(dir, name));
451
+ if (state?.phase === 'admission_unknown' && state.apiUrl === here && state.gameId === gameId) {
452
+ rows.push({ journal: path.join(dir, name), quoteId: state.quoteId || null, createdAt: createdTime(state) });
453
+ }
454
+ }
455
+ return rows.sort(newestFirst);
456
+ }
457
+
458
+ /** Refuses a new hosted purchase while an earlier admission's outcome is unknown, unless overridden. */
459
+ export async function assertNoUnknownAdmission({ repoRoot, apiUrl, gameId, evenIfUnknown = false }) {
460
+ if (evenIfUnknown) return;
461
+ const rows = await unknownAdmissions({ repoRoot, apiUrl, gameId });
462
+ if (!rows.length) return;
463
+ const newest = rows[0], more = rows.length > 1 ? ` (and ${rows.length - 1} more)` : '';
464
+ throw new CliError(`An earlier hosted admission for game ${gameId} has no known outcome yet: ${attemptName(newest)}${more}. It may have been charged, so no new run was quoted or bought. Ask the server what happened first: ravensight-playtest hosted status. To buy another run anyway, pass --even-if-unknown. Nothing was charged.`, ExitCode.ENVIRONMENT);
375
465
  }
376
466
 
377
467
  // The terms a person accepted. A fresh quote taken while waiting for capacity
@@ -108,11 +108,14 @@ export function modeLine(row) {
108
108
  return `${row.name}: ${parts.join(', ')}.`;
109
109
  }
110
110
 
111
- // The server's FIFO queue for hosted runs (game_tracker fix/hosted-capacity-and-reaper).
112
- // ASSUMED field names, read in this one place until that branch's contract lands:
113
- // `queue: { position: <whole number, 1 is next>, estimatedStartAt: <ISO time or null> }`
114
- // on the admission acknowledgement and on GET /hosted/runs/:admissionId.
115
- // Position 0, or an estimate already past, reads as starting now.
111
+ // The server's FIFO queue for hosted runs (game_tracker
112
+ // hostedPlaytest/directQueue.js forAdmission, added by recordedCustomer.js
113
+ // withQueue beside `queued: true` on the admission acknowledgement and on GET
114
+ // /hosted/runs/:admissionId). The CLI reads two of its fields here:
115
+ // `position` (1 is next in line, 0 is starting now) and `estimatedStartAt`
116
+ // (ISO, null while launches are paused). The rest is for the dashboard and is
117
+ // only type checked (recordedRun.js validQueue). An estimate already past
118
+ // also reads as starting now.
116
119
  export function queueInfo(source) {
117
120
  const q = source?.queue;
118
121
  if (!q || typeof q !== 'object' || !Number.isSafeInteger(q.position) || q.position < 0) return null;
package/src/run/args.js CHANGED
@@ -19,6 +19,8 @@ const VALUED = new Map([
19
19
  ['--compare-with', 'compareWith'],
20
20
  ['--build-url', 'buildUrl'],
21
21
  ['--build-dir', 'buildDir'],
22
+ // The page to open inside --build-dir when it has several .html files.
23
+ ['--build-entry', 'buildEntry'],
22
24
  ['--godot-project', 'godotProject'],
23
25
  // The Godot binary, as check and the driver docs take it. RAVENSIGHT_GODOT
24
26
  // and GODOT still work when it is not given.
package/src/run/resume.js CHANGED
@@ -120,7 +120,8 @@ export async function resumeJob({ api, gameId, jobId, job, runs, state, repoRoot
120
120
  // process: serve the same folder again (or the one passed now) and play there.
121
121
  let servedTarget = null;
122
122
  if (driverName === 'playwright_web' && (options.buildDir || journal.buildDir)) {
123
- try { servedTarget = (await (injected.serveBuildDir || serveBuildDir)(options.buildDir || journal.buildDir)).url; } catch (error) {
123
+ const entry = options.buildEntry ?? (options.buildDir ? undefined : journal.buildEntry);
124
+ try { servedTarget = (await (injected.serveBuildDir || serveBuildDir)(options.buildDir || journal.buildDir, entry === undefined ? {} : { entry })).url; } catch (error) {
124
125
  log(`${error.message} Pass --build-dir with the build folder, or --build-url.`);
125
126
  return EXIT.ENVIRONMENT;
126
127
  }
@@ -1,6 +1,8 @@
1
1
  import { createServer } from 'node:http';
2
- import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';
2
+ import { createReadStream } from 'node:fs';
3
+ import { lstat, readdir, realpath, stat } from 'node:fs/promises';
3
4
  import path from 'node:path';
5
+ import { pipeline } from 'node:stream/promises';
4
6
  import { CliError } from '../errors.js';
5
7
 
6
8
  /**
@@ -19,8 +21,11 @@ import { CliError } from '../errors.js';
19
21
  * host, and that should keep working, without cookies.
20
22
  * - `no-store`, so a rebuilt export is never played from a stale cache.
21
23
  *
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
+ * It reads only files under the build folder (no symlink out of it, no
25
+ * dotfile or dot folder), answers GET and HEAD only, listens on the loopback
26
+ * address only and answers only a loopback Host header, so a page elsewhere
27
+ * cannot reach it through a name that resolves to 127.0.0.1. Files are
28
+ * streamed, with a single byte range when one is asked for.
24
29
  */
25
30
 
26
31
  export const CONTENT_TYPES = Object.freeze({
@@ -80,6 +85,29 @@ export function pickEntry(names) {
80
85
  * @param {{entry?: string|null, host?: string}} [options]
81
86
  * @returns {Promise<{url: string, origin: string, entry: string, root: string, close: () => Promise<void>}>}
82
87
  */
88
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);
89
+ const hidden = rel => rel.split('/').some(part => part.startsWith('.') && part.length > 0);
90
+
91
+ /** The file a request names inside root, or null: no escape, no dotfile, no symlink out. */
92
+ async function fileIn(root, rel) {
93
+ if (rel.includes('\0') || hidden(rel)) return null;
94
+ const file = path.resolve(root, '.' + (rel.startsWith('/') ? rel : '/' + rel));
95
+ if (file !== root && !file.startsWith(root + path.sep)) return null;
96
+ try {
97
+ const info = await lstat(file);
98
+ const real = await realpath(file);
99
+ const target = await stat(real);
100
+ if (!real.startsWith(root + path.sep) || !target.isFile() || (!info.isFile() && !info.isSymbolicLink())) return null;
101
+ return { real, size: target.size };
102
+ } catch { return null; }
103
+ }
104
+
105
+ /**
106
+ * Start serving a build folder.
107
+ * @param {string} dir
108
+ * @param {{entry?: string|null, host?: string}} [options] entry: the page to open, relative to dir (--build-entry)
109
+ * @returns {Promise<{url: string, origin: string, entry: string, root: string, close: () => Promise<void>}>}
110
+ */
83
111
  export async function serveBuildDir(dir, { entry = null, host = '127.0.0.1' } = {}) {
84
112
  let root;
85
113
  try {
@@ -89,26 +117,58 @@ export async function serveBuildDir(dir, { entry = null, host = '127.0.0.1' } =
89
117
  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
118
  }
91
119
  const names = (await readdir(root, { withFileTypes: true })).filter(item => item.isFile()).map(item => item.name);
92
- const page = entry || pickEntry(names);
120
+ let page = null;
121
+ if (entry !== null && entry !== undefined) {
122
+ const named = String(entry).replace(/\\/g, '/').replace(/^\.\//, '');
123
+ if (!named || path.isAbsolute(named) || !(await fileIn(root, named))) {
124
+ throw new CliError(`--build-entry ${entry} is not a file inside --build-dir ${dir}. Name the page relative to that folder, such as play.html.`);
125
+ }
126
+ page = named;
127
+ } else page = pickEntry(names);
93
128
  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)' : ''}.`);
129
+ 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: choose one with --build-entry <file>)' : ''}.`);
95
130
  }
131
+ let port = 0;
96
132
  const server = createServer((req, res) => {
97
- respond(root, req, res).catch(() => { if (!res.headersSent) res.writeHead(500, ISOLATION_HEADERS); res.end(); });
133
+ respond(root, port, req, res).catch(() => { if (!res.headersSent) res.writeHead(500, ISOLATION_HEADERS); res.end(); });
98
134
  });
99
135
  await new Promise((resolve, reject) => {
100
136
  server.once('error', reject);
101
137
  server.listen(0, host, resolve);
102
138
  });
139
+ port = server.address().port;
103
140
  // The server lives as long as the run that started it, and never keeps the
104
141
  // process alive on its own once the run is over.
105
142
  server.unref();
106
- const origin = `http://${host}:${server.address().port}`;
143
+ const origin = `http://${host}:${port}`;
107
144
  const url = `${origin}/${page.split('/').map(encodeURIComponent).join('/')}`;
108
145
  return { url, origin, entry: page, root, close: () => new Promise(resolve => server.close(() => resolve())) };
109
146
  }
110
147
 
111
- async function respond(root, req, res) {
148
+ /** True when the Host header names a loopback address on this server's port. */
149
+ export function loopbackHost(value, port) {
150
+ if (typeof value !== 'string') return false;
151
+ const match = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(value.trim().toLowerCase());
152
+ return Boolean(match) && LOOPBACK_HOSTS.has(match[1]) && Number(match[2]) === port;
153
+ }
154
+
155
+ /** A single `bytes=` range of a file of `size` bytes: {start, end}, null for none, or false when unsatisfiable. */
156
+ export function byteRange(header, size) {
157
+ if (typeof header !== 'string' || !header.trim()) return null;
158
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
159
+ if (!match || (!match[1] && !match[2])) return null; // several ranges or another unit: the whole file
160
+ let start, end;
161
+ if (!match[1]) { const suffix = Number(match[2]); if (!suffix) return false; start = Math.max(0, size - suffix); end = size - 1; }
162
+ else { start = Number(match[1]); end = match[2] ? Math.min(Number(match[2]), size - 1) : size - 1; }
163
+ if (start >= size || start > end) return false;
164
+ return { start, end };
165
+ }
166
+
167
+ async function respond(root, port, req, res) {
168
+ if (!loopbackHost(req.headers.host, port)) {
169
+ res.writeHead(421, ISOLATION_HEADERS);
170
+ return res.end();
171
+ }
112
172
  if (req.method !== 'GET' && req.method !== 'HEAD') {
113
173
  res.writeHead(405, { ...ISOLATION_HEADERS, allow: 'GET, HEAD' });
114
174
  return res.end();
@@ -120,18 +180,17 @@ async function respond(root, req, res) {
120
180
  }
121
181
  if (rel.includes('\0')) { res.writeHead(400, ISOLATION_HEADERS); return res.end(); }
122
182
  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);
183
+ const found = await fileIn(root, rel);
184
+ if (!found) { res.writeHead(404, ISOLATION_HEADERS); return res.end(); }
185
+ const headers = { ...contentHeaders(found.real), ...ISOLATION_HEADERS, 'accept-ranges': 'bytes' };
186
+ const range = byteRange(req.headers.range, found.size);
187
+ if (range === false) {
188
+ res.writeHead(416, { ...headers, 'content-range': `bytes */${found.size}` });
132
189
  return res.end();
133
190
  }
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);
191
+ const { start, end } = range || { start: 0, end: found.size - 1 };
192
+ res.writeHead(range ? 206 : 200, { ...headers, 'content-length': Math.max(0, end - start + 1),
193
+ ...(range ? { 'content-range': `bytes ${start}-${end}/${found.size}` } : {}) });
194
+ if (req.method === 'HEAD' || found.size === 0) return res.end();
195
+ await pipeline(createReadStream(found.real, { start, end }), res);
137
196
  }