@wildshard/engine 0.1.20 → 0.1.21
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/CHANGELOG.md +8 -0
- package/lint/engine-sides.json +1 -0
- package/package.json +2 -1
- package/scripts/chaos-proxy-core.mjs +14 -1
- package/scripts/chaos-proxy-proof.mjs +22 -0
- package/scripts/failmode-cases.d.mts +8 -0
- package/scripts/failmode-cases.mjs +97 -0
- package/scripts/failmode-proof.mjs +532 -0
- package/scripts/grid-crossing-nightly.mjs +5 -4
- package/scripts/grid-crossing-report.mjs +5 -2
- package/scripts/grid-crossing-tour.mjs +25 -8
- package/scripts/hover-speed-probe.mjs +136 -0
- package/scripts/net-lag-proof.mjs +3 -2
- package/scripts/online-rig.mjs +9 -7
- package/scripts/release-cook.mjs +109 -0
- package/scripts/vps/rebuild.sh +35 -9
- package/scripts/vps/wildshard-apply.mjs +5 -1
- package/scripts/vps/wildshard-config +117 -1
- package/src/client/engine/boot/contentRead.ts +54 -5
- package/src/client/engine/boot/gpuFiles.ts +3 -3
- package/src/client/engine/boot/leaveAfterPaint.ts +4 -1
- package/src/client/engine/core/shadowLayer.ts +18 -0
- package/src/client/engine/explore/pick.ts +13 -1
- package/src/client/engine/net/predictor.ts +12 -4
- package/src/client/engine/player/TouchControls.ts +3 -2
- package/src/client/engine/render/families/sceneSurface.ts +3 -1
- package/src/client/engine/telemetry/browserErrors.ts +3 -1
- package/src/client/engine/ui/ErrorModal.ts +1 -1
- package/src/client/engine/ui/Loading.ts +14 -2
- package/src/client/engine/ui/errorScreen.ts +51 -9
- package/src/client/engine/ui/hoverBoost.ts +31 -4
- package/src/client/engine/ui/styles/touch.css +6 -0
- package/src/client/game/boot/spawnDownload.ts +44 -6
- package/src/client/game/grid/live.ts +2 -2
- package/src/client/game/grid/liveSession.ts +2 -2
- package/src/client/game/grid/session.ts +2 -0
- package/src/client/game/grid/shardfileFar.ts +13 -2
- package/src/client/game/shardfile/clientSource.ts +7 -3
- package/src/client/game/shardfile/clientWorker.ts +4 -4
- package/src/client/game/shardfile/groundMerge.ts +5 -3
- package/src/client/host/online/linkScreens.ts +12 -6
- package/src/client/host/online/reconnectStrip.ts +3 -2
- package/src/client/host/online/release.ts +87 -16
- package/src/client/host/online/releaseScreens.ts +108 -0
- package/src/client/host/online/shell.ts +11 -1
- package/src/client/host/online/voice.ts +45 -1
- package/src/client/host/online/voiceUi.ts +24 -6
- package/src/server/engine/sim/playerSim.ts +1 -1
- package/src/server/game/grid/simulation.ts +12 -6
- package/src/server/host/dedicated/cellHost.ts +7 -0
- package/src/server/host/dedicated/cellWorker.ts +1 -1
- package/src/server/host/dedicated/dedicatedRoom.ts +14 -1
- package/src/server/host/dedicated/roadRoom.ts +3 -0
- package/src/server/host/standalone/gridServer.ts +1 -1
- package/src/shared/engine/boot/loadingWaits.ts +10 -2
- package/src/shared/engine/core/config.ts +3 -0
- package/src/shared/engine/player/hoverSpeed.ts +3 -3
- package/src/shared/engine/strings.ts +12 -1
- package/src/shared/game/grid/rules.ts +12 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Scope } from '../../../shared/engine/app/scope';
|
|
2
2
|
import type { Events } from '../../../shared/engine/events/events';
|
|
3
|
+
import { engineString } from '../../../shared/engine/strings';
|
|
3
4
|
import { isDev, onDev } from '../core/devMode';
|
|
4
5
|
|
|
5
6
|
// QA row 42 (Jake, 2026-11-10): "Let's get rid of the boost button. Let's make boost be like an undocumented double tap on the
|
|
@@ -50,12 +51,38 @@ export function pressHover(player: HoverPort, taps: HoverTaps, now: number): voi
|
|
|
50
51
|
/** Boost shows while it moves the board: Developer mode, riding, latched. */
|
|
51
52
|
export const boostShown = (player: Pick<HoverPort, 'hover' | 'hoverBoost'>): boolean => isDev() && player.hover && player.hoverBoost;
|
|
52
53
|
|
|
53
|
-
/** The
|
|
54
|
-
|
|
55
|
-
const
|
|
54
|
+
/** The word BOOST, hidden until `follow` shows it. */
|
|
55
|
+
function boostWord(scope: Scope): HTMLElement {
|
|
56
|
+
const word = document.createElement('b');
|
|
57
|
+
word.className = 'ws-touch-boost-word'; word.textContent = engineString('s_hover_boost'); word.hidden = true;
|
|
58
|
+
scope.onDispose(() => { word.remove(); });
|
|
59
|
+
return word;
|
|
60
|
+
}
|
|
61
|
+
/** Run `show` with whether boost is shown now and on every change that can move it, until `scope` ends. */
|
|
62
|
+
function follow(player: Pick<HoverPort, 'hover' | 'hoverBoost'>, events: Events, scope: Scope, show: (on: boolean) => void): void {
|
|
63
|
+
const sync = (): void => { show(boostShown(player)); };
|
|
56
64
|
events.on('player.hover', sync, scope);
|
|
57
65
|
events.on('player.boost', sync, scope);
|
|
58
66
|
scope.onDispose(onDev(sync));
|
|
59
|
-
scope.onDispose(() => { button.classList.remove('boost'); });
|
|
60
67
|
sync();
|
|
61
68
|
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The HOVER tab turns amber (`.boost`) while boost is shown, and says BOOST under its HOVER. QA 11-15 row 9 (Jake: "I want that little
|
|
72
|
+
* icon on the left edge of the screen to say hover boost. I just want the word boost there, boost is on. I want the word boost gone [when]
|
|
73
|
+
* boost is off."): the word is there only while boost is on.
|
|
74
|
+
*/
|
|
75
|
+
export function mountBoostLook(button: HTMLElement, player: Pick<HoverPort, 'hover' | 'hoverBoost'>, events: Events, scope: Scope): void {
|
|
76
|
+
const word = boostWord(scope);
|
|
77
|
+
button.append(word);
|
|
78
|
+
scope.onDispose(() => { button.classList.remove('boost'); });
|
|
79
|
+
follow(player, events, scope, on => { button.classList.toggle('boost', on); word.hidden = !on; });
|
|
80
|
+
}
|
|
81
|
+
/** QA 11-15 row 9 on a keyboard page, which has no HOVER tab: the same word on the left edge, where the phone's tab stands, only while
|
|
82
|
+
* boost is on. */
|
|
83
|
+
export function mountBoostTag(hud: HTMLElement, player: Pick<HoverPort, 'hover' | 'hoverBoost'>, events: Events, scope: Scope): void {
|
|
84
|
+
const tag = boostWord(scope);
|
|
85
|
+
tag.classList.add('ws-touch-boost-tag');
|
|
86
|
+
hud.append(tag);
|
|
87
|
+
follow(player, events, scope, on => { tag.hidden = !on; });
|
|
88
|
+
}
|
|
@@ -300,4 +300,10 @@ html[data-ws-keyboard] .ws-touch { visibility: hidden; pointer-events: none; }
|
|
|
300
300
|
|
|
301
301
|
/* QA row 42: no BOOST button. A double tap of HOVER latches Developer boost; the tab burns amber while it moves the board
|
|
302
302
|
(ui/hoverBoost.ts `.boost`), as do the board's repulsors. */
|
|
303
|
+
/* QA 11-15 row 9: the word BOOST under HOVER while boost is on, gone while it is off (ui/hoverBoost.ts `.ws-touch-boost-word`). A keyboard
|
|
304
|
+
page has no tab: the word stands alone on the left edge, at the tab's height, in the tab's amber. */
|
|
305
|
+
.ws-touch-boost-word { display: block; font: inherit; font-weight: 700; letter-spacing: inherit; line-height: 1; }
|
|
306
|
+
.ws-touch-boost-word[hidden] { display: none; }
|
|
307
|
+
#hud .ws-touch-boost-tag { position: absolute; z-index: calc(var(--ws-layer-hud) + 2); left: env(safe-area-inset-left, 0px); top: 46%; transform: translateY(-50%); padding: 8px 10px 8px 8px; border: 1px solid var(--ws-amber); border-left: 0; border-radius: 0 10px 10px 0; background: var(--ws-amber); color: #2a1600; box-shadow: 0 0 0 2px rgba(255, 181, 71, 0.35), 0 0 18px rgba(255, 181, 71, 0.75); font-family: var(--ws-mono); font-size: 10px; letter-spacing: 0.2em; text-transform: uppercase; pointer-events: none; }
|
|
308
|
+
#hud .ws-touch-boost-tag[hidden] { display: none; }
|
|
303
309
|
#hud .ws-touch .ws-touch-hover.on.boost { color: #2a1600; border-color: var(--ws-amber); background: var(--ws-amber); box-shadow: 0 0 0 2px rgba(255, 181, 71, 0.35), 0 0 18px rgba(255, 181, 71, 0.75); text-shadow: none; font-weight: 700; }
|
|
@@ -2,6 +2,9 @@ import {joinSpawnManifest, packsBookPath, readSpawnCodeList, readSpawnManifest,
|
|
|
2
2
|
import {assetCacheName} from '@wildshard/engine/pwa/cacheNames';
|
|
3
3
|
import {jsonSlot} from '@wildshard/engine/saves/slots';
|
|
4
4
|
import { bootMark,bootProgress,bootTiming,downloadShown } from '@wildshard/engine/boot/timing';
|
|
5
|
+
import { beginLoadingWait, finishLoadingWait } from '@wildshard/engine/boot/loadingWaits';
|
|
6
|
+
import { diagnosticNow } from '@wildshard/engine/core/clock';
|
|
7
|
+
import { Scope } from '@wildshard/engine/app/scope';
|
|
5
8
|
import {contentBase, contentURL, isContentOrigin, pageURL} from '@wildshard/engine/boot/contentBase';
|
|
6
9
|
import {bareSlug} from '../../../shared/game/grid/catalogueSlot';
|
|
7
10
|
import {placedLoose, placedSpawn} from './placedSpawn';
|
|
@@ -315,7 +318,8 @@ function isQuota(failure: unknown): boolean { return typeof failure === 'object'
|
|
|
315
318
|
* worker-cache response credits immediately without reading/checksumming it. */
|
|
316
319
|
export function downloadSpawnManifest(address: SpawnManifestAddress, ports: SpawnDownloadPorts, base: string, packs: string = base): SpawnDownload {
|
|
317
320
|
const controller = new AbortController(), listeners = new Set<(snapshot: SpawnDownloadSnapshot) => void>(), aliases = new Map<string, string>();
|
|
318
|
-
let cacheWriteDenied = false;
|
|
321
|
+
let cacheWriteDenied = false, storageFull: number | null = null;
|
|
322
|
+
const endStorageFull = (): void => { if (storageFull !== null) finishLoadingWait(storageFull); storageFull = null; };
|
|
319
323
|
// Verified bytes remain usable when optional disk publication exhausts quota.
|
|
320
324
|
// Do not retry the part, claim cached credit, or publish an index for unkept bytes.
|
|
321
325
|
const keepCopy = async (write: SpawnDownloadPorts['store'], url: string, response: Response): Promise<boolean> => {
|
|
@@ -326,7 +330,10 @@ export function downloadSpawnManifest(address: SpawnManifestAddress, ports: Spaw
|
|
|
326
330
|
await write(url, response); retained = true; return true;
|
|
327
331
|
} catch (failure) {
|
|
328
332
|
if (!isQuota(failure)) throw failure;
|
|
329
|
-
cacheWriteDenied = true; bootMark('download:cache-write-quota');
|
|
333
|
+
cacheWriteDenied = true; bootMark('download:cache-write-quota');
|
|
334
|
+
// FM6 mode 43: the card says so while this download runs; the world plays on from the bytes in memory
|
|
335
|
+
storageFull ??= beginLoadingWait('Storage is full', { kind: 'work', failmode: 'storage-full', line: 'Storage is full · the world will load more slowly' });
|
|
336
|
+
return false;
|
|
330
337
|
} finally { if (!retained) void response.body?.cancel().catch(() => undefined); }
|
|
331
338
|
};
|
|
332
339
|
let completedBytes = 0, cachedBytes = 0, filesDone = 0, complete = false, progressKnown = false, error: string | null = null;
|
|
@@ -690,11 +697,12 @@ export function downloadSpawnManifest(address: SpawnManifestAddress, ports: Spaw
|
|
|
690
697
|
// The tap starts work before its composition root reaches the await. Keep
|
|
691
698
|
// its original rejection for that await without a premature global report.
|
|
692
699
|
void work.catch(() => undefined); void ready.catch(() => undefined);
|
|
700
|
+
void ready.finally(endStorageFull).catch(() => undefined);
|
|
693
701
|
const listed = Promise.race([listedOnly, ready]);
|
|
694
702
|
void listed.catch(() => undefined);
|
|
695
703
|
return {ready, listed, snapshot, subscribe: listener => {listeners.add(listener); listener(snapshot()); return () => {listeners.delete(listener);};},
|
|
696
704
|
resolve: input => {const url = new URL(input, base); return url.origin === new URL(base).origin ? aliases.get(url.pathname) ?? url.href : url.href;},
|
|
697
|
-
cancel: () => {controller.abort(); releaseWaits(); nudge(); markStopped(controller.signal.reason); listeners.clear();}};
|
|
705
|
+
cancel: () => {controller.abort(); endStorageFull(); releaseWaits(); nudge(); markStopped(controller.signal.reason); listeners.clear();}};
|
|
698
706
|
}
|
|
699
707
|
|
|
700
708
|
let current: {key: string; download: SpawnDownload; foreground: boolean} | undefined;
|
|
@@ -847,6 +855,36 @@ function spawnSelection(slug: string, flow: 'client' | 'grid', tier: 'phone' | '
|
|
|
847
855
|
declare const __BUILD_ID__: string;
|
|
848
856
|
let packsBook: {readonly url: string; readonly book: Promise<unknown>} | undefined;
|
|
849
857
|
const PACKS_BOOK_MS = 20_000;
|
|
858
|
+
/** FM6 mode 35 (meta MMO-FAILURE-MODES-PLAN): a server error or busy answer on the book is read again on content's ladder (a
|
|
859
|
+
* 429's Retry-After as told, at least 2 s) for up to BOOK_TRIES reads, the loading card saying `book-5xx` meanwhile, before the
|
|
860
|
+
* named refusal. FM3's proof found a single 503 refusing the whole start ("Something broke"). A 404 still refuses at once. */
|
|
861
|
+
const BOOK_LINE = 'The world\'s book didn\'t arrive';
|
|
862
|
+
const BOOK_TRIES = 6, BOOK_LADDER_MS: readonly number[] = [2000, 4000, 8000, 16_000, 30_000];
|
|
863
|
+
async function bookResponse(url: string, fresh: () => AbortSignal, stalled: (error: unknown) => never): Promise<Response> {
|
|
864
|
+
let wait: number | undefined, shellFoot: HTMLElement | null = null;
|
|
865
|
+
try {
|
|
866
|
+
for (let attempt = 0; ; attempt++) {
|
|
867
|
+
// each read has its own 20 s limit (DL21), body included; the waits between reads are the ladder's, not a stall
|
|
868
|
+
const response = await fetch(url, {signal: fresh()}).catch(stalled);
|
|
869
|
+
if (response.ok) return response;
|
|
870
|
+
const busy = response.status === 429 || response.status >= 500;
|
|
871
|
+
if (!busy || attempt + 1 >= BOOK_TRIES) throw new Error(`Packs book unavailable (${response.status})`);
|
|
872
|
+
void response.body?.cancel().catch(() => undefined);
|
|
873
|
+
const told = Number(response.headers.get('retry-after'));
|
|
874
|
+
const ms = Math.max(2000, response.status === 429 && Number.isFinite(told) && told > 0 ? Math.min(told, 60) * 1000 : BOOK_LADDER_MS[attempt] ?? 30_000);
|
|
875
|
+
// at START, before Loading owns the card, only the shell's foot is on screen: it says so too (Loading repaints it later)
|
|
876
|
+
const foot = document.querySelector?.<HTMLElement>('.ws-load [data-el="foot"]') ?? null;
|
|
877
|
+
if (foot !== null) { foot.textContent = BOOK_LINE; foot.dataset['failmode'] = 'book-5xx'; shellFoot = foot; }
|
|
878
|
+
if (wait === undefined) wait = beginLoadingWait('Packs book', {kind: 'file', resource: url, failmode: 'book-5xx', line: BOOK_LINE, dueAt: diagnosticNow() + ms});
|
|
879
|
+
else { finishLoadingWait(wait); wait = beginLoadingWait('Packs book', {kind: 'file', resource: url, failmode: 'book-5xx', line: BOOK_LINE, dueAt: diagnosticNow() + ms}); }
|
|
880
|
+
const pause = new Scope('packs-book-retry');
|
|
881
|
+
try { await new Promise<void>(resolve => { pause.timeout(ms, resolve); }); } finally { pause.dispose(); }
|
|
882
|
+
}
|
|
883
|
+
} finally {
|
|
884
|
+
if (wait !== undefined) finishLoadingWait(wait);
|
|
885
|
+
if (shellFoot?.dataset['failmode'] === 'book-5xx') { delete shellFoot.dataset['failmode']; shellFoot.textContent = ''; }
|
|
886
|
+
}
|
|
887
|
+
}
|
|
850
888
|
function readPacksBook(): Promise<unknown> {
|
|
851
889
|
const url = contentURL(new URL(`/${packsBookPath(__BUILD_ID__)}`, document.baseURI).href);
|
|
852
890
|
if (packsBook?.url === url) return packsBook.book;
|
|
@@ -854,11 +892,11 @@ function readPacksBook(): Promise<unknown> {
|
|
|
854
892
|
try {
|
|
855
893
|
// DL21 (E526): a stalled book is a named refusal with the loading card's retry, never an endless wait.
|
|
856
894
|
// The limit covers the body too (sp-x9): a stalled body is the same named refusal.
|
|
857
|
-
|
|
895
|
+
let signal = AbortSignal.timeout(PACKS_BOOK_MS);
|
|
896
|
+
const stalled = (error: unknown): never => {
|
|
858
897
|
throw signal.aborted ? new Error(`Packs book did not arrive in ${PACKS_BOOK_MS / 1000} s`) : error;
|
|
859
898
|
};
|
|
860
|
-
const response = await
|
|
861
|
-
if (!response.ok) throw new Error(`Packs book unavailable (${response.status})`);
|
|
899
|
+
const response = await bookResponse(url, () => (signal = AbortSignal.timeout(PACKS_BOOK_MS)), stalled);
|
|
862
900
|
const value: unknown = await response.json().catch(stalled);
|
|
863
901
|
// Bound to its purpose and this build: a valid default book or another build's book is refused (sp-x9).
|
|
864
902
|
if (get(value, 'book') !== 'packs' || get(value, 'build') !== __BUILD_ID__) throw new Error('Packs book is not this build\'s whole-level book');
|
|
@@ -466,7 +466,7 @@ export class LiveGridHost {
|
|
|
466
466
|
}
|
|
467
467
|
private retainedFits(instance: string): boolean {
|
|
468
468
|
const policy = this.ports.lastCell;
|
|
469
|
-
return policy !== undefined && this.ports.allocator.ownerCost(instance).playing <= Math.min(
|
|
469
|
+
return policy !== undefined && this.ports.allocator.ownerCost(instance).playing <= Math.min(this.ports.allocator.envelope(), policy.playingBytes);
|
|
470
470
|
}
|
|
471
471
|
/** Call only after entered leave hooks finish. Keep the same ready world,
|
|
472
472
|
* without a second claim, snapshot, physics host or shader preparation. */
|
|
@@ -897,7 +897,7 @@ export class LiveGridHost {
|
|
|
897
897
|
private retainedState(): Exclude<LiveGridState['retainedCell'], undefined> {
|
|
898
898
|
const last = this.lastCell, policy = this.ports.lastCell;
|
|
899
899
|
return last === null || policy === undefined ? null : { instance: last.instance, remainingMs: Math.max(0, last.until - diagnosticNow()),
|
|
900
|
-
playingBytes: this.ports.allocator.ownerCost(last.instance).playing, capBytes: Math.min(
|
|
900
|
+
playingBytes: this.ports.allocator.ownerCost(last.instance).playing, capBytes: Math.min(this.ports.allocator.envelope(), policy.playingBytes) };
|
|
901
901
|
}
|
|
902
902
|
/** Read-only crossing evidence and failures for the real grid physics harness. */
|
|
903
903
|
state(): LiveGridState { return { current: this.active, worldFeet: this.worldFeet(), crossings: this.crossings, ahead: { instance: this.ahead, warms: this.warms, refused: this.warmRefusal, deferred: [...new Set([...this.deferredProducts.keys(), ...this.deferredDemand.keys()])], demanded: this.demanded, released: this.released }, transitions: this.transitions.map((row) => ({ ...row })), residents: [...this.residents.keys()].sort(), pending: [...new Set([...this.requests.keys(), ...this.productRequests.keys()])].sort(), pendingWork: [
|
|
@@ -27,7 +27,7 @@ import { Vector3, type PerspectiveCamera } from 'three';
|
|
|
27
27
|
import { createProgramKeeper, RETAINED_PROGRAM_BYTES, RETAINED_PROGRAM_LIMIT, type ProgramKeeper } from '@wildshard/engine/render/programRetention';
|
|
28
28
|
import { diagnosticNow } from '@wildshard/engine/core/clock';
|
|
29
29
|
import { WORK_SLICE_MS, workSlice } from '@wildshard/engine/core/workSlice';
|
|
30
|
-
import { CHUNK_HALF,
|
|
30
|
+
import { CHUNK_HALF, ENTRY_ASPHALT } from '@wildshard/engine/core/config';
|
|
31
31
|
import type { DisposeStep, Scope } from '@wildshard/engine/app/scope';
|
|
32
32
|
import type { Events } from '@wildshard/engine/events/events';
|
|
33
33
|
import type { Physics } from '@wildshard/engine/physics/Physics';
|
|
@@ -293,7 +293,7 @@ export class LiveGridSession {
|
|
|
293
293
|
const highwayBytes = (ports.initialStripBytes ?? ports.strips.reduce((sum, strip) => sum + strip.mesh.positions.byteLength + strip.mesh.indices.byteLength, 0))
|
|
294
294
|
+ assembly.cells.length * TRANSFER_WALL_BYTES;
|
|
295
295
|
try { this.live = new LiveGridHost(assembly, {
|
|
296
|
-
lastCell: { windowMs: 30_000, playingBytes:
|
|
296
|
+
lastCell: { windowMs: 30_000, playingBytes: ports.allocator.envelope(), schedule: (expire, ms) => {
|
|
297
297
|
const timer = scope.child('grid.last-cell-expiry');
|
|
298
298
|
timer.timeout(ms, () => { timer.dispose(); scope.run(expire); });
|
|
299
299
|
return () => { timer.dispose(); };
|
|
@@ -890,6 +890,8 @@ export class GridSession {
|
|
|
890
890
|
const homeClaim = residency.home(), homeResidency = (): { instance: string; bytes: number } => ({ instance: homeClaim.instance, bytes: homeClaim.bytes });
|
|
891
891
|
host.scope.onDispose(app.debug.scopedExpose('grid', { state: () => this.state(), roadView: () => this.roadBudget.view(), roadResident: () => this.roadBudget.resident(),
|
|
892
892
|
roadTileResidency: () => this.roadTiles?.state() ?? null,
|
|
893
|
+
// GC6: the hybrid hooks' timings (each entry's world, kit, play and their after-hooks), for the crossing tour
|
|
894
|
+
hookTimings: () => this.live?.hookTimings() ?? null,
|
|
893
895
|
// G144 admission receipts read the same allocator, without reserving or changing any claim.
|
|
894
896
|
residency: () => ({ cost: this.allocator.cost(), claims: this.allocator.entries(), home: homeResidency() }),
|
|
895
897
|
// Per-frame travel needs the same fresh live/crossing facts, without the
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Mesh, type BufferGeometry, type Object3D } from 'three';
|
|
1
|
+
import { Matrix4, Mesh, type BufferGeometry, type Object3D } from 'three';
|
|
2
2
|
import { prepareRigLoader } from '@wildshard/engine/anim/rig';
|
|
3
3
|
import { workSlice } from '@wildshard/engine/core/workSlice';
|
|
4
4
|
import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
|
|
@@ -52,6 +52,17 @@ function shardfileHaze(fog: ShardfileFarRows['fog']): FarPrepared['look'] {
|
|
|
52
52
|
return { family: 'pbr', haze: { colour: fog ?? [1, 1, 1] } };
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
const IDENTITY = new Matrix4();
|
|
56
|
+
/** GC6: a mesh's geometry in its scene pose. The loader's accessor bounds would be recomputed from every vertex by
|
|
57
|
+
* `applyMatrix4` (two passes; ~45 % of the near bake's main-thread time on Driftwood to Nalati, where the neighbours' near
|
|
58
|
+
* views load on the road beside the entry's preparation), and nothing reads a part's bounds: the merged draw computes its
|
|
59
|
+
* own once. An identity pose is no transform at all. */
|
|
60
|
+
export function bakePose(node: Mesh): BufferGeometry {
|
|
61
|
+
const geometry = node.geometry;
|
|
62
|
+
geometry.boundingBox = null; geometry.boundingSphere = null;
|
|
63
|
+
return node.matrixWorld.equals(IDENTITY) ? geometry : geometry.applyMatrix4(node.matrixWorld);
|
|
64
|
+
}
|
|
65
|
+
|
|
55
66
|
/**
|
|
56
67
|
* G348: any shardfile's own near placeholder (its admitted `near` row, which `wildshard build` bakes for every terrain
|
|
57
68
|
* shardfile, an unknown uploaded one included): its content GLBs' meshes merged into the near view's one draw, masked by
|
|
@@ -77,7 +88,7 @@ export async function loadShardfileNear(rows: ShardfileNearRows, read: (ref: str
|
|
|
77
88
|
await slice.check();
|
|
78
89
|
for (const material of Array.isArray(node.material) ? node.material : [node.material]) material.dispose();
|
|
79
90
|
// NM13: the light layer stays apart from the lit draw (drawn additively, unlit)
|
|
80
|
-
(node.name === NEAR_LIGHT ? lights : node.name === NEAR_COLOUR ? colours : parts).push(
|
|
91
|
+
(node.name === NEAR_LIGHT ? lights : node.name === NEAR_COLOUR ? colours : parts).push(bakePose(node));
|
|
81
92
|
}
|
|
82
93
|
}
|
|
83
94
|
} catch (error) { for (const part of [...parts, ...lights, ...colours]) part.dispose(); throw error; }
|
|
@@ -10,11 +10,12 @@ import { isOutputIndex } from '@wildshard/format/outputAddress';
|
|
|
10
10
|
import { SHARDFILE_ADMISSION_LIMITS as limits } from '@wildshard/format/admissionLimits';
|
|
11
11
|
import type { Shardfile } from '@wildshard/format/shardSchema';
|
|
12
12
|
import { isDev } from '@wildshard/engine/core/devMode';
|
|
13
|
-
import { CONTENT_CAPS, _applyChunkConstants } from '@wildshard/engine/core/config';
|
|
13
|
+
import { CONTENT_CAPS, PHONE_PLAYING_BYTES, _applyChunkConstants } from '@wildshard/engine/core/config';
|
|
14
14
|
import { configureLevel } from '@wildshard/engine/level/selection';
|
|
15
15
|
import { pageGridInstance, sourceManifest, compiledPageBoot, type PageMode } from '../plugin/context';
|
|
16
16
|
import { PageResidency } from '../grid/pageResidency';
|
|
17
17
|
import { ResidencyAllocator } from '../../../shared/game/grid/allocator';
|
|
18
|
+
import { TIER, type Tier } from '@wildshard/engine/core/tier';
|
|
18
19
|
import type { GridRecoveryRecord } from '../../../shared/game/grid/recovery';
|
|
19
20
|
import { bootPageMode, pageGridRecovery } from '../grid/pageEntry';
|
|
20
21
|
import { currentPageMode } from '../../../shared/game/grid/pageMode';
|
|
@@ -51,13 +52,16 @@ export interface PageResidencyBoot {
|
|
|
51
52
|
* against their declared sim cost, then their actual library and tile claims. The root disposes failed hydration; the
|
|
52
53
|
* successful session installs the owner's level lifetime.
|
|
53
54
|
*/
|
|
55
|
+
/** GC13: the page's playing envelope: the phone tier's 1.0 GB (G65), else the shared caps' */
|
|
56
|
+
export function pagePlayingBytes(tier: Tier = TIER): number { return tier === 'phone' ? PHONE_PLAYING_BYTES : CONTENT_CAPS.playing; }
|
|
57
|
+
|
|
54
58
|
export function preparePageResidency(manifest: Pick<ShardManifest, 'slug' | 'shardfile' | 'runtimeCost'>, configuredSlug?: string, memory: MemoryAdmission = new MemoryAdmission(() => MEMORY_GATES.reportOnly || isDev())): PageResidencyBoot {
|
|
55
59
|
const mode = bootPageMode(configuredSlug ?? manifest.slug);
|
|
56
60
|
const measuredHome = configuredSlug === undefined && manifest.shardfile === undefined;
|
|
57
61
|
if (mode !== 'grid' && (!measuredHome || manifest.runtimeCost === undefined)) return { mode, instance: null, memory };
|
|
58
62
|
const instance = mode === 'grid' ? pageGridInstance() : manifest.slug;
|
|
59
63
|
if (instance === null) throw new Error('Grid residency requires the consumed home instance');
|
|
60
|
-
const residency = new PageResidency(new ResidencyAllocator({ memory }));
|
|
64
|
+
const residency = new PageResidency(new ResidencyAllocator({ memory, playing: pagePlayingBytes() }));
|
|
61
65
|
try {
|
|
62
66
|
if (measuredHome) {
|
|
63
67
|
if (manifest.runtimeCost === undefined) throw new Error('Grid runtime home requires reviewed memory measurements before bootstrap');
|
|
@@ -100,7 +104,7 @@ function clientSource(admitted: AdmittedProduct, options: ProductOptions, bindin
|
|
|
100
104
|
const sections = outputDescriptor(source)?.sections;
|
|
101
105
|
if (sections !== undefined) prepareClientModuleGroups(source, sections);
|
|
102
106
|
const ownedBindings = { ...bindings,
|
|
103
|
-
...(bindings.allocator === undefined && bindings.residency === undefined && options.memory !== undefined ? { allocator: new ResidencyAllocator({ memory: options.memory }) } : {}),
|
|
107
|
+
...(bindings.allocator === undefined && bindings.residency === undefined && options.memory !== undefined ? { allocator: new ResidencyAllocator({ memory: options.memory, playing: pagePlayingBytes() }) } : {}),
|
|
104
108
|
...(options.firstParty ? {} : { instance: admitted.instance ?? '' }) };
|
|
105
109
|
const residency = clientResidency(source, ownedBindings);
|
|
106
110
|
const assets = new ClientAssets(source, admitted.assets, options);
|
|
@@ -162,8 +162,8 @@ export interface WorkerClientReport {
|
|
|
162
162
|
retired: Readonly<Record<string, number>>;
|
|
163
163
|
/** The longest a row of each kind took to spawn, in ms: a model built late shows here. */
|
|
164
164
|
spawnMs: Readonly<Record<string, number>>;
|
|
165
|
-
/** What
|
|
166
|
-
missed: Readonly<NetPlayer['predictor']['missed']>; misses: readonly (readonly number[])[];
|
|
165
|
+
/** What corrections disagreed on, and server-owned transitions that were deliberately not corrections. */
|
|
166
|
+
missed: Readonly<NetPlayer['predictor']['missed']>; misses: readonly (readonly number[])[]; authoritative: Readonly<NetPlayer['predictor']['authoritative']>;
|
|
167
167
|
}
|
|
168
168
|
/** A fight as a proof reads it: its row, where its body stands and the server's name for it. */
|
|
169
169
|
export type WorkerClientFight = EncounterRow & { readonly at: { readonly x: number; readonly y: number; readonly z: number } | null; readonly name: string | null };
|
|
@@ -465,7 +465,7 @@ async function startWorkerClient(ports: WorkerClientPorts, card: ReturnType<type
|
|
|
465
465
|
if (shell.redials === true) others = new (await import('@wildshard/engine/net/otherPlayers')).OtherPlayers(client, ports.scene, scope, player.position);
|
|
466
466
|
if (new URLSearchParams(location.search).has('bossGod')) shell.bossGod();
|
|
467
467
|
bootMark('server:ready-send'); shell.ready();
|
|
468
|
-
const started = diagnosticNow(), report: WorkerClientReport = { drawn: wirePage.drawn, frames: 0, framesPerSecond: 0, ticksPerSecond: 0, correctionsPerMinute: 0, corrections: 0, retired: {}, spawnMs: {}, missed: net.predictor.missed, misses: net.predictor.misses, worstOffset: 0, queue: 0, replaysPerFrame: 0, delayMs: 0, jitterMs: 0, interpHeld: 0, interpStarved: 0, mainMsP95: 0, workerTickMs: 0, rows: 0, attacks: 0, hits: 0, kills: 0, refused: 0, held: 0, dropped: 0, hp: 0, falls: 0, closed: null, x: 0, z: 0, cell: 0, serverX: 0, serverZ: 0, restored, savedTick: -1, savedOk: false, receipts: [], quests: {}, flags: [], paid: 0, fights: [], owned: {}, sky: null, day: null, clawed: false, own: null, movers: 0, posed: 0, sand: 0 };
|
|
468
|
+
const started = diagnosticNow(), report: WorkerClientReport = { drawn: wirePage.drawn, frames: 0, framesPerSecond: 0, ticksPerSecond: 0, correctionsPerMinute: 0, corrections: 0, retired: {}, spawnMs: {}, missed: net.predictor.missed, misses: net.predictor.misses, authoritative: net.predictor.authoritative, worstOffset: 0, queue: 0, replaysPerFrame: 0, delayMs: 0, jitterMs: 0, interpHeld: 0, interpStarved: 0, mainMsP95: 0, workerTickMs: 0, rows: 0, attacks: 0, hits: 0, kills: 0, refused: 0, held: 0, dropped: 0, hp: 0, falls: 0, closed: null, x: 0, z: 0, cell: 0, serverX: 0, serverZ: 0, restored, savedTick: -1, savedOk: false, receipts: [], quests: {}, flags: [], paid: 0, fights: [], owned: {}, sky: null, day: null, clawed: false, own: null, movers: 0, posed: 0, sand: 0 };
|
|
469
469
|
if (unseated) void shell.booted.then(answer => { report.restored = answer.restored; bootMark('server:seated-late'); return undefined; }, () => undefined);
|
|
470
470
|
scope.onDispose(client.onLedger(receipt => { report.receipts.push(`${receipt.grant}:${receipt.name}`); }));
|
|
471
471
|
const contacts: NetCombatEvent[] = [];
|
|
@@ -556,7 +556,7 @@ async function startWorkerClient(ports: WorkerClientPorts, card: ReturnType<type
|
|
|
556
556
|
report.frames++;
|
|
557
557
|
if (firstTick === -1 && tick > 0) firstTick = tick;
|
|
558
558
|
report.ticksPerSecond = firstTick === -1 ? 0 : (tick - firstTick) / ((now - ticksFrom) / 1000); // each world keeps its own clock
|
|
559
|
-
report.missed = predictor.missed; report.corrections = predictor.corrections; report.correctionsPerMinute = predictor.corrections / seconds * 60; report.worstOffset = net.worstOffset; report.queue = predictor.pending;
|
|
559
|
+
report.missed = predictor.missed; report.authoritative = predictor.authoritative; report.corrections = predictor.corrections; report.correctionsPerMinute = predictor.corrections / seconds * 60; report.worstOffset = net.worstOffset; report.queue = predictor.pending;
|
|
560
560
|
report.replaysPerFrame = predictor.replays / report.frames; report.delayMs = client.clock.delayMs; report.jitterMs = client.clock.jitterMs; report.interpHeld = client.interpolator.held; report.interpStarved = client.interpolator.starved;
|
|
561
561
|
report.refused = net.attacks.refused; report.attacks = net.attacks.pending; report.held = net.heldSlot;
|
|
562
562
|
if (report.closed === null && client.closed !== null && !ended && client.closed !== 'reload' && shell.redials !== true) showError(`The game's server stopped (${client.closed})`);
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
*/
|
|
21
21
|
import { Box3, BufferAttribute, BufferGeometry, InterleavedBufferAttribute, Matrix3, Matrix4, Mesh, Sphere, Vector3, type Material, type Object3D } from 'three';
|
|
22
22
|
import type { Scope } from '@wildshard/engine/app/scope';
|
|
23
|
-
import { SHADOW_LAYER } from '@wildshard/engine/core/shadowLayer';
|
|
23
|
+
import { MERGED_COPY, MERGED_VIEW, SHADOW_LAYER } from '@wildshard/engine/core/shadowLayer';
|
|
24
24
|
|
|
25
25
|
const HALF = 250, COARSE = 125, BLOCK = 250;
|
|
26
26
|
/** an attribute's change count (an interleaved one counts on its buffer) */
|
|
@@ -270,7 +270,7 @@ export function propMerge(parent: Object3D, material: Material, draw: PropDraw):
|
|
|
270
270
|
const key = `${String(draw.receive)}|${String(draw.order)}`;
|
|
271
271
|
let merge = byDraw.get(key);
|
|
272
272
|
if (merge === undefined) {
|
|
273
|
-
merge = new GroundMerge(parent, material,
|
|
273
|
+
merge = new GroundMerge(parent, material, MERGED_COPY, (mesh) => { mesh.castShadow = false; mesh.receiveShadow = draw.receive; mesh.renderOrder = draw.order; }, 'block');
|
|
274
274
|
byDraw.set(key, merge);
|
|
275
275
|
}
|
|
276
276
|
return merge;
|
|
@@ -280,5 +280,7 @@ export function propMerge(parent: Object3D, material: Material, draw: PropDraw):
|
|
|
280
280
|
export function mergeView(parent: Object3D, mesh: Mesh, material: Material, scope: Scope): void {
|
|
281
281
|
if (mesh.material !== material) throw new Error('Prop merge member draws another material');
|
|
282
282
|
propMerge(parent, material, { receive: mesh.receiveShadow, order: mesh.renderOrder }).add(mesh, scope);
|
|
283
|
-
|
|
283
|
+
// SHARD-SOURCE ss4d: still the World Explorer's to pick (explore/pick.ts reads this mark), though it draws on SHADOW_LAYER
|
|
284
|
+
mesh.visible = true; mesh.layers.set(SHADOW_LAYER); mesh.userData[MERGED_VIEW] = true;
|
|
285
|
+
scope.onDispose(() => { mesh.userData[MERGED_VIEW] = false; });
|
|
284
286
|
}
|
|
@@ -69,18 +69,25 @@ const CSS = `
|
|
|
69
69
|
.ws-link details p{margin:8px 0 0;font-size:10.5px;color:rgba(230,242,248,.55);overflow-wrap:anywhere;-webkit-user-select:text;user-select:text}
|
|
70
70
|
@keyframes ws-link-fade{from{opacity:0}}@keyframes ws-link-rise{from{opacity:0;transform:translateY(8px)}}
|
|
71
71
|
.ws-link-notice{animation-name:ws-link-fade}
|
|
72
|
+
.ws-link-page{background:#05101a;animation:ws-link-fade .2s ease-out}.ws-link-page .ws-link-box{animation:none}
|
|
73
|
+
.ws-link-mark{position:fixed;left:50%;bottom:calc(6px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);z-index:2147482200;padding:3px 10px;pointer-events:none;background:rgba(13,27,38,.78);border:1px solid rgba(255,181,71,.5);font-size:10px;letter-spacing:.22em;text-transform:uppercase;color:var(--a)}
|
|
72
74
|
@media (max-width:420px){.ws-link-banner{max-width:calc(100% - 220px);padding-left:12px;padding-right:12px}.ws-link-banner b{letter-spacing:.08em}}
|
|
73
75
|
@media (min-width:700px){.ws-link-banner{max-width:min(620px,calc(100% - 440px))}.ws-link-box{padding:28px 26px 20px}.ws-link h1{font-size:28px}}
|
|
74
76
|
@media (prefers-reduced-motion:reduce){.ws-link,.ws-link *{animation:none!important;transition:none!important}}
|
|
75
77
|
`;
|
|
76
78
|
|
|
77
|
-
const make = <K extends keyof HTMLElementTagNameMap>(tag: K, className = '', text = ''): HTMLElementTagNameMap[K] => {
|
|
79
|
+
export const make = <K extends keyof HTMLElementTagNameMap>(tag: K, className = '', text = ''): HTMLElementTagNameMap[K] => {
|
|
78
80
|
const node = document.createElement(tag);
|
|
79
81
|
if (className !== '') node.className = className;
|
|
80
82
|
if (text !== '') node.textContent = text;
|
|
81
83
|
return node;
|
|
82
84
|
};
|
|
83
|
-
const ring = (): HTMLElement => { const node = make('span', 'ring'); node.setAttribute('aria-hidden', 'true'); return node; };
|
|
85
|
+
export const ring = (): HTMLElement => { const node = make('span', 'ring'); node.setAttribute('aria-hidden', 'true'); return node; };
|
|
86
|
+
|
|
87
|
+
/** The screens' stylesheet. It lives as long as the document: a second shell (a reload in place) shares it. */
|
|
88
|
+
export function linkStyle(): void {
|
|
89
|
+
if (document.getElementById('ws-link-style') === null) { const style = make('style'); style.id = 'ws-link-style'; style.textContent = CSS; document.head.append(style); }
|
|
90
|
+
}
|
|
84
91
|
|
|
85
92
|
/** What the screens ask of the link and the page. */
|
|
86
93
|
export interface LinkScreenHooks {
|
|
@@ -130,7 +137,7 @@ const awayFor = (ms: number): string => ms < 90_000 ? `${String(Math.round(ms /
|
|
|
130
137
|
const blockedIds = (ids: string): string => ids.split(' ').map(id => `${id}-blocked`).join(' ');
|
|
131
138
|
|
|
132
139
|
/** A card's frame: the scrim, the box, a tag and a title. The caller fills the rest. */
|
|
133
|
-
function card(scope: Scope, ids: string, tone: 'info' | 'warn' | 'bad', tag: string, title: string): { root: HTMLElement; box: HTMLElement } {
|
|
140
|
+
export function card(scope: Scope, ids: string, tone: 'info' | 'warn' | 'bad', tag: string, title: string): { root: HTMLElement; box: HTMLElement } {
|
|
134
141
|
const root = scope.ownNode(make('div', 'ws-link ws-link-scrim')), box = make('div', 'ws-link-box');
|
|
135
142
|
root.dataset['failmode'] = ids; root.dataset['tone'] = tone; root.setAttribute('role', 'alertdialog'); root.setAttribute('aria-modal', 'true'); root.setAttribute('aria-label', title);
|
|
136
143
|
box.append(make('p', 'ws-link-tag', tag), make('h1', '', title)); root.append(box);
|
|
@@ -147,7 +154,7 @@ function card(scope: Scope, ids: string, tone: 'info' | 'warn' | 'bad', tag: str
|
|
|
147
154
|
});
|
|
148
155
|
return { root, box };
|
|
149
156
|
}
|
|
150
|
-
function buttons(scope: Scope, actions: readonly { readonly label: string; readonly primary?: true; readonly busy?: string; readonly act: () => void }[]): HTMLElement {
|
|
157
|
+
export function buttons(scope: Scope, actions: readonly { readonly label: string; readonly primary?: true; readonly busy?: string; readonly act: () => void }[]): HTMLElement {
|
|
151
158
|
const column = make('div', 'ws-link-col');
|
|
152
159
|
for (const action of actions) {
|
|
153
160
|
const button = make('button', action.primary === true ? 'go' : '', action.label);
|
|
@@ -169,8 +176,7 @@ function buttons(scope: Scope, actions: readonly { readonly label: string; reado
|
|
|
169
176
|
*/
|
|
170
177
|
export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLElement = document.body): LinkScreens {
|
|
171
178
|
const report = hooks.report ?? captureBrowserError;
|
|
172
|
-
|
|
173
|
-
if (document.getElementById('ws-link-style') === null) { const style = make('style'); style.id = 'ws-link-style'; style.textContent = CSS; document.head.append(style); }
|
|
179
|
+
linkStyle();
|
|
174
180
|
// the banner keeps the old strip's id, so the online proofs still find it
|
|
175
181
|
const banner = scope.ownNode(make('div', 'ws-link ws-link-banner')), head = make('b'), line = make('span');
|
|
176
182
|
banner.id = 'ws-reconnect-strip'; banner.setAttribute('role', 'status'); banner.hidden = true; banner.append(head, line);
|
|
@@ -11,8 +11,9 @@ const NEW_BUILD_BUTTON = 'min-height:44px;padding:8px 32px;border:1px solid #8fe
|
|
|
11
11
|
export function newBuildPanel(scope: Scope, again: () => Promise<boolean>, reload: () => void, parent: HTMLElement = document.body): void {
|
|
12
12
|
if (document.getElementById('ws-new-build') !== null) return;
|
|
13
13
|
const panel = scope.ownNode(document.createElement('div')), words = document.createElement('p'), go = document.createElement('button');
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
// FM5 mode 23 (`version-skew`): the page's build and the world's differ, and the one automatic reload didn't land
|
|
15
|
+
panel.id = 'ws-new-build'; panel.dataset['failmode'] = 'version-skew'; panel.setAttribute('role', 'alertdialog'); panel.style.cssText = NEW_BUILD;
|
|
16
|
+
words.textContent = 'A new version is out. Reload to play on.'; words.style.margin = '0';
|
|
16
17
|
go.type = 'button'; go.textContent = 'Reload'; go.style.cssText = NEW_BUILD_BUTTON;
|
|
17
18
|
// RL3: the panel is already full-page; the tap's own turn turns it and its button into RELOADING
|
|
18
19
|
scope.listen(go, 'click', () => { go.disabled = true; go.setAttribute('aria-busy', 'true'); go.textContent = 'Reloading…'; words.textContent = 'Reloading'; reload(); });
|
|
@@ -15,11 +15,32 @@ const importKey = async (publicKey: string): Promise<CryptoKey> => {
|
|
|
15
15
|
}
|
|
16
16
|
};
|
|
17
17
|
|
|
18
|
+
/** FM5: why a release read failed, as the page can measure it. A browser never says DNS or TLS, so `network` is all an opaque fetch
|
|
19
|
+
* failure is; `offline` is one the browser itself calls offline; `portal` is an answer that isn't the file (HTML, an unapproved redirect,
|
|
20
|
+
* malformed text), which could be a captive portal or a broken origin. */
|
|
21
|
+
export type ReleaseFault =
|
|
22
|
+
| { readonly kind: 'offline' } | { readonly kind: 'network' } | { readonly kind: 'timeout'; readonly ms: number }
|
|
23
|
+
| { readonly kind: 'status'; readonly status: number; readonly retryAfterMs: number | null }
|
|
24
|
+
| { readonly kind: 'portal'; readonly why: 'html' | 'redirect' | 'malformed' } | { readonly kind: 'unsigned' };
|
|
25
|
+
/** A failed release read and what failed. Its message keeps the technical words for Details; a player's screen never shows it raw. */
|
|
26
|
+
export class ReleaseReadError extends Error {
|
|
27
|
+
readonly fault: ReleaseFault;
|
|
28
|
+
constructor(message: string, fault: ReleaseFault, cause?: unknown) { super(message, cause === undefined ? undefined : { cause }); this.name = 'ReleaseReadError'; this.fault = fault; }
|
|
29
|
+
}
|
|
30
|
+
|
|
18
31
|
/** The file's text as what it says. It throws on a bad signature, and where a browser has no Ed25519. `publicKey` is SPKI DER in hex. */
|
|
19
32
|
export async function readSignedRelease(text: string, publicKey: string): Promise<ReleaseFile> {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
33
|
+
let signed: v.InferOutput<typeof SignedSchema>;
|
|
34
|
+
try { signed = v.parse(SignedSchema, JSON.parse(text)); } catch (error) { throw new ReleaseReadError('A release file that is not a signed file', { kind: 'portal', why: 'malformed' }, error); }
|
|
35
|
+
const key = await importKey(publicKey);
|
|
36
|
+
if (!await crypto.subtle.verify({ name: 'Ed25519' }, key, hexBytes(signed.signature), new TextEncoder().encode(signed.body))) throw new ReleaseReadError('A release file has a bad signature', { kind: 'unsigned' });
|
|
37
|
+
try { return v.parse(ReleaseSchema, JSON.parse(signed.body)); } catch (error) { throw new ReleaseReadError('A signed release file this page cannot read', { kind: 'portal', why: 'malformed' }, error); }
|
|
38
|
+
}
|
|
39
|
+
/** FM5 mode 12: a `Retry-After` of seconds or an HTTP date, in ms from `now`; anything else (or past 10 min) is no answer. */
|
|
40
|
+
export function retryAfterMs(header: string | null, now: number = Date.now()): number | null {
|
|
41
|
+
if (header === null) return null;
|
|
42
|
+
const text = header.trim(), ms = /^\d{1,6}$/u.test(text) ? Number(text) * 1000 : /[a-z]/iu.test(text) ? Date.parse(text) - now : Number.NaN;
|
|
43
|
+
return Number.isFinite(ms) && ms >= 0 && ms <= 600_000 ? Math.round(ms) : null;
|
|
23
44
|
}
|
|
24
45
|
/** FM5 (catalogue mode 11): a release read that has not answered, body and all, in 8 s has failed. */
|
|
25
46
|
export const RELEASE_DEADLINE_MS = 8000;
|
|
@@ -30,19 +51,24 @@ export const KEPT_RELEASE_MS: number = 7 * 24 * 60 * 60 * 1000;
|
|
|
30
51
|
export async function fetchSignedRelease(url: string, publicKey: string, deadlineMs: number = RELEASE_DEADLINE_MS, read: typeof fetch = fetch): Promise<ReleaseFile> {
|
|
31
52
|
return readSignedRelease(await fetchReleaseText(url, deadlineMs, read), publicKey);
|
|
32
53
|
}
|
|
33
|
-
|
|
54
|
+
const browserOnline = (): boolean => typeof navigator === 'undefined' || navigator.onLine;
|
|
55
|
+
async function fetchReleaseText(url: string, deadlineMs: number, read: typeof fetch, online: () => boolean = browserOnline): Promise<string> {
|
|
34
56
|
const abort = new AbortController(), scope = new Scope('online.release-read');
|
|
35
57
|
scope.timeout(deadlineMs, () => { abort.abort(); });
|
|
36
58
|
try {
|
|
37
59
|
const response = await read(url, { cache: 'no-store', signal: abort.signal });
|
|
38
|
-
if (!response.ok) throw new
|
|
39
|
-
|
|
60
|
+
if (!response.ok) throw new ReleaseReadError(`No release file at ${url}: ${String(response.status)}`, { kind: 'status', status: response.status, retryAfterMs: retryAfterMs(response.headers.get('retry-after')) });
|
|
61
|
+
// FM5 mode 38: an answer from somewhere else, or a page instead of the file, isn't the world's file; nothing in it is followed
|
|
62
|
+
if (response.redirected && response.url !== '' && new URL(response.url).origin !== new URL(url).origin) throw new ReleaseReadError(`The release read was sent to another address (${String(response.status)})`, { kind: 'portal', why: 'redirect' });
|
|
63
|
+
const text = await response.text();
|
|
64
|
+
if (/html/iu.test(response.headers.get('content-type') ?? '') || /^\s*</u.test(text)) throw new ReleaseReadError(`A page instead of the release file (${response.headers.get('content-type') ?? 'no type'})`, { kind: 'portal', why: 'html' });
|
|
65
|
+
return text;
|
|
40
66
|
} catch (error) {
|
|
41
|
-
if (
|
|
42
|
-
throw error;
|
|
67
|
+
if (error instanceof ReleaseReadError) throw error;
|
|
68
|
+
if (abort.signal.aborted) throw new ReleaseReadError(`No release file at ${url} in ${String(deadlineMs)} ms`, { kind: 'timeout', ms: deadlineMs }, error);
|
|
69
|
+
throw new ReleaseReadError(error instanceof Error ? error.message : String(error), online() ? { kind: 'network' } : { kind: 'offline' }, error);
|
|
43
70
|
} finally { scope.dispose(); }
|
|
44
71
|
}
|
|
45
|
-
|
|
46
72
|
/** OF4: the last release file a page read and believed: which release, when, and its text as signed. */
|
|
47
73
|
export interface KeptRelease { readonly of: string; readonly at: number; readonly text: string }
|
|
48
74
|
export interface ReleaseKeep { readonly read: () => KeptRelease | null; readonly write: (kept: KeptRelease) => void }
|
|
@@ -58,17 +84,62 @@ export async function keptRelease(url: string, publicKey: string, keep: ReleaseK
|
|
|
58
84
|
|
|
59
85
|
/** What a page dials from: the file, and when that was the kept copy, the fresh read still under way (null if it fails). */
|
|
60
86
|
export interface ReleaseToDial { readonly file: ReleaseFile; readonly fresh: Promise<ReleaseFile | null> | null }
|
|
87
|
+
|
|
88
|
+
/** FM5: the screen a failed read with no kept copy shows (meta MMO-FAILURE-MODES-PLAN modes 1, 11, 12, 37 to 39). */
|
|
89
|
+
export type ReleaseScreen = 'offline-launch' | 'release-5xx' | 'release-429' | 'release-404' | 'captive-portal' | 'release-unsigned';
|
|
90
|
+
export function releaseScreen(fault: ReleaseFault): ReleaseScreen {
|
|
91
|
+
if (fault.kind === 'offline') return 'offline-launch';
|
|
92
|
+
if (fault.kind === 'portal') return 'captive-portal';
|
|
93
|
+
if (fault.kind === 'unsigned') return 'release-unsigned';
|
|
94
|
+
if (fault.kind === 'status' && fault.status === 429) return 'release-429';
|
|
95
|
+
if (fault.kind === 'status' && fault.status === 404) return 'release-404';
|
|
96
|
+
return 'release-5xx';
|
|
97
|
+
}
|
|
98
|
+
/** Mode 11's ladder: 2, 4, 8, 16 s, then every 30 s. */
|
|
99
|
+
const LADDER_MS: readonly number[] = [2000, 4000, 8000, 16_000], LADDER_END_MS = 30_000;
|
|
100
|
+
/** Mode 12: a 429 with no readable Retry-After waits this long first. Mode 37: a 404 is read again each minute. */
|
|
101
|
+
const BUSY_MS = 20_000, MISSING_MS = 60_000;
|
|
102
|
+
/** FM5's retry policy: how long after the `attempt`th failed read (from 0) the page reads again by itself, or null when only the player
|
|
103
|
+
* (Try again), the network coming back or the page coming into view reads again: offline, a captive portal, a file that fails its
|
|
104
|
+
* signature (no retry loop on a file we can't verify). */
|
|
105
|
+
export function releaseRetryMs(fault: ReleaseFault, attempt: number): number | null {
|
|
106
|
+
const ladder = LADDER_MS[attempt] ?? LADDER_END_MS;
|
|
107
|
+
if (fault.kind === 'offline' || fault.kind === 'portal' || fault.kind === 'unsigned') return null;
|
|
108
|
+
if (fault.kind !== 'status') return ladder;
|
|
109
|
+
// a Retry-After of 0 is no licence to loop: never sooner than the ladder's first step, and never sooner than the first refusal's wait
|
|
110
|
+
if (fault.status === 429) return Math.max(fault.retryAfterMs ?? BUSY_MS, LADDER_MS[0] ?? 2000, fault.retryAfterMs === null ? ladder : 0);
|
|
111
|
+
return fault.status === 404 ? MISSING_MS : ladder;
|
|
112
|
+
}
|
|
113
|
+
/** FM5: what a page shows while it has no release file to dial from. `after` shows the fault and settles when the page should read again
|
|
114
|
+
* (the policy's wait, Try again, the network back); it rejects when the player leaves. `done` closes whatever it showed. */
|
|
115
|
+
export interface ReleaseWait {
|
|
116
|
+
readonly after: (fault: ReleaseFault, attempt: number, retryMs: number | null, detail: string) => Promise<void>;
|
|
117
|
+
readonly done: () => void;
|
|
118
|
+
}
|
|
119
|
+
|
|
61
120
|
/** OF4: the release file a page dials from. A verified kept copy answers at once, so a load never waits on the read; the fresh read
|
|
62
|
-
* replaces it once its own signature holds. With no copy the page waits for the read (8 s at most), and a failed read throws
|
|
63
|
-
|
|
121
|
+
* replaces it once its own signature holds. With no copy the page waits for the read (8 s at most each), and a failed read throws, or,
|
|
122
|
+
* given `wait` (FM5), shows why and reads again by its policy until a verified file answers or the player leaves. */
|
|
123
|
+
export async function releaseToDial(url: string, publicKey: string, ports: { readonly keep: ReleaseKeep; readonly fetch?: typeof fetch; readonly now?: () => number; readonly deadlineMs?: number; readonly wait?: ReleaseWait; readonly online?: () => boolean }): Promise<ReleaseToDial> {
|
|
64
124
|
const now = ports.now ?? Date.now, kept = await keptRelease(url, publicKey, ports.keep, now());
|
|
65
|
-
const reading =
|
|
66
|
-
const text = await fetchReleaseText(url, ports.deadlineMs ?? RELEASE_DEADLINE_MS, ports.fetch ?? fetch), file = await readSignedRelease(text, publicKey);
|
|
125
|
+
const reading = async (): Promise<ReleaseFile> => {
|
|
126
|
+
const text = await fetchReleaseText(url, ports.deadlineMs ?? RELEASE_DEADLINE_MS, ports.fetch ?? fetch, ports.online), file = await readSignedRelease(text, publicKey);
|
|
67
127
|
// a release only moves forward (J179, the server's own rule in releaseFile.ts): an older signed file never replaces the kept one
|
|
68
128
|
if (kept !== null && file.serial < kept.serial) throw new Error(`A release file older than the kept one (${String(file.serial)} < ${String(kept.serial)})`);
|
|
69
129
|
try { ports.keep.write({ of: url, at: now(), text }); } catch { /* a page that can keep nothing reads again next time */ }
|
|
70
130
|
return file;
|
|
71
|
-
}
|
|
72
|
-
if (kept
|
|
73
|
-
|
|
131
|
+
};
|
|
132
|
+
if (kept !== null) return { file: kept, fresh: reading().catch(() => null) };
|
|
133
|
+
const { wait } = ports;
|
|
134
|
+
if (wait === undefined) return { file: await reading(), fresh: null };
|
|
135
|
+
for (let attempt = 0; ; attempt++) {
|
|
136
|
+
try {
|
|
137
|
+
const file = await reading();
|
|
138
|
+
wait.done();
|
|
139
|
+
return { file, fresh: null };
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (!(error instanceof ReleaseReadError)) { wait.done(); throw error; }
|
|
142
|
+
await wait.after(error.fault, attempt, releaseRetryMs(error.fault, attempt), error.message);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
74
145
|
}
|