Files
faunosteo/packages/anatomy/tests/r5.format-oracles.test.ts
T

392 lines
9.7 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* R5.2 freeze (owner brief 2026-10-22 §9): the formatting and JavaScript
* semantics the Rust pipeline must reproduce, recorded from the tools
* themselves on generic inputs, not only on the equine data. Three oracles
* under crates/core/tests/oracles/r5/:
*
* - prettier-json.json: `formatJson` (Prettier 3, parser json, the
* repository options) over synthetic values probing the layout rules:
* short arrays collapsed, number arrays filled, the 80-column boundary at
* several depths and key widths, nested arrays, objects, empty
* containers, Unicode widths.
* - markdown-tables.json: `formatMarkdown` over raw tables as
* `markdown.ts` writes them (alignment, padding, Unicode widths, escaped
* pipes, empty cells).
* - js-semantics.json: `slugify`, `deterministicUuid`, `inferRegionCode`,
* `Number()`, the points split of the SVG reader, `Math.round`,
* `Object.entries` key order of `JSON.parse`, `toLowerCase`, NFD.
*
* `MAKE_R5_ORACLES=1` writes the files; otherwise the tools still match the
* freeze.
*/
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { formatJson, formatMarkdown } from '../src/format'
import { table } from '../src/markdown'
import { deterministicUuid, inferRegionCode, slugify } from '../src'
const HERE = dirname(fileURLToPath(import.meta.url))
const OUT = resolve(HERE, '../../../crates/core/tests/oracles/r5')
const MAKE = process.env.MAKE_R5_ORACLES === '1'
/** Numbers of `digits` characters each, deterministic. */
function numbers(count: number, digits: number): number[] {
return Array.from({ length: count }, (_, i) =>
Number(String((i * 7919 + 13) % 10 ** digits).padStart(1, '0')),
)
}
function strings(count: number, width: number): string[] {
return Array.from({ length: count }, (_, i) =>
`${String.fromCharCode(97 + (i % 26))}`.repeat(width),
)
}
/** One value per layout rule, each nested so the boundary moves. */
function jsonCases(): unknown[] {
const cases: unknown[] = [
{},
[],
{ a: {} },
{ a: [] },
{ a: [{}] },
{ a: [[]] },
{ a: [null, true, false] },
{ a: [1e21, -0, 1e-7, -5, 0.5, 123456789012345680000] },
{ a: [-1, -2, -3] },
{ a: [1, 'b', null] },
{ a: [[1, 2], [3]] },
{ a: [[1], [2]] },
{
a: [
[1, 2],
[3, 4],
],
},
{ a: [[1, 2], { b: 1 }] },
{ a: [{ b: 1 }, { c: 2 }] },
{
a: [
{ b: 1, c: 2 },
{ d: 3, e: 4 },
],
},
{
a: [
[
[1, 2],
[3, 4],
],
[[5, 6]],
],
},
{
a: [
['x', 'y'],
['z', 'w'],
],
},
{ a: [['x'], ['y', 'z']] },
{ 'clé é': ['é', 'à', '«»'], 漢字: ['漢字漢字', '😀'] },
{ a: ['é', 'full', '​'] },
{ a: 'x'.repeat(200), b: ['y'.repeat(100)] },
{ 'a"b': ['\\', '"', '\n', '\u0001'] },
]
for (const depth of [0, 1, 3, 6]) {
for (const key of ['k', 'key_of_twenty_chars_', 'k'.repeat(40)]) {
for (const count of [1, 2, 3, 8, 12, 13, 14, 15, 16, 30]) {
for (const digits of [1, 3, 4, 6]) {
let value: unknown = { [key]: numbers(count, digits) }
for (let d = 0; d < depth; d++) value = { n: value }
cases.push(value)
}
for (const width of [1, 5, 12]) {
let value: unknown = { [key]: strings(count, width), z: 1 }
for (let d = 0; d < depth; d++) value = { n: [value] }
cases.push(value)
}
}
}
}
for (let total = 70; total <= 90; total++) {
const pad = 'p'.repeat(total - 20)
cases.push({ [pad]: [1, 2] }, { [pad]: [1, 2], last: true })
cases.push({ [pad]: ['ab', 'cd'] }, [{ [pad]: [1, 2, 3] }])
cases.push({ x: [[Number('1'.repeat(Math.max(1, total - 70))), 2]] })
}
return cases
}
type Row = Array<string | number | null>
function tableCases(): Array<{ head: string[]; rows: Row[] }> {
return [
{ head: ['A', 'B'], rows: [['1', '2']] },
{
head: ['Mesure', 'Valeur'],
rows: [
['Nœuds', 792],
['x', null],
],
},
{ head: ['a'], rows: [['']] },
{
head: ['Code', 'Objet'],
rows: [
['`a|b`', 'x | y'],
['ligne\nsuite', ''],
],
},
{
head: ['é', 'é'],
rows: [
['àéîõü', 'ç'],
['–—', '«»'],
],
},
{
head: ['漢字', 'emoji'],
rows: [
['漢字漢字', '😀'],
['full', '👍🏽'],
],
},
{
head: ['ctl', 'zw'],
rows: [
['a\u0001b', 'a​b'],
['️', 'x'],
],
},
{
head: ['Long', 'Court'],
rows: [
['x'.repeat(150), 'y'],
['`code`', '**gras**'],
],
},
{ head: ['Total'], rows: [['**Total**'], ['']] },
{
head: ['n', 'm', 'o'],
rows: [
[1, 22, 333],
[4444, 5, 66],
],
},
]
}
/** IEEE 754 bits in hex: `String(-0)` is `"0"`, the bits keep the sign. */
function bitsOf(value: number): string {
const view = new DataView(new ArrayBuffer(8))
view.setFloat64(0, value)
return view.getBigUint64(0).toString(16).padStart(16, '0')
}
const SPACES = [' ', '\t', '\n', ' ', '', '
', ' ', '​']
function semantics() {
const slugInputs = [
'Cheval',
'Épaule',
'İstanbul',
'KK',
'ΣΑΣ ΟΔΟΣ',
'Straße',
'fin',
'full',
'Džemal',
'Ⅻ',
'x̧́y',
'①②',
'a—b–c',
'__a__',
'œuvre Æther',
'Ünïcödé',
'😀 smile',
'한국어',
'ğ ş ı',
'1/2 et 3/4',
'a'.repeat(63) + 'é' + 'b',
'-'.repeat(70) + 'z',
]
const uuidNames = [
'faunosteo:sheet:canine:v1',
'faunosteo:sheet:feline:v12',
'faunosteo:asset:' + 'f'.repeat(64),
'x'.repeat(1000),
'é',
'😀',
'\u0000',
]
const regionLabels: Array<[string | null, string | null]> = [
['Cervicales', null],
[null, 'Thoracic'],
['DORSALES', 'Lumbar'],
['Région sacrée', 'Sacral'],
['Coccygiennes', null],
['Lombaires', 'x'],
['Épaule', 'Shoulder'],
[null, null],
['', 'caudal'],
['Thoracolombaire', ''],
['CERVICALES', 'CERVICAL'],
['Sacrum', 'Sacrum'],
]
const numberTexts = [
'',
' ',
'12',
' 12 ',
'0x1A',
'0X1a',
'0b11',
'0o17',
'1e3',
'1E-3',
'.5',
'5.',
'+5',
'-5',
'Infinity',
'-Infinity',
'+Infinity',
'infinity',
'NaN',
'abc',
'1,5',
' 12 ',
'7',
'12px',
'1_000',
'00012',
'-0',
'0x',
'1e',
'1e+',
' \n\t3 ',
'
3',
'1.7976931348623157e309',
'5e-325',
'0.1e1',
'-.5',
'--5',
'+-5',
'0x-1',
]
const pointTexts = [
' 1,2 3,4 ',
'1,,2',
',1,2',
'1 2 3',
'',
'1e3,2',
' 1 2',
'1.5,2.25 ',
'1,2,3,4,5,6',
'a,b',
' ',
'1\n2\t3 4',
]
const roundValues = [
0.5, 1.5, 2.5, -0.5, -1.5, -2.5, 0.49999999999999994, -0.49999999999999994,
4503599627370495.5, -4503599627370495.5, 1e21, -0.4, 3.7, -3.7, 0, -0,
2.4999999999999996, 1.0000000000000002,
]
const keyTexts = [
'{"b":1,"2":2,"a":3,"1":4,"01":5,"4294967295":6,"4294967294":7,"-1":8,"1.5":9}',
'{"z":1,"y":2,"10":3,"9":4,"0":5}',
'{"a":1,"a":2,"b":3}',
]
return {
slugify: slugInputs.map((label) => ({ label, slug: slugify(label) })),
deterministicUuid: uuidNames.map((name) => ({
name,
uuid: deterministicUuid(name),
})),
inferRegionCode: regionLabels.map(([fr, en]) => ({
fr,
en,
match: inferRegionCode(fr, en),
})),
number: numberTexts.map((text) => {
const value = Number(text)
return { text, string: String(value), negativeZero: Object.is(value, -0) }
}),
points: pointTexts.map((text) => ({
text,
numbers: text
.trim()
.split(/[\s,]+/)
.map((n) => String(Number(n))),
})),
mathRound: roundValues.map((value) => {
const r = Math.round(value)
return {
bits: bitsOf(value),
value: String(value),
round: String(r),
negativeZero: Object.is(r, -0),
}
}),
objectEntriesOrder: keyTexts.map((text) => ({
text,
keys: Object.keys(JSON.parse(text) as object),
})),
trim: SPACES.map((space) => ({
text: `${space}x${space}`,
trimmed: `${space}x${space}`.trim(),
isSpace: /\s/.test(space),
})),
}
}
async function prettierJson() {
const cases = jsonCases()
const out = []
for (const value of cases) {
out.push({ input: JSON.stringify(value), output: await formatJson(value) })
}
return {
tool: 'prettier formatJson (packages/anatomy/src/format.ts)',
cases: out,
}
}
async function markdownTables() {
const out = []
for (const { head, rows } of tableCases()) {
const raw = `# T\n\n${table(head, rows)}\n`
out.push({ raw, output: await formatMarkdown(raw) })
}
return {
tool: 'prettier formatMarkdown (packages/anatomy/src/format.ts)',
cases: out,
}
}
function check(name: string, value: unknown): void {
const text = `${JSON.stringify(value)}\n`
if (MAKE) {
mkdirSync(OUT, { recursive: true })
writeFileSync(resolve(OUT, name), text)
}
expect(text).toBe(readFileSync(resolve(OUT, name), 'utf8'))
}
describe('R5.2 format and semantics oracles', () => {
it('prettier-json.json', async () => {
check('prettier-json.json', await prettierJson())
})
it('markdown-tables.json', async () => {
check('markdown-tables.json', await markdownTables())
})
it('js-semantics.json', () => {
check('js-semantics.json', semantics())
})
})