@rig-c/parts 2.44.0 → 2.46.0

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.
@@ -0,0 +1,130 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { linkSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join, relative, resolve, sep } from 'node:path';
4
+ import { SHA256_PATTERN } from './editreceipt.ts';
5
+ import { PartsError } from './errors.ts';
6
+ import { readBinaryMask } from './maskvalues.ts';
7
+ import { decodePngBytes } from './raster/png.ts';
8
+ import { parseReceiptProducer, receiptObject, receiptProducerJson, receiptText, type ReceiptProducer } from './receiptproducer.ts';
9
+
10
+ const SPEC = 'rig-parts-external-receipt/1';
11
+ type FileBinding = { path: string; sha256: string };
12
+ type Grid = { width: number; height: number };
13
+ type ExternalReceipt = {
14
+ spec: typeof SPEC;
15
+ kind: 'mask';
16
+ file: FileBinding;
17
+ painting: FileBinding;
18
+ grid: Grid;
19
+ producer: ReceiptProducer;
20
+ };
21
+
22
+ function refuse(code: string, object: string, detail: string): never {
23
+ throw new PartsError([{ code, object, detail }]);
24
+ }
25
+
26
+ function keys(value: unknown, expected: string[]): value is Record<string, unknown> {
27
+ return receiptObject(value) && Object.keys(value).length === expected.length && expected.every(key => Object.hasOwn(value, key));
28
+ }
29
+
30
+ function validPath(value: unknown): value is string {
31
+ return receiptText(value) && !value.includes('\0');
32
+ }
33
+
34
+ function binding(value: unknown): value is FileBinding {
35
+ return keys(value, ['path', 'sha256']) && validPath(value.path) && !/^(?:\/|[A-Za-z]:)/.test(value.path) &&
36
+ !value.path.includes('\\') && typeof value.sha256 === 'string' && SHA256_PATTERN.test(value.sha256);
37
+ }
38
+
39
+ function grid(value: unknown): value is Grid {
40
+ return keys(value, ['width', 'height']) &&
41
+ [value.width, value.height].every(n => typeof n === 'number' && Number.isSafeInteger(n) && n > 0);
42
+ }
43
+
44
+ function parseReceipt(path: string): ExternalReceipt {
45
+ let value: unknown;
46
+ try { value = JSON.parse(readFileSync(path, 'utf8')); }
47
+ catch { return refuse('EXTERNAL_RECEIPT_SCHEMA', path, `a readable ${SPEC} JSON file is required`); }
48
+ if (!keys(value, ['spec', 'kind', 'file', 'painting', 'grid', 'producer']) ||
49
+ value.spec !== SPEC || value.kind !== 'mask' || !binding(value.file) || !binding(value.painting) || !grid(value.grid)) {
50
+ return refuse('EXTERNAL_RECEIPT_SCHEMA', path, `requires ${SPEC}, kind "mask", file and painting bindings, a measured grid and a producer`);
51
+ }
52
+ return { spec: SPEC, kind: 'mask', file: value.file, painting: value.painting, grid: value.grid,
53
+ producer: parseReceiptProducer(value.producer, `${path} producer`) };
54
+ }
55
+
56
+ function readInput(path: string, role: 'file' | 'painting', expected?: string) {
57
+ let bytes: Buffer;
58
+ try { bytes = readFileSync(path); }
59
+ catch { return refuse('EXTERNAL_RECEIPT_INPUT', path, `${role} is unreadable; a readable PNG is required`); }
60
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
61
+ if (expected !== undefined && sha256 !== expected) {
62
+ const code = role === 'file' ? 'EXTERNAL_RECEIPT_FILE_HASH' : 'EXTERNAL_RECEIPT_PAINTING_HASH';
63
+ refuse(code, path, `${role} sha256 is ${sha256}; receipt requires ${expected}`);
64
+ }
65
+ try { return { sha256, raster: decodePngBytes(bytes, path) }; }
66
+ catch { return refuse('EXTERNAL_RECEIPT_PNG', path, `${role} is not a decodable PNG`); }
67
+ }
68
+
69
+ function measure(file: string, painting: string, expected?: ExternalReceipt) {
70
+ const source = readInput(painting, 'painting', expected?.painting.sha256);
71
+ const mask = readInput(file, 'file', expected?.file.sha256);
72
+ const { width, height } = source.raster;
73
+ const checkGrid = (object: string, measured: Grid): void => {
74
+ if (measured.width !== width || measured.height !== height) {
75
+ refuse('EXTERNAL_RECEIPT_GRID', object, `is ${measured.width}x${measured.height}; painting ${painting} requires ${width}x${height}`);
76
+ }
77
+ };
78
+ checkGrid(file, mask.raster);
79
+ if (expected !== undefined) checkGrid('receipt grid', expected.grid);
80
+ readBinaryMask(mask.raster, detail => refuse('EXTERNAL_RECEIPT_MASK_VALUES', file, detail));
81
+ return { fileSha: mask.sha256, paintingSha: source.sha256, grid: { width, height } };
82
+ }
83
+
84
+ function publish(path: string, receipt: ExternalReceipt): void {
85
+ let staging: string | undefined;
86
+ try {
87
+ staging = mkdtempSync(join(dirname(path), '.external-receipt-'));
88
+ const staged = join(staging, 'receipt.json');
89
+ writeFileSync(staged, JSON.stringify(receipt, null, 2) + '\n');
90
+ linkSync(staged, path);
91
+ } catch {
92
+ refuse('EXTERNAL_RECEIPT_OUTPUT', path, 'could not publish the receipt; an unused path in a writable directory is required');
93
+ } finally {
94
+ if (staging !== undefined) rmSync(staging, { recursive: true, force: true });
95
+ }
96
+ }
97
+
98
+ export function externalReceipt(flags: ReadonlyMap<string, string>): void {
99
+ const verify = flags.get('--verify');
100
+ if (verify !== undefined) {
101
+ if (flags.size !== 1 || !validPath(verify)) {
102
+ refuse('EXTERNAL_RECEIPT_ARGUMENT', '--verify', 'requires one receipt path and no write flags');
103
+ }
104
+ const path = resolve(verify);
105
+ const receipt = parseReceipt(path);
106
+ measure(resolve(dirname(path), receipt.file.path), resolve(dirname(path), receipt.painting.path), receipt);
107
+ return;
108
+ }
109
+ if (flags.get('--kind') !== 'mask') {
110
+ refuse('EXTERNAL_RECEIPT_ARGUMENT', '--kind', `is ${JSON.stringify(flags.get('--kind'))}; "mask" is the accepted value`);
111
+ }
112
+ const argument = (flag: string): string => {
113
+ const value = flags.get(flag);
114
+ if (!validPath(value)) return refuse('EXTERNAL_RECEIPT_ARGUMENT', flag, 'requires a nonblank value');
115
+ return value;
116
+ };
117
+ const path = resolve(argument('--out'));
118
+ const file = resolve(argument('--file'));
119
+ const painting = resolve(argument('--painting'));
120
+ const producer = receiptProducerJson(flags.get('--producer') ?? '', '--producer');
121
+ const bound = (input: string, sha256: string): FileBinding => {
122
+ const pathFromReceipt = relative(dirname(path), input).split(sep).join('/');
123
+ const value = { path: pathFromReceipt, sha256 };
124
+ if (!binding(value)) refuse('EXTERNAL_RECEIPT_ARGUMENT', input, 'requires a portable path relative to the receipt directory');
125
+ return value;
126
+ };
127
+ const measured = measure(file, painting);
128
+ publish(path, { spec: SPEC, kind: 'mask', file: bound(file, measured.fileSha),
129
+ painting: bound(painting, measured.paintingSha), grid: measured.grid, producer });
130
+ }
@@ -0,0 +1,21 @@
1
+ import type { Raster } from './raster/types.ts';
2
+
3
+ /** Read an opaque black/white mask, reporting the first invalid pixel. */
4
+ export function readBinaryMask(
5
+ mask: Raster,
6
+ refuse: (detail: string) => never,
7
+ ): Uint8Array {
8
+ const { width, height, data } = mask;
9
+ const inside = new Uint8Array(width * height);
10
+ for (let p = 0; p < inside.length; p++) {
11
+ const offset = p * 4;
12
+ const r = data[offset], g = data[offset + 1], b = data[offset + 2], a = data[offset + 3];
13
+ const white = r === 255 && g === 255 && b === 255;
14
+ const black = r === 0 && g === 0 && b === 0;
15
+ if (a !== 255 || (!white && !black)) {
16
+ refuse(`holds (${r}, ${g}, ${b}, ${a}) at pixel ${p % width},${Math.floor(p / width)}; only opaque white and opaque black, as assemble writes it, are taken`);
17
+ }
18
+ if (white) inside[p] = 1;
19
+ }
20
+ return inside;
21
+ }
@@ -0,0 +1,40 @@
1
+ import { PartsError } from './errors.ts';
2
+
3
+ /**
4
+ * Filesystem spelling for a diagnostic name. See STABILITY's "Diagnostic path
5
+ * segments" for the single public definition. Encode code units, not UTF-8:
6
+ * even an unpaired surrogate has its own spelling rather than U+FFFD's.
7
+ */
8
+ export function diagnosticSegment(name: string, suffix = ''): string {
9
+ let encoded = '';
10
+ const escape = (unit: number): string => '~' + unit.toString(16).padStart(4, '0');
11
+ for (let i = 0; i < name.length; i++) {
12
+ const unit = name[i];
13
+ encoded += /^[A-Za-z0-9_@+.-]$/.test(unit) && !(unit === '.' && i === name.length - 1)
14
+ ? unit : escape(name.charCodeAt(i));
15
+ }
16
+ if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(encoded)) encoded = escape(name.charCodeAt(0)) + encoded.slice(1);
17
+ const segment = encoded + suffix;
18
+ if (name.length === 0 || segment.length > 255) throw new PartsError([{
19
+ code: 'DIAGNOSTIC_PATH_SEGMENT', object: `diagnostic name ${JSON.stringify(name)}`,
20
+ detail: name.length === 0 ? 'is empty; a nonempty original name is required for a diagnostic filesystem segment'
21
+ : `encodes to ${segment.length} characters including fixed suffix ${JSON.stringify(suffix)}; at most 255 are required for a diagnostic filesystem segment; shorten the original name, no truncation is applied`,
22
+ }]);
23
+ return segment;
24
+ }
25
+
26
+ /** Validate the entire sibling scope before a caller creates any of its paths. */
27
+ export function diagnosticSiblings(names: readonly { name: string; suffix?: string }[], scope: string): string[] {
28
+ const seen = new Map<string, { name: string; folder: string }>();
29
+ return names.map(({ name, suffix }) => {
30
+ const folder = diagnosticSegment(name, suffix);
31
+ const folded = folder.toLowerCase(); // Mapped segments contain ASCII only.
32
+ const previous = seen.get(folded);
33
+ if (previous !== undefined) throw new PartsError([{
34
+ code: 'DIAGNOSTIC_PATH_SEGMENT', object: `diagnostic names ${JSON.stringify(previous.name)} and ${JSON.stringify(name)}`,
35
+ detail: `folders ${JSON.stringify(previous.folder)} and ${JSON.stringify(folder)} share ASCII-case-folded folder ${JSON.stringify(folded)} in sibling scope ${JSON.stringify(scope)}; distinct case-folded sibling folders are required`,
36
+ }]);
37
+ seen.set(folded, { name, folder });
38
+ return folder;
39
+ });
40
+ }
package/src/parts.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { assemblyFieldDigest } from './assembly-reading.ts';
2
+ import { orderedEditedPartReceipt, type EditedPartReceipt } from './editedparts.ts';
3
+ import { parseReceiptProducer, receiptText } from './receiptproducer.ts';
1
4
  import { takenSourceProblems, type TakenLayerSource } from './takesource.ts';
