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
+352
View File
@@ -0,0 +1,352 @@
import { test, expect } from '@playwright/test';
import { DEFAULT_LIMITS } from '../../src/recording-loader.js';
const blockName = 'lamgc/asciiplayer';
const fixtureRoot = '/wp-content/uploads/asciiplayer-fixtures';
const messages = {
bytes: 'This recording exceeds the file size limit.',
markers: 'This recording contains too many markers.',
dimensions: 'This recording requests terminal dimensions that exceed the supported limits.',
cells: 'This recording requests too many terminal cells.',
};
async function openEditor(page) {
await page.goto('/wp-login.php');
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
await page.locator('#wp-submit').click();
await expect(page).toHaveURL(/\/wp-admin\//);
await page.goto('/wp-admin/post-new.php');
await page.waitForFunction((name) => Boolean(
window.wp?.blocks?.getBlockType(name) &&
window.wp?.data?.select('core/editor')?.getCurrentPostId()
), blockName);
await page.evaluate(() => {
for (const scope of ['core/edit-post', 'core/editor']) {
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
}
});
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
}
function canvas(page) {
return page.frameLocator('iframe[name="editor-canvas"]');
}
async function insertPlayer(page, attributes = {}) {
const id = await page.evaluate(({ name, attrs }) => {
const block = window.wp.blocks.createBlock(name, attrs);
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
return block.clientId;
}, { name: blockName, attrs: attributes });
return { id, block: canvas(page).locator(`[data-block="${id}"]`) };
}
async function removePlayer(page, id) {
await page.evaluate((clientId) => window.wp.data.dispatch('core/block-editor').removeBlocks([clientId]), id);
await expect(canvas(page).locator(`[data-block="${id}"]`)).toHaveCount(0);
}
async function changeSource(block, source) {
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(source);
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
}
async function readyPreview(block) {
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
await expect(block.locator('.ap-wrapper')).toHaveCount(1);
await expect(block.locator('.ap-term')).toBeVisible();
}
async function expectGrid(block, cols, rows) {
await expect.poll(() => block.locator('.ap-term').evaluate((terminal) => ({
cols: Number(terminal.style.getPropertyValue('--term-cols')),
rows: Number(terminal.style.getPropertyValue('--term-rows')),
}))).toEqual({ cols, rows });
}
async function dimensions(page) {
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
if (!await columns.isVisible()) {
await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click();
}
await expect(columns).toBeVisible();
return { columns, rows };
}
async function expectNativeSize(page, cols, rows) {
const controls = await dimensions(page);
await expect(controls.columns).toHaveAttribute('placeholder', cols === undefined ? 'From recording' : String(cols));
await expect(controls.rows).toHaveAttribute('placeholder', rows === undefined ? 'From recording' : String(rows));
return controls;
}
function recording(version = 2, { cols = 64, rows = 12, label = 'bounded', events } = {}) {
const output = (part) => `\u001b[2J\u001b[H${part} ${label}\r\n`;
if (version === 1) {
return JSON.stringify({ version, width: cols, height: rows, duration: 12, stdout: [
[0, output('START')], [8, output('SEEK')], [4, output('END')],
] }, null, 2);
}
const header = version === 3 ? { version, term: { cols, rows } } : { version, width: cols, height: rows };
const frames = events || [[0, 'o', output('START')], [8, 'o', output('SEEK')], [version === 3 ? 4 : 12, 'o', output('END')]];
// The bundled parser permits blank/comment lines after either JSONL header.
// Routing the original bytes tests compatibility through the real loader.
return `${JSON.stringify(header)}\n\n# An ignored comment before output.\n${frames.map(JSON.stringify).join('\n\n# Between events.\n')}\n`;
}
async function routeRecording(page, name, body) {
const source = new URL(`${fixtureRoot}/bounded-${name}.cast`, page.url()).href;
let requests = 0;
await page.route(source, async (route) => {
requests += 1;
await route.fulfill({ contentType: 'text/plain; charset=utf-8', body });
});
return { source, requests: () => requests };
}
async function playAndSeek(block, label) {
await block.locator('.ap-overlay-start .ap-play-button').click();
await expect(block.locator('.ap-term-text')).toContainText(`START ${label}`);
const playback = block.locator('.ap-playback-button');
await expect(playback).toHaveAttribute('aria-label', 'Pause');
await playback.click();
await expect(playback).toHaveAttribute('aria-label', 'Play');
// The real player's numeric shortcuts seek to 80% and then back to 0%.
// The second frame is eight seconds in, so this cannot pass by just playing.
await block.locator('.ap-term-text').press('8');
await expect(block.locator('.ap-term-text')).toContainText(`SEEK ${label}`);
await expect(block.locator('.ap-term-text')).not.toContainText(`START ${label}`);
await block.locator('.ap-term-text').press('0');
await expect(block.locator('.ap-term-text')).toContainText(`START ${label}`);
await expect(block.locator('.ap-term-text')).not.toContainText(`SEEK ${label}`);
}
for (const version of [1, 2, 3]) {
test(`bounded v${version} recordings play and seek in the editor iframe, including zero header dimensions`, async ({ page }) => {
await openEditor(page);
for (const zero of [false, true]) {
const label = `v${version}-${zero ? 'zero' : 'native'}`;
const routed = await routeRecording(page, label, recording(version, {
cols: zero ? 0 : 64, rows: zero ? 0 : 12, label,
}));
const { id, block } = await insertPlayer(page, { source: routed.source, controls: 'always' });
await readyPreview(block);
await expectGrid(block, zero ? 80 : 64, zero ? 24 : 12);
const controls = await expectNativeSize(page, zero ? undefined : 64, zero ? undefined : 12);
await expect(controls.columns).toHaveValue('');
await expect(controls.rows).toHaveValue('');
await playAndSeek(block, label);
// Native-size hints and seeks must reuse the same validated fetch.
expect(routed.requests()).toBe(1);
const attributes = await page.evaluate((clientId) => window.wp.data.select('core/block-editor').getBlockAttributes(clientId), id);
expect(attributes.cols).toBeUndefined();
expect(attributes.rows).toBeUndefined();
await removePlayer(page, id);
}
});
}
const firstUnsafeRows = Math.floor(DEFAULT_LIMITS.cells / DEFAULT_LIMITS.dimension) + 1;
const rejectedRecordings = [
{
name: 'actual received byte limit', code: 'bytes',
body: () => {
const header = `${JSON.stringify({ version: 2, width: 64, height: 12 })}\n`;
// Keep every comment line well below the line limit and use no
// events, isolating the total-byte cap without huge terminal output.
const comment = `#${'x'.repeat(1022)}\n`;
return header + comment.repeat(Math.ceil((DEFAULT_LIMITS.bytes + 1 - header.length) / comment.length));
},
},
{
name: 'marker count limit', code: 'markers',
body: () => recording(2, { events: Array.from({ length: DEFAULT_LIMITS.markers + 1 }, (_, index) => [index / 1000, 'm', 'marker']) }),
},
{
name: 'resize axis limit', code: 'dimensions',
body: () => recording(2, { events: [[0, 'o', 'safe'], [1, 'r', `${DEFAULT_LIMITS.dimension + 1}x12`]] }),
},
{
name: 'resize cell limit', code: 'cells',
body: () => recording(3, { events: [[0, 'o', 'safe'], [1, 'r', `${DEFAULT_LIMITS.dimension}x${firstUnsafeRows}`]] }),
},
{
name: 'initial terminal dimensions before player creation', code: 'cells', noFetch: true,
attributes: { cols: DEFAULT_LIMITS.dimension, rows: firstUnsafeRows },
body: () => recording(),
},
{
name: 'effective resize dimensions with one overridden axis', code: 'cells',
attributes: { cols: DEFAULT_LIMITS.dimension },
body: () => recording(2, { events: [[0, 'o', 'safe'], [1, 'r', `64x${firstUnsafeRows}`]] }),
},
];
for (const entry of rejectedRecordings) {
test(`bounded preview rejects ${entry.name} with a useful error and recovers`, async ({ page }) => {
await openEditor(page);
const rejected = await routeRecording(page, `reject-${entry.code}`, entry.body());
const valid = await routeRecording(page, 'recovery', recording(2, { label: 'recovered' }));
const { id, block } = await insertPlayer(page, { source: rejected.source, ...entry.attributes });
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
await expect(block.locator('.components-notice')).toContainText(messages[entry.code]);
await expect(block.getByRole('button', { name: 'Retry preview', exact: true })).toBeVisible();
await expectNativeSize(page);
expect(rejected.requests()).toBe(entry.noFetch ? 0 : 1);
if (entry.noFetch) await expect(block.locator('.ap-wrapper')).toHaveCount(0);
// Remove intentional overrides while changing source in one store update,
// so recovery cannot fail for the previous effective-size violation.
await page.evaluate(({ clientId, source }) => window.wp.data.dispatch('core/block-editor').updateBlockAttributes(clientId, {
source, cols: undefined, rows: undefined,
}), { clientId: id, source: valid.source });
await readyPreview(block);
await expect(block.locator('.components-notice')).toHaveCount(0);
await expectNativeSize(page, 64, 12);
await expectGrid(block, 64, 12);
await playAndSeek(block, 'recovered');
expect(valid.requests()).toBe(1);
});
}
test('bounded playback preserves independent dimension overrides across recorded resizes', async ({ page }) => {
await openEditor(page);
const routed = await routeRecording(page, 'safe-overrides', recording(2, { events: [
[0, 'o', 'Original terminal\r\n'], [8, 'r', '100x30'], [8, 'o', 'Resized terminal\r\n'], [12, 'o', 'Finished\r\n'],
] }));
for (const rows of [undefined, 20]) {
const { id, block } = await insertPlayer(page, { source: routed.source, cols: 80, rows, controls: 'always' });
await readyPreview(block);
await expectGrid(block, 80, rows || 12);
await expectNativeSize(page, 64, 12);
await block.locator('.ap-overlay-start .ap-play-button').click();
await expect(block.locator('.ap-term-text')).toContainText('Original terminal');
await block.locator('.ap-playback-button').click();
await block.locator('.ap-term-text').press('8');
await expect(block.locator('.ap-term-text')).toContainText('Resized terminal');
await expectGrid(block, 80, rows || 30);
await expectNativeSize(page, 64, 12);
await removePlayer(page, id);
}
expect(routed.requests()).toBe(2);
});
function deferred() {
let release;
const promise = new Promise((resolve) => { release = resolve; });
return { promise, release };
}
async function observeNativeFetch(page) {
await canvas(page).locator('body').evaluate((body) => {
const window = body.ownerDocument.defaultView;
const fetch = window.fetch;
window.__boundedFetches = [];
// Observation only: retain the actual browser fetch, Response/stream,
// player, parser, and AbortController. No player API is mocked.
window.fetch = function (source, options) {
const entry = { source: String(source), aborted: Boolean(options?.signal?.aborted) };
window.__boundedFetches.push(entry);
options?.signal?.addEventListener('abort', () => { entry.aborted = true; }, { once: true });
return fetch.call(this, source, options);
};
});
}
async function expectFetchAborted(page, source) {
await expect.poll(() => canvas(page).locator('body').evaluate((body, url) =>
body.ownerDocument.defaultView.__boundedFetches?.find((entry) => entry.source === url)?.aborted, source
)).toBe(true);
}
for (const action of ['change URL', 'unmount block']) {
test(`${action} aborts an in-flight bounded fetch and ignores its delayed result`, async ({ page }) => {
await openEditor(page);
await observeNativeFetch(page);
const pageErrors = [];
page.on('pageerror', (error) => pageErrors.push(error.message));
const oldSource = new URL(`${fixtureRoot}/bounded-delayed.cast`, page.url()).href;
const current = await routeRecording(page, 'current', recording(2, { label: 'current' }));
const gate = deferred();
let requested = false;
let settled = false;
await page.route(oldSource, async (route) => {
requested = true;
await gate.promise;
await route.fulfill({ contentType: 'text/plain', body: recording(2, { cols: 120, rows: 30, label: 'stale' }) }).catch(() => {});
settled = true;
});
try {
const old = await insertPlayer(page, { source: oldSource });
await expect.poll(() => requested).toBe(true);
let active = old;
if (action === 'change URL') await changeSource(old.block, current.source);
else {
await removePlayer(page, old.id);
active = await insertPlayer(page, { source: current.source });
}
await expectFetchAborted(page, oldSource);
await readyPreview(active.block);
await expectNativeSize(page, 64, 12);
await active.block.locator('.ap-term').evaluate((terminal) => { terminal.dataset.boundedIdentity = 'current'; });
gate.release();
await expect.poll(() => settled).toBe(true);
await readyPreview(active.block);
await expect(active.block.locator('.ap-term')).toHaveAttribute('data-bounded-identity', 'current');
await expectNativeSize(page, 64, 12);
await expectGrid(active.block, 64, 12);
await expect(canvas(page).locator('.ap-wrapper')).toHaveCount(1);
await playAndSeek(active.block, 'current');
expect(current.requests()).toBe(1);
expect(pageErrors).toEqual([]);
} finally {
gate.release();
}
});
}
for (const action of ['change URL', 'unmount block']) {
test(`${action} while player assets are pending never starts the stale recording fetch`, async ({ page }) => {
await openEditor(page);
const pageErrors = [];
page.on('pageerror', (error) => pageErrors.push(error.message));
const old = await routeRecording(page, 'before-assets', recording(2, { cols: 120, rows: 30, label: 'stale' }));
const current = await routeRecording(page, 'after-assets', recording(2, { label: 'current' }));
const scriptUrl = await page.evaluate(() => window.wpAsciiplayerSettings.playerScriptUrl);
expect(await canvas(page).locator('body').evaluate((body) => typeof body.ownerDocument.defaultView.AsciinemaPlayer)).toBe('undefined');
const gate = deferred();
let assetRequested = false;
await page.route(scriptUrl, async (route) => {
assetRequested = true;
await gate.promise;
// Resume the installed plugin's real local asset, not a test double.
await route.continue().catch(() => {});
});
try {
let active = await insertPlayer(page, { source: old.source });
await expect.poll(() => assetRequested).toBe(true);
await expect(active.block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'loading');
if (action === 'change URL') await changeSource(active.block, current.source);
else {
await removePlayer(page, active.id);
active = await insertPlayer(page, { source: current.source });
}
expect(old.requests()).toBe(0);
expect(current.requests()).toBe(0);
gate.release();
await readyPreview(active.block);
await expectNativeSize(page, 64, 12);
await expectGrid(active.block, 64, 12);
await expect(canvas(page).locator('.ap-wrapper')).toHaveCount(1);
await playAndSeek(active.block, 'current');
expect(old.requests()).toBe(0);
expect(current.requests()).toBe(1);
expect(pageErrors).toEqual([]);
} finally {
gate.release();
}
});
}
+2 -2
View File
@@ -10,7 +10,7 @@ const copy = {
help: 'Help', retry: 'Retry preview', captionLabel: 'Recording caption',
previewError: 'Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.',
frontendError: 'Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.',
uploadError: 'Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).',
uploadError: 'Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).',
},
zh_CN: {
title: 'Asciicast 播放器', source: '录制文件 URL', apply: '应用 URL',
@@ -18,7 +18,7 @@ const copy = {
help: '帮助', retry: '重试预览', captionLabel: '录屏说明文字',
previewError: '无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。',
frontendError: '无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。',
uploadError: '请上传有效的 Asciicast v2/v3 JSONL 或格式化的 v1 .cast 录制文件(最大 32 MiB;v1 最大 2 MiB;最多 100,000 个事件;每行 JSONL最大 256 KiB;列数和行数均不超过 1,000)。',
uploadError: '请上传有效的 Asciicast v2/v3 JSONL 或 v1 .cast 录屏(最大 32 MiB;v1 最大 2 MiB、100,000 个事件、每行 JSONL 最大 256 KiB、1,000 个时间标记、1,000 列或行、40,000 个终端单元格,且 JSON 结构复杂度受限)。',
},
};
+1 -1
View File
@@ -278,7 +278,7 @@ test('native Media Library rejects an invalid cast upload without applying a sou
const malformed = await readFile(new URL('../fixtures/malformed.cast', import.meta.url));
const result = await uploadRecording(page, dialog, `asciiplayer-invalid-${Date.now()}-${testInfo.retry}.cast`, malformed);
expect(result.success, JSON.stringify(result)).toBe(false);
const validationMessage = 'Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).';
const validationMessage = 'Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).';
// A filesystem/permission failure is not evidence of content validation.
expect(result.data.message).toBe(validationMessage);
await expect(dialog).toContainText(validationMessage);
+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 );
} );
+12
View File
@@ -0,0 +1,12 @@
<?php
/** Test-only decoder instrumentation, loaded before production calls. */
namespace LamGC\Asciiplayer {
// Instrument the real decoder without adding a production test hook. A gate
// failure must not build the rejected whole-document object graph.
function json_decode( $json, $associative = null, $depth = 512, $flags = 0 ) {
$GLOBALS['cast_decode_lengths'][] = strlen( $json );
return \json_decode( $json, $associative, $depth, $flags );
}
}
+110
View File
@@ -0,0 +1,110 @@
<?php
/** Resource-bound regressions; included after the existing upload contracts. */
namespace {
use function LamGC\Asciiplayer\is_cast_json_within_budget;
use function LamGC\Asciiplayer\is_cast_v1;
use const LamGC\Asciiplayer\CAST_MAX_JSON_CONTAINERS;
use const LamGC\Asciiplayer\CAST_MAX_JSON_TOKENS;
function cast_budget_accepts( $text ) {
$containers = 0;
$tokens = 0;
return is_cast_json_within_budget( $text, $containers, $tokens );
}
foreach ( array(
'zero v2 dimensions' => '{"version":2,"width":0,"height":0}',
'zero v3 dimensions' => '{"version":3,"term":{"cols":0,"rows":0}}',
'40,000 cells' => '{"version":2,"width":1000,"height":40}',
'normal ignored lines' => $v2 . "\n\n# comment\nnot an event\n [broken ignored JSON\n[0,\"o\",\"works\"]\n",
'1,000 markers' => $v2 . "\n" . str_repeat( "[0,\"m\",\"mark\"]\n", 1000 ),
'40,000-cell resize' => $v2 . "\n[0,\"r\",\"200x200\"]\n",
) as $description => $contents ) {
same( true, cast_contents_are_valid( $contents ), 'Accept ' . $description . '.' );
}
foreach ( array(
'cell-product overflow' => '{"version":2,"width":201,"height":200}',
'zero width defaults before cell check' => '{"version":2,"width":0,"height":501}',
'zero height defaults before cell check' => '{"version":2,"width":1000,"height":0}' . "\n[0,\"r\",\"1000x41\"]\n",
'v3 cell-product overflow' => '{"version":3,"term":{"cols":201,"rows":200}}',
'1,001 markers' => $v3 . "\n" . str_repeat( "[0,\"m\",\"mark\"]\n", 1001 ),
'resize cell-product overflow' => $v2 . "\n[0,\"r\",\"201x200\"]\n",
'zero resize has no header defaults' => $v3 . "\n[0,\"r\",\"80x0\"]\n",
'ignored line count overflow' => $v2 . "\n" . str_repeat( "\n", 100001 ),
'ignored line byte overflow' => $v2 . "\n#" . str_repeat( 'x', 262144 ),
'missing dimensions' => '{"version":2}',
'empty malformed event' => $v2 . "\n[]\n",
) as $description => $contents ) {
same( false, cast_contents_are_valid( $contents ), 'Reject ' . $description . '.' );
}
$containers = 0;
$tokens = 0;
$escaped = json_encode( array( 'key"\\' => '[{}], : \\" braces', 'value' => true ) );
same( true, is_cast_json_within_budget( " \n\t" . $escaped . "\r\n", $containers, $tokens ), 'Escapes and JSON whitespace are scanned.' );
same( 1, $containers, 'String punctuation does not inflate containers.' );
same( 4, $tokens, 'Keys and scalar values each consume a token.' );
same( true, cast_budget_accepts( str_repeat( '[', 15 ) . '0' . str_repeat( ']', 15 ) ), 'Container nesting 15 fits decoder depth 16.' );
same( false, cast_budget_accepts( str_repeat( '[', 16 ) . '0' . str_repeat( ']', 16 ) ), 'Reject depth before decoder allocation.' );
same( true, cast_budget_accepts( '[' . str_repeat( '0,', CAST_MAX_JSON_TOKENS - 1 ) . '0]' ), 'Scalar token budget is inclusive.' );
same( false, cast_budget_accepts( '[' . str_repeat( '0,', CAST_MAX_JSON_TOKENS ) . '0]' ), 'Reject excessive scalar tokens.' );
same( true, cast_budget_accepts( '[' . str_repeat( '{},', CAST_MAX_JSON_CONTAINERS - 2 ) . '{}]' ), 'Container budget is inclusive.' );
same( false, cast_budget_accepts( '[' . str_repeat( '{},', CAST_MAX_JSON_CONTAINERS - 1 ) . '{}]' ), 'Reject excessive empty containers.' );
$containers = 0;
$tokens = CAST_MAX_JSON_TOKENS - 2;
same( true, is_cast_json_within_budget( '[0,"o"]', $containers, $tokens ), 'Shared record budget reaches its boundary.' );
same( false, is_cast_json_within_budget( '[0]', $containers, $tokens ), 'Shared record budget cannot reset per event.' );
foreach ( array(
'wide metadata scalars' => '[' . str_repeat( '0,', CAST_MAX_JSON_TOKENS ) . '0]',
'wide metadata containers' => '[' . str_repeat( '{},', CAST_MAX_JSON_CONTAINERS ) . '{}]',
'duplicate metadata keys' => '{' . str_repeat( '"x":0,', 200000 ) . '"x":0}',
'deep metadata' => str_repeat( '[', 16 ) . '0' . str_repeat( ']', 16 ),
) as $description => $metadata ) {
$text = "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":[],\"metadata\":" . $metadata . '}';
$GLOBALS['cast_decode_lengths'] = array();
same( false, is_cast_v1( $text ), 'Reject ' . $description . ' before decoding.' );
same( array(), $GLOBALS['cast_decode_lengths'], 'No native decode runs for ' . $description . '.' );
same( false, cast_contents_are_valid( $text ), 'Upload path rejects ' . $description . '.' );
same( false, in_array( strlen( $text ), $GLOBALS['cast_decode_lengths'], true ), 'Upload path never decodes the full rejected document.' );
}
$prefix = '{"version":2,"width":80,"height":24,"metadata":[';
same( true, cast_contents_are_valid( $prefix . str_repeat( '0,', 19992 ) . '0]}' ), 'JSONL header accepts exactly 20,000 scalar/key tokens.' );
same( false, cast_contents_are_valid( $prefix . str_repeat( '0,', 19993 ) . '0]}' ), 'JSONL header rejects 20,001 scalar/key tokens.' );
foreach ( array( 2, 3 ) as $version ) {
$prefix = 2 === $version ? '{"version":2,"width":80,"height":24,"metadata":[' : '{"version":3,"term":{"cols":80,"rows":24},"metadata":[';
$wide_header = $prefix . str_repeat( '0,', 20000 ) . '0]}';
$GLOBALS['cast_decode_lengths'] = array();
same( false, cast_contents_are_valid( $wide_header ), 'Wide JSONL header is rejected without v1 budget fallback.' );
same( false, in_array( strlen( $wide_header ), $GLOBALS['cast_decode_lengths'], true ), 'Over-budget v2/v3 header never reaches full decoder.' );
}
foreach ( array(
'escaped version key' => '{"ver\\u0073ion":1,"width":80,"height":24,"stdout":[]}',
'duplicate version last wins' => '{"version":2,"version":1,"width":80,"height":24,"stdout":[]}',
'nested version ignored' => '{"version":1,"meta":{"version":2},"width":80,"height":24,"stdout":[]}',
'frame-rich first line' => '{"stdout":[' . str_repeat( '[0,""],', 10000 ) . '[0,""]],'. "\n" .'"version":1,"width":80,"height":24}',
'title-rich first line' => '{"title":"' . str_repeat( 'x', 262144 ) . '",'. "\n" .'"version":1,"width":80,"height":24,"stdout":[]}',
) as $description => $text ) {
same( true, cast_contents_are_valid( $text ), 'Format discriminator preserves ' . $description . '.' );
}
$text = '{"version":1,"version":2,"width":80,"height":24,"stdout":[],"metadata":[' . str_repeat( '0,', 20000 ) . '0]}';
$GLOBALS['cast_decode_lengths'] = array();
same( false, cast_contents_are_valid( $text ), 'Last duplicate version cannot receive a legacy budget.' );
same( false, in_array( strlen( $text ), $GLOBALS['cast_decode_lengths'], true ), 'Last duplicate version rejects before full decode.' );
$wide_event = '[0,"o",[' . str_repeat( '0,', 19999 ) . '0]]';
$GLOBALS['cast_decode_lengths'] = array();
same( false, cast_contents_are_valid( $v2 . "\n" . $wide_event ), 'Reject wide event data with the per-line gate.' );
same( false, in_array( strlen( $wide_event ), $GLOBALS['cast_decode_lengths'], true ), 'Wide event never reaches the native decoder.' );
$deep_header = '{"version":2,"width":80,"height":24,"metadata":' . str_repeat( '[', 14 ) . '0' . str_repeat( ']', 14 ) . '}';
same( true, cast_contents_are_valid( $deep_header ), 'Decoder and lexical gate agree on depth boundary.' );
$GLOBALS['cast_decode_lengths'] = array();
same( false, is_cast_v1( '{"version":1,broken}' ), 'Final decoder still rejects malformed JSON.' );
same( true, in_array( strlen( '{"version":1,broken}' ), $GLOBALS['cast_decode_lengths'], true ), 'Within-budget grammar errors reach the real decoder.' );
$text = '{"version":1,"width":0,"height":0,"stdout":[' . str_repeat( '[0,""],', 99999 ) . '[0,""]]}';
same( true, cast_contents_are_valid( $text ), '100,000 compact v1 frames fit byte, structure and event budgets.' );
$GLOBALS['cast_decode_lengths'] = array();
}
+2
View File
@@ -1,6 +1,7 @@
<?php
/** Run with PHP 7.4+: php tests/php/run.php */
require __DIR__ . '/cast-budget-decoder.php';
require __DIR__ . '/bootstrap.php';
use function LamGC\Asciiplayer\enqueue_content_assets;
@@ -179,6 +180,7 @@ try {
same( array( 'lamgc-asciiplayer-style' ), $GLOBALS['ap_test']['style_print_calls'], 'Late/widget styles print once in the footer.' );
require __DIR__ . '/uploads.php';
require __DIR__ . '/cast-budget.php';
echo "OK: {$assertions} assertions passed.\n";
} catch ( Throwable $error ) {
+11 -11
View File
@@ -56,6 +56,16 @@ $v2 = '{"version":2,"width":80,"height":24}';
$v3 = '{"version":3,"term":{"cols":100,"rows":30}}';
$v1 = array( 'version' => 1, 'width' => 80, 'height' => 24, 'duration' => 1.5, 'stdout' => array( array( 0.1, "Hello\r\n" ), array( 1.4, 'World' ) ) );
foreach ( array(
'zero width' => '{"version":2,"width":0,"height":24}',
'event object' => $v2 . "\n{\"0\":0,\"1\":\"o\",\"2\":\"bad\"}\n",
'trailing HTML' => $v2 . "\n[0,\"o\",\"ok\"]\n<script>alert(1)</script>\n",
'trailing JSON object' => $v2 . "\n[0,\"o\",\"ok\"]\n{\"unrelated\":true}\n",
'blank event line' => $v2 . "\n\n",
'indented event ignored by bundled player' => $v2 . "\n [0,\"o\",\"invisible\"]\n",
'v2 comment' => $v2 . "\n# comment\n",
'v3 indented comment' => $v3 . "\n # not a comment\n",
'compact v1' => json_encode( $v1 ),
'large compact v1' => json_encode( array_merge( $v1, array( 'title' => str_repeat( 'a', CAST_MAX_LINE_BYTES + 1 ) ) ) ),
'pretty v1' => json_encode( $v1, JSON_PRETTY_PRINT ),
'v2 output' => $v2 . "\n[0.1,\"o\",\"Hello\\r\\n\"]\n",
'v3 relative events' => $v3 . "\n[5,\"o\",\"Hello\"]\n[0.1,\"r\",\"120x40\"]\n[0,\"x\",\"0\"]\n",
@@ -80,7 +90,6 @@ foreach ( array(
'SVG' => '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>',
'unsupported version' => '{"version":4,"width":80,"height":24}',
'string version' => '{"version":"2","width":80,"height":24}',
'zero width' => '{"version":2,"width":0,"height":24}',
'oversized width' => '{"version":2,"width":1001,"height":24}',
'negative height' => '{"version":2,"width":80,"height":-1}',
'fractional width' => '{"version":2,"width":80.5,"height":24}',
@@ -89,8 +98,6 @@ foreach ( array(
'v3 terminal array' => '{"version":3,"term":[100,30]}',
'v1 absent stdout' => "{\n\"version\":1,\"width\":80,\"height\":24\n}",
'v1 stdout object' => "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":{\"0\":[0,\"x\"]}\n}",
'compact v1 unsupported by bundled player' => json_encode( $v1 ),
'large compact v1 unsupported by bundled player' => json_encode( array_merge( $v1, array( 'title' => str_repeat( 'a', CAST_MAX_LINE_BYTES + 1 ) ) ) ),
'v1 negative delay' => json_encode( array_merge( $v1, array( 'stdout' => array( array( -1, 'x' ) ) ) ), JSON_PRETTY_PRINT ),
'v1 malformed later frame' => json_encode( array_merge( $v1, array( 'stdout' => array( array( 0, 'ok' ), array( 0, array( 'x' ) ) ) ) ), JSON_PRETTY_PRINT ),
'v1 extra frame element' => json_encode( array_merge( $v1, array( 'stdout' => array( array( 0, 'ok', 'extra' ) ) ) ), JSON_PRETTY_PRINT ),
@@ -102,7 +109,6 @@ foreach ( array(
'milliseconds overflow' => $v2 . "\n[1e308,\"o\",\"bad\"]\n",
'v3 cumulative milliseconds overflow' => $v3 . "\n[1e305,\"o\",\"first\"]\n[1e305,\"o\",\"second\"]\n",
'v2 out of order' => $v2 . "\n[2,\"o\",\"first\"]\n[1,\"o\",\"second\"]\n",
'event object' => $v2 . "\n{\"0\":0,\"1\":\"o\",\"2\":\"bad\"}\n",
'missing event data' => $v2 . "\n[0,\"o\"]\n",
'extra event element' => $v2 . "\n[0,\"o\",\"bad\",1]\n",
'event data array' => $v2 . "\n[0,\"o\",[\"bad\"]]\n",
@@ -111,12 +117,6 @@ foreach ( array(
'oversized resize' => $v2 . "\n[0,\"r\",\"2000x20\"]\n",
'malformed resize' => $v2 . "\n[0,\"r\",\"80,24\"]\n",
'bad later JSON' => $v2 . "\n[0,\"o\",\"ok\"]\n[1,\"o\",\"truncated\"\n",
'trailing HTML' => $v2 . "\n[0,\"o\",\"ok\"]\n<script>alert(1)</script>\n",
'trailing JSON object' => $v2 . "\n[0,\"o\",\"ok\"]\n{\"unrelated\":true}\n",
'blank event line' => $v2 . "\n\n",
'indented event ignored by bundled player' => $v2 . "\n [0,\"o\",\"invisible\"]\n",
'v2 comment' => $v2 . "\n# comment\n",
'v3 indented comment' => $v3 . "\n # not a comment\n",
'UTF-8 BOM' => "\xef\xbb\xbf" . $v2,
'invalid UTF-8' => $v2 . "\n[0,\"o\",\"\xff\"]\n",
'oversized JSONL line' => $v2 . "\n[0,\"o\",\"" . str_repeat( 'a', CAST_MAX_LINE_BYTES ) . "\"]\n",
@@ -166,7 +166,7 @@ try {
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Upload permissions are enforced for valid content too.' );
same( $denied, check_cast_filetype( $approved, $path, 'recording.cast' ), 'MIME override never grants upload capability.' );
$GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true, 'unfiltered_upload' => true );
file_put_contents( $path, $v2 . "\n<script>alert(1)</script>\n" );
file_put_contents( $path, $v2 . "\n[invalid JSON\n" );
clearstatcache( true, $path );
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Malformed content fails even with unfiltered_upload.' );
same( $denied, check_cast_filetype( $approved, $path, 'recording.cast' ), 'Invalid content cannot keep a previous MIME approval.' );