mirror of
https://github.com/LamGC/wp-asciiplayer.git
synced 2026-11-26 20:55:48 +00:00
Refresh wp-asciiplayer with native block editor playback (#36)
Build and WordPress integration / PHP 7.4 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / PHP 8.3 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / WordPress 6.3 / PHP 7.4 (push) Canceled after 0s
Build and WordPress integration / WordPress latest / PHP 8.2 (push) Canceled after 0s
Build and WordPress integration / PHP 7.4 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / PHP 8.3 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / WordPress 6.3 / PHP 7.4 (push) Canceled after 0s
Build and WordPress integration / WordPress latest / PHP 8.2 (push) Canceled after 0s
* Refresh player with native block editor preview and local assets Preserve shortcode rendering, normalize options, bundle the player locally, and add reproducible packaging and WordPress integration tests. * Fix emitted frontend boot and verify bundled runtime initialization * Record verified WordPress 7.1.3 compatibility * Use WordPress readme major-version compatibility format * Add responsive player layout, captions and native terminal sizing * Keep editor caption geometry stable during block selection * Respect WordPress editor gutters with border-box sizing * Improve automatic previews and toolbar terminal sizing (1.2.1) * Show native cast dimensions and add Media Library recordings (1.2.2) * Fix Media Library test storage and scope sidebar selectors * Document bounded temporary-upload stream exceptions * Move block explanations into collapsed sidebar help (1.2.3) * Add bundled English and Simplified Chinese UI translations (1.1.0-dev) * Use native RichText labels and supported Chinese HTML language tags in locale tests
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import gettext from 'gettext-parser';
|
||||
|
||||
const po = gettext.po.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN.po'));
|
||||
const mo = gettext.mo.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN.mo'));
|
||||
const pot = gettext.po.parse(fs.readFileSync('languages/wp-asciiplayer.pot'));
|
||||
const editor = JSON.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-editor.json')).locale_data.messages;
|
||||
const view = JSON.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-view.json')).locale_data.messages;
|
||||
|
||||
test('all extracted strings and gettext contexts round-trip through MO and both script catalogs', () => {
|
||||
let count = 0;
|
||||
for (const [context, entries] of Object.entries(pot.translations)) {
|
||||
for (const entry of Object.values(entries)) {
|
||||
if (!entry.msgid) continue;
|
||||
count++;
|
||||
const translated = po.translations[context][entry.msgid].msgstr;
|
||||
assert.ok(translated[0]);
|
||||
assert.deepEqual(mo.translations[context][entry.msgid].msgstr, translated);
|
||||
const key = context ? `${context}\u0004${entry.msgid}` : entry.msgid;
|
||||
assert.deepEqual(editor[key], translated);
|
||||
assert.deepEqual(view[key], translated);
|
||||
}
|
||||
}
|
||||
assert.ok(count >= 75);
|
||||
});
|
||||
|
||||
test('catalogs use Chinese plural rules, exact locale, and standard WordPress textdomain', () => {
|
||||
assert.equal(po.headers.language, 'zh_CN');
|
||||
assert.equal(mo.headers.language, 'zh_CN');
|
||||
assert.equal(editor[''].lang, 'zh_CN');
|
||||
assert.equal(editor[''].domain, 'wp-asciiplayer');
|
||||
assert.equal(editor['']['plural-forms'], 'nplurals=1; plural=0;');
|
||||
assert.equal(editor['block title\u0004Asciicast Player'][0], 'Asciicast 播放器');
|
||||
assert.equal(editor['Recording URL'][0], '录制文件 URL');
|
||||
});
|
||||
|
||||
test('Unicode, punctuation, percentages and literal author content are preserved', () => {
|
||||
assert.equal(editor['Add a caption…'][0], '添加说明文字…');
|
||||
assert.match(editor['Use a CSS length, such as 480px or 65%. The player stays within its available space.'][0], /480px.*65%/);
|
||||
assert.equal(editor['Author caption / 作者说明'], undefined);
|
||||
const serialized = JSON.stringify(editor);
|
||||
assert.deepEqual(JSON.parse(serialized), editor);
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { normalizeDisplayAlign, normalizePlayerOptions, terminalDimension, normalizeWidth } from '../../src/options.js';
|
||||
test('display placement and scaling never create terminal grid overrides', () => {
|
||||
for (const width of ['25%', '480px', '100%']) {
|
||||
const options = normalizePlayerOptions({ width, displayAlign: 'right', caption: 'Demo' });
|
||||
assert.equal(options.cols, undefined);
|
||||
assert.equal(options.rows, undefined);
|
||||
assert.equal(options.width, undefined);
|
||||
assert.equal(options.caption, undefined);
|
||||
}
|
||||
assert.equal(normalizeDisplayAlign('right'), 'right');
|
||||
assert.equal(normalizeDisplayAlign('unsafe'), 'center');
|
||||
assert.equal(normalizeWidth('480px'), '480px');
|
||||
assert.equal(normalizeWidth('480px;display:none'), '100%');
|
||||
});
|
||||
test('terminal overrides are optional bounded integers', () => {
|
||||
for (const value of ['', '0', '-1', '2.5', '1001', 'Infinity', null]) assert.equal(terminalDimension(value), undefined);
|
||||
assert.equal(terminalDimension('120'), 120);
|
||||
assert.equal(terminalDimension(1), 1);
|
||||
const options = normalizePlayerOptions({ cols: terminalDimension('120'), rows: terminalDimension('') });
|
||||
assert.equal(options.cols, 120);
|
||||
assert.equal(options.rows, undefined);
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { attributesFromShortcode, booleanValue, canTransformShortcode, finiteNumber, normalizeControls, normalizePlayerOptions, normalizeSource, normalizeWidth, previewHeight, secondsValue } from '../../src/options.js';
|
||||
|
||||
test( 'source validation permits explicit web URLs and site-relative cast paths', () => {
|
||||
for ( const value of [ 'https://example.com/recording.cast', 'http://localhost:8888/a.cast?x=1&y=2', '/uploads/hello.cast', "https://example.com/it's.cast" ] ) assert.equal( normalizeSource( ` ${ value } ` ), value );
|
||||
} );
|
||||
|
||||
test( 'source validation rejects executable, credentialed, ambiguous and malformed URLs', () => {
|
||||
for ( const value of [ '', '//evil.test/cast', '/\\evil.test/cast', 'javascript:alert(1)', 'data:text/plain,cast', 'blob:https://example.com/a', 'file:///tmp/a.cast', 'https://user:[email protected]/a.cast', 'https://example.com/\na.cast', 'https://example.com/<script>', 'relative.cast', {}, null ] ) assert.equal( normalizeSource( value ), '' );
|
||||
} );
|
||||
|
||||
test( 'source validation rejects a missing HTTP authority separator', () => {
|
||||
assert.equal( normalizeSource( 'https:example.com/a.cast' ), '' );
|
||||
} );
|
||||
|
||||
test( 'source validation rejects a single HTTP authority slash', () => {
|
||||
assert.equal( normalizeSource( 'https:/example.com/a.cast' ), '' );
|
||||
} );
|
||||
|
||||
test( 'source validation rejects an extra HTTP authority slash', () => {
|
||||
assert.equal( normalizeSource( 'https:///example.com/a.cast' ), '' );
|
||||
} );
|
||||
|
||||
test( 'string false options never become true through truthiness', () => {
|
||||
for ( const value of [ false, 0, 'false', '0', 'off', 'no', ' FALSE ' ] ) assert.equal( booleanValue( value, true ), false );
|
||||
for ( const value of [ true, 1, 'true', '1', 'on', 'yes' ] ) assert.equal( booleanValue( value ), true );
|
||||
assert.equal( booleanValue( 'wrong', null ), null );
|
||||
} );
|
||||
|
||||
test( 'controls convert editor choices to the actual player API types', () => {
|
||||
assert.equal( normalizeControls( 'always' ), true );
|
||||
assert.equal( normalizeControls( 'true' ), true );
|
||||
assert.equal( normalizeControls( 'never' ), false );
|
||||
assert.equal( normalizeControls( 'false' ), false );
|
||||
assert.equal( normalizeControls( 'auto' ), 'auto' );
|
||||
assert.equal( normalizeControls( 'unexpected' ), 'auto' );
|
||||
} );
|
||||
|
||||
test( 'numeric validation rejects non-finite, empty and boolean values', () => {
|
||||
for ( const value of [ Infinity, NaN, '', ' ', {}, null, true, '-1', '101', '0x10', '0b10' ] ) assert.equal( finiteNumber( value, 5, 0, 100 ), 5 );
|
||||
assert.equal( finiteNumber( '0', 5 ), 0 );
|
||||
assert.equal( finiteNumber( '1.5', 5 ), 1.5 );
|
||||
} );
|
||||
|
||||
test( 'timecodes match the PHP supported syntax and preserve zero', () => {
|
||||
assert.equal( secondsValue( '1:02:03.5' ), 3723.5 );
|
||||
assert.equal( secondsValue( '2:03.5' ), 123.5 );
|
||||
assert.equal( secondsValue( ' 2:03 ' ), 123 );
|
||||
for ( const value of [ '1:99', '1:90:00', '1:2:3:4', -1, null ] ) assert.equal( secondsValue( value ), 0 );
|
||||
} );
|
||||
|
||||
test( 'preview forces only its own preload and autoplay settings', () => {
|
||||
const attributes = { autoPlay: true, preload: false, speed: 2, controls: 'always', loop: true };
|
||||
const saved = normalizePlayerOptions( attributes );
|
||||
const preview = normalizePlayerOptions( attributes, { preview: true } );
|
||||
assert.equal( saved.autoPlay, true );
|
||||
assert.equal( saved.preload, false );
|
||||
assert.equal( preview.autoPlay, false );
|
||||
assert.equal( preview.preload, true );
|
||||
assert.equal( preview.speed, 2 );
|
||||
assert.equal( preview.controls, true );
|
||||
assert.equal( attributes.autoPlay, true );
|
||||
} );
|
||||
|
||||
test( 'zero idle limit omits the override and finite legacy loops survive playback', () => {
|
||||
assert.equal( Object.hasOwn( normalizePlayerOptions( { idleTimeLimit: 0 } ), 'idleTimeLimit' ), false );
|
||||
assert.equal( normalizePlayerOptions( { idleTimeLimit: 2 } ).idleTimeLimit, 2 );
|
||||
assert.equal( normalizePlayerOptions( { loop: 3 } ).loop, 3 );
|
||||
assert.equal( normalizePlayerOptions( { fit: false } ).fit, 'none' );
|
||||
} );
|
||||
|
||||
test( 'optional dimensions, fonts and posters are validated consistently', () => {
|
||||
const options = normalizePlayerOptions( { cols: 120, rows: 35, terminalLineHeight: 0.1, terminalFontFamily: '"Fira Code", monospace', terminalFontSize: '1.2rem', poster: 'npt:2:03' } );
|
||||
assert.equal( options.cols, 120 );
|
||||
assert.equal( options.rows, 35 );
|
||||
assert.equal( options.terminalLineHeight, 0.1 );
|
||||
assert.equal( options.terminalFontSize, '1.2rem' );
|
||||
assert.equal( options.poster, 'npt:2:03' );
|
||||
const invalid = normalizePlayerOptions( { cols: 1.5, rows: 1001, terminalLineHeight: 11, terminalFontFamily: 'x; color:red', terminalFontSize: 'url(https://evil.test)', poster: 'https://evil.test/poster' } );
|
||||
for ( const key of [ 'cols', 'rows', 'terminalLineHeight', 'terminalFontFamily', 'terminalFontSize', 'poster' ] ) assert.equal( Object.hasOwn( invalid, key ), false );
|
||||
} );
|
||||
|
||||
test( 'width accepts safe CSS lengths only', () => {
|
||||
for ( const value of [ '0', '80%', '640px', '.5rem', '80vw', '30ch' ] ) assert.equal( normalizeWidth( value ), value );
|
||||
for ( const value of [ 'calc(100% - 1px)', '80%;color:red', 'expression(alert(1))', 'auto', null ] ) assert.equal( normalizeWidth( value ), '100%' );
|
||||
} );
|
||||
|
||||
test( 'legacy height fitting gets a usable preview without changing saved styles', () => {
|
||||
assert.equal( previewHeight( { fit: 'width' } ), undefined );
|
||||
assert.equal( previewHeight( { fit: 'height' } ), '320px' );
|
||||
assert.equal( previewHeight( { fit: 'both', legacyStyle: 'width:80%; height:400px;' } ), '400px' );
|
||||
assert.equal( previewHeight( { fit: 'height', legacyStyle: 'height:expression(alert(1))' } ), '320px' );
|
||||
} );
|
||||
|
||||
test( 'shortcode conversion maps lowercased legacy names and typed booleans', () => {
|
||||
const attrs = attributesFromShortcode( { controls: 'false', autoplay: 'true', preload: 'false', startat: '1:23', idletimelimit: '2', fontsize: 'small', fit: 'false', style: 'width: 80%; height: 300px;' }, 'https://example.com/test.cast' );
|
||||
assert.equal( attrs.source, 'https://example.com/test.cast' );
|
||||
assert.equal( attrs.controls, 'never' );
|
||||
assert.equal( attrs.autoPlay, true );
|
||||
assert.equal( attrs.preload, false );
|
||||
assert.equal( attrs.startAt, 83 );
|
||||
assert.equal( attrs.idleTimeLimit, 2 );
|
||||
assert.equal( attrs.terminalFontSize, 'small' );
|
||||
assert.equal( attrs.fit, 'none' );
|
||||
assert.equal( attrs.width, '80%' );
|
||||
assert.equal( attrs.legacyStyle, 'width: 80%; height: 300px;' );
|
||||
} );
|
||||
|
||||
test( 'shortcode conversion normalizes legacy option case and whitespace like PHP', () => {
|
||||
const attrs = attributesFromShortcode( { fit: ' HEIGHT ', fontsize: ' 15PX ', fontfamily: ' "Fira Code", monospace ' }, '/example.cast' );
|
||||
assert.equal( attrs.fit, 'height' );
|
||||
assert.equal( attrs.terminalFontSize, '15px' );
|
||||
assert.equal( attrs.terminalFontFamily, '"Fira Code", monospace' );
|
||||
} );
|
||||
|
||||
test( 'lossy transforms are refused, so unsupported legacy shortcodes remain untouched', () => {
|
||||
assert.equal( canTransformShortcode( { named: { loop: '2' } } ), false );
|
||||
assert.equal( canTransformShortcode( { named: { customOption: 'x' } } ), false );
|
||||
assert.equal( canTransformShortcode( { named: { style: 'width:calc(100% - 1px)' } } ), false );
|
||||
assert.equal( canTransformShortcode( { named: {}, numeric: [ 'unexpected' ] } ), false );
|
||||
assert.equal( canTransformShortcode( { named: { loop: 'true', controls: 'false', style: 'width:80%;height:300px' } } ), true );
|
||||
} );
|
||||
@@ -0,0 +1,115 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { playerForDocument } from '../../src/player-bridge.js';
|
||||
|
||||
const assets = { script: 'https://site.test/player.js', style: 'https://site.test/player.css' };
|
||||
const flush = () => new Promise( ( resolve ) => setImmediate( resolve ) );
|
||||
|
||||
function fakeDocument() {
|
||||
const nodes = [];
|
||||
const document = {
|
||||
defaultView: { setTimeout, clearTimeout },
|
||||
head: { appendChild( node ) { nodes.push( node ); } },
|
||||
get scripts() { return nodes.filter( ( node ) => node.tag === 'script' ); },
|
||||
querySelectorAll() { return nodes.filter( ( node ) => node.tag === 'link' ); },
|
||||
createElement( tag ) {
|
||||
const events = new Map();
|
||||
return {
|
||||
tag, dataset: {},
|
||||
addEventListener( name, callback ) { events.set( name, callback ); },
|
||||
removeEventListener( name ) { events.delete( name ); },
|
||||
dispatch( name ) { events.get( name )?.(); },
|
||||
remove() { const index = nodes.indexOf( this ); if ( index >= 0 ) nodes.splice( index, 1 ); },
|
||||
};
|
||||
},
|
||||
};
|
||||
return { document, nodes };
|
||||
}
|
||||
|
||||
test( 'bridge waits for CSS even if the player global already exists', async () => {
|
||||
const { document, nodes } = fakeDocument();
|
||||
const api = { create() {} };
|
||||
document.defaultView.AsciinemaPlayer = api;
|
||||
let resolved = false;
|
||||
const pending = playerForDocument( document, assets ).then( ( value ) => { resolved = true; return value; } );
|
||||
await flush();
|
||||
assert.equal( resolved, false );
|
||||
assert.equal( nodes.length, 1 );
|
||||
nodes[ 0 ].sheet = {};
|
||||
nodes[ 0 ].dispatch( 'load' );
|
||||
assert.equal( await pending, api );
|
||||
assert.equal( nodes.length, 1 );
|
||||
} );
|
||||
|
||||
test( 'parallel previews deduplicate local CSS and script and use the canvas realm', async () => {
|
||||
const { document, nodes } = fakeDocument();
|
||||
const first = playerForDocument( document, assets );
|
||||
const second = playerForDocument( document, assets );
|
||||
assert.equal( nodes.length, 1 );
|
||||
nodes[ 0 ].sheet = {};
|
||||
nodes[ 0 ].dispatch( 'load' );
|
||||
await flush();
|
||||
assert.equal( document.scripts.length, 1 );
|
||||
const canvasAPI = { create() {} };
|
||||
document.defaultView.AsciinemaPlayer = canvasAPI;
|
||||
document.scripts[ 0 ].dispatch( 'load' );
|
||||
assert.equal( await first, canvasAPI );
|
||||
assert.equal( await second, canvasAPI );
|
||||
assert.equal( await playerForDocument( document, assets ), canvasAPI );
|
||||
} );
|
||||
|
||||
test( 'failed owned script is removed and retry starts a new request', async () => {
|
||||
const { document, nodes } = fakeDocument();
|
||||
const pending = playerForDocument( document, assets );
|
||||
const rejection = assert.rejects( pending, /script could not be loaded/ );
|
||||
nodes[ 0 ].sheet = {};
|
||||
nodes[ 0 ].dispatch( 'load' );
|
||||
await flush();
|
||||
document.scripts[ 0 ].dispatch( 'error' );
|
||||
await rejection;
|
||||
assert.equal( document.scripts.length, 0 );
|
||||
const retry = playerForDocument( document, assets );
|
||||
await flush();
|
||||
assert.equal( document.scripts.length, 1 );
|
||||
document.defaultView.AsciinemaPlayer = { create() {} };
|
||||
document.scripts[ 0 ].dispatch( 'load' );
|
||||
assert.equal( await retry, document.defaultView.AsciinemaPlayer );
|
||||
} );
|
||||
|
||||
test( 'failed stylesheet is retryable and never starts a script before CSS', async () => {
|
||||
const { document, nodes } = fakeDocument();
|
||||
const pending = playerForDocument( document, assets );
|
||||
const rejection = assert.rejects( pending, /stylesheet could not be loaded/ );
|
||||
nodes[ 0 ].dispatch( 'error' );
|
||||
await rejection;
|
||||
assert.equal( nodes.length, 0 );
|
||||
const retry = playerForDocument( document, assets );
|
||||
assert.equal( nodes.length, 1 );
|
||||
nodes[ 0 ].sheet = {};
|
||||
nodes[ 0 ].dispatch( 'load' );
|
||||
await flush();
|
||||
document.defaultView.AsciinemaPlayer = { create() {} };
|
||||
document.scripts[ 0 ].dispatch( 'load' );
|
||||
await retry;
|
||||
} );
|
||||
|
||||
test( 'existing enqueued assets are reused while still loading', async () => {
|
||||
const { document, nodes } = fakeDocument();
|
||||
const style = document.createElement( 'link' );
|
||||
style.href = assets.style;
|
||||
style.sheet = {};
|
||||
const script = document.createElement( 'script' );
|
||||
script.src = assets.script;
|
||||
document.head.appendChild( style );
|
||||
document.head.appendChild( script );
|
||||
const pending = playerForDocument( document, assets );
|
||||
await flush();
|
||||
assert.equal( nodes.length, 2 );
|
||||
document.defaultView.AsciinemaPlayer = { create() {} };
|
||||
script.dispatch( 'load' );
|
||||
assert.equal( await pending, document.defaultView.AsciinemaPlayer );
|
||||
} );
|
||||
|
||||
test( 'document with no window fails cleanly', async () => {
|
||||
await assert.rejects( playerForDocument( { defaultView: null }, assets ), /canvas is unavailable/ );
|
||||
} );
|
||||
@@ -0,0 +1,124 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { MAX_HEADER_BYTES, readRecordingSize, recordingSizeFromHeader } from '../../src/recording-metadata.js';
|
||||
|
||||
test( 'original dimensions use each supported asciicast header schema', () => {
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 1, width: 132, height: 43 } ), { cols: 132, rows: 43 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: 110, height: 35 } ), { cols: 110, rows: 35 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 3, term: { cols: 150, rows: 50 }, width: 1, height: 1 } ), { cols: 150, rows: 50 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: 1, height: 1000 } ), { cols: 1, rows: 1000 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: 1500, height: 1200 } ), { cols: 1500, rows: 1200 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: Number.MAX_SAFE_INTEGER, height: 1 } ), { cols: Number.MAX_SAFE_INTEGER, rows: 1 } );
|
||||
} );
|
||||
|
||||
test( 'missing, unsupported and invalid dimensions stay unknown, never 80 by 24', () => {
|
||||
for ( const header of [ null, undefined, '', [], {}, { width: 80, height: 24 }, { version: '2', width: 80, height: 24 }, { version: 4, width: 80, height: 24 }, { version: 3, width: 80, height: 24 }, { version: 3, term: {} } ] ) {
|
||||
assert.equal( recordingSizeFromHeader( header ), null );
|
||||
}
|
||||
for ( const invalid of [ undefined, null, '', '80', true, false, NaN, Infinity, -1, 0, 1.5, Number.MAX_SAFE_INTEGER + 1 ] ) {
|
||||
assert.equal( recordingSizeFromHeader( { version: 2, width: invalid, height: 24 } ), null );
|
||||
assert.equal( recordingSizeFromHeader( { version: 3, term: { cols: 80, rows: invalid } } ), null );
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'metadata reads the first header and preserves the full original response for playback', async () => {
|
||||
const text = '{"version":2,"width":132,"height":43}\n[1,"r","200x60"]\n[2,"o","hello"]\n';
|
||||
const response = new Response( text );
|
||||
let clones = 0;
|
||||
const clone = response.clone.bind( response );
|
||||
response.clone = () => { clones++; return clone(); };
|
||||
assert.deepEqual( await readRecordingSize( response ), { cols: 132, rows: 43 } );
|
||||
assert.equal( clones, 1 );
|
||||
assert.equal( response.bodyUsed, false );
|
||||
assert.equal( await response.text(), text );
|
||||
} );
|
||||
|
||||
test( 'v3 reads terminal metadata, not nested output or subsequent resize events', async () => {
|
||||
const text = '{"version":3,"env":{"cols":500,"rows":500},"term":{"cols":120,"rows":30}}\n[0,"r","90x20"]\n';
|
||||
const response = new Response( text );
|
||||
assert.deepEqual( await readRecordingSize( response ), { cols: 120, rows: 30 } );
|
||||
await response.text();
|
||||
} );
|
||||
|
||||
function chunkedResponse( chunks ) {
|
||||
let reads = 0;
|
||||
let canceled = false;
|
||||
return {
|
||||
response: {
|
||||
ok: true,
|
||||
body: { getReader() { throw new Error( 'Do not read the original response.' ); } },
|
||||
clone: () => ( {
|
||||
body: { getReader: () => ( {
|
||||
async read() {
|
||||
const value = chunks[ reads++ ];
|
||||
return value ? { value, done: false } : { done: true };
|
||||
},
|
||||
cancel() {
|
||||
canceled = true;
|
||||
// A real tee's cancel can wait for its other branch.
|
||||
return new Promise( () => {} );
|
||||
},
|
||||
} ) },
|
||||
} ),
|
||||
},
|
||||
get reads() { return reads; },
|
||||
get canceled() { return canceled; },
|
||||
};
|
||||
}
|
||||
|
||||
test( 'pretty-printed v1 reads dimensions before stdout and does not await tee cancellation', async () => {
|
||||
const encode = new TextEncoder();
|
||||
const stream = chunkedResponse( [
|
||||
encode.encode( '{\n "version": 1,\n "width": 104,\n' ),
|
||||
encode.encode( ' "height": 28,\n "stdout": [\n' ),
|
||||
encode.encode( `[0,${ JSON.stringify( 'output'.repeat( MAX_HEADER_BYTES ) ) }]]}` ),
|
||||
] );
|
||||
assert.deepEqual( await readRecordingSize( stream.response ), { cols: 104, rows: 28 } );
|
||||
assert.equal( stream.reads, 2 );
|
||||
assert.equal( stream.canceled, true );
|
||||
} );
|
||||
|
||||
test( 'streaming JSON handles split UTF-8, escapes and nested objects without false fields', async () => {
|
||||
const text = JSON.stringify( { title: '尺寸 \\ " }, \\ ', env: { width: 300, height: 500 }, width: 137, height: 47, version: 1, stdout: [] } );
|
||||
const chunks = Array.from( new TextEncoder().encode( text ), ( value ) => Uint8Array.of( value ) );
|
||||
const stream = chunkedResponse( chunks );
|
||||
assert.deepEqual( await readRecordingSize( stream.response ), { cols: 137, rows: 47 } );
|
||||
assert.ok( stream.reads < chunks.length );
|
||||
assert.equal( stream.canceled, true );
|
||||
} );
|
||||
|
||||
test( 'headers over the byte limit stay unknown without draining the recording', async () => {
|
||||
const encode = new TextEncoder();
|
||||
const stream = chunkedResponse( [
|
||||
encode.encode( '{"version":2,"title":"' + 'x'.repeat( MAX_HEADER_BYTES ) ),
|
||||
encode.encode( '","width":132,"height":43}\n[1,"o","hello"]' ),
|
||||
] );
|
||||
assert.equal( await readRecordingSize( stream.response ), null );
|
||||
assert.equal( stream.reads, 1 );
|
||||
assert.equal( stream.canceled, true );
|
||||
} );
|
||||
|
||||
test( 'byte limit accepts a complete header at its boundary and ignores larger output chunks', async () => {
|
||||
const base = '{"version":2,"width":132,"height":43,"title":"';
|
||||
const header = base + 'x'.repeat( MAX_HEADER_BYTES - base.length - 2 ) + '"}';
|
||||
const stream = chunkedResponse( [ new TextEncoder().encode( header + '\n[1,"o","' + 'x'.repeat( MAX_HEADER_BYTES ) + '"]' ) ] );
|
||||
assert.deepEqual( await readRecordingSize( stream.response ), { cols: 132, rows: 43 } );
|
||||
assert.equal( stream.reads, 1 );
|
||||
} );
|
||||
|
||||
test( 'invalid JSON, nested lookalikes and incomplete dimensions never become defaults', async () => {
|
||||
for ( const text of [ '', 'not a cast', '<html>error</html>', '[]', '{}', '{"version":2,"env":{"width":80,"height":24}}', '{"version":2,"width":80,"height":24,}', '{"version":2,,"width":80,"height":24}', '{"version":2,"width":80,"height":24]', '{"version":2,"width":80,"height":24', '{"version":3,"term":{"cols":80}}' ] ) {
|
||||
const response = new Response( text );
|
||||
assert.equal( await readRecordingSize( response ), null, text );
|
||||
await response.text();
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'failed responses, unavailable streams and rejected reads quietly stay unknown', async () => {
|
||||
assert.equal( await readRecordingSize( { ok: false } ), null );
|
||||
assert.equal( await readRecordingSize( { ok: true, body: null } ), null );
|
||||
assert.equal( await readRecordingSize( { ok: true, body: { getReader() {} }, clone() { throw new Error( 'locked' ); } } ), null );
|
||||
const broken = chunkedResponse( [] );
|
||||
broken.response.clone = () => ( { body: { getReader: () => ( { read: () => Promise.reject( new Error( 'aborted' ) ), cancel: () => Promise.reject( new Error( 'aborted' ) ) } ) } } );
|
||||
assert.equal( await readRecordingSize( broken.response ), null );
|
||||
} );
|
||||
Reference in New Issue
Block a user