@wildshard/shard-format 0.67.0 → 0.68.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/package.json +7 -19
  2. package/src/cli/corpus-deprecations.ts +57 -0
  3. package/src/cli/corpus-gate.ts +114 -0
  4. package/src/cli/corpus-migrated.ts +68 -0
  5. package/src/cli/corpus.ts +300 -0
  6. package/src/cli/main.ts +41 -0
  7. package/src/format/cook-preparation.ts +22 -6
  8. package/src/format/creature-layers.ts +4 -0
  9. package/src/format/deprecations.ts +228 -0
  10. package/src/format/empty-shardfile.json +56 -0
  11. package/src/format/empty-shardfile.ts +43 -0
  12. package/src/format/format-migrate-inventory.ts +142 -0
  13. package/src/format/format-migrate-rebuild.ts +269 -0
  14. package/src/format/format-migrate.ts +290 -0
  15. package/src/format/format-migration-journal.ts +129 -0
  16. package/src/format/format-migration-ops.ts +230 -0
  17. package/src/format/format-migration-prune.ts +106 -0
  18. package/src/format/format-migrations.ts +124 -0
  19. package/src/format/issue-codes.ts +3 -1
  20. package/src/format/journal-glyphs.json +12 -0
  21. package/src/format/memory-armed.json +1 -39
  22. package/src/format/memory-armed.ts +41 -8
  23. package/src/format/memory-epoch.ts +2 -2
  24. package/src/format/memory-line.ts +4 -3
  25. package/src/format/memoryAdmission.ts +1 -1
  26. package/src/format/policy-verdict.ts +95 -0
  27. package/src/format/rows.ts +6 -4
  28. package/src/format/runtime-tier.ts +3 -3
  29. package/src/format/shardSections.ts +11 -1
  30. package/src/format/shardfile-assets.ts +12 -8
  31. package/src/format/shardfile-stream-admit.ts +41 -16
  32. package/src/format/shardfile-stream-rows.ts +3 -1
  33. package/src/format/shardfile-stream.ts +12 -9
  34. package/src/format/shardfileValidation.ts +30 -18
  35. package/src/format/stateLineage.ts +1 -1
  36. package/src/format/version.ts +11 -13
  37. package/src/format/baked-terrain.golden.json +0 -2760
  38. package/src/format/colliders.golden.json +0 -1619
  39. package/src/format/forest-placement.golden.json +0 -4588
  40. package/src/format/geometry-layout.golden.json +0 -180
  41. package/src/format/interact-table.golden.json +0 -340
  42. package/src/format/item-catalogue.golden.json +0 -2310
  43. package/src/format/memory-ratchet.ts +0 -107
  44. package/src/format/small-laws.golden.json +0 -57
  45. package/src/format/terrain-field.golden.json +0 -3998
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wildshard/shard-format",
3
- "version": "0.67.0",
3
+ "version": "0.68.1",
4
4
  "description": "The raw shardfile format: the spec, the validator and a validate CLI. The public, versioned contract every other repo builds on.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -21,15 +21,9 @@
21
21
  "!src/format/*.golden-specs.ts",
22
22
  "src/format/memoryGates.json",
23
23
  "src/format/memory-armed.json",
24
+ "src/format/empty-shardfile.json",
25
+ "src/format/journal-glyphs.json",
24
26
  "src/format/seeded-rng.golden.json",
25
- "src/format/terrain-field.golden.json",
26
- "src/format/baked-terrain.golden.json",
27
- "src/format/forest-placement.golden.json",
28
- "src/format/geometry-layout.golden.json",
29
- "src/format/colliders.golden.json",
30
- "src/format/small-laws.golden.json",
31
- "src/format/interact-table.golden.json",
32
- "src/format/item-catalogue.golden.json",
33
27
  "src/tools/runtime-hosts.json",
34
28
  "packages/wire/src/net-command.ts",
35
29
  "src/cli/*.ts",
@@ -124,7 +118,6 @@
124
118
  "./director": "./src/format/director.ts",
125
119
  "./detail-layer": "./src/format/detail-layer.ts",
126
120
  "./pbr-emissive": "./src/format/pbr-emissive.ts",
127
- "./pbr-fur": "./src/format/pbr-fur.ts",
128
121
  "./fur-strands": "./src/format/fur-strands.ts",
129
122
  "./scene-render": "./src/format/scene-render.ts",
