fix(docs): address persistence format history review
This commit is contained in:
1 parent
b08f6c421b
commit
765c87fb87
130 files changed
+6368
-6261
No files matched your search
@@ -120,6 +120,23 @@ function historicalSurface(operation: 'required' | 'optional' | 'absent', event
|
||||
}
|
||||
|
||||
describe('historical persistence snapshot parsing', () => {
|
||||
it('preserves source paths and fingerprints in historical inventories', () => {
|
||||
const snapshot = historicalSurface('required')
|
||||
const root = snapshot.roots[0]!
|
||||
const sources = ['packages/core/example/src/types.ts']
|
||||
const complete = { ...snapshot, types: [{ schema: root.schema, digest: root.digest, names: ['Example'], sources }] }
|
||||
expect(parseHistoricalPersistenceSnapshot(complete)).toEqual(complete)
|
||||
})
|
||||
|
||||
it.each([':8', ':8:3', '#L8', '#L8-L12'])('rejects source coordinates %s only in historical inventories', (suffix) => {
|
||||
const snapshot = historicalSurface('required')
|
||||
const root = snapshot.roots[0]!
|
||||
const sources = [`packages/core/example/src/types.ts${suffix}`]
|
||||
const complete = { ...snapshot, types: [{ schema: root.schema, digest: root.digest, names: [], sources }] }
|
||||
expect(() => parseHistoricalPersistenceSnapshot(complete)).toThrow('historical schema sources must omit line numbers')
|
||||
expect(parsePersistenceSnapshot(complete)).toEqual(complete)
|
||||
})
|
||||
|
||||
it('admits optional surface operations only through the historical parser', () => {
|
||||
const snapshot = historicalSurface('optional')
|
||||
expect(() => parsePersistenceSnapshot(snapshot)).toThrow('surface metadata')
|
||||
|
||||
@@ -250,8 +250,8 @@ export function parsePersistenceSnapshot(value: unknown): PersistenceSchemaInven
|
||||
return parseSnapshot(value, false)
|
||||
}
|
||||
|
||||
/** Parse an archived release inventory, including its optional surface operation fields.
|
||||
* @param value - JSON reconstructed from a historical release tag.
|
||||
/** Parse a historical inventory with path-only source references and optional surface operations.
|
||||
* @param value - JSON captured from a historical source tree.
|
||||
* @returns the validated inventory; current acknowledgements use the strict parser.
|
||||
*/
|
||||
export function parseHistoricalPersistenceSnapshot(value: unknown): PersistenceSchemaInventory {
|
||||
@@ -285,7 +285,12 @@ function parseSnapshot(value: unknown, historical: boolean): PersistenceSchemaIn
|
||||
const schema = parseSchema(type.schema, 'shared schema')
|
||||
if (digest(type.digest, 'shared digest') !== schemaDigest(schema)) throw new Error('shared schema digest mismatch')
|
||||
for (const name of array(type.names, 'type names')) textValue(name, 'type name')
|
||||
for (const source of array(type.sources, 'type sources')) textValue(source, 'type source')
|
||||
for (const source of array(type.sources, 'type sources')) {
|
||||
const location = textValue(source, 'type source')
|
||||
if (historical && /:\d+(?::\d+)?$|#L\d+(?:-L\d+)?$/u.test(location)) {
|
||||
throw new Error('historical schema sources must omit line numbers')
|
||||
}
|
||||
}
|
||||
}
|
||||
return input as unknown as PersistenceSchemaInventory
|
||||
}
|
||||
|
||||
@@ -21,15 +21,19 @@ function replaceRegion(source: string, name: string, content: string, path: stri
|
||||
function historicalSchema(entry: PersistenceFormatEntry, language: Language): string {
|
||||
const schema = basename(entry.schemaPath)
|
||||
const introduction = language === 'en'
|
||||
? `The [complete machine inventory](${schema}) contains ${entry.inventory.roots.length} roots and ${entry.inventory.types.length} reachable types. Digests include all referenced fields; source names and locations describe the selected historical tree.`
|
||||
: `[完整机器目录](${schema})包含 ${entry.inventory.roots.length} 个根类型和 ${entry.inventory.types.length} 种可达类型。摘要包含所有引用字段;源码名称和位置描述所选的历史源码树。`
|
||||
? `The [complete machine inventory](${schema}) contains ${entry.inventory.roots.length} roots and ${entry.inventory.types.length} reachable types. Digests include all referenced fields; source names and paths describe the selected historical tree.`
|
||||
: `[完整机器目录](${schema})包含 ${entry.inventory.roots.length} 个根类型和 ${entry.inventory.types.length} 种可达类型。摘要包含所有引用字段;源码名称和路径描述所选的历史源码树。`
|
||||
return [
|
||||
'<a id="schema"></a>',
|
||||
renderPersistenceSchemaIndex(entry.inventory, language, [introduction]),
|
||||
language === 'en' ? '## Complete schemas' : '## 完整 schema',
|
||||
'',
|
||||
introduction,
|
||||
'',
|
||||
renderPersistenceSchemaIndex(entry.inventory, language, [], 3),
|
||||
'<details>',
|
||||
language === 'en' ? '<summary>Complete resolved types</summary>' : '<summary>完整解析类型</summary>',
|
||||
'',
|
||||
renderPersistenceSchemaDefinitions(entry.inventory, language, () => undefined),
|
||||
renderPersistenceSchemaDefinitions(entry.inventory, language, () => undefined, 3),
|
||||
'</details>',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
/** Format reference coverage follows the writer version and retains complete historical schemas. */
|
||||
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { dump } from 'js-yaml'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { loadPersistenceFormats, runPersistenceFormats } from './persistence-formats.ts'
|
||||
import { parseHistoricalPersistenceSnapshot } from './persistence-changes.ts'
|
||||
import { canonicalizeSchema, schemaDigest } from './persistence-schema-model.ts'
|
||||
import type { PersistenceRoot, PersistenceSchemaInventory, PersistenceType, SchemaNode } from './persistence-schema-model.ts'
|
||||
|
||||
@@ -109,7 +110,98 @@ function prepareFacts(root: string, currentVersion = 3): void {
|
||||
}
|
||||
}
|
||||
|
||||
describe('archive current persistence format', () => {
|
||||
it('keeps every reachable type and drops extractor-retained types and source line numbers', () => {
|
||||
const root = fixture()
|
||||
const original = inventory(3)
|
||||
const sources = [
|
||||
'packages/example/src/types.ts:12', 'packages/other/src/types.ts:8:2', 'packages/example/src/types.ts:34:5',
|
||||
'packages/plain/src/types.ts', 'packages/fragment/src/types.ts#L8', 'packages/fragment/src/types.ts#L8-L12',
|
||||
]
|
||||
const types = original.types.map(type => ({ ...type, names: ['Example'], sources }))
|
||||
const schema = canonicalizeSchema([{ kind: 'literal', value: 'unreferenced' }], 0)
|
||||
replaceSnapshot(root, 3, 3, { ...original, types: [...types, { schema, digest: schemaDigest(schema), names: [], sources: [] }] })
|
||||
const before = readFileSync(join(root, 'docs/persistence-schema.json'), 'utf8')
|
||||
|
||||
expect(runPersistenceFormats(['--archive', '3'], root)).toBe('Archived Session format v3 to docs/persistence-formats/v3.schema.json.')
|
||||
const serialized = readFileSync(join(root, 'docs/persistence-formats/v3.schema.json'), 'utf8')
|
||||
const archived = parseHistoricalPersistenceSnapshot(JSON.parse(serialized))
|
||||
expect(archived).toEqual({
|
||||
...original,
|
||||
types: types.map(type => ({ ...type, sources: [
|
||||
'packages/example/src/types.ts', 'packages/other/src/types.ts', 'packages/plain/src/types.ts', 'packages/fragment/src/types.ts',
|
||||
] })),
|
||||
})
|
||||
expect(serialized).toBe(JSON.stringify(archived, null, 2) + '\n')
|
||||
expect(readFileSync(join(root, 'docs/persistence-schema.json'), 'utf8')).toBe(before)
|
||||
expect(existsSync(join(root, 'docs/persistence-formats/v3.md'))).toBe(false)
|
||||
|
||||
saveReference(root, 3, 4, archived)
|
||||
write(root, 'packages/core/session/src/types.ts', 'export const SESSION_FORMAT_VERSION = 4 as const\n')
|
||||
saveReference(root, 4, 4)
|
||||
expect(loadPersistenceFormats(root).entries[3]?.inventory).toEqual(archived)
|
||||
})
|
||||
|
||||
it('creates the first archive directory and honors --root', () => {
|
||||
const root = fixture(0)
|
||||
rmSync(join(root, 'docs/persistence-formats'), { recursive: true })
|
||||
expect(runPersistenceFormats(['--root', root, '--archive', '0'])).toBe('Archived Session format v0 to docs/persistence-formats/v0.schema.json.')
|
||||
expect(JSON.parse(readFileSync(join(root, 'docs/persistence-formats/v0.schema.json'), 'utf8'))).toEqual(inventory(0))
|
||||
})
|
||||
|
||||
it.each(['-1', '1.5', '01', '3junk', '9007199254740992'])('rejects an invalid archive version %s', (version) => {
|
||||
const root = fixture()
|
||||
expect(() => runPersistenceFormats([`--archive=${version}`], root)).toThrow('--archive must be a non-negative safe integer')
|
||||
expect(existsSync(join(root, 'docs/persistence-formats/v3.schema.json'))).toBe(false)
|
||||
})
|
||||
|
||||
it.each(['2', '4'])('rejects archive v%s when the current writer is v3', (version) => {
|
||||
const root = fixture()
|
||||
expect(() => runPersistenceFormats(['--archive', version], root)).toThrow(`Cannot archive v${version}: current writer is v3`)
|
||||
expect(existsSync(join(root, 'docs/persistence-formats/v3.schema.json'))).toBe(false)
|
||||
})
|
||||
|
||||
it('refuses to overwrite an existing archive', () => {
|
||||
const root = fixture()
|
||||
write(root, 'docs/persistence-formats/v3.schema.json', 'Retained history.\n')
|
||||
expect(() => runPersistenceFormats(['--archive', '3'], root)).toThrow('docs/persistence-formats/v3.schema.json already exists')
|
||||
expect(readFileSync(join(root, 'docs/persistence-formats/v3.schema.json'), 'utf8')).toBe('Retained history.\n')
|
||||
})
|
||||
|
||||
it('rejects --archive with --write before writing', () => {
|
||||
const root = fixture()
|
||||
expect(() => runPersistenceFormats(['--archive', '3', '--write'], root)).toThrow('--archive and --write cannot be combined')
|
||||
expect(existsSync(join(root, 'docs/persistence-formats/v3.schema.json'))).toBe(false)
|
||||
})
|
||||
|
||||
it.each(['invalid-json', 'digest-drift', 'missing-type', 'missing-source-metadata', 'outdated-header'])('rejects %s before creating an archive', (variant) => {
|
||||
const root = fixture()
|
||||
const original = inventory(3)
|
||||
if (variant === 'invalid-json') write(root, 'docs/persistence-schema.json', '{')
|
||||
else if (variant === 'digest-drift') replaceSnapshot(root, 3, 3, { ...original, roots: [{ ...original.roots[0]!, digest: '0'.repeat(64) }, ...original.roots.slice(1)] })
|
||||
else if (variant === 'missing-type') replaceSnapshot(root, 3, 3, { ...original, types: original.types.slice(1) })
|
||||
else if (variant === 'missing-source-metadata') edit(root, 'docs/persistence-schema.json', ',"sources":[]', '')
|
||||
else replaceSnapshot(root, 3, 3, inventory(2))
|
||||
expect(() => runPersistenceFormats(['--archive', '3'], root)).toThrow(variant === 'invalid-json' ? SyntaxError
|
||||
: variant === 'digest-drift' ? 'schema digest mismatch' : variant === 'missing-type' ? 'cover every reachable type'
|
||||
: variant === 'missing-source-metadata' ? 'missing field sources' : 'SessionHeader.version must match')
|
||||
expect(existsSync(join(root, 'docs/persistence-formats/v3.schema.json'))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('complete persistence format references', () => {
|
||||
it.each(['.md', '.zh.md'])('rejects source coordinates in authored format evidence in %s', (suffix) => {
|
||||
const root = fixture()
|
||||
const path = `docs/persistence-formats/v1${suffix}`
|
||||
const original = readFileSync(join(root, path), 'utf8')
|
||||
for (const position of [':36', ':36:2', '#L36', '#L36-L38']) {
|
||||
write(root, path, original + `\nSource: \`packages/core/session/src/types.ts${position}\`.\n`)
|
||||
expect(() => loadPersistenceFormats(root)).toThrow('historical source references must omit line numbers')
|
||||
}
|
||||
write(root, path, original + '\nSource: `packages/core/session/src/types.ts`.\n')
|
||||
expect(loadPersistenceFormats(root).entries).toHaveLength(4)
|
||||
})
|
||||
|
||||
it('loads a contiguous archive and the current catalog without Git or historical package sources', () => {
|
||||
const formats = loadPersistenceFormats(fixture())
|
||||
expect(formats.currentVersion).toBe(3)
|
||||
@@ -317,7 +409,16 @@ describe('complete persistence format references', () => {
|
||||
expect(runPersistenceFormats([], root)).toBe('Persistence formats: v0 through v3 verified (4 complete references).')
|
||||
expect(paths.map(path => readFileSync(join(root, path), 'utf8'))).toEqual(before)
|
||||
expect(readFileSync(join(root, 'docs/persistence-formats/README.md'), 'utf8')).toContain('Authored context.')
|
||||
expect(readFileSync(join(root, 'docs/persistence-formats/v1.md'), 'utf8')).toContain('pullRequest: 3349')
|
||||
const english = readFileSync(join(root, 'docs/persistence-formats/v1.md'), 'utf8')
|
||||
expect(english).toContain('pullRequest: 3349')
|
||||
const [visible, collapsed] = english.split('<details>')
|
||||
expect(visible).toContain('\n## Complete schemas\n')
|
||||
expect(visible).toContain('\n### Persistence type fingerprints\n')
|
||||
expect(collapsed).toContain('\n### Resolved persistence types\n')
|
||||
expect(collapsed).toContain('\n#### `SessionHeader`\n')
|
||||
expect(english.match(/^## /gmu)).toHaveLength(1)
|
||||
expect(english.match(/^### /gmu)).toHaveLength(2)
|
||||
expect(english.match(/^#### /gmu)).toHaveLength(inventory(1).types.length)
|
||||
edit(root, 'docs/persistence-formats/v1.md', '<summary>Complete resolved types</summary>', '<summary>Missing definitions</summary>')
|
||||
expect(() => runPersistenceFormats([], root)).toThrow('Stale persistence format facts')
|
||||
})
|
||||
@@ -326,7 +427,7 @@ describe('complete persistence format references', () => {
|
||||
const root = fixture(0)
|
||||
prepareFacts(root, 0)
|
||||
runPersistenceFormats(['--write'], root)
|
||||
expect(runPersistenceFormats([], root)).toBe('Persistence formats: v0 through v0 verified (1 complete references).')
|
||||
expect(runPersistenceFormats([], root)).toBe('Persistence formats: v0 through v0 verified (1 complete reference).')
|
||||
})
|
||||
|
||||
it.each(['missing', 'stale'])('rejects a %s format pairing record and refreshes it with --write', (variant) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Verify complete Session format references from version zero through the current writer. */
|
||||
/** Archive and verify complete Session format references through the current writer. */
|
||||
|
||||
import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { parseArgs } from 'node:util'
|
||||
import { JSON_SCHEMA, load } from 'js-yaml'
|
||||
@@ -9,6 +9,7 @@ import { parseHistoricalPersistenceSnapshot, parsePersistenceSnapshot } from './
|
||||
import { persistenceFormatFactArtifacts } from './persistence-format-facts.ts'
|
||||
import { canonicalizeSchema, schemaDigest } from './persistence-schema-model.ts'
|
||||
import type { PersistenceSchemaInventory } from './persistence-schema-model.ts'
|
||||
import { withoutPersistenceSourceLines } from './persistence-source-metadata.ts'
|
||||
|
||||
const DIRECTORY = 'docs/persistence-formats'
|
||||
const CURRENT_DOCUMENT = 'docs/persistence-catalog.md'
|
||||
@@ -47,6 +48,9 @@ function fields(value: unknown, expected: readonly string[], label: string): Rec
|
||||
}
|
||||
|
||||
function machineBlock(document: string, label: string): string {
|
||||
if (/\.[cm]?[jt]sx?(?::\d+(?::\d+)?|#L\d+(?:-L\d+)?)/u.test(document)) {
|
||||
throw new Error(`${label}: historical source references must omit line numbers`)
|
||||
}
|
||||
const frontmatter = /^---\n([\s\S]*?)\n---(?:\n|$)/u.exec(document)?.[1]
|
||||
const metadata: unknown = frontmatter === undefined ? undefined : load(frontmatter, { schema: JSON_SCHEMA })
|
||||
if (metadata === null || typeof metadata !== 'object' || !('kind' in metadata) || metadata.kind !== 'persistence-format') {
|
||||
@@ -83,7 +87,7 @@ function parseRecord(block: string, version: number): PersistenceFormatRecord {
|
||||
return { source: parseSource(record.source, label), roots }
|
||||
}
|
||||
|
||||
function validateInventory(inventory: PersistenceSchemaInventory, version: number, current: boolean): void {
|
||||
function validateInventory(inventory: PersistenceSchemaInventory, version: number, current: boolean): ReadonlySet<string> {
|
||||
const label = `v${version}`
|
||||
for (const key of ['SessionHeader', 'JsonlHeaderLine', 'SessionEventEnvelope']) {
|
||||
const root = inventory.roots.find(root => root.key === key)
|
||||
@@ -110,6 +114,7 @@ function validateInventory(inventory: PersistenceSchemaInventory, version: numbe
|
||||
remaining.delete(type.digest)
|
||||
}
|
||||
if (remaining.size > 0) throw new Error(`${label}: schema types must cover every reachable type`)
|
||||
return reachable
|
||||
}
|
||||
|
||||
function validateDocument(
|
||||
@@ -176,21 +181,42 @@ export function loadPersistenceFormats(root: string): PersistenceFormats {
|
||||
return { currentVersion, entries }
|
||||
}
|
||||
|
||||
function archiveCurrentInventory(root: string, requestedVersion: string): string {
|
||||
const version = Number(requestedVersion)
|
||||
if (!/^(?:0|[1-9]\d*)$/u.test(requestedVersion) || !Number.isSafeInteger(version)) {
|
||||
throw new Error('--archive must be a non-negative safe integer')
|
||||
}
|
||||
const currentVersion = readCurrentSessionFormatVersion(root)
|
||||
if (version !== currentVersion) throw new Error(`Cannot archive v${version}: current writer is v${currentVersion}`)
|
||||
const path = `${DIRECTORY}/v${version}.schema.json`
|
||||
if (existsSync(join(root, path))) throw new Error(`Cannot archive v${version}: ${path} already exists`)
|
||||
const inventory = parsePersistenceSnapshot(JSON.parse(readFileSync(join(root, CURRENT_SCHEMA), 'utf8')))
|
||||
const reachable = validateInventory(inventory, version, true)
|
||||
const archive = withoutPersistenceSourceLines({ ...inventory, types: inventory.types.filter(type => reachable.has(type.digest)) })
|
||||
mkdirSync(join(root, DIRECTORY), { recursive: true })
|
||||
writeFileSync(join(root, path), JSON.stringify(archive, null, 2) + '\n', { flag: 'wx' })
|
||||
return `Archived Session format v${version} to ${path}.`
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate format coverage and check or refresh the historical schema and index regions.
|
||||
* @param args - CLI arguments; --write refreshes generated facts after complete validation.
|
||||
* Archive the current schema or validate and optionally refresh format references.
|
||||
* @param args - --archive N creates the current version's schema once; --write refreshes validated facts.
|
||||
* @param root - default checkout directory, overridden by --root when provided.
|
||||
* @returns the verified format count and optional number of refreshed artifacts.
|
||||
* @returns the created schema path or verified format count and refreshed artifact count.
|
||||
*/
|
||||
export function runPersistenceFormats(args: readonly string[], root = resolve(import.meta.dirname, '..')): string {
|
||||
const { values } = parseArgs({ args: [...args], options: { root: { type: 'string' }, write: { type: 'boolean' } } })
|
||||
const { values } = parseArgs({ args: [...args], options: { root: { type: 'string' }, write: { type: 'boolean' }, archive: { type: 'string' } } })
|
||||
root = resolve(values.root ?? root)
|
||||
if (values.archive !== undefined) {
|
||||
if (values.write) throw new Error('--archive and --write cannot be combined')
|
||||
return archiveCurrentInventory(root, values.archive)
|
||||
}
|
||||
const formats = loadPersistenceFormats(root)
|
||||
const changed = persistenceFormatFactArtifacts(root, formats).filter(artifact => !existsSync(join(root, artifact.path))
|
||||
|| readFileSync(join(root, artifact.path), 'utf8') !== artifact.content)
|
||||
if (!values.write && changed.length > 0) throw new Error(`Stale persistence format facts: ${changed.map(artifact => artifact.path).join(', ')}. Run pnpm run verify-persistence-formats --write.`)
|
||||
if (values.write) for (const artifact of changed) writeFileSync(join(root, artifact.path), artifact.content)
|
||||
return `Persistence formats: v0 through v${formats.currentVersion} verified (${formats.entries.length} complete references).`
|
||||
return `Persistence formats: v0 through v${formats.currentVersion} verified (${formats.entries.length} complete reference${formats.entries.length === 1 ? '' : 's'}).`
|
||||
+ (values.write ? ` Refreshed ${changed.length} file${changed.length === 1 ? '' : 's'}.` : '')
|
||||
}
|
||||
|
||||
|
||||
@@ -119,6 +119,26 @@ function replaceSnapshot(fixture: Fixture, index: number, snapshot: PersistenceS
|
||||
}
|
||||
|
||||
describe('pinned persistence releases', () => {
|
||||
it.each(['.md', '.zh.md'])('rejects historical source coordinates in %s records', (suffix) => {
|
||||
const data = fixture()
|
||||
const path = join(data.directory, TAGS[0] + suffix)
|
||||
const original = readFileSync(path, 'utf8')
|
||||
for (const position of [':36', ':36:2', '#L36', '#L36-L38']) {
|
||||
writeFileSync(path, original + `\nSource: \`packages/core/session/src/types.ts${position}\`.\n`)
|
||||
expect(() => loadPersistenceReleases(data.root)).toThrow('historical source references must omit line numbers')
|
||||
}
|
||||
writeFileSync(path, original + '\nSource: `packages/core/session/src/types.ts`.\n')
|
||||
expect(loadPersistenceReleases(data.root).entries).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('rejects historical source coordinates in release schema metadata', () => {
|
||||
const data = fixture()
|
||||
const snapshot = data.snapshots[0]!
|
||||
replaceSnapshot(data, 0, { ...snapshot, types: snapshot.types.map((type, index) => index === 0
|
||||
? { ...type, sources: ['packages/core/session/src/types.ts:36'] } : type) })
|
||||
expect(() => loadPersistenceReleases(data.root)).toThrow('historical schema sources must omit line numbers')
|
||||
})
|
||||
|
||||
it('reconstructs breaking version-zero changes and unchanged releases from a tree without Git or package sources', () => {
|
||||
const data = fixture()
|
||||
const archive = loadPersistenceReleases(data.root)
|
||||
|
||||
@@ -121,6 +121,9 @@ function parseManifest(value: unknown): PersistenceReleaseManifest {
|
||||
}
|
||||
|
||||
function machineBlock(source: string, label: string): string {
|
||||
if (/\.[cm]?[jt]sx?(?::\d+(?::\d+)?|#L\d+(?:-L\d+)?)/u.test(source)) {
|
||||
throw new Error(`${label}: historical source references must omit line numbers`)
|
||||
}
|
||||
const metadata = /^---\n([\s\S]*?)\n---(?:\n|$)/u.exec(source)?.[1]
|
||||
const frontmatter: unknown = metadata === undefined ? undefined : load(metadata, { schema: JSON_SCHEMA })
|
||||
if (frontmatter === null || typeof frontmatter !== 'object' || !('kind' in frontmatter) || frontmatter.kind !== 'persistence-release') {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/** Stable source-file metadata for saved persistence inventories. */
|
||||
|
||||
import type { PersistenceSchemaInventory } from './persistence-schema-model.ts'
|
||||
|
||||
/**
|
||||
* Remove source line positions without changing schemas, names, or fingerprints.
|
||||
* @param inventory - validated inventory whose source metadata will be copied.
|
||||
* @returns an inventory with unique source paths in their original order.
|
||||
*/
|
||||
export function withoutPersistenceSourceLines(inventory: PersistenceSchemaInventory): PersistenceSchemaInventory {
|
||||
return {
|
||||
...inventory,
|
||||
types: inventory.types.map(type => ({
|
||||
...type,
|
||||
sources: [...new Set(type.sources.map(source => source.replace(/(?::\d+(?::\d+)?|#L\d+(?:-L\d+)?)$/u, '')))],
|
||||
})),
|
||||
}
|
||||
}
|
||||
@@ -48,15 +48,20 @@ describe('persistence schema catalog', () => {
|
||||
expect(before).not.toBe(after)
|
||||
})
|
||||
|
||||
it('renders historical source locations without linking them to current files', () => {
|
||||
const inventory = fixture()
|
||||
const definitions = renderPersistenceSchemaDefinitions(inventory, 'en', () => undefined)
|
||||
expect(definitions).toContain('Sources: `packages/core/example/src/types.ts:8`')
|
||||
it('renders historical source paths and nested headings within their reference section', () => {
|
||||
const current = fixture()
|
||||
const inventory = { ...current, types: current.types.map(type => ({ ...type, sources: type.sources.map(source => source.replace(/:\d+$/u, '')) })) }
|
||||
const definitions = renderPersistenceSchemaDefinitions(inventory, 'en', () => undefined, 3)
|
||||
expect(definitions).toContain('Sources: `packages/core/example/src/types.ts`')
|
||||
expect(definitions).not.toContain('types.ts:8')
|
||||
expect(definitions).not.toContain('(../packages/')
|
||||
const index = renderPersistenceSchemaIndex(inventory, 'en', ['[Historical schema](v0.schema.json)'])
|
||||
expect(definitions).toContain('### Resolved persistence types')
|
||||
expect(definitions).toContain('#### `ErrorInfo`')
|
||||
const index = renderPersistenceSchemaIndex(inventory, 'en', ['[Historical schema](v0.schema.json)'], 3)
|
||||
expect(index).toContain('[Historical schema](v0.schema.json)')
|
||||
expect(index).toContain('### Persistence type fingerprints')
|
||||
expect(index).not.toContain('(persistence-schema.json)')
|
||||
expect(renderPersistenceSchemaDefinitions(inventory)).toContain('(../packages/core/example/src/types.ts)')
|
||||
expect(renderPersistenceSchemaDefinitions(current)).toContain('[`packages/core/example/src/types.ts:8`](../packages/core/example/src/types.ts)')
|
||||
})
|
||||
|
||||
it('refuses a current inventory that omits a referenced definition', () => {
|
||||
|
||||
@@ -106,11 +106,12 @@ function definition(
|
||||
entries: ReadonlyMap<string, TypeDisplay>,
|
||||
locale: PersistenceCatalogLocale,
|
||||
sourceLink: (source: string) => string | undefined,
|
||||
headingLevel: number,
|
||||
): string[] {
|
||||
const text = persistenceCatalogText[locale]
|
||||
const schema = entry.type.schema
|
||||
const node = nodeAt(schema, 0)
|
||||
const lines = [`<a id="${entry.anchor}"></a>`, '', `### ${code(entry.label)}`, '', `SHA-256: ${code(entry.type.digest)}`, '']
|
||||
const lines = [`<a id="${entry.anchor}"></a>`, '', `${'#'.repeat(headingLevel)} ${code(entry.label)}`, '', `SHA-256: ${code(entry.type.digest)}`, '']
|
||||
if (entry.type.sources.length > 0) {
|
||||
lines.push(`${text.sources}${entry.type.sources.map((source) => {
|
||||
const href = sourceLink(sourcePath(source))
|
||||
@@ -155,17 +156,19 @@ function definition(
|
||||
* @param inventory - complete current-source schemas and declaration metadata.
|
||||
* @param locale - generated document language.
|
||||
* @param introduction - paragraphs before the root table; defaults to current-source links.
|
||||
* @param headingLevel - section depth within the containing reference.
|
||||
* @returns Markdown index including the history and contributor workflow links.
|
||||
*/
|
||||
export function renderPersistenceSchemaIndex(
|
||||
inventory: PersistenceSchemaInventory,
|
||||
locale: PersistenceCatalogLocale = 'en',
|
||||
introduction: readonly string[] = [persistenceCatalogText[locale].fingerprintsIntro, persistenceCatalogText[locale].historyIntro],
|
||||
headingLevel: 2 | 3 = 2,
|
||||
): string {
|
||||
const entries = displays(inventory)
|
||||
const text = persistenceCatalogText[locale]
|
||||
return [
|
||||
`## ${text.fingerprints}`, '', ...introduction.flatMap(paragraph => [paragraph, '']),
|
||||
`${'#'.repeat(headingLevel)} ${text.fingerprints}`, '', ...introduction.flatMap(paragraph => [paragraph, '']),
|
||||
text.rootColumns, '|---|---|---|---|',
|
||||
...inventory.roots.map(root => `| ${code(root.key)} | ${root.kind} | ${code(root.digest)} | ${reference(root.digest, entries)} |`), '',
|
||||
].join('\n')
|
||||
@@ -176,19 +179,21 @@ export function renderPersistenceSchemaIndex(
|
||||
* @param inventory - complete current-source schemas and declaration metadata.
|
||||
* @param locale - generated document language.
|
||||
* @param sourceLink - source path to URL; undefined keeps historical locations as text.
|
||||
* @param headingLevel - section depth; individual definitions use the next heading level.
|
||||
* @returns Markdown definitions whose anchors use names or owning paths instead of hashes.
|
||||
*/
|
||||
export function renderPersistenceSchemaDefinitions(
|
||||
inventory: PersistenceSchemaInventory,
|
||||
locale: PersistenceCatalogLocale = 'en',
|
||||
sourceLink: (source: string) => string | undefined = source => `../${source}`,
|
||||
headingLevel: 2 | 3 = 2,
|
||||
): string {
|
||||
const entries = displays(inventory)
|
||||
const text = persistenceCatalogText[locale]
|
||||
const sorted = [...entries.values()].sort((left, right) => left.anchor < right.anchor ? -1 : left.anchor > right.anchor ? 1 : 0)
|
||||
return [
|
||||
`## ${text.definitions}`, '', text.definitionsIntro, '',
|
||||
...sorted.flatMap(entry => definition(entry, entries, locale, sourceLink)),
|
||||
`${'#'.repeat(headingLevel)} ${text.definitions}`, '', text.definitionsIntro, '',
|
||||
...sorted.flatMap(entry => definition(entry, entries, locale, sourceLink, headingLevel + 1)),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user