@flighthq/skeleton2d-formats 0.3.0 → 0.3.1-next.1041.35b950c

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.
@@ -2,12 +2,209 @@ import { easeCubicBezier } from '@flighthq/easing/contract';
2
2
  import { collectImportDiagnostics } from '@flighthq/importdiagnostics/contract';
3
3
  import { applyAnimationClipToSkeleton2D, cloneSkeleton2D } from '@flighthq/skeleton2d/contract';
4
4
  import type { RegionAttachment2D } from '@flighthq/types/contract';
5
- import { RegionAttachment2DKind, TransformMode2D } from '@flighthq/types/contract';
5
+ import { ImportDiagnosticSeverity, RegionAttachment2DKind, TransformMode2D } from '@flighthq/types/contract';
6
6
  import { describe, expect, it } from 'vitest';
7
7
 
8
8
  import { parseSpineSkeletonBinary } from './spineBinaryParse';
9
9
 
10
10
  describe('parseSpineSkeletonBinary', () => {
11
+ // ★ PER-RECORD, AND THAT IS THE WHOLE POINT. The all-five fixture below backs a PER-RECORD claim with a
12
+ // WHOLE-STREAM oracle: the region attachment on the far side reading back intact. A record whose width is
13
+ // walked wrong is only caught if its desync survives every following record to reach that oracle, and
14
+ // whether it survives depends on the downstream bytes rather than on the code under test. Measured: with
15
+ // all five present, deleting the boundingbox skip is caught and deleting the point-colour skip is NOT.
16
+ // Detection was luck, per record — the self-synchronising trap one level up, where last time the fixture
17
+ // VALUE absorbed the error and here the ORACLE POSITION does.
18
+ //
19
+ // Isolating one record per file makes the reader's END POSITION the oracle instead, which is structural
20
+ // and type-independent: a skip that is too short leaves bytes unread (spine.binary-tail-unparsed), one
21
+ // that is too long runs past the end (spine.binary-truncated). Neither can be absorbed by a sibling
22
+ // record, because there is no sibling. An empty list of DATA-INTEGRITY crumbs is the offset assertion.
23
+ //
24
+ // Skip is excluded rather than ignored: walking a record we do not model raises one aggregated Skip by
25
+ // design, which is a correct report of a capability gap on correct input. `toEqual([])` would be a false
26
+ // assertion here, not a stronger one.
27
+ it.each(UNMODELED_ATTACHMENT_TYPES)('walks an unmodeled %s record byte-exactly, in isolation', (type) => {
28
+ for (const nonessential of [false, true]) {
29
+ const unread = unreadByteCount(buildSpineBinary({ nonessential, unmodeledAttachmentTypes: [type] }));
30
+
31
+ expect(unread, `unmodeled ${type} (nonessential=${nonessential}) left the reader ${unread} bytes off`).toBe(0);
32
+ }
33
+ });
34
+
35
+ // EVERY PREFIX OF A VALID FILE, not a handful of chosen cut points. Truncation is the one malformation
36
+ // a corpus can never supply — no exporter emits a half-written file — and it is the one the parser has
37
+ // the most machinery for: `isSpineBinaryReaderOverrun` is a sticky mark, and 38 of this file's loops are
38
+ // written `for (i = 0; i < n && !isSpineBinaryReaderOverrun(reader); i++)` specifically to bail out on it.
39
+ // None of that containment had a test.
40
+ //
41
+ // The property is CONTAINMENT, not correctness: a prefix has no right answer, so there is nothing to
42
+ // assert about what comes back except that it came back. What this catches, verified by removing the
43
+ // guard from `readSpineBinaryFloat` and watching it go red, is a read that stops guarding the buffer end
44
+ // — a DataView RangeError thrown from deep inside a record on somebody's truncated download.
45
+ //
46
+ // What it does NOT catch, also verified: the per-loop overrun checks. Truncation is contained by the
47
+ // READER alone, since every read past the end returns a neutral value, so those loops finish quickly
48
+ // whether or not they test for overrun. Deleting one leaves this test green. The input that discriminates
49
+ // them is an inflated count, which is the test above — the two malformations look alike and are not.
50
+ // THE OTHER MALFORMATION, and the one the loop guards actually exist for. Truncation is contained by the
51
+ // READER alone — once overrun, every read returns a neutral value — so the per-loop overrun checks are
52
+ // invisible to it. What they contain is an INFLATED COUNT: a declared count is a varint the file supplies,
53
+ // and a corrupt or hostile one declares two billion bones in thirty bytes. The reader keeps returning
54
+ // neutral values forever while the loop keeps allocating a bone per iteration.
55
+ //
56
+ // MEASURED, so the margin is not a guess: with the guard this parse returns in ~1ms; with the guard
57
+ // removed the same thirty bytes did not finish in 60 SECONDS. The assertion below is on the bone count
58
+ // rather than on elapsed time, because a count is deterministic where a clock is not — but note that a
59
+ // regression here shows up as this file timing out rather than as this assertion failing, since the
60
+ // unguarded parse never reaches a return.
61
+ // The same hazard one level deeper, and the one that actually bit. A weighted mesh declares an influence
62
+ // count PER VERTEX, inside a loop whose outer bound is already guarded — so the outer guard is consulted
63
+ // between vertices while this inner loop pushes four values a turn. Before the guard on it, this exact
64
+ // input threw `RangeError: Invalid array length` out of `Array.push` after ~4.2 SECONDS and several
65
+ // gigabytes, from 327 bytes. The parser is documented to treat third-party bytes as untrusted and to
66
+ // return sentinels rather than raise, so a throw here is a contract violation, not merely slow.
67
+ // THE WHOLE COUNT-GUARD FAMILY IN ONE SWEEP, and it is only affordable because the guards exist. Every
68
+ // count in this format is a varint the file supplies and a loop bound the parser obeys, and there are 36
69
+ // such loops; a case per loop would pin the loops that EXIST and miss the next one added. So instead:
70
+ // splice an inflated five-byte varint over each byte position in turn and require the parse to come back.
71
+ // A position that lands on a count inflates it; a position that lands elsewhere is garbage the parser must
72
+ // survive anyway. Neither needs to know where the counts are, which is the point.
73
+ //
74
+ // MEASURED BOTH WAYS, and the difference is the reason this test can exist at all: before the bounds
75
+ // checks landed, this sweep did not finish — one position allocated until it threw and another never
76
+ // returned. With them, all 359 positions complete in ~47ms, worst case 3ms. So it is simultaneously a
77
+ // regression net for the denial-of-service class and cheap enough to keep. If a guard is ever removed,
78
+ // this file stops finishing rather than reporting a failed assertion.
79
+ it('survives an inflated count spliced at every byte position of a valid file', () => {
80
+ const base = buildSpineBinary({ animations: true, bezier: true, ikConstraints: 1, weightedMesh: true });
81
+
82
+ for (let at = 0; at < base.length; at++) {
83
+ const spliced = Uint8Array.from([
84
+ ...base.subarray(0, at),
85
+ 0xff,
86
+ 0xff,
87
+ 0xff,
88
+ 0xff,
89
+ 0x07, // varint 0x7fffffff, in place of whatever byte was here
90
+ ...base.subarray(at + 1),
91
+ ]);
92
+ let result: ReturnType<typeof parseSpineSkeletonBinary> | undefined;
93
+ expect(() => {
94
+ result = parseSpineSkeletonBinary(spliced);
95
+ }, `inflated varint spliced at byte ${at} of ${base.length}`).not.toThrow();
96
+
97
+ // Restored now that the importer bounds a bone's parent — see the note that used to sit below.
98
+ // A skeleton handed back from a corrupt file must still be one `validateSkeleton2D` would accept,
99
+ // because a caller who got a non-null return has no reason to go and ask.
100
+ const bones = result?.skeleton.bones;
101
+ if (bones === undefined) continue;
102
+ for (const bone of bones) {
103
+ expect(bone.parentIndex, `parentIndex after splice at ${at}`).toBeLessThan(bones.length);
104
+ expect(bone.parentIndex, `parentIndex after splice at ${at}`).toBeGreaterThanOrEqual(-1);
105
+ }
106
+ }
107
+ });
108
+
109
+ // The two ALLOCATION-shaped counts, which the per-loop overrun guards cannot help with because the array
110
+ // is sized from the file's number before the first read. Measured before the bounds check existed, on a
111
+ // 304-byte valid file with one varint rewritten: the triangle count RETURNED AFTER 59 SECONDS and the
112
+ // vertex count never returned at all. The 59-second one is the more dangerous of the pair — it produces
113
+ // a correct answer with no exception and no crumb, so nothing about it tells a caller it happened.
114
+ //
115
+ // Asserted on the crumb rather than on elapsed time: a clock is flaky and a diagnostic is not, and the
116
+ // crumb is also the thing a caller acts on. A regression that reinstates the hang fails this file by
117
+ // timing out rather than by this assertion, since an unbounded parse never reaches a return.
118
+ it.each([
119
+ [
120
+ 'vertex',
121
+ [
122
+ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f,
123
+ 0x80, 0x00, 0x00, 0x3f, 0x80, 0x00, 0x00,
124
+ ],
125
+ 'vertexCount',
126
+ ],
127
+ ['triangle', [0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02], 'triangleCount'],
128
+ ] as const)('refuses a mesh %s count the remaining bytes cannot satisfy', (_label, marker, field) => {
129
+ const base = buildSpineBinary();
130
+ let at = -1;
131
+ for (let i = 0; at < 0 && i + marker.length <= base.length; i++) {
132
+ if (marker.every((byte, k) => base[i + k] === byte)) at = i;
133
+ }
134
+ expect(at, `${field} marker not found — the builder's mesh layout moved`).toBeGreaterThanOrEqual(0);
135
+ const hostile = Uint8Array.from([...base.subarray(0, at), 0xff, 0xff, 0xff, 0xff, 0x07, ...base.subarray(at + 1)]);
136
+
137
+ const crumbs = collectImportDiagnostics((sink) => {
138
+ expect(() => parseSpineSkeletonBinary(hostile, sink)).not.toThrow();
139
+ });
140
+
141
+ const crumb = crumbs.find((c) => c.kind === 'spine.binary-count-unsatisfiable');
142
+ expect(crumb, 'no crumb named the unsatisfiable count').toBeDefined();
143
+ expect(crumb!.detail).toMatchObject({ field });
144
+ });
145
+
146
+ it('contains an influence count the file inflates, rather than pushing until push throws', () => {
147
+ const base = buildSpineBinary({ weightedMesh: true });
148
+ // Vertex 0 of the weighted block: varint(1) influence count, varint(1) bone index, then x, y, weight.
149
+ const marker = [0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x80, 0x00, 0x00];
150
+ let at = -1;
151
+ for (let i = 0; at < 0 && i + marker.length <= base.length; i++) {
152
+ if (marker.every((byte, k) => base[i + k] === byte)) at = i;
153
+ }
154
+ // If the builder's weighted layout ever changes this goes looking for the wrong bytes, and a test that
155
+ // silently stops testing is worse than one that fails.
156
+ expect(at, 'influence-count byte not found in the built weighted mesh').toBeGreaterThanOrEqual(0);
157
+
158
+ // Replace the single-byte count with a 5-byte varint for 0x7fffffff.
159
+ const hostile = Uint8Array.from([...base.subarray(0, at), 0xff, 0xff, 0xff, 0xff, 0x07, ...base.subarray(at + 1)]);
160
+
161
+ expect(() => parseSpineSkeletonBinary(hostile)).not.toThrow();
162
+ });
163
+
164
+ it('contains a count the file inflates, rather than allocating what it declares', () => {
165
+ const out: number[] = [];
166
+ for (let i = 0; i < 8; i++) out.push(0); // export hash
167
+ writeString(out, '4.1.17');
168
+ for (let i = 0; i < 4; i++) writeFloat(out, 0); // authoring bounds
169
+ out.push(0); // nonessential
170
+ writeVarint(out, 0); // string table, empty
171
+ writeVarint(out, 0x7fffffff); // BONE COUNT — two billion, in a file with no bones after it
172
+
173
+ const result = parseSpineSkeletonBinary(Uint8Array.from(out));
174
+
175
+ // It must stop when the bytes run out, not when the count says to.
176
+ expect(result).not.toBeNull();
177
+ expect(result!.skeleton.bones.length).toBeLessThan(4);
178
+ });
179
+
180
+ it('survives every truncation of a valid file, returning rather than throwing or spinning', () => {
181
+ const complete = buildSpineBinary({
182
+ animations: true,
183
+ bezier: true,
184
+ ikConstraints: 2,
185
+ nonessential: true,
186
+ weightedMesh: true,
187
+ });
188
+
189
+ for (let length = 0; length <= complete.length; length++) {
190
+ const truncated = complete.subarray(0, length);
191
+ let result: ReturnType<typeof parseSpineSkeletonBinary> | undefined;
192
+ expect(() => {
193
+ result = parseSpineSkeletonBinary(truncated);
194
+ }, `truncated to ${length} of ${complete.length} bytes`).not.toThrow();
195
+
196
+ // Whatever survives must still be internally coherent: a bone may not name a parent outside the
197
+ // array, which is the shape a half-read count corrupts first and which nothing downstream re-checks.
198
+ if (result != null) {
199
+ const bones = result.skeleton.bones;
200
+ for (const bone of bones) {
201
+ expect(bone.parentIndex, `parentIndex at ${length} bytes`).toBeLessThan(bones.length);
202
+ expect(bone.parentIndex, `parentIndex at ${length} bytes`).toBeGreaterThanOrEqual(-1);
203
+ }
204
+ }
205
+ }
206
+ });
207
+
11
208
  it('parses the header, bones, and slots of a 4.x file', () => {
12
209
  const result = parseSpineSkeletonBinary(buildSpineBinary())!;
13
210
  expect(result).not.toBeNull();
@@ -108,7 +305,10 @@ describe('parseSpineSkeletonBinary', () => {
108
305
  // The mesh is the second attachment on the slot; it is not the setup one, so reach it via the region's
109
306
  // sibling — the parse must still have consumed it correctly for the file to end cleanly.
110
307
  const crumbs = collectImportDiagnostics((sink) => parseSpineSkeletonBinary(buildSpineBinary(), sink));
111
- expect(crumbs.find((c) => c.kind === 'spine.binary-tail-unparsed')!.detail).toMatchObject({ bytes: 0 });
308
+ expect(
309
+ crumbs.map((c) => c.kind),
310
+ 'a fully consumed fixture must parse silently',
311
+ ).toEqual([]);
112
312
  expect(skin.skeleton.slots!.length).toBe(1);
113
313
  });
114
314
 
@@ -118,8 +318,10 @@ describe('parseSpineSkeletonBinary', () => {
118
318
  const crumbs = collectImportDiagnostics((sink) =>
119
319
  parseSpineSkeletonBinary(buildSpineBinary({ weightedMesh: true }), sink),
120
320
  );
121
- expect(crumbs.find((c) => c.kind === 'spine.binary-tail-unparsed')!.detail).toMatchObject({ bytes: 0 });
122
- expect(crumbs.map((c) => c.kind)).not.toContain('spine.binary-truncated');
321
+ expect(
322
+ crumbs.map((c) => c.kind),
323
+ 'a fully consumed fixture must parse silently',
324
+ ).toEqual([]);
123
325
  });
124
326
 
125
327
  it('CONSUMES IK constraint records it does not model, so the skin after them still parses', () => {
@@ -142,6 +344,26 @@ describe('parseSpineSkeletonBinary', () => {
142
344
  expect(kinds).toContain('spine.ik-constraint-unsupported');
143
345
  });
144
346
 
347
+ // ★ THE VERSION THAT ACTUALLY EXISTS IN THE WILD, and the case a prefix gate got wrong. Every one of the
348
+ // 23 real exports in the spine-fixtures corpus is 4.2.22, and the old `startsWith('4.')` admitted them
349
+ // into a reader built for 4.1 — each produced a Skeleton2DImport with zero bones from a 64 KB file, a
350
+ // silent empty success rather than a refusal. Refusing is strictly better: the caller can tell.
351
+ it.each(['4.2.22', '4.3.0', '5.0.0'])('REJECTS %s rather than reading it with a layout built for 4.1', (version) => {
352
+ const crumbs = collectImportDiagnostics((sink) =>
353
+ expect(parseSpineSkeletonBinary(buildSpineBinary({ version }), sink)).toBeNull(),
354
+ );
355
+
356
+ const crumb = crumbs.find((c) => c.kind === 'spine.binary-version-unsupported')!;
357
+ expect(crumb, `no unsupported crumb for ${version}`).toBeDefined();
358
+ expect(crumb.detail).toMatchObject({ version });
359
+ });
360
+
361
+ // The layouts that ARE implemented still parse — a gate that rejects everything would pass the test
362
+ // above and be useless.
363
+ it.each(['4.1.17', '4.1.0'])('still reads %s, the layout it was verified against', (version) => {
364
+ expect(parseSpineSkeletonBinary(buildSpineBinary({ version }))).not.toBeNull();
365
+ });
366
+
145
367
  it('REJECTS a version whose record layout this importer does not describe', () => {
146
368
  const crumbs = collectImportDiagnostics((sink) =>
147
369
  expect(parseSpineSkeletonBinary(buildSpineBinary({ version: '3.8.99' }), sink)).toBeNull(),
@@ -157,14 +379,28 @@ describe('parseSpineSkeletonBinary', () => {
157
379
  expect(kinds).toContain('spine.binary-header-unreadable');
158
380
  });
159
381
 
160
- it('reports how many bytes of the file it did not parse', () => {
161
- const bytes = buildSpineBinary();
162
- const crumbs = collectImportDiagnostics((sink) => parseSpineSkeletonBinary(bytes, sink));
382
+ it('reports how many bytes of the file it did not parse, and says nothing when it parsed them all', () => {
383
+ // Both arms, because the crumb previously fired unconditionally — including with `bytes: 0`, which the
384
+ // superseded test asserted as correct. A complaint raised on every successful parse cannot distinguish
385
+ // a file that ended cleanly from one the walk abandoned, so it was as silent as no complaint at all.
386
+ const consumed = buildSpineBinary();
387
+ expect(
388
+ collectImportDiagnostics((sink) => parseSpineSkeletonBinary(consumed, sink)).map((c) => c.kind),
389
+ 'a file consumed to its last byte has no tail to report',
390
+ ).toEqual([]);
391
+
392
+ const withTail = new Uint8Array(consumed.length + 24);
393
+ withTail.set(consumed);
394
+ const crumbs = collectImportDiagnostics((sink) => parseSpineSkeletonBinary(withTail, sink));
163
395
  const tail = crumbs.find((c) => c.kind === 'spine.binary-tail-unparsed')!;
164
- // The fixture ends exactly where this landing stops parsing, so nothing is left over — the crumb still
165
- // fires to record that the importer STOPPED rather than finished, which is the honest signal while the
166
- // event and animation sections are still unmodeled.
167
- expect(tail.detail).toMatchObject({ bytes: 0 });
396
+ expect(tail).toBeDefined();
397
+ expect(tail.detail).toMatchObject({ bytes: 24 });
398
+ // Drop. Skip was never available: skip claims RECOGNITION — you can only skip what you identified — and
399
+ // an unparsed remainder is by definition unidentified. Recover is not available either: nothing stands
400
+ // in for the missing bytes, and the skeleton being usable is a consequence, not a substitute. This
401
+ // assertion has now been wrong twice (Skip, then Recover), so it is pinned with the reason rather than
402
+ // the value alone.
403
+ expect(tail.severity).toBe(ImportDiagnosticSeverity.Drop);
168
404
  });
169
405
 
170
406
  it('RECOVERS from a truncated file, keeping whatever records were complete', () => {
@@ -194,6 +430,30 @@ describe('parseSpineSkeletonBinary', () => {
194
430
  expect(beyond[1].transformMode).toEqual(TransformMode2D.Normal);
195
431
  });
196
432
 
433
+ // ★ EVERY UNMODELED ATTACHMENT TYPE, WALKED BYTE-EXACTLY, WITH AND WITHOUT NONESSENTIAL DATA. Five types
434
+ // Flight does not model — boundingbox, clipping, point, linkedmesh, path — each of which still occupies
435
+ // bytes the reader must step over exactly. Nine of this file's branch arms are the `if (nonessential)`
436
+ // half of those skips, and none had ever run: the flag changes the width of every one of these records,
437
+ // so a reader that honours it in some and not others desynchronises only for files exported from the
438
+ // editor, which is the export most likely to be handed to a developer debugging something else.
439
+ //
440
+ // The proof is a KNOWN attachment on the far side. All five unmodeled records are written before the
441
+ // region, so a wrong width anywhere shows up as the region reading back as garbage — the same shape as
442
+ // the IK-constraint test above, and the reason this asserts field values rather than a bare not-null.
443
+ it.each([false, true])('walks every unmodeled attachment type byte-exactly (nonessential=%s)', (nonessential) => {
444
+ const result = parseSpineSkeletonBinary(buildSpineBinary({ nonessential, unmodeledAttachments: true }))!;
445
+
446
+ expect(result).not.toBeNull();
447
+ expect(result.skeleton.slots![0].attachment).toMatchObject({
448
+ height: 32,
449
+ name: 'body-attachment',
450
+ rotation: 12.5,
451
+ width: 64,
452
+ x: 3.5,
453
+ y: 4.5,
454
+ });
455
+ });
456
+
197
457
  it('honors the nonessential flag, which changes the bone record width', () => {
198
458
  // With nonessential set, each bone carries a trailing editor color. Reading the flag but not the color
199
459
  // would desynchronize every following record, so the slot below is the canary.
@@ -224,6 +484,8 @@ function buildSpineBinary(
224
484
  options: {
225
485
  version?: string;
226
486
  nonessential?: boolean;
487
+ unmodeledAttachments?: boolean;
488
+ unmodeledAttachmentTypes?: readonly UnmodeledAttachmentType[];
227
489
  transformMode?: number;
228
490
  darkColor?: number;
229
491
  ikConstraints?: number;
@@ -285,7 +547,10 @@ function buildSpineBinary(
285
547
  // Default skin: one slot entry carrying a region and a mesh.
286
548
  writeVarint(out, 1); // slot entries
287
549
  writeVarint(out, 0); // slot index
288
- writeVarint(out, 2); // attachments on it
550
+ const unmodeled =
551
+ options.unmodeledAttachmentTypes ?? (options.unmodeledAttachments === true ? UNMODELED_ATTACHMENT_TYPES : []);
552
+ writeVarint(out, unmodeled.length + 2); // attachments on it
553
+ for (const type of unmodeled) writeUnmodeledAttachment(out, type, nonessential);
289
554
  writeVarint(out, 1); // key -> 'body-attachment'
290
555
  writeVarint(out, 0); // name: absent, so the key is used
291
556
  out.push(0); // type: region
@@ -322,6 +587,11 @@ function buildSpineBinary(
322
587
  }
323
588
  writeVarint(out, 0); // hull length
324
589
  out.push(0); // sequence: absent
590
+ if (nonessential) {
591
+ writeVarint(out, 0); // editor edge count
592
+ writeFloat(out, 0); // width
593
+ writeFloat(out, 0); // height
594
+ }
325
595
 
326
596
  writeVarint(out, 0); // alternate skins
327
597
  writeVarint(out, 0); // event definitions
@@ -452,3 +722,97 @@ function writeVarint(out: number[], value: number): void {
452
722
  }
453
723
  out.push(remaining);
454
724
  }
725
+
726
+ // The five attachment types Flight does not model but must still WALK BYTE-EXACTLY, each written at the
727
+ // width the importer skips. Emitted BEFORE the region attachment on purpose: the region is the known
728
+ // quantity on the far side, so if any of these widths is walked wrong the region reads back as garbage and
729
+ // the test fails there rather than here.
730
+ //
731
+ // ★ WHAT THIS CAN AND CANNOT PROVE. The widths below are the ones the importer skips, so this cannot
732
+ // confirm them against the real format — for that the layout was read against a purchased 4.1 export (see
733
+ // the package status).
734
+ //
735
+ // ★ AND IT IS A WHOLE-STREAM ORACLE, NOT A PER-RECORD ONE. This fixture used to claim it proved each
736
+ // record stays in step with the reader. It cannot: the only thing checked is the region attachment at the
737
+ // far end, so a record walked wrong is caught only if its desync SURVIVES every following record to reach
738
+ // that oracle — which depends on the downstream bytes, not on the code under test. Measured: with all five
739
+ // present, deleting the boundingbox skip was caught and deleting the point-colour skip was not.
740
+ //
741
+ // The per-record claim belongs to the isolation test above ('walks an unmodeled %s record byte-exactly'),
742
+ // which makes the reader's own end offset the oracle. What THIS fixture still earns is coverage of the
743
+ // five records INTERACTING — consecutive records in one stream, which the isolated files never exercise.
744
+ // ★ THE COLOUR VALUE IS LOAD-BEARING AND 0xffffffff WOULD MAKE THIS TEST UNABLE TO FAIL. Every byte of
745
+ // 0xffffffff has the varint continuation bit set, so when a reader is four bytes behind, the next varint
746
+ // SWALLOWS the stray colour and resynchronises by accident — measured: dropping the boundingbox skip
747
+ // entirely left this test green. A colour whose bytes are below 0x80 terminates a varint immediately, so
748
+ // the same drop desynchronises and is caught. The fixture value decides whether the test can detect the
749
+ // bug at all, which is the fixture-symmetry trap in a form specific to variable-length encodings.
750
+ const UNMODELED_ATTACHMENT_COLOR = 0x01020304;
751
+
752
+ function writeUnmodeledAttachment(out: number[], type: UnmodeledAttachmentType, nonessential: boolean): void {
753
+ const vertices = (count: number) => {
754
+ writeVarint(out, count);
755
+ out.push(0); // not weighted
756
+ for (let i = 0; i < count * 2; i++) writeFloat(out, i);
757
+ };
758
+ const header = (typeOrdinal: number) => {
759
+ writeVarint(out, 3); // key
760
+ writeVarint(out, 0); // name absent, key is used
761
+ out.push(typeOrdinal);
762
+ };
763
+
764
+ if (type === 'boundingbox') {
765
+ header(1);
766
+ vertices(2);
767
+ if (nonessential) writeInt(out, UNMODELED_ATTACHMENT_COLOR);
768
+ } else if (type === 'clipping') {
769
+ header(6);
770
+ writeVarint(out, 0); // end slot
771
+ vertices(2);
772
+ if (nonessential) writeInt(out, UNMODELED_ATTACHMENT_COLOR);
773
+ } else if (type === 'point') {
774
+ header(5);
775
+ writeFloat(out, 0); // rotation
776
+ writeFloat(out, 0); // x
777
+ writeFloat(out, 0); // y
778
+ if (nonessential) writeInt(out, UNMODELED_ATTACHMENT_COLOR);
779
+ } else if (type === 'linkedmesh') {
780
+ header(3);
781
+ writeVarint(out, 0); // path
782
+ writeInt(out, UNMODELED_ATTACHMENT_COLOR); // color
783
+ writeVarint(out, 0); // skin name
784
+ writeVarint(out, 0); // parent mesh
785
+ out.push(0); // inherit timelines
786
+ out.push(0); // sequence absent
787
+ if (nonessential) {
788
+ writeFloat(out, 0); // width
789
+ writeFloat(out, 0); // height
790
+ }
791
+ } else {
792
+ header(4); // path
793
+ out.push(0); // closed
794
+ out.push(0); // constantSpeed
795
+ vertices(3);
796
+ writeFloat(out, 0); // one per-curve length for 3 vertices
797
+ if (nonessential) writeInt(out, UNMODELED_ATTACHMENT_COLOR);
798
+ }
799
+ }
800
+
801
+ const UNMODELED_ATTACHMENT_TYPES = ['boundingbox', 'clipping', 'point', 'linkedmesh', 'path'] as const;
802
+
803
+ type UnmodeledAttachmentType = (typeof UNMODELED_ATTACHMENT_TYPES)[number];
804
+
805
+ // How many bytes of a file the parser did not consume — the reader's end offset, observed through the only
806
+ // seam that reports it. The per-record test asserts this is ZERO rather than comparing against a baseline
807
+ // built from the same fixture, and the difference is load-bearing: a baseline-relative check subtracts out
808
+ // any whole-fixture desync, so it would have SILENTLY ABSORBED the defect that this fixture actually had —
809
+ // the mesh attachment's nonessential block (an edge count, then width and height) was never written, so
810
+ // every `nonessential: true` parse ran 9 bytes adrift from the mesh onward and left 19 bytes unread. An
811
+ // absolute zero is the assertion that a recurrence cannot hide from.
812
+ function unreadByteCount(bytes: Readonly<Uint8Array>): number {
813
+ const crumbs = collectImportDiagnostics((sink) => parseSpineSkeletonBinary(bytes, sink));
814
+ const truncated = crumbs.find((crumb) => crumb.kind === 'spine.binary-truncated');
815
+ if (truncated !== undefined) return Number.NaN; // ran PAST the end: never equal to a baseline
816
+ const tail = crumbs.find((crumb) => crumb.kind === 'spine.binary-tail-unparsed');
817
+ return tail === undefined ? 0 : (tail.detail as { bytes: number }).bytes;
818
+ }
@@ -10,6 +10,7 @@ import {
10
10
  import type { ImportDiagnostic, MeshAttachment2D, RegionAttachment2D, Slot2D } from '@flighthq/types/contract';
11
11
  import {
12
12
  AnimationInterpolationLinear,
13
+ ImportDiagnosticSeverity,
13
14
  MeshAttachment2DKind,
14
15
  RegionAttachment2DKind,
15
16
  TransformMode2D,
@@ -43,6 +44,66 @@ const SPINE_TWO_BONES = JSON.stringify({
43
44
  // A draw-order keyframe states only the slots that MOVE; everything else keeps its relative order and
44
45
  // closes the gaps. Each keyframe resolves to a WHOLE ordering, because a track has to answer what is in
45
46
  // effect at time t from one keyframe alone.
47
+ // A document reaching every structure the importer's type guards protect: bones, slots, skins with
48
+ // attachments, constraints, events, and an animation carrying bone, slot, deform and draw-order
49
+ // timelines. Rich on purpose — a type sweep is only as wide as the document it walks.
50
+ const SPINE_RICH = {
51
+ animations: {
52
+ walk: {
53
+ bones: {
54
+ arm: {
55
+ rotate: [
56
+ { time: 0, value: 0 },
57
+ { curve: 'stepped', time: 1, value: 90 },
58
+ ],
59
+ },
60
+ },
61
+ deform: { default: { body: { mesh: [{ offset: 1, time: 0, vertices: [1, 2] }] } } },
62
+ drawOrder: [{ offsets: [{ offset: 1, slot: 'body' }], time: 0 }],
63
+ events: [{ name: 'step', time: 0.5 }],
64
+ slots: { body: { attachment: [{ name: 'mesh', time: 0 }], color: [{ color: 'ffffffff', time: 0 }] } },
65
+ },
66
+ },
67
+ bones: [{ name: 'root' }, { length: 50, name: 'arm', parent: 'root', rotation: 45, x: 10 }],
68
+ events: { step: { float: 1, int: 2, string: 'x' } },
69
+ ik: [{ bones: ['arm'], name: 'aim', target: 'root' }],
70
+ path: [{ bones: ['arm'], name: 'follow', target: 'body' }],
71
+ skeleton: { hash: 'x', spine: '4.1' },
72
+ skins: [
73
+ {
74
+ attachments: {
75
+ body: { mesh: { triangles: [0, 1, 2], type: 'mesh', uvs: [0, 0, 1, 0, 1, 1], vertices: [0, 0, 1, 0, 1, 1] } },
76
+ },
77
+ name: 'default',
78
+ },
79
+ ],
80
+ slots: [{ attachment: 'mesh', bone: 'root', color: 'ffffffff', name: 'body' }],
81
+ transform: [{ bones: ['arm'], name: 'aim2', target: 'root' }],
82
+ };
83
+
84
+ // Every path to a value in `doc`, leaves and containers alike.
85
+ function everyJsonPath(node: unknown, prefix: readonly (string | number)[] = []): (string | number)[][] {
86
+ const here: (string | number)[][] = prefix.length > 0 ? [[...prefix]] : [];
87
+ if (Array.isArray(node)) {
88
+ node.forEach((child, i) => here.push(...everyJsonPath(child, [...prefix, i])));
89
+ } else if (node !== null && typeof node === 'object') {
90
+ for (const [key, child] of Object.entries(node)) here.push(...everyJsonPath(child, [...prefix, key]));
91
+ }
92
+ return here;
93
+ }
94
+
95
+ function withValueAt(doc: unknown, path: readonly (string | number)[], value: unknown): unknown {
96
+ const copy: any = Array.isArray(doc) ? [...doc] : { ...(doc as object) };
97
+ let node = copy;
98
+ for (let i = 0; i < path.length - 1; i++) {
99
+ const key = path[i];
100
+ node[key] = Array.isArray(node[key]) ? [...node[key]] : { ...node[key] };
101
+ node = node[key];
102
+ }
103
+ node[path[path.length - 1]] = value;
104
+ return copy;
105
+ }
106
+
46
107
  describe('parseSpineDrawOrderTimeline', () => {
47
108
  const SLOTS = [slot('a'), slot('b'), slot('c')];
48
109
 
@@ -90,6 +151,9 @@ describe('parseSpineDrawOrderTimeline', () => {
90
151
 
91
152
  expect(timeline).toBeNull();
92
153
  expect(diagnostics.map((entry) => entry.kind)).toEqual(['spine.draworder-keyframe-unresolved']);
154
+ // Drop, not Skip: the feature is supported and the DATA failed, so this is lost data rather than a
155
+ // capability gap. Pinned because a Skip here would exempt itself from every severity-based check.
156
+ expect(diagnostics[0].severity).toBe(ImportDiagnosticSeverity.Drop);
93
157
  });
94
158
 
95
159
  it('skips a keyframe where two slots claim one position', () => {
@@ -109,11 +173,6 @@ describe('parseSpineDrawOrderTimeline', () => {
109
173
  });
110
174
  });
111
175
 
112
- // A one-bone document whose single animation carries `keys` as bone `b`'s timeline of the given kind.
113
- function curveDoc(keys: readonly Record<string, unknown>[], kind = 'rotate'): Record<string, unknown> {
114
- return { bones: [{ name: 'b' }], animations: { a: { bones: { b: { [kind]: keys } } } } };
115
- }
116
-
117
176
  describe('parseSpineSkeleton', () => {
118
177
  it('keeps BOTH axes when a bone carries the per-axis translatex and translatey timelines', () => {
119
178
  // Spine 4 writes these lowercased with their own keyframe times. Merged onto the paired path they
@@ -817,6 +876,45 @@ describe('parseSpineSkeleton', () => {
817
876
  });
818
877
  });
819
878
 
879
+ // A one-bone document whose single animation carries `keys` as bone `b`'s timeline of the given kind.
880
+ function curveDoc(keys: readonly Record<string, unknown>[], kind = 'rotate'): Record<string, unknown> {
881
+ return { bones: [{ name: 'b' }], animations: { a: { bones: { b: { [kind]: keys } } } } };
882
+ }
883
+
884
+ // ONE test for a family of ~23 guards, not one test each. The idea behind them is a single policy — THE
885
+ // IMPORTER NEVER TRUSTS A FIELD'S TYPE — and a document is untrusted input arriving over a network or out
886
+ // of a user's project folder, so every field of it can be anything. Writing a case per guard would pin the
887
+ // same policy twenty-three times and still miss the field nobody thought of; walking the document reaches
888
+ // the ones nobody thought of by construction.
889
+ //
890
+ // The assertion is deliberately weak on CONTENT and strict on SURVIVAL. A wrongly-typed field has no
891
+ // correct interpretation, so there is nothing to assert about what comes back — only that something did,
892
+ // and that what came back is internally coherent rather than half-built.
893
+ describe('parseSpineSkeleton type resilience', () => {
894
+ it('never trusts a field type: any value replaced by a wrong-typed one still imports coherently', () => {
895
+ const paths = everyJsonPath(SPINE_RICH);
896
+ expect(paths.length, 'the rich document walked no paths').toBeGreaterThan(40);
897
+
898
+ for (const path of paths) {
899
+ for (const wrong of [42, 'wrong', [], {}, null, true]) {
900
+ const label = `${path.join('.')} = ${JSON.stringify(wrong)}`;
901
+ const json = JSON.stringify(withValueAt(SPINE_RICH, path, wrong));
902
+ let result: ReturnType<typeof parseSpineSkeleton> | undefined;
903
+ expect(() => {
904
+ result = parseSpineSkeleton(json);
905
+ }, label).not.toThrow();
906
+
907
+ const bones = result?.skeleton.bones;
908
+ if (bones === undefined) continue;
909
+ for (const bone of bones) {
910
+ expect(bone.parentIndex, `parentIndex after ${label}`).toBeLessThan(bones.length);
911
+ expect(bone.parentIndex, `parentIndex after ${label}`).toBeGreaterThanOrEqual(-1);
912
+ }
913
+ }
914
+ }
915
+ });
916
+ });
917
+
820
918
  function slot(name: string): Slot2D {
821
919
  return { attachment: null, boneIndex: 0, color: 0xffffffff, name };
822
920
  }