feedBack/tests/js/beats_loaded.test.js
Byron Gamatos 2281cac438
refactor(highway): lift 79 per-instance closure vars into hwState (R3c H lift) (#849)
* refactor(highway): lift 79 per-instance closure vars into `hwState` (R3c H lift)

Collapses createHighway()'s 79 mutable closure `let`s into one per-instance
`hwState` object. Scope-resolved rewrite via acorn + eslint-scope: 1059 edits
(1057 references + 79 defs - the deleted `let canvas, ctx, ws`), with the four
names shadowed in inner scopes (chartTime/ctx/notes/chordTemplates) resolved
correctly so only closure-bound refs move. Enables the later module split:
extracted renderer/ws modules close over `hwState` as a factory arg, so
multi-panel plugins (highway_3d, note_detect, splitscreen) don't share one
highway's state.

Container is `hwState`, NOT `H` — `H` is already canvas height (70 uses). The
frame-time gate caught that collision instantly (0 draws, `H._drawHooks is not
iterable` in the shared draw-hook path).

PERF (the whole risk): identical to the pre-lift baseline. Draw p50 2.1-2.2 ms,
p95 2.7-3.0 ms (pre-lift 2.7-3.2), measured on the Arcturus feedpak, headless.
Each closure-slot read became a `hwState.<slot>` monomorphic property load; the
hot loop pays nothing. On-device: Byron confirmed the 2D highway plays smoothly.

Tests: the ~30 highway JS suites brace-extract functions/patterns from the
source; their state references + the monotonic-clock vm sandbox now use
`hwState.<slot>` (the const _CHART_MAX_INTERP_MS etc. stay top-level, not
lifted). node --test: 1030/1030 green. Two self-inflicted over-replacements
caught and reverted (`_lefty` is a prefix of the 3D-local `_leftyCached`;
`STRING_COLORS` a suffix of `DEFAULT_STRING_COLORS`) — substring replaces on the
brace-extract regexes need word care.

Transformer saved at ~/.local/share/feedback-editor/highway-h-lift.mjs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(highway): pin the setNoteStateProvider assertion to hwState._noteStateProvider (CodeRabbit)

The [^}]* form matched an unqualified _noteStateProvider =, so a regression to
closure-level state could still pass. Require the hwState-qualified assignment.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 23:19:20 +02:00

80 lines
3.4 KiB
JavaScript

// Verify static/highway.js emits `beats:loaded` exactly once when the
// WebSocket delivers the song's beats array, with `{ count }` payload.
// Plugins that need to know when beats are available (metronome, beat-
// snapping editors, sync visualizers) consume this contract.
//
// Same isolation strategy as the other tests/js/ files — extract just
// the relevant case-block source by string matching and exercise it in
// a vm sandbox with stubbed deps.
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const HIGHWAY_JS = path.join(__dirname, '..', '..', 'static', 'highway.js');
// Extract a single switch case body so assertions can match against just
// that block rather than a fixed-length slice (more robust to harmless
// edits adjacent to the case).
function getCaseBlock(src, label) {
const start = src.indexOf(`case '${label}'`);
assert.ok(start !== -1, `case '${label}' not found in highway.js`);
const tail = src.slice(start);
const nextCase = tail.search(/\n\s*case\s+['"]/);
const nextDefault = tail.search(/\n\s*default\s*:/);
let end = tail.length;
if (nextCase > 0) end = Math.min(end, nextCase);
if (nextDefault > 0) end = Math.min(end, nextDefault);
return tail.slice(0, end);
}
test('beats:loaded emit is wired into the WS beats case', () => {
// Source-level guard: catch a future contributor removing the emit
// (regression) or replacing window.feedBack.emit with something
// else (intentional refactor — this test then needs updating).
const src = fs.readFileSync(HIGHWAY_JS, 'utf8');
const block = getCaseBlock(src, 'beats');
assert.match(
block,
/window\.feedBack\.emit\(\s*['"]beats:loaded['"]/,
'beats case must emit beats:loaded',
);
assert.match(
block,
/count:\s*hwState\.beats\.length/,
'beats:loaded payload must include count = beats.length',
);
});
test('beats:loaded emit is guarded against missing window.feedBack', () => {
// The WS handler can fire before the feedBack namespace is defined
// (early in app boot). The emit must be guarded so a missing
// namespace doesn't throw inside the WS message dispatcher.
// Looser pattern accepts any guard that reads window.feedBack
// (including typeof checks and combined conditions) rather than
// mandating the exact `if (window.feedBack)` form.
const src = fs.readFileSync(HIGHWAY_JS, 'utf8');
const block = getCaseBlock(src, 'beats');
assert.match(
block,
/if\s*\(\s*[^)]*window\.feedBack\b[^)]*\)/,
'beats:loaded emit must be guarded against a missing window.feedBack',
);
});
test('beats:loaded guard verifies emit is callable (typeof check)', () => {
// A partially-attached namespace (window.feedBack exists but emit
// isn't a function yet during early boot) would throw without this
// extra check. A truthy check (`window.feedBack.emit && ...`) lets
// non-callable values pass; require an explicit typeof === 'function'
// check so the guard catches that real edge.
const src = fs.readFileSync(HIGHWAY_JS, 'utf8');
const block = getCaseBlock(src, 'beats');
assert.match(
block,
/typeof\s+window\.feedBack\.emit\s*===\s*['"]function['"]/,
'guard must use typeof === \'function\' (not just truthy) to confirm emit is callable',
);
});