Files
feuerwerk/src/core/store/http.ts
T
adminandClaude Opus 5.5 bc688f3efc
game-maker / gate (push) Successful in 3m50s
game-maker / suite (push) Successful in 12m3s
Refactoring round 7: split BehaviorSystem, fewer copies (#85)
Recurring cleanup round over the code since round 6 (056a622), 105
commits. Behaviour is unchanged. Duplicated code in src went from 29
clones with 229 lines (0.32 %) to 14 clones with 109 lines (0.15 %),
measured with jscpd and the same settings as round 6.

- BehaviorSystem.ts shrinks from 941 to 589 lines. Collecting the
  pulses (keys, timers, collisions, animations) moved to
  behaviorPulses.ts. The NodeContext the nodes receive moved to
  behaviorContext.ts. Imports from outside stay the same, TimeScaled
  is still exported from BehaviorSystem.ts.
- PointKindButton and drawPointGrip replace the "Point:" button with
  its menu and the point and handle drawing that the curve and the
  vector art tab each had on their own.
- lerpVec, cubicAt and splitCubic in src/core/util/vec.ts replace four
  copies of the cubic curve and two de Casteljau splits.
- mapNested in Properties.ts is the one walk over lists and structs
  that liveObjects and objectRefs did separately. withFieldRenamed
  and withoutField replace three copies of renaming a struct field
  and two of removing one.
- jsonBody and staleRevision build the JSON body and turn a 409 into
  StaleRevisionError for all stores. The auth store turns a 401 into
  its error in one place.
- Smaller helpers: structAssetFrom for the two "Make struct type"
  commands, shownObject in the inspector, selectedItem for the size
  gizmo and the polygon corners, solidTiles in the tilemap collision,
  requireVariablesAsset and requireBehaviorVariable.
- Left as is on purpose: the plain forwarding from the collision and
  physics systems to Solids, the pointer wiring of the canvases and
  the identical last lines of the two make commands.
- Removed unused code: tilemapTileIds and tilemapsUsing were never
  called since #128 and #131. EditorState.runtimeProject became unused
  with GameRun in #266. The assetId getter of the make commands was
  read only by a test.
- 60 values used only in their own file lost their export. The shader
  and particle node catalogues stay exported as in round 6.
- Five comments that told history now describe the current state. The
  doc comment of BehaviorSystem sits on the class again.
- README lists the struct, clip area and curve assets and mentions the
  game link from #266.

Findings:
- Deleting a tile that is painted on a tilemap leaves its cells in
  place, and they draw nothing. The delete dialog does not mention the
  tilemaps. That was probably the job of the unused tilemapsUsing.
  Left as is, because fixing it changes behaviour.
- The solid filter for tile surfaces was untested. A bent filter
  stayed green. A new test in tests/core/surface.test.ts now fails
  against it.

Tests:
- ./check.sh: 195 files, 2815 tests, exit 0 (one test removed with
  tilemapsUsing, one added for tile surfaces).
- Full e2e run: ALL PASSED, 1580 checks.
- Smokes jumprun, tetris, actor: 24, 19 and 21 checks, all passed.
  The example project files were restored byte for byte afterwards.
- Counter-checks, 12, all fail as expected: 10 in unit tests (among
  them mapNested, splitCubic, cubicAt, staleRevision, the stay pulse,
  the late timer and the time scale), 2 in the browser (Point button
  always enabled fails 47, selectedItem without a hit fails 29).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:16:37 +02:00

73 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* A failed response does not always come from our API: nginx caps request bodies at 1 MB and
* answers a larger one with its own HTML page, so there is no `{error}` object to read.
*/
const STATUS_MESSAGES: Record<number, string> = {
400: 'Bad request',
403: 'Forbidden',
404: 'Not found',
413: 'Request too large',
500: 'Server error',
502: 'Server unavailable',
503: 'Server unavailable',
504: 'Server timed out',
};
function statusMessage(status: number, statusText: string): string {
return STATUS_MESSAGES[status] ?? (statusText || `HTTP ${status}`);
}
/** The request part of a JSON payload; nothing at all without one. */
export function jsonBody(payload?: unknown): Pick<RequestInit, 'headers' | 'body'> {
return payload === undefined
? {}
: { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) };
}
/**
* One call against the PHP API. Routing goes through the `r` query parameter because the site's
* nginx config does not pass PATH_INFO to PHP; `query` adds further parameters beside it, which is
* how an upload sends its file name while the body stays the raw bytes. An empty value is dropped
* rather than sent as `&name=`.
*
* `mapError` lets a store turn a particular status into its own error type before the generic
* one is thrown.
*/
export async function apiRequest<T>(
endpoint: string,
method: string,
route: string,
init: Pick<RequestInit, 'headers' | 'body'> & { query?: Record<string, string> } = {},
mapError?: (status: number, data: unknown) => Error | undefined,
): Promise<T> {
const { query, ...request } = init;
let url = `${endpoint}?r=${encodeURIComponent(route)}`;
for (const [key, value] of Object.entries(query ?? {})) {
if (value !== '') url += `&${key}=${encodeURIComponent(value)}`;
}
const response = await fetch(url, { method, ...request });
if (response.status === 204) return undefined as T;
const text = await response.text();
let data: unknown;
try {
data = text ? JSON.parse(text) : null;
} catch {
// A body nginx refused is an HTML page, so a failure is explained by its status rather than
// as "invalid JSON" – which would only be true of a *successful* response.
if (response.ok) throw new Error(`API ${method} ${route}: invalid JSON (${response.status})`);
data = null;
}
const mapped = mapError?.(response.status, data);
if (mapped) throw mapped;
if (!response.ok) {
const message =
(data as { error?: string } | null)?.error ?? statusMessage(response.status, response.statusText);
throw new Error(`API ${method} ${route}: ${message} (${response.status})`);
}
return data as T;
}