2
5
  import { AUTOMATIC_WRITERS, provenanceAddsUp, type PixelProvenance, type CutOwnership } from './provenance.ts';
3
6
  import { baseAnchorProblems, orderedBaseAnchor, type BaseAnchor } from './baseanchor.ts';
@@ -164,6 +167,8 @@ export interface LimbRecord {
164
167
  export interface HybridBandRecord {
165
168
  upper: string;
166
169
  width: number;
170
+ /** The centered source-run width before applying an override, including a nonpositive reading the default would refuse. */
171
+ measured_width?: number;
167
172
  radius: number;
168
173
  at: [number, number];
169
174
  axis: [number, number];
@@ -288,7 +293,7 @@ const CUT_KEYS = ['cut_offset', 'cut_at', 'cut_crossed', 'joint_crossed', 'band_
288
293
  function orderedLimb(l: LimbRecord): Record<string, unknown> {
289
294
  const cap = l.cap === undefined ? undefined : Object.fromEntries(CAP_KEYS.filter((k) => (l.cap as CapRecord)[k] !== undefined).map((k) => [k, (l.cap as CapRecord)[k]]));
290
295
  const band = (value: HybridBandRecord & { part?: string }): Record<string, unknown> => Object.fromEntries(
291
- (['part', 'upper', 'width', 'radius', 'at', 'axis'] as const).filter((k) => value[k] !== undefined).map((k) => [k, value[k]]));
296
+ (['part', 'upper', 'width', 'measured_width', 'radius', 'at', 'axis'] as const).filter((k) => value[k] !== undefined).map((k) => [k, value[k]]));
292
297
  const values = { ...l, cap, ...(l.hybrid === undefined ? {} : { hybrid: band(l.hybrid) }), ...(l.band === undefined ? {} : { band: band(l.band) }) };
293
298
  return Object.fromEntries(LIMB_KEYS.filter((k) => values[k] !== undefined).map((k) => [k, values[k]]));
294
299
  }
@@ -418,7 +423,13 @@ export interface OccluderGuardRecord {
418
423
  guarded_px_after: number;
419
424
  }
420
425
 
426
+ export interface AssemblyConfigRecord {
427
+ sha256: string;
428
+ fields: Array<{ name: string; sha256: string }>;
429
+ }
430
+
421
431
  export interface PartsFile {
432
+ assembly_config?: AssemblyConfigRecord;
422
433
  /** Optional on legacy packages; binds the opaque RGB raster assemble actually read. */
423
434
  painting_in_rig?: PaintingInRig;
424
435
  /** Structural moves, independent of per-pixel value equality. */
@@ -477,8 +488,8 @@ export interface SceneRecord {
477
488
  figure_mask: string;
478
489
  }
479
490
 
480
- const TOP_KEYS = ['painting_in_rig', 'rig_size', 'scale_rig_per_source', 'parts', 'ghost_px', 'recomposite', 'scene', 'occluder_plates', 'occluder_grow', 'occluder_guard', 'single_run_pad', 'alternates', 'motion_seams', 'cut_ownership'] as const;
481
- const REQUIRED_TOP_KEYS = TOP_KEYS.filter((k) => k !== 'painting_in_rig' && k !== 'recomposite' && k !== 'scene' && k !== 'single_run_pad' && k !== 'occluder_plates' && k !== 'occluder_grow' && k !== 'occluder_guard' && k !== 'alternates' && k !== 'motion_seams' && k !== 'cut_ownership');
491
+ const TOP_KEYS = ['assembly_config', 'painting_in_rig', 'rig_size', 'scale_rig_per_source', 'parts', 'ghost_px', 'recomposite', 'scene', 'occluder_plates', 'occluder_grow', 'occluder_guard', 'single_run_pad', 'alternates', 'motion_seams', 'cut_ownership'] as const;
492
+ const REQUIRED_TOP_KEYS = TOP_KEYS.filter((k) => k !== 'assembly_config' && k !== 'painting_in_rig' && k !== 'recomposite' && k !== 'scene' && k !== 'single_run_pad' && k !== 'occluder_plates' && k !== 'occluder_grow' && k !== 'occluder_guard' && k !== 'alternates' && k !== 'motion_seams' && k !== 'cut_ownership');
482
493
  export const OCCLUDER_PLATE_KEYS = ['receipt', 'receipt_sha256', 'occluder_sha256', 'painting_sha256', 'output_sha256', 'mask_sha256'] as const;
483
494
  export const OCCLUDER_GROW_KEYS = ['occluder', 'image', 'grow', 'covered_px_before', 'covered_px_after'] as const;
484
495
  export const OCCLUDER_GUARD_KEYS = ['occluder', 'image', 'guard', 'guarded_px_before', 'guarded_px_after'] as const;
@@ -544,6 +555,14 @@ export function tagOf(from: string): string | null {
544
555
  return f === null || f.run === 'painting' ? null : f.tag;
545
556
  }
546
557
 
558
+ function validEditedPartAuthor(receipt: EditedPartReceipt): boolean {
559
+ const keys = Object.keys(receipt).sort().join(',');
560
+ if (keys === 'editor,file,from_sha256,part,sha256') return receiptText(receipt.editor);
561
+ if (keys !== 'file,from_sha256,part,producer,sha256') return false;
562
+ try { parseReceiptProducer(receipt.producer, 'edited part producer'); return true; }
563
+ catch { return false; }
564
+ }
565
+
547
566
  const OWNERSHIP_KEYS = ['edit', 'from', 'into', 'moved_in_opaque_px', 'retained_band_opaque_px', 'cleared_opaque_px', 'under_filled_px', 'under_filled_opaque_px', 'net_cleared_opaque_px', 'under_plate'] as const;
548
567
  const REQUIRED_OWNERSHIP_KEYS = OWNERSHIP_KEYS.filter((k) => k !== 'under_plate');
549
568
  function orderedOwnership(rows: readonly CutOwnership[]): Array<Record<string, unknown>> {
@@ -595,8 +614,7 @@ function orderedProvenance(p: PixelProvenance): PixelProvenance {
595
614
  ...(p.depth === undefined ? {} : { depth: { kind: p.depth.kind, values: p.depth.values.map(v => ({ group: v.group, ...(v.bone === undefined ? {} : { bone: v.bone }), value: v.value })) } }),
596
615
  ...(p.edited_part === undefined ? {} : { edited_part: {
597
616
  edit: p.edited_part.edit, dir: p.edited_part.dir,
598
- receipt: { part: p.edited_part.receipt.part, file: p.edited_part.receipt.file,
599
- sha256: p.edited_part.receipt.sha256, from_sha256: p.edited_part.receipt.from_sha256, editor: p.edited_part.receipt.editor },
617
+ receipt: orderedEditedPartReceipt(p.edited_part.receipt),
600
618
  changed_px: p.edited_part.changed_px, changed_counted_px: p.edited_part.changed_counted_px,
601
619
  changed_excluded_px: p.edited_part.changed_excluded_px, removed_opaque_px: p.edited_part.removed_opaque_px,
602
620
  } }) };
@@ -645,6 +663,7 @@ export function serializeParts(file: PartsFile): string {
645
663
  path: file.painting_in_rig.path, sha256: file.painting_in_rig.sha256, resample: file.painting_in_rig.resample,
646
664
  } }),
647
665
  parts: serializePartList(file.parts),
666
+ ...(file.assembly_config === undefined ? {} : { assembly_config: { sha256: file.assembly_config.sha256, fields: file.assembly_config.fields.map(({ name, sha256 }) => ({ name, sha256 })) } }),
648
667
  ...(file.cut_ownership === undefined ? {} : { cut_ownership: orderedOwnership(file.cut_ownership) }),
649
668
  ...(file.motion_seams === undefined ? {} : { motion_seams: file.motion_seams.map(({ part, neighbour }) => ({ part, neighbour })) }),
650
669
  ghost_px: Object.fromEntries(Object.keys(file.ghost_px).sort().map((k) => [k, file.ghost_px[k]])),
@@ -732,7 +751,8 @@ export function partsFileReferences(dir: string): PartsFileReference[] {
732
751
  return [...unique.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.role < b.role ? -1 : a.role > b.role ? 1 : 0);
733
752
  }
734
753
 
735
- function readPartsManifest(path: string): PartsFile {
754
+ /** Read the manifest before checking any sidecar files beside it. */
755
+ export function readPartsManifest(path: string): PartsFile {
736
756
  if (!existsSync(path)) refuseIfAny([{ code: 'PARTS_FILE_PRESENT', object: path, detail: 'no such file; --parts names the directory holding parts.json and parts/ (work/rig from assemble --out work, or out from build --out out)' }]);
737
757
  let raw: unknown;
738
758
  try {
@@ -821,10 +841,10 @@ function checkProvenance(raw: unknown, opaque: unknown, object: string, fail: (c
821
841
  typeof e.edit === 'string' && /^edited_parts\[\d+\]$/.test(e.edit) && relativePath(e.dir) &&
822
842
  [e.changed_px, e.changed_counted_px, e.changed_excluded_px, e.removed_opaque_px].every(count) &&
823
843
  e.receipt !== null && typeof e.receipt === 'object' && !Array.isArray(e.receipt) &&
824
- Object.keys(e.receipt).sort().join(',') === 'editor,file,from_sha256,part,sha256' &&
825
- nonempty(e.receipt.part) && e.receipt.part === identity?.name && relativePath(e.receipt.file) && nonempty(e.receipt.editor) &&
844
+ validEditedPartAuthor(e.receipt) &&
845
+ nonempty(e.receipt.part) && e.receipt.part === identity?.name && relativePath(e.receipt.file) &&
826
846
  [e.receipt.sha256, e.receipt.from_sha256].every(s => typeof s === 'string' && /^[a-f0-9]{64}$/.test(s));
827
- if (!valid) fail('PARTS_FIELD_TYPE', object + ' edited_part', 'requires edited_parts[i], a config-relative dir, a receipt with the enclosing part name, dir-relative file, two lowercase sha256 hashes and editor, and four nonnegative safe integer change counts');
847
+ if (!valid) fail('PARTS_FIELD_TYPE', object + ' edited_part', 'requires edited_parts[i], a config-relative dir, a receipt with the enclosing part name, dir-relative file, two lowercase sha256 hashes and either editor or producer, and four nonnegative safe integer change counts');
828
848
  else {
829
849
  const area = typeof identity?.w === 'number' && typeof identity.h === 'number' ? identity.w * identity.h : NaN;
830
850
  if (!Number.isSafeInteger(area) || !count(opaque) || e.changed_px !== e.changed_counted_px + e.changed_excluded_px ||
@@ -860,6 +880,19 @@ function checkParts(raw: unknown, path: string): PartsFile {
860
880
  const o = raw as Record<string, unknown>;
861
881
  for (const k of Object.keys(o)) if (!(TOP_KEYS as readonly string[]).includes(k)) fail('PARTS_KEY_KNOWN', `${path} key "${k}"`, `is not a parts.json field; known: ${TOP_KEYS.join(', ')}`);
862
882
  for (const k of REQUIRED_TOP_KEYS) if (!(k in o)) fail('PARTS_FIELD_PRESENT', `${path} field "${k}"`, 'is absent and required');
883
+ if ('assembly_config' in o) {
884
+ const value = o.assembly_config as Partial<AssemblyConfigRecord> | null;
885
+ const digest = (input: unknown): input is string => typeof input === 'string' && /^[a-f0-9]{64}$/.test(input);
886
+ if (value === null || typeof value !== 'object' || Object.keys(value).some(key => key !== 'sha256' && key !== 'fields') ||
887
+ !digest(value.sha256) || !Array.isArray(value.fields) || value.fields.length === 0 ||
888
+ !value.fields.every((row, i) => row !== null && typeof row === 'object' && Object.keys(row).length === 2 &&
889
+ typeof row.name === 'string' && /^[a-z_]+(?:\.[a-z_]+)*$/.test(row.name) &&
890
+ digest(row.sha256) && (i === 0 || value.fields![i - 1].name < row.name)) ||
891
+ assemblyFieldDigest(value.fields) !== value.sha256) {
892
+ fail('PARTS_FIELD_TYPE', `${path} field "assembly_config"`, 'requires sorted distinct field names with lowercase SHA-256 digests and their matching aggregate digest');
893
+ }
894
+ }
895
+
863
896
  if ('painting_in_rig' in o) {
864
897
  const p = o.painting_in_rig;
865
898
  if (typeof p !== 'object' || p === null || Array.isArray(p) ||
@@ -1203,7 +1236,11 @@ function checkLimbRecords(recordsRaw: unknown[], prefix: string, fail: (code: st
1203
1236
  else {
1204
1237
  const b = h as Record<string, unknown>;
1205
1238
  const pair = (v: unknown): v is number[] => Array.isArray(v) && v.length === 2 && v.every((n) => typeof n === 'number' && Number.isFinite(n));
1206
- if (Object.keys(b).sort().join(',') !== (field === 'hybrid' ? 'at,axis,part,radius,upper,width' : 'at,axis,radius,upper,width') || (field === 'hybrid' && (typeof b.part !== 'string' || b.part === '')) || !(typeof b.radius === 'number' && Number.isFinite(b.radius) && b.radius > 0) || typeof b.upper !== 'string' || b.upper === '' || b.upper === q.bone || !(typeof b.width === 'number' && Number.isFinite(b.width) && b.width > 0) || !pair(b.at) || !pair(b.axis) || Math.abs(edgeLength(b.axis[0], b.axis[1]) - 1) > 1e-6 || (field === 'band' && 'range' in q)) fail('PARTS_FIELD_TYPE', `${object} ${field}`, `is ${show(h)}; distinct upper carrier, positive width, finite at, unit axis and no duplicate range are required`);
1239
+ const keys = Object.keys(b).filter((k) => k !== 'measured_width').sort().join(',');
1240
+ if (keys !== (field === 'hybrid' ? 'at,axis,part,radius,upper,width' : 'at,axis,radius,upper,width') || (field === 'hybrid' && (typeof b.part !== 'string' || b.part === '')) || !(typeof b.radius === 'number' && Number.isFinite(b.radius) && b.radius > 0) || typeof b.upper !== 'string' || b.upper === '' || b.upper === q.bone || !(typeof b.width === 'number' && Number.isFinite(b.width) && b.width > 0) || !pair(b.at) || !pair(b.axis) || Math.abs(edgeLength(b.axis[0], b.axis[1]) - 1) > 1e-6 || (field === 'band' && 'range' in q)) fail('PARTS_FIELD_TYPE', `${object} ${field}`, `is ${show(h)}; distinct upper carrier, positive width, finite at, unit axis and no duplicate range are required`);
1241
+ if (Object.hasOwn(b, 'measured_width') && !(typeof b.measured_width === 'number' && Number.isFinite(b.measured_width))) {
1242
+ fail('PARTS_FIELD_TYPE', `${object} ${field}.measured_width`, `is ${show(b.measured_width)}; a finite centered source-run width is required`);
1243
+ }
1207
1244
  }
1208
1245
  }
1209
1246
  if (caps && 'cap' in q) checkCap(q.cap, `${object} "cap"`, fail);
@@ -1230,7 +1267,7 @@ function checkLimbRecords(recordsRaw: unknown[], prefix: string, fail: (code: st
1230
1267
  const record = (v: unknown): Record<string, unknown> | undefined => typeof v === 'object' && v !== null && !Array.isArray(v) ? v as Record<string, unknown> : undefined;
1231
1268
  const bl = record(target?.limb);
1232
1269
  const b = record(bl?.band);
1233
- const same = b !== undefined && ['upper', 'width', 'radius', 'at', 'axis'].every((k) => JSON.stringify(b[k]) === JSON.stringify(joint[k]));
1270
+ const same = b !== undefined && b.measured_width === joint.measured_width && ['upper', 'width', 'radius', 'at', 'axis'].every((k) => JSON.stringify(b[k]) === JSON.stringify(joint[k]));
1234
1271
  if (bl === undefined || bl.name !== l.name || bl.segment !== l.segment || bl.bone !== l.bone || bl.of !== l.of || bl.joint !== l.joint || !same) fail('PARTS_HYBRID_PAIR', `${prefix}part "${String(r.name)}" hybrid "${String(joint.part)}"`, 'requires its matching band on the same source, joint, carriers and measured geometry');
1235
1272
  }
1236
1273
  }
package/src/plate.ts CHANGED
@@ -31,6 +31,7 @@
31
31
  * of every file it names; `verifyPlateReceipt` reads it back against the bytes
32
32
  * on disk. Every path in it is relative to the receipt's own directory.
33
33
  */
34
+ import { readBinaryMask } from './maskvalues.ts';
34
35
  import { readMatteSource } from './matte.ts';
35
36
  import { isSeeThroughTransform, inverseSeeThroughMask } from './seethrough-transform.ts';
36
37
  import { createHash } from 'node:crypto';
@@ -314,12 +315,7 @@ export function readSourceMask(source: MaskSource, dir: string, width: number, h
314
315
  if (r.width !== width || r.height !== height) {
315
316
  fail('PLATE_MASK_GRID', maskPath, `is ${r.width}x${r.height}; the painting's ${width}x${height} is required — the rig grid is not the painting's when the rig is scaled, and the mask is never fitted`);
316
317
  }
317
- for (let p = 0; p < width * height; p++) {
318
- const [R, G, B, A] = [r.data[p * 4], r.data[p * 4 + 1], r.data[p * 4 + 2], r.data[p * 4 + 3]];
319
- const white = R === 255 && G === 255 && B === 255, black = R === 0 && G === 0 && B === 0;
320
- if (A !== 255 || (!white && !black)) fail('PLATE_MASK_VALUES', maskPath, `holds (${R}, ${G}, ${B}, ${A}) at pixel ${p % width},${Math.floor(p / width)}; only opaque white and opaque black, as assemble writes it, are taken`);
321
- if (white) inside[p] = 1;
322
- }
318
+ inside = readBinaryMask(r, detail => fail('PLATE_MASK_VALUES', maskPath, detail));
323
319
  }
324
320
  if (!inside.some((v) => v === 1)) fail('PLATE_MASK_EMPTY', `${source}:${dir}`, 'holds no figure pixel on the painting grid; a figure to remove or matte is required');
325
321
  return { width, height, inside };