Files
gitbook/scripts/oxlint-caching-plugin.test.mjs
T

76 lines
3.0 KiB
JavaScript

import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import test from 'node:test';
const REPO_ROOT = path.resolve(import.meta.dirname, '..');
const OXLINT_BIN = path.join(REPO_ROOT, 'node_modules/.bin/oxlint');
const PLUGIN_PATH = path.join(import.meta.dirname, 'oxlint-caching-plugin.mjs');
function runLint(source) {
const dir = mkdtempSync(path.join(tmpdir(), 'oxlint-gbo-caching-test-'));
try {
const configPath = path.join(dir, 'oxlint.json');
const filePath = path.join(dir, 'sample.ts');
writeFileSync(
configPath,
JSON.stringify({
jsPlugins: [PLUGIN_PATH],
rules: {
'gitbook-cache/no-unbounded-permanent-redirect': 'error',
},
})
);
writeFileSync(filePath, source);
const result = spawnSync(OXLINT_BIN, ['-c', configPath, filePath], {
encoding: 'utf8',
});
return {
status: result.status,
output: `${result.stdout}\n${result.stderr}`,
};
} finally {
rmSync(dir, { recursive: true, force: true });
}
}
test('no-unbounded-permanent-redirect flags 301/308 redirects missing a bounded Cache-Control', () => {
const bad = runLint(`
export function f(permanent: boolean) {
const a = Response.redirect('https://example.com', 308);
const b = new Response(null, { status: 301, headers: { Location: '/x' } });
const c = new Response(null, { status: permanent ? 308 : 307, headers: { Location: '/x' } });
const d = new Response(null, { status: 308, headers: { Location: '/x', 'Cache-Control': 'private' } });
const e = new Response(null, { status: 308, headers: undefined });
const g = new Response(null, { status: 308, headers: new Headers({ Location: '/x' }) });
return [a, b, c, d, e, g];
}
`);
assert.equal(bad.status, 1);
assert.equal(
(bad.output.match(/gitbook-cache\(no-unbounded-permanent-redirect\)/g) ?? []).length,
6
);
});
test('no-unbounded-permanent-redirect allows bounded 308 redirects and temporary redirects', () => {
const ok = runLint(`
export function f() {
const a = Response.redirect('https://example.com', 302);
const b = new Response(null, {
status: 308,
headers: { Location: '/x', 'Cache-Control': 'private, max-age=86400' },
});
const c = new Response(null, {
status: 308,
headers: new Headers({ Location: '/x', 'Cache-Control': 'private, no-store' }),
});
const d = new Response(null, { status: 307, headers: { Location: '/x' } });
return [a, b, c, d];
}
`);
assert.equal(ok.status, 0);
});