Bound recording loading, terminal allocation, markers and upload JSON complexity

This commit is contained in:
2026-10-15 10:13:55 +08:00
parent ffff9704e5
commit 92de7f86f4
24 changed files with 1831 additions and 115 deletions
+118
View File
@@ -0,0 +1,118 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { recordingErrorMessage } from '../../src/recording-errors.js';
// Front-end lifecycle contract with the real bounded loader and a minimal DOM.
// Actual vendor playback/iframe rendering is covered by WordPress Playwright.
globalThis.document = { readyState: 'loading', addEventListener() {} };
const { mountPlayers } = await import('../../src/view.js');
delete globalThis.document;
function setup({ preload = false, fetchImpl, options = {} } = {}) {
const notices = [];
const calls = [];
let observer;
const ownerDocument = {
body: { classList: { contains: () => false } }, documentElement: {},
querySelector: () => null,
createElement: () => ({ setAttribute() {} }),
defaultView: {
AbortController, fetch: fetchImpl, setInterval, clearInterval,
MutationObserver: class {
constructor(callback) { observer = this; this.callback = callback; }
observe() {} disconnect() { this.disconnected = true; }
},
AsciinemaPlayer: { create(source, container, options) {
const listeners = {};
const player = { dispose() { this.disposed = true; }, getDuration: () => undefined,
addEventListener(name, callback) { listeners[name] = callback; } };
calls.push({ source, container, options, player, listeners });
return player;
} },
},
};
const container = { ownerDocument, isConnected: true,
dataset: { apSrc: '/demo.cast', apOptions: JSON.stringify({ preload, ...options }) },
querySelector: () => notices[0], appendChild: (notice) => notices.push(notice),
};
const root = { ownerDocument, querySelectorAll: () => [container] };
return { root, calls, container, notices, remove() {
container.isConnected = false;
observer.callback([{ removedNodes: [container] }]);
assert.equal(observer.disconnected, true);
} };
}
const cast = '{"version":2,"width":80,"height":24}\n[0,"o","hello"]\n';
test('public preload=false stays lazy, loads parsed data once and owns one instance', async () => {
let requests = 0;
const fixture = setup({ fetchImpl: async (_url, options) => {
requests++;
assert.equal(options.credentials, 'same-origin');
return new Response(cast);
} });
mountPlayers(fixture.root);
mountPlayers(fixture.root);
assert.equal(fixture.calls.length, 1);
assert.equal(requests, 0);
assert.equal(fixture.container.dataset.apStatus, 'idle');
const data = await fixture.calls[0].source.data();
assert.equal(requests, 1);
assert.equal(data[0].version, 2);
assert.equal(data[1][2], 'hello');
fixture.calls[0].listeners.playing();
assert.equal(fixture.container.dataset.apStatus, 'ready');
fixture.remove();
assert.equal(fixture.calls[0].player.disposed, true);
});
test('removing a public player aborts the in-flight fetch and keeps cancellation quiet', async () => {
let signal;
const fixture = setup({ fetchImpl: (_url, options) => {
signal = options.signal;
return new Promise(() => {});
} });
mountPlayers(fixture.root);
const pending = fixture.calls[0].source.data();
await new Promise(resolve => setImmediate(resolve));
fixture.remove();
assert.equal(signal.aborted, true);
await assert.rejects(pending, { code: 'aborted' });
fixture.calls[0].listeners.error();
assert.equal(fixture.notices.length, 0);
});
test('validation errors remain specific when the upstream player emits a generic error', async () => {
const fixture = setup({ fetchImpl: async () => new Response('{"version":2,"width":1001,"height":24}\n') });
mountPlayers(fixture.root);
await assert.rejects(fixture.calls[0].source.data(), { code: 'dimensions' });
fixture.calls[0].listeners.error();
fixture.calls[0].listeners.playing();
assert.equal(fixture.container.dataset.apStatus, 'error');
assert.equal(fixture.notices.length, 1);
assert.match(fixture.notices[0].textContent, /terminal dimensions/);
fixture.remove();
});
test('error messages are localized fixed copy; cancellation never leaks an exception', () => {
assert.equal(recordingErrorMessage({ code: 'aborted', message: '<secret>' }), '');
for (const code of ['bytes', 'line', 'events', 'markers', 'dimensions', 'cells', 'complexity', 'time', 'timeout', 'network', 'stream', 'policy', 'invalid']) {
const message = recordingErrorMessage({ code, message: '<secret>' });
assert.ok(message.length > 10);
assert.ok(!message.includes('<secret>'));
}
assert.match(recordingErrorMessage(null, { frontend: true }), /terminal recording/);
});
test('public initial terminal grid is bounded before create even with preload disabled', () => {
for (const preload of [false, true]) {
let requests = 0;
const fixture = setup({ preload, options: { cols: 1000, rows: 1000 }, fetchImpl: () => { requests++; } });
mountPlayers(fixture.root);
assert.equal(fixture.calls.length, 0);
assert.equal(requests, 0);
assert.equal(fixture.container.dataset.apStatus, 'error');
assert.match(fixture.notices[0].textContent, /terminal cells/);
}
});
+116
View File
@@ -0,0 +1,116 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { transformSync } from '@babel/core';
import * as options from '../../src/options.js';
import * as errors from '../../src/recording-errors.js';
import * as loader from '../../src/recording-loader.js';
const compiled = transformSync(fs.readFileSync(new URL('../../src/preview.js', import.meta.url), 'utf8'), {
configFile: false, babelrc: false,
presets: [['@babel/preset-react', { pragma: 'element' }]],
plugins: ['@babel/plugin-transform-modules-commonjs'],
}).code;
const flush = () => new Promise(resolve => setImmediate(resolve));
function harness(attributes = {}) {
let effect;
let resolveAssets;
const assets = new Promise(resolve => { resolveAssets = resolve; });
const updates = [];
const sizes = [];
const calls = [];
const timers = new Map();
let nextTimer = 0;
const window = { AbortController,
setTimeout(callback) { timers.set(++nextTimer, callback); return nextTimer; },
clearTimeout(id) { timers.delete(id); }, setInterval: () => 0, clearInterval() {},
fetch: async () => new Response('{"version":2,"width":80,"height":24}\n[0,"o","ok"]\n'),
};
const container = { ownerDocument: { defaultView: window }, replaceChildren() {} };
const api = { create(source) {
const player = { addEventListener() {}, getDuration: () => undefined,
dispose() { this.disposed = true; } };
calls.push({ source, player });
return player;
} };
const modules = {
'@wordpress/components': {}, '@wordpress/compose': { useRefEffect(callback) { effect = callback; } },
'@wordpress/element': { useRef: value => ({ current: value }), useState: value => [value, update => updates.push(update)] },
'@wordpress/i18n': { __: value => value }, './options.js': options,
'./recording-errors.js': errors, './recording-loader.js': loader,
'./player-bridge.js': { playerAssets: () => ({}), playerForDocument: () => assets },
};
const module = { exports: {} };
new Function('require', 'module', 'exports', 'element', compiled)(name => {
assert.ok(Object.hasOwn(modules, name), `Unexpected module ${name}`);
return modules[name];
}, module, module.exports, () => null);
module.exports.default({ source: '/original.cast', attributes, attempt: 0, onRecordingSize: (...args) => sizes.push(args) });
const cleanup = effect(container);
return { cleanup, updates, sizes, calls, timers, window, resolveAssets: () => resolveAssets(api) };
}
test('unmount while player assets load never creates a player or stale state', async () => {
const h = harness();
h.cleanup();
const count = h.updates.length;
h.resolveAssets();
await flush();
assert.equal(h.calls.length, 0);
assert.equal(h.updates.length, count);
assert.equal(h.timers.size, 0);
});
test('asset startup deadline cannot create a late player after showing an error', async () => {
const h = harness();
[...h.timers.values()][0]();
assert.equal(h.updates.at(-1), 'error');
h.resolveAssets();
await flush();
assert.equal(h.calls.length, 0);
h.cleanup();
});
test('unmount during a request aborts it without stale metadata or status', async () => {
const h = harness();
let signal;
h.window.fetch = (_source, init) => { signal = init.signal; return new Promise(() => {}); };
h.resolveAssets();
await flush();
const pending = h.calls[0].source.data();
await flush();
h.cleanup();
const count = h.updates.length;
await assert.rejects(pending, { code: 'aborted' });
assert.equal(signal.aborted, true);
assert.equal(h.calls[0].player.disposed, true);
assert.deepEqual(h.sizes, [['/original.cast', null]]);
assert.equal(h.updates.length, count);
});
test('preview reports original dimensions only after validated data finishes', async () => {
const h = harness();
h.resolveAssets();
await flush();
const data = await h.calls[0].source.data();
assert.equal(data[0].width, 80);
assert.deepEqual(h.sizes, [['/original.cast', null], ['/original.cast', { cols: 80, rows: 24 }]]);
h.cleanup();
});
test('preview rejects unsafe initial options before create or recording fetch', async () => {
for (const attributes of [{ cols: 1000, rows: 1000 }, { rows: 1000 }]) {
const h = harness(attributes);
let requests = 0;
h.window.fetch = () => { requests++; };
h.resolveAssets();
await flush();
assert.equal(h.calls.length, 0);
assert.equal(requests, 0);
assert.equal(h.updates.at(-1), 'error');
assert.match(h.updates.at(-2), /terminal cells/);
h.cleanup();
}
});
+281
View File
@@ -0,0 +1,281 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { loadRecording, DEFAULT_LIMITS, RecordingLoadError, validateInitialDimensions } from '../../src/recording-loader.js';
const encode = ( text ) => new TextEncoder().encode( text );
const h2 = { version: 2, width: 80, height: 24 };
const h3 = { version: 3, term: { cols: 80, rows: 24 } };
const cast = ( header = h2, events = [ [ 0, 'o', 'hello' ] ] ) => [ header, ...events ].map( JSON.stringify ).join( '\n' );
function fixture( text, { chunks, headers } = {} ) {
let reads = 0;
let canceled = false;
let released = false;
const parts = chunks || [ encode( text ) ];
const response = { ok: true, headers: new Headers( headers ), body: { getReader: () => ( {
read: async () => reads < parts.length ? { value: parts[ reads++ ], done: false } : { done: true },
cancel: () => { canceled = true; return Promise.resolve(); },
releaseLock: () => { released = true; },
} ) } };
const calls = [];
const fetchImpl = async ( ...args ) => { calls.push( args ); return response; };
return { fetchImpl, calls, get canceled() { return canceled; }, get released() { return released; } };
}
async function rejectCode( text, code, config = {}, responseOptions ) {
const input = fixture( text, responseOptions );
await assert.rejects( loadRecording( '/cast', { fetchImpl: input.fetchImpl, ...config } ), ( error ) => error instanceof RecordingLoadError && error.code === code );
assert.equal( input.canceled, true );
assert.equal( input.released, true );
}
test( 'single fetch returns validated v2 data and original metadata', async () => {
const input = fixture( cast() );
const metadata = [];
assert.deepEqual( await loadRecording( '/cast', { fetchImpl: input.fetchImpl, options: { cols: 100 }, onMetadata: ( value ) => metadata.push( value ) } ), [ h2, [ 0, 'o', 'hello' ] ] );
assert.deepEqual( metadata, [ { cols: 80, rows: 24 } ] );
assert.equal( input.calls.length, 1 );
assert.equal( input.calls[ 0 ][ 1 ].credentials, 'same-origin' );
assert.ok( input.calls[ 0 ][ 1 ].signal instanceof AbortSignal );
assert.equal( input.canceled, false );
assert.equal( input.released, true );
} );
test( 'stream boundaries preserve UTF-8, escapes, and CRLF', async () => {
const content = cast( h3, [ [ 0, 'o', '你好 🌱 " \\ \n' ], [ 1, 'x-custom', 'safe' ] ] ).replaceAll( '\n', '\r\n' );
const bytes = encode( content );
const input = fixture( '', { chunks: Array.from( bytes, ( byte ) => Uint8Array.of( byte ) ) } );
assert.deepEqual( await loadRecording( '/cast', { fetchImpl: input.fetchImpl } ), [ h3, [ 0, 'o', '你好 🌱 " \\ \n' ], [ 1, 'x-custom', 'safe' ] ] );
} );
test( 'blank, comment, and non-event lines retain upstream filtering semantics', async () => {
const content = `${ JSON.stringify( h3 ) }\n\n# comment\nignored\n [999999,"o","ignored"]\n[0,"o","ok"]\n`;
assert.deepEqual( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl } ), [ h3, [ 0, 'o', 'ok' ] ] );
} );
test( 'v1 compact, pretty, CRLF, and large single line are accepted as objects', async () => {
const header = { version: 1, width: 80, height: 24, stdout: [ [ 0.1, 'hello' ], [ 0.2, 'world' ] ] };
for ( const content of [ JSON.stringify( header ), JSON.stringify( header, null, 2 ), JSON.stringify( header, null, 2 ).replaceAll( '\n', '\r\n' ) ] ) {
assert.deepEqual( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl } ), header );
}
const large = { ...header, stdout: [ [ 0, 'x'.repeat( DEFAULT_LIMITS.lineBytes ) ] ] };
assert.deepEqual( await loadRecording( '/cast', { fetchImpl: fixture( JSON.stringify( large ) ).fetchImpl } ), large );
} );
test( 'normal 100000-frame v1 fits preparse allocation budgets', async () => {
const header = { version: 1, width: 80, height: 24, stdout: Array.from( { length: 100000 }, () => [ 0, '' ] ) };
const result = await loadRecording( '/cast', { fetchImpl: fixture( JSON.stringify( header ) ).fetchImpl } );
assert.equal( result.stdout.length, 100000 );
} );
test( 'zero header dimensions preserve default behavior and unknown metadata', async () => {
for ( const header of [ { ...h2, width: 0, height: 0 }, { version: 3, term: { cols: 0, rows: 0 } } ] ) {
let metadata = 'unset';
const result = await loadRecording( '/cast', { fetchImpl: fixture( cast( header ) ).fetchImpl, onMetadata: ( value ) => { metadata = value; } } );
assert.deepEqual( result[ 0 ], header );
assert.equal( metadata, null );
}
} );
test( 'actual received bytes reject oversized chunks despite missing or false Content-Length', async () => {
for ( const headers of [ {}, { 'Content-Length': '1' }, { 'Content-Length': 'not-a-number' } ] ) {
await rejectCode( cast(), 'bytes', { limits: { bytes: 10 } }, { headers } );
}
// An advertised size is not a replacement for measuring decoded bytes.
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( cast(), { headers: { 'Content-Length': '999999999' } } ).fetchImpl } ) ).length, 2 );
} );
test( 'line byte limit counts multibyte output and ignored lines', async () => {
await rejectCode( cast( h2, [ [ 0, 'o', '界'.repeat( 30 ) ] ] ), 'line', { limits: { lineBytes: 80 } } );
await rejectCode( `${ JSON.stringify( h2 ) }\n#${ 'x'.repeat( 81 ) }`, 'line', { limits: { lineBytes: 80 } } );
} );
test( 'v1 byte cap covers pretty documents and compact documents', async () => {
const header = { version: 1, width: 80, height: 24, stdout: [ [ 0, 'x'.repeat( 100 ) ] ] };
await rejectCode( JSON.stringify( header, null, 2 ), 'bytes', { limits: { v1Bytes: 100 } } );
await rejectCode( JSON.stringify( header ), 'line', { limits: { v1Bytes: 100 } } );
} );
test( 'depth, container, and token budgets run before parsing unknown metadata', async () => {
await rejectCode( cast( { ...h2, extra: [ [ [ [] ] ] ] } ), 'complexity', { limits: { depth: 4 } } );
await rejectCode( cast( { ...h2, extra: [ [], [], [] ] } ), 'complexity', { limits: { containers: 4 } } );
await rejectCode( cast( { ...h2, extra: [ 1, 2, 3, 4, 5 ] } ), 'complexity', { limits: { lineTokens: 10 } } );
} );
test( 'event and marker boundaries are inclusive', async () => {
const content = cast( h2, [ [ 0, 'm', 'one' ], [ 1, 'm', 'two' ] ] );
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl, limits: { markers: 2, events: 2 } } ) ).length, 3 );
await rejectCode( content, 'markers', { limits: { markers: 1 } } );
await rejectCode( content, 'events', { limits: { events: 1 } } );
await rejectCode( content, 'markers', { options: { markers: [ [ 0, 'external' ] ] }, limits: { markers: 2 } } );
} );
test( 'all dimensions, late resizes, raw cells and independent effective overrides are validated', async () => {
await rejectCode( cast( { ...h2, width: 1001 } ), 'dimensions', { options: { cols: 80 } } );
await rejectCode( cast( { ...h2, width: 1000, height: 1000 } ), 'cells', { options: { cols: 80, rows: 24 } } );
await rejectCode( cast( { ...h2, height: 100 } ), 'cells', { options: { cols: 1000 } } );
await rejectCode( cast(), 'cells', { options: { cols: 1000, rows: 1000 } } );
for ( const resize of [ '0x24', '80x0', '1001x24', '-1x24', '80x24oops' ] ) {
await rejectCode( cast( h2, [ [ 0, 'o', 'safe' ], [ 100, 'r', resize ] ] ), 'dimensions' );
}
await rejectCode( cast( h2, [ [ 100, 'r', '80x100' ] ] ), 'cells', { options: { cols: 1000 } } );
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( cast( { ...h2, width: 1000, height: 40 } ) ).fetchImpl } ) ).length, 2 );
} );
test( 'non-finite timestamps and cumulative time overflow are rejected', async () => {
await rejectCode( `${ JSON.stringify( h2 ) }\n[1e999,"o","x"]`, 'time' );
await rejectCode( cast( h2, [ [ -1, 'o', 'x' ] ] ), 'time' );
await rejectCode( cast( h3, [ [ 1e305, 'o', 'x' ], [ 1e305, 'o', 'x' ] ] ), 'time' );
await rejectCode( JSON.stringify( { version: 1, width: 80, height: 24, stdout: [ [ 1e305, 'x' ], [ 1e305, 'x' ] ] } ), 'time' );
} );
test( 'invalid records do not report metadata', async () => {
for ( const content of [ '', '{}', cast( h2, [ [ 0, 'o', {} ] ] ), cast( h2, [ [ 0, '', 'x' ] ] ), `${ JSON.stringify( h2 ) }\n[invalid` ] ) {
let notified = false;
await assert.rejects( loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl, onMetadata: () => { notified = true; } } ) );
assert.equal( notified, false );
}
} );
test( 'invalid UTF-8 cannot be repaired across a newline', async () => {
await rejectCode( '', 'invalid', {}, { chunks: [ encode( `${ JSON.stringify( h2 ) }\n` ), Uint8Array.of( 0xe2, 10, 0x82, 0xac ) ] } );
} );
test( 'untrusted prototype-shaped metadata remains inert', async () => {
const header = JSON.parse( '{"version":2,"width":80,"height":24,"__proto__":{"polluted":true},"constructor":{"prototype":{"polluted":true}}}' );
const result = await loadRecording( '/cast', { fetchImpl: fixture( cast( header ) ).fetchImpl } );
assert.equal( {}.polluted, undefined );
assert.equal( Object.getPrototypeOf( result[ 0 ] ), Object.prototype );
assert.equal( Object.hasOwn( result[ 0 ], '__proto__' ), true );
} );
test( 'pre-abort never fetches', async () => {
const controller = new AbortController();
controller.abort();
const input = fixture( cast() );
await assert.rejects( loadRecording( '/cast', { fetchImpl: input.fetchImpl, signal: controller.signal } ), { code: 'aborted' } );
assert.equal( input.calls.length, 0 );
} );
test( 'abort and idle timeout interrupt stalled reads even when cancellation stalls', async () => {
for ( const explicitAbort of [ true, false ] ) {
const controller = new AbortController();
let canceled = false;
let fetchSignal;
const fetchImpl = async ( _, config ) => {
fetchSignal = config.signal;
return { ok: true, body: { getReader: () => ( { read: () => new Promise( () => {} ), cancel: () => { canceled = true; return new Promise( () => {} ); }, releaseLock() {} } ) } };
};
const promise = loadRecording( '/cast', { fetchImpl, signal: controller.signal, limits: { idleTimeoutMs: explicitAbort ? 1000 : 10 } } );
if ( explicitAbort ) setTimeout( () => controller.abort(), 5 );
await assert.rejects( promise, { code: explicitAbort ? 'aborted' : 'timeout' } );
assert.equal( canceled, true );
assert.equal( fetchSignal.aborted, true );
}
} );
test( 'total deadline interrupts an indefinitely pending fetch', async () => {
await assert.rejects( loadRecording( '/cast', { fetchImpl: () => new Promise( () => {} ), limits: { totalTimeoutMs: 10, idleTimeoutMs: 1000 } } ), { code: 'timeout' } );
} );
test( 'unsupported streaming and network failures use stable codes', async () => {
await assert.rejects( loadRecording( '/cast', { fetchImpl: async () => ( { ok: true } ) } ), { code: 'stream' } );
await assert.rejects( loadRecording( '/cast', { fetchImpl: async () => ( { ok: false } ) } ), { code: 'network' } );
await assert.rejects( loadRecording( '/cast', { fetchImpl: async () => { throw new TypeError( 'Failed to fetch' ); } } ), { code: 'network' } );
} );
test( 'ignored JSONL lines count toward the processing budget', async () => {
await rejectCode( `${ JSON.stringify( h2 ) }\n\n#comment\n[0,"o","x"]`, 'events', { limits: { lines: 2 } } );
} );
test( 'one-byte-over boundaries and exact boundaries use actual body bytes', async () => {
const content = cast();
const bytes = encode( content ).byteLength;
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl, limits: { bytes } } ) ).length, 2 );
await rejectCode( content, 'bytes', { limits: { bytes: bytes - 1 } } );
const first = encode( content.slice( 0, 10 ) );
const rest = encode( content.slice( 10 ) );
await rejectCode( '', 'bytes', { limits: { bytes: bytes - 1 } }, { chunks: [ first, rest ] } );
} );
test( 'v1 allocation budgets count scalar tokens separately from containers', async () => {
const content = JSON.stringify( { version: 1, width: 80, height: 24, stdout: [ [ 0, '' ] ] } );
// Seven header scalar/key tokens, plus stdout key, then two frame scalars.
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl, limits: { tokens: 9, containers: 3 } } ) ).stdout.length, 1 );
await rejectCode( content, 'complexity', { limits: { tokens: 8 } } );
await rejectCode( content, 'complexity', { limits: { containers: 2 } } );
} );
test( 'total deadline also bounds continuously resolved reads', async () => {
let canceled = false;
const fetchImpl = async () => ( { ok: true, body: { getReader: () => ( {
read: async () => ( { value: new Uint8Array(), done: false } ),
cancel: async () => { canceled = true; }, releaseLock() {},
} ) } } );
await assert.rejects( loadRecording( '/cast', { fetchImpl, limits: { totalTimeoutMs: 10, idleTimeoutMs: 1000 } } ), { code: 'timeout' } );
assert.equal( canceled, true );
} );
test( 'initial BOM is removed but later BOM-prefixed lines remain ignored', async () => {
const content = `\ufeff${ JSON.stringify( h2 ) }\n\ufeff[0,"o","ignored"]\n[1,"o","ok"]`;
const input = fixture( '', { chunks: Array.from( encode( content ), ( byte ) => Uint8Array.of( byte ) ) } );
assert.deepEqual( await loadRecording( '/cast', { fetchImpl: input.fetchImpl } ), [ h2, [ 1, 'o', 'ok' ] ] );
} );
test( 'v2 absolute timestamps cannot move backward; equal timestamps remain valid', async () => {
await rejectCode( cast( h2, [ [ 2, 'o', 'x' ], [ 1, 'o', 'y' ] ] ), 'time' );
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( cast( h2, [ [ 1, 'o', 'x' ], [ 1, 'o', 'y' ] ] ) ).fetchImpl } ) ).length, 3 );
} );
test( 'JSONL line budget includes newline bytes like the upload validator', async () => {
const headerLine = JSON.stringify( h2 );
await rejectCode( `${ headerLine }\n`, 'line', { limits: { lineBytes: encode( headerLine ).length } } );
} );
test( 'v2 header complexity is rejected before allocating the header JSON tree', async () => {
const content = cast( { ...h2, extra: Array( 40 ).fill( 1 ) } );
const original = JSON.parse;
let treeParses = 0;
JSON.parse = ( text, ...args ) => {
if ( text.startsWith( '{' ) ) treeParses++;
return original( text, ...args );
};
try {
await rejectCode( content, 'complexity', { limits: { lineTokens: 20 } } );
assert.equal( treeParses, 0 );
} finally { JSON.parse = original; }
} );
test( 'version sniffing honors escaped keys, nesting and last duplicate value', async () => {
const v1 = '{"stdout":[[0,"ok"]],"nested":{"version":2},"width":80,"height":24,"vers\\u0069on":1}';
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( v1 ).fetchImpl } ) ).version, 1 );
const v2 = '{"version":1,"width":80,"height":24,"extra":[1,2,3,4,5,6,7,8,9,10],"version":2}';
await rejectCode( v2, 'complexity', { limits: { lineTokens: 15 } } );
} );
test( 'initial options are validated synchronously before the player can allocate a terminal', () => {
assert.doesNotThrow( () => validateInitialDimensions() );
assert.doesNotThrow( () => validateInitialDimensions( { cols: 1000, rows: 40 } ) );
assert.throws( () => validateInitialDimensions( { cols: 1000, rows: 1000 } ), { code: 'cells' } );
assert.throws( () => validateInitialDimensions( { rows: 1000 } ), { code: 'cells' } );
assert.throws( () => validateInitialDimensions( { cols: 1001 } ), { code: 'dimensions' } );
assert.throws( () => validateInitialDimensions( { cols: -1 } ), { code: 'dimensions' } );
assert.throws( () => validateInitialDimensions( { rows: NaN } ), { code: 'dimensions' } );
assert.throws( () => validateInitialDimensions( { cols: 0 } ), { code: 'dimensions' } );
} );
test( 'multiline v1 can put version after an allocation-heavy first member', async () => {
const frames = Array( 10001 ).fill( '[0,""]' ).join( ',' );
const content = `{"stdout":[${ frames }],\n"version":1,"width":80,"height":24}`;
const result = await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl } );
assert.equal( result.version, 1 );
assert.equal( result.stdout.length, 10001 );
} );
test( 'multiline v1 can put version after a first line larger than the JSONL cap', async () => {
const title = 'x'.repeat( DEFAULT_LIMITS.lineBytes );
const content = `{"title":"${ title }",\n"version":1,"width":80,"height":24,"stdout":[[0,""]]}`;
const result = await loadRecording( '/cast', { fetchImpl: fixture( content ).fetchImpl } );
assert.equal( result.version, 1 );
assert.equal( result.title.length, title.length );
} );