130
123
  "./look-level": "./src/format/look-level.ts",
@@ -349,10 +342,12 @@
349
342
  "./scripts": "./src/format/scripts.ts",
350
343
  "./sections": "./src/format/sections.ts",
351
344
  "./shardSchema": "./src/format/shardSchema.ts",
345
+ "./emptyShardfile": "./src/format/empty-shardfile.ts",
346
+ "./migrate": "./src/format/format-migrate.ts",
347
+ "./formatMigrations": "./src/format/format-migrations.ts",
352
348
  "./shardSections": "./src/format/shardSections.ts",
353
349
  "./sketch": "./src/format/sketch.ts",
354
350
  "./skinAssets": "./src/format/skinAssets.ts",
355
- "./skinTextures": "./src/format/skin-textures.ts",
356
351
  "./skinData": "./src/format/skinData.ts",
357
352
  "./skinLayers": "./src/format/skinLayers.ts",
358
353
  "./skins": "./src/format/skins.ts",
@@ -435,24 +430,16 @@
435
430
  "./seeded-rng.golden.json": "./src/format/seeded-rng.golden.json",
436
431
  "./noise": "./src/format/noise.ts",
437
432
  "./terrainField": "./src/format/terrain-field.ts",
438
- "./terrain-field.golden.json": "./src/format/terrain-field.golden.json",
439
433
  "./forestPlacement": "./src/format/forest-placement.ts",
440
434
  "./grassField": "./src/format/grass-field.ts",
441
- "./forest-placement.golden.json": "./src/format/forest-placement.golden.json",
442
435
  "./nativeGeometryChannels": "./src/format/native-geometry-channels.ts",
443
436
  "./wholePartition": "./src/format/whole-partition.ts",
444
- "./geometry-layout.golden.json": "./src/format/geometry-layout.golden.json",
445
437
  "./colliders": "./src/format/colliders.ts",
446
- "./colliders.golden.json": "./src/format/colliders.golden.json",
447
438
  "./headlessSections": "./src/format/headless-sections.ts",
448
439
  "./roadLight": "./src/format/road-light.ts",
449
440
  "./moverPose": "./src/format/mover-pose.ts",
450
- "./small-laws.golden.json": "./src/format/small-laws.golden.json",
451
441
  "./interactTable": "./src/format/interact-table.ts",
452
- "./interact-table.golden.json": "./src/format/interact-table.golden.json",
453
442
  "./itemCatalogue": "./src/format/item-catalogue.ts",
454
- "./item-catalogue.golden.json": "./src/format/item-catalogue.golden.json",
455
- "./baked-terrain.golden.json": "./src/format/baked-terrain.golden.json",
456
443
  "./rigLooks": "./src/format/rig-looks.ts"
457
444
  },
458
445
  "engines": {
@@ -469,6 +456,7 @@
469
456
  "format:check": "npr oxfmt -c kit/.oxfmtrc.json --check kit src '!src/format/**' '!src/test/fixtures/**'",
470
457
  "test": "node --test 'src/!(format|ci)/**/*.test.ts'",
471
458
  "test:ci": "node --test 'src/ci/**/*.test.ts'",
459
+ "test:chain": "node --test 'src/tools/*.chain.ts'",
472
460
  "test:format": "vitest run src/format --testTimeout=30000 --maxWorkers=2",
473
461
  "check:asks": "node kit/scripts/asks.mjs check",
474
462
  "check:agents": "node .githooks/agents-md.mjs lint",
@@ -0,0 +1,57 @@
1
+ /** The corpus's deprecation count (SHARD-COMPAT FE7): how many kept originals use each deprecated path, and which. */
2
+ import { createReadStream } from 'node:fs'
3
+
4
+ import { nodeStreamPorts } from '../format/shardfile-stream-node.ts'
5
+ import { validateShardfileStream } from '../format/shardfile-stream.ts'
6
+ import { migratedVerdict } from './corpus-migrated.ts'
7
+
8
+ import type { CorpusRow } from './corpus.ts'
9
+
10
+ /** A valid original's deprecated paths, and the chain steps that made it valid when it was refused as stored. */
11
+ interface StoredVerdict {
12
+ readonly deprecations: readonly string[]
13
+ /** `migrated: <steps>` when the chain's copy is what validated. */
14
+ readonly reason?: string
15
+ }
16
+
17
+ /** Validate one stored original (brotli unless `plain`) as the API stored it; one the format refuses is judged again
18
+ * through the migration chain (J486). Throws the copy's refusal when that fails too. */
19
+ async function storedDeprecations(
20
+ file: string,
21
+ plain: boolean,
22
+ ): Promise<StoredVerdict> {
23
+ try {
24
+ const validated = await validateShardfileStream(
25
+ (): AsyncIterable<Uint8Array> => createReadStream(file),
26
+ { ...nodeStreamPorts({ brotli: !plain }), judged: 'stored' },
27
+ )
28
+ return { deprecations: validated.deprecations }
29
+ } catch (error: unknown) {
30
+ const copy = await migratedVerdict(file, plain, error)
31
+ return {
32
+ deprecations: copy.deprecations,
33
+ reason: `migrated: ${copy.applied.join(', ')}`,
34
+ }
35
+ }
36
+ }
37
+
38
+ /** FE7: one line per deprecated path a kept original uses, with how many and which. */
39
+ function deprecationLines(
40
+ rows: readonly Pick<CorpusRow, 'slug' | 'revision' | 'deprecations'>[],
41
+ ): string[] {
42
+ const users = new Map<string, string[]>()
43
+ for (const found of rows) {
44
+ for (const id of found.deprecations) {
45
+ users.set(id, [
46
+ ...(users.get(id) ?? []),
47
+ `${found.slug} r${String(found.revision)}`,
48
+ ])
49
+ }
50
+ }
51
+ return [...users].map(
52
+ ([id, names]: readonly [string, readonly string[]]): string =>
53
+ `deprecated ${id}: ${String(names.length)} kept originals (${names.join(', ')})`,
54
+ )
55
+ }
56
+
57
+ export { type StoredVerdict, deprecationLines, storedDeprecations }
@@ -0,0 +1,114 @@
1
+ import {
2
+ array,
3
+ minLength,
4
+ number,
5
+ parse,
6
+ pipe,
7
+ regex,
8
+ safeInteger,
9
+ strictObject,
10
+ string,
11
+ } from 'valibot'
12
+
13
+ import type { CorpusRow } from './corpus.ts'
14
+
15
+ // SHARD-COMPAT FE5 (meta, J486, Q51): the corpus gates a format release. A stored original that fails blocks the
16
+ // release unless `corpus/known-failures.json` lists it with the row that owns its repair; a listed one that passes
17
+ // again is named as stale, so the list only shrinks.
18
+
19
+ /** A stored original known to fail, and the row that owns its repair. */
20
+ interface KnownFailure {
21
+ readonly hash: string
22
+ readonly slug: string
23
+ readonly revision: number
24
+ readonly owner: string
25
+ }
26
+
27
+ /** What the gate decided: the failures that block, the stale entries, and one line for each. */
28
+ interface CorpusGate {
29
+ readonly blocking: readonly CorpusRow[]
30
+ readonly stale: readonly KnownFailure[]
31
+ readonly lines: readonly string[]
32
+ }
33
+
34
+ const HASH = pipe(string(), regex(/^[a-f0-9]{64}$/u))
35
+ const REVISION = pipe(number(), safeInteger())
36
+ const NAMED = 1
37
+ const OWNER = pipe(string(), minLength(NAMED))
38
+ const KnownFailuresSchema = array(
39
+ strictObject({
40
+ hash: HASH,
41
+ slug: string(),
42
+ revision: REVISION,
43
+ owner: OWNER,
44
+ }),
45
+ )
46
+
47
+ /** Parse `corpus/known-failures.json`. */
48
+ function readKnownFailures(text: string): readonly KnownFailure[] {
49
+ const input: unknown = JSON.parse(text)
50
+ return parse(KnownFailuresSchema, input)
51
+ }
52
+
53
+ function named(found: Readonly<{ slug: string; revision: number }>): string {
54
+ return `${found.slug} r${String(found.revision)}`
55
+ }
56
+
57
+ /** The failing rows, each with its owner when the list knows it. */
58
+ function failures(
59
+ rows: readonly CorpusRow[],
60
+ owners: ReadonlyMap<string, string>,
61
+ ): readonly (readonly [CorpusRow, string | undefined])[] {
62
+ return rows
63
+ .filter((found: Readonly<CorpusRow>): boolean => found.verdict === 'fails')
64
+ .map((found: CorpusRow): readonly [CorpusRow, string | undefined] => [
65
+ found,
66
+ owners.get(found.hash),
67
+ ])
68
+ }
69
+
70
+ /** Split the corpus rows by the known failures. */
71
+ function corpusGate(
72
+ rows: readonly CorpusRow[],
73
+ known: readonly KnownFailure[],
74
+ ): CorpusGate {
75
+ const owners = new Map(
76
+ known.map((entry: KnownFailure): readonly [string, string] => [
77
+ entry.hash,
78
+ entry.owner,
79
+ ]),
80
+ )
81
+ const failing = failures(rows, owners)
82
+ const valid = new Set(
83
+ rows
84
+ .filter(
85
+ (found: Readonly<CorpusRow>): boolean => found.verdict === 'valid',
86
+ )
87
+ .map((found: Readonly<CorpusRow>): string => found.hash),
88
+ )
89
+ const blocking = failing
90
+ .filter(([, owner]): boolean => owner === undefined)
91
+ .map(([found]): CorpusRow => found)
92
+ const stale = known.filter((entry: KnownFailure): boolean =>
93
+ valid.has(entry.hash),
94
+ )
95
+ const lines = [
96
+ ...failing
97
+ .filter(([, owner]): boolean => owner !== undefined)
98
+ .map(
99
+ ([found, owner]): string =>
100
+ `known failure ${named(found)} (${owner ?? ''})`,
101
+ ),
102
+ ...stale.map(
103
+ (entry: KnownFailure): string =>
104
+ `stale known failure ${named(entry)}: it passes now; drop it from corpus/known-failures.json`,
105
+ ),
106
+ ...blocking.map(
107
+ (found: Readonly<CorpusRow>): string =>
108
+ `BLOCKS THE RELEASE: ${named(found)} ${found.reason ?? ''}`,
109
+ ),
110
+ ]
111
+ return { blocking, stale, lines }
112
+ }
113
+
114
+ export { type CorpusGate, type KnownFailure, corpusGate, readKnownFailures }
@@ -0,0 +1,68 @@
1
+ /** The corpus judges an older original through the migration chain (J486, SHARD-COMPAT CP1): a file the current
2
+ * format refuses as stored still counts as valid when the chain's copy validates, with the author's own preparation
3
+ * when the steps leave it sealed. */
4
+ import { createHash } from 'node:crypto'
5
+ import { readFile } from 'node:fs/promises'
6
+ import { promisify } from 'node:util'
7
+ import { brotliDecompress } from 'node:zlib'
8
+
9
+ import { migrateShardfile, validateMigrated } from '../format/format-migrate.ts'
10
+ import { prepareAssetDecoders } from '../format/shardfile-assets.ts'
11
+ import { readTar } from '../format/tar.ts'
12
+
13
+ /** What the chain did to a refused original whose copy validates. */
14
+ interface MigratedVerdict {
15
+ readonly applied: readonly string[]
16
+ readonly deprecations: readonly string[]
17
+ }
18
+
19
+ const NONE = 0
20
+ const unbrotli = promisify(brotliDecompress)
21
+
22
+ function sha256(bytes: Readonly<Uint8Array>): string {
23
+ return createHash('sha256').update(bytes).digest('hex')
24
+ }
25
+
26
+ /** The chain's copy of an original tarball, or `undefined` when it cannot be read or the chain cannot run on it. */
27
+ function tryChain(
28
+ tar: Readonly<Uint8Array>,
29
+ ): ReturnType<typeof migrateShardfile> | undefined {
30
+ try {
31
+ return migrateShardfile(readTar(tar), { hash: sha256 })
32
+ } catch {
33
+ return undefined
34
+ }
35
+ }
36
+
37
+ /** The chain's copy of an original, or the stored refusal when the chain cannot run or changes nothing. */
38
+ function chainCopy(
39
+ tar: Readonly<Uint8Array>,
40
+ refused: unknown,
41
+ ): ReturnType<typeof migrateShardfile> {
42
+ const copy = tryChain(tar)
43
+ if (copy === undefined || copy.applied.length === NONE) {
44
+ throw refused
45
+ }
46
+ return copy
47
+ }
48
+
49
+ /** Migrate one stored original (brotli unless `plain`) and validate the copy. Throws the copy's refusal; when the chain cannot
50
+ * run or changes nothing, the stored refusal (`refused`). */
51
+ async function migratedVerdict(
52
+ file: string,
53
+ plain: boolean,
54
+ refused: unknown,
55
+ ): Promise<MigratedVerdict> {
56
+ const stored = new Uint8Array(await readFile(file))
57
+ const tar = plain ? stored : new Uint8Array(await unbrotli(stored))
58
+ const copy = chainCopy(tar, refused)
59
+ await prepareAssetDecoders()
60
+ const validated = validateMigrated(copy.files, {
61
+ hash: sha256,
62
+ judged: 'stored',
63
+ preparation: copy.preparation === 'stale' ? 'migrated' : 'author',
64
+ })
65
+ return { applied: copy.applied, deprecations: validated.deprecations }
66
+ }
67
+
68
+ export { type MigratedVerdict, migratedVerdict }
@@ -0,0 +1,300 @@
1
+ import { createWriteStream } from 'node:fs'
2
+ import { mkdir, open, readFile, rm, writeFile } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { Readable } from 'node:stream'
5
+ import { pipeline } from 'node:stream/promises'
6
+
7
+ import {
8
+ array,
9
+ number,
10
+ object,
11
+ optional,
12
+ parse,
13
+ pipe,
14
+ regex,
15
+ safeInteger,
16
+ string,
17
+ } from 'valibot'
18
+
19
+ import { deprecationLines, storedDeprecations } from './corpus-deprecations.ts'
20
+
21
+ import type { InferOutput } from 'valibot'
22
+
23
+ // `shard-format corpus` (meta SHARD-COMPAT FE3, J486 Q47 Q52): run this
24
+ // validator over every stored shard file the API keeps, as a stored
25
+ // original (`judged: 'stored'`: readability, not memory policy), and list
26
+ // every failure by shard, revision and reason. It reads the API's public
27
+ // list (`GET /api/shardfiles`: originals prune has not marked) and each
28
+ // original by hash (`GET /api/shardfiles/<hash>`), so it needs no token.
29
+ // The stream validator keeps only the index and JSON members and hashes
30
+ // blobs as they pass, so memory stays bounded; a verdict is cached by
31
+ // original hash and validator version, so a warm run fetches only new
32
+ // uploads. The migration chain (CP1) joins here when it exists.
33
+
34
+ const NamedSchema = object({ shard: string(), revision: number() })
35
+ const RecordSchema = object({
36
+ hash: pipe(string(), regex(/^[a-f0-9]{64}$/u)),
37
+ storedBytes: pipe(number(), safeInteger()),
38
+ revisions: array(NamedSchema),
39
+ })
40
+ const ListSchema = object({ shardfiles: array(RecordSchema) })
41
+ const IDS = array(string())
42
+ const CachedSchema = object({
43
+ validator: string(),
44
+ verdict: string(),
45
+ reason: optional(string()),
46
+ deprecations: optional(IDS),
47
+ })
48
+
49
+ type StoredRecord = Readonly<{
50
+ hash: string
51
+ storedBytes: number
52
+ revisions: readonly Readonly<InferOutput<typeof NamedSchema>>[]
53
+ }>
54
+
55
+ interface CorpusRow {
56
+ readonly slug: string
57
+ readonly revision: number
58
+ readonly hash: string
59
+ readonly storedBytes: number
60
+ readonly verdict: 'valid' | 'fails'
61
+ readonly reason: string | undefined
62
+ readonly cached: boolean
63
+ readonly deprecations: readonly string[]
64
+ }
65
+
66
+ type Judgement = Readonly<{
67
+ verdict: 'valid' | 'fails'
68
+ reason?: string
69
+ deprecations?: readonly string[]
70
+ transient: boolean
71
+ }>
72
+
73
+ interface CorpusOptions {
74
+ readonly api: string
75
+ readonly cache: string
76
+ readonly validator: string
77
+ readonly fetch?: typeof fetch
78
+ }
79
+
80
+ const NONE = 0
81
+ const TAR_MAGIC_AT = 257
82
+ const TAR_MAGIC = 'ustar'
83
+ const PEEK_BYTES = 512
84
+ const FETCH_TIMEOUT_MS = 900_000
85
+ /** One original is at most a few hundred MB; a download that takes longer has stalled. */
86
+ const DOWNLOAD_TIMEOUT_MS = 180_000
87
+ const DOWNLOAD_TRIES = 3
88
+ const FIRST_TRY = 1
89
+ const OK_LOW = 200
90
+ const OK_HIGH = 300
91
+ const SHORT_HASH = 12
92
+ const VERDICT_WIDTH = 5
93
+ const FIRST = 0
94
+
95
+ function shortReason(error: unknown): string {
96
+ const text = error instanceof Error ? error.message : String(error)
97
+ const code =
98
+ typeof error === 'object' && error !== null && 'code' in error
99
+ ? `${String(error.code)}: `
100
+ : ''
101
+ return `${code}${text}`.split('\n')[FIRST] ?? text
102
+ }
103
+
104
+ /** Whether the first bytes are a plain tarball (`ustar` at 257) rather than Brotli. */
105
+ function isPlainTar(head: Readonly<Uint8Array>): boolean {
106
+ const magic = new TextDecoder().decode(
107
+ head.subarray(TAR_MAGIC_AT, TAR_MAGIC_AT + TAR_MAGIC.length),
108
+ )
109
+ return magic === TAR_MAGIC
110
+ }
111
+
112
+ /** Downloads one original to `file`: the validator reads it twice, so it is fetched once and read from disk. */
113
+ async function download(
114
+ options: Readonly<CorpusOptions>,
115
+ hash: string,
116
+ file: string,
117
+ ): Promise<void> {
118
+ const url = new URL(`/api/shardfiles/${hash}`, options.api)
119
+ const response = await (options.fetch ?? fetch)(url, {
120
+ headers: { 'accept-encoding': 'br' },
121
+ signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
122
+ })
123
+ if (response.status < OK_LOW || response.status >= OK_HIGH) {
124
+ throw new Error(`download ${hash}: HTTP ${String(response.status)}`)
125
+ }
126
+ if (response.body === null) {
127
+ throw new Error(`download ${hash}: no body`)
128
+ }
129
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(file))
130
+ }
131
+
132
+ async function firstBytes(file: string): Promise<Uint8Array> {
133
+ const handle = await open(file)
134
+ try {
135
+ const bytes = new Uint8Array(PEEK_BYTES)
136
+ await handle.read(bytes, NONE, PEEK_BYTES, NONE)
137
+ return bytes
138
+ } finally {
139
+ await handle.close()
140
+ }
141
+ }
142
+
143
+ /** One original through the stream validator, as a stored file. */
144
+ /** A download, tried again when it stalls or drops; the last error is thrown. */
145
+ async function downloadWithRetries(
146
+ options: Readonly<CorpusOptions>,
147
+ hash: string,
148
+ file: string,
149
+ ): Promise<void> {
150
+ let last: unknown = undefined
151
+ for (
152
+ let attempt = FIRST_TRY;
153
+ attempt <= DOWNLOAD_TRIES;
154
+ attempt += FIRST_TRY
155
+ ) {
156
+ try {
157
+ // oxlint-disable-next-line eslint/no-await-in-loop -- a retry waits for the try before it
158
+ await download(options, hash, file)
159
+ return
160
+ } catch (error: unknown) {
161
+ last = error
162
+ }
163
+ }
164
+ throw last
165
+ }
166
+
167
+ /** One original through the stream validator, as a stored file. A download that never completes is not a verdict. */
168
+ async function judge(
169
+ options: Readonly<CorpusOptions>,
170
+ hash: string,
171
+ ): Promise<Judgement> {
172
+ const file = path.join(options.cache, `${hash}.download`)
173
+ try {
174
+ try {
175
+ await downloadWithRetries(options, hash, file)
176
+ } catch (error: unknown) {
177
+ return {
178
+ verdict: 'fails',
179
+ reason: `download: ${shortReason(error)}`,
180
+ transient: true,
181
+ }
182
+ }
183
+ const plain = isPlainTar(await firstBytes(file))
184
+ const stored = await storedDeprecations(file, plain)
185
+ return { verdict: 'valid', ...stored, transient: false }
186
+ } catch (error: unknown) {
187
+ return { verdict: 'fails', reason: shortReason(error), transient: false }
188
+ } finally {
189
+ await rm(file, { force: true })
190
+ }
191
+ }
192
+
193
+ async function cachedVerdict(
194
+ options: Readonly<CorpusOptions>,
195
+ hash: string,
196
+ ): Promise<InferOutput<typeof CachedSchema> | undefined> {
197
+ try {
198
+ const raw: unknown = JSON.parse(
199
+ await readFile(path.join(options.cache, `${hash}.json`), 'utf8'),
200
+ )
201
+ const cached = parse(CachedSchema, raw)
202
+ // A valid verdict cached before FE7 has no deprecation list: judge it again.
203
+ const stale =
204
+ cached.verdict === 'valid' && cached.deprecations === undefined
205
+ return cached.validator === options.validator && !stale ? cached : undefined
206
+ } catch {
207
+ return undefined
208
+ }
209
+ }
210
+
211
+ async function row(
212
+ options: Readonly<CorpusOptions>,
213
+ stored: StoredRecord,
214
+ ): Promise<CorpusRow> {
215
+ const named = stored.revisions[FIRST]
216
+ const base = {
217
+ slug: named?.shard ?? '?',
218
+ revision: named?.revision ?? NONE,
219
+ hash: stored.hash,
220
+ storedBytes: stored.storedBytes,
221
+ }
222
+ const cached = await cachedVerdict(options, stored.hash)
223
+ if (cached !== undefined) {
224
+ return {
225
+ ...base,
226
+ verdict: cached.verdict === 'valid' ? 'valid' : 'fails',
227
+ reason: cached.reason,
228
+ cached: true,
229
+ deprecations: cached.deprecations ?? [],
230
+ }
231
+ }
232
+ await mkdir(options.cache, { recursive: true })
233
+ const { transient, ...judged } = await judge(options, stored.hash)
234
+ if (!transient) {
235
+ await writeFile(
236
+ path.join(options.cache, `${stored.hash}.json`),
237
+ `${JSON.stringify({ validator: options.validator, ...judged })}\n`,
238
+ )
239
+ }
240
+ return {
241
+ ...base,
242
+ ...judged,
243
+ reason: judged.reason,
244
+ cached: false,
245
+ deprecations: judged.deprecations ?? [],
246
+ }
247
+ }
248
+
249
+ /** Every kept original's verdict, in the API's upload order. */
250
+ async function runCorpus(
251
+ options: Readonly<CorpusOptions>,
252
+ ): Promise<CorpusRow[]> {
253
+ const listed = await (options.fetch ?? fetch)(
254
+ new URL('/api/shardfiles', options.api),
255
+ {
256
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
257
+ },
258
+ )
259
+ if (listed.status < OK_LOW || listed.status >= OK_HIGH) {
260
+ throw new Error(`list: HTTP ${String(listed.status)}`)
261
+ }
262
+ const { shardfiles } = parse(ListSchema, await listed.json())
263
+ const rows: CorpusRow[] = []
264
+ for (const stored of shardfiles) {
265
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one original at a time keeps memory bounded
266
+ rows.push(await row(options, stored))
267
+ }
268
+ return rows
269
+ }
270
+
271
+ function corpusReport(rows: readonly CorpusRow[]): string {
272
+ const lines = rows.map(
273
+ (found: Readonly<CorpusRow>): string =>
274
+ `${found.verdict.padEnd(VERDICT_WIDTH)} ${found.slug} r${String(found.revision)} ${found.hash.slice(FIRST, SHORT_HASH)}${found.reason === undefined ? '' : ` ${found.reason}`}`,
275
+ )
276
+ const failed = rows.filter(
277
+ (found: Readonly<CorpusRow>): boolean => found.verdict === 'fails',
278
+ ).length
279
+ const fetched = rows.filter(
280
+ (found: Readonly<CorpusRow>): boolean => !found.cached,
281
+ )
282
+ const bytes = fetched.reduce(
283
+ (sum: number, found: Readonly<CorpusRow>): number =>
284
+ sum + found.storedBytes,
285
+ NONE,
286
+ )
287
+ lines.push(
288
+ `corpus: ${String(rows.length)} kept originals, ${String(rows.length - failed)} valid, ${String(failed)} fail; fetched ${String(fetched.length)} (${String(bytes)} stored bytes), ${String(rows.length - fetched.length)} from cache`,
289
+ ...deprecationLines(rows),
290
+ )
291
+ return lines.join('\n')
292
+ }
293
+
294
+ export {
295
+ type CorpusOptions,
296
+ type CorpusRow,
297
+ corpusReport,
298
+ isPlainTar,
299
+ runCorpus,
300
+ }