@rig-c/parts 2.49.1 → 2.51.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,656 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { accessSync, constants, existsSync, lstatSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import { basename, dirname, join, resolve, sep } from 'node:path';
4
+ import { bustClearanceDetail, type CharacterConfig, DEFAULT_BUST_ALPHA, DEFAULT_BUST_BONE_L, DEFAULT_BUST_BONE_R, DEFAULT_BUST_CLEARANCE, DEFAULT_BUST_SPACING, loadConfig } from './config.ts';
5
+ import { BUST_SHAPE_FIELDS, type BustShapeKey, type ConfigWritePatch, type PendingBustShape } from './configwrite.ts';
6
+ import { SHA256_PATTERN } from './editreceipt.ts';
7
+ import { PartsError, type Problem } from './errors.ts';
8
+ import { type PartsFile, readParts } from './parts.ts';
9
+
10
+ /**
11
+ * `rig-parts bust-landmarks` (issue #1382): the file `propose --bust-landmarks`
12
+ * reads, written from the one chest row of a Review chest-landmarks act, with a
13
+ * provenance record beside it.
14
+ *
15
+ * The act is read as JSON by path and only what this command uses is validated:
16
+ * the envelope's `schema` and `actId`, and from each `value.chestLandmarks[]`
17
+ * row its `edit.slot`, `edit.skin`, `edit.attachment`, `edit.basis`,
18
+ * `edit.source.hash`, `edit.source.frame`, `edit.bust` and `sha256`. Review is
19
+ * not imported; its grammar for the act is its own, and this reader refuses by
20
+ * name what it cannot use.
21
+ *
22
+ * The row's `sha256` is recomputed and a mismatch is refused: sha256 (lowercase
23
+ * hex) of `JSON.stringify` of the row's raw `edit` with object keys sorted
24
+ * recursively (`Object.keys(v).sort()`) and array order kept. That rule is a
25
+ * copy of Review's request digest; the contract is held in two places, and the
26
+ * selftest computes its fixtures' digests with its own inline copy.
27
+ *
28
+ * The five shape fields the landmarks file does not carry must agree with the
29
+ * config, or, with `--write-config`, are taken into the config's existing
30
+ * `contour.bust` through the CLI's staged config writer. With no `contour.bust`
31
+ * yet, the fields that differ from the defaults are recorded in the sidecar as
32
+ * a pending shape, which `propose --write-config --bust-landmarks` writes with
33
+ * the points and marks applied ({@link readBustSidecar}). The outputs are
34
+ * written to temporary siblings and renamed into place only once both are
35
+ * staged; a failure removes the temporaries and leaves earlier files as they were.
36
+ */
37
+
38
+ /** The act schema this command reads; another act version is refused by name. */
39
+ export const BUST_LANDMARKS_ACT_SCHEMA = 'rig-review/act@9';
40
+ /** The provenance record's spec. */
41
+ export const BUST_LANDMARKS_PROVENANCE_SPEC = 'rig-parts-bust-landmarks-provenance/1';
42
+ /** The provenance record is written beside `--out` under this suffix, as `depth-bind` writes `<map>.binding.json`. */
43
+ export const BUST_LANDMARKS_PROVENANCE_SUFFIX = '.provenance.json';
44
+
45
+ /** The keys of a row's `edit.bust`: Parts' own `meshes.<part>.contour.bust` shorthand. */
46
+ const BUST_KEYS = ['apex_r', 'apex_l', 'cleavage', 'alpha', 'clearance', 'bone_r', 'bone_l', 'spacing'] as const;
47
+ /** The bust fields the landmarks file does not carry, in the shorthand's key order (the config writer's list): they
48
+ * must agree with the config, be taken into it, or be left pending in the sidecar, so none is dropped. */
49
+ const SHAPE_KEYS = BUST_SHAPE_FIELDS;
50
+ type ShapeKey = BustShapeKey;
51
+ type Shape = { alpha: number; clearance: number; spacing: number; bone_r: string; bone_l: string };
52
+ const SHAPE_DEFAULTS: Shape = {
53
+ alpha: DEFAULT_BUST_ALPHA,
54
+ clearance: DEFAULT_BUST_CLEARANCE,
55
+ spacing: DEFAULT_BUST_SPACING,
56
+ bone_r: DEFAULT_BUST_BONE_R,
57
+ bone_l: DEFAULT_BUST_BONE_L,
58
+ };
59
+
60
+ type Point = [number, number];
61
+
62
+ /** The landmarks file, in the key order `propose --bust-landmarks` documents. */
63
+ export interface BustLandmarksFile {
64
+ apex_r: Point;
65
+ apex_l: Point;
66
+ cleavage?: Point;
67
+ }
68
+
69
+ /** The provenance record written beside the landmarks file. Fixed key order, no clock. */
70
+ export interface BustLandmarksProvenance {
71
+ spec: typeof BUST_LANDMARKS_PROVENANCE_SPEC;
72
+ act: { schema: typeof BUST_LANDMARKS_ACT_SCHEMA; act_id: string; file_sha256: string };
73
+ row_sha256: string;
74
+ slot: string;
75
+ source: { hash: string; frame: { width: number; height: number } };
76
+ landmarks_sha256: string;
77
+ /**
78
+ * Present only when the config declared no `contour.bust` and the act's shape differs from the defaults: the
79
+ * act's fields whose effective value differs, in the shorthand's key order. `pending` until `propose
80
+ * --write-config --bust-landmarks` writes them with the points, then `applied`.
81
+ */
82
+ shape?: { status: 'pending' | 'applied'; fields: Partial<Record<BustShapeKey, number | string>> };
83
+ }
84
+
85
+ interface ChestRow {
86
+ index: number;
87
+ slot: string;
88
+ skin: string;
89
+ attachment: string;
90
+ hash: string;
91
+ frame: { width: number; height: number };
92
+ landmarks: BustLandmarksFile;
93
+ shape: Partial<Shape>;
94
+ sha256: string;
95
+ }
96
+
97
+ const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
98
+ /** A value as JSON, with a number JSON cannot hold (1e999 reads as Infinity) written as itself, never as null. */
99
+ const show = (v: unknown): string => {
100
+ const text = JSON.stringify(v, (_key, x: unknown) => typeof x === 'number' && !Number.isFinite(x) ? `\u0000${String(x)}\u0000` : x);
101
+ return text === undefined ? 'absent' : text.replace(/"\\u0000(-?Infinity|NaN)\\u0000"/g, '$1');
102
+ };
103
+ /** True when a value holds a number that is not finite, anywhere inside it. */
104
+ const nonFinite = (v: unknown): boolean => typeof v === 'number' ? !Number.isFinite(v) : Array.isArray(v) && v.some(nonFinite);
105
+ /** The error code of a failed file operation, or UNKNOWN. */
106
+ const errorCode = (error: unknown): string => isObject(error) && typeof error.code === 'string' ? error.code : 'UNKNOWN';
107
+ /** The rule the row digest is checked by: Review's request digest, a copy of its canonical JSON. */
108
+ const DIGEST_RULE = 'sha256 (lowercase hex) of JSON.stringify of the row\'s edit with object keys sorted recursively and array order kept';
109
+ /** Review's canonical JSON for the row digest: object keys sorted recursively by `Object.keys(v).sort()`, array order kept. */
110
+ const canonicalJson = (value: unknown): string => {
111
+ const sorted = (v: unknown): unknown => Array.isArray(v) ? v.map(sorted)
112
+ : isObject(v) ? Object.fromEntries(Object.keys(v).sort().map(key => [key, sorted(v[key])])) : v;
113
+ return JSON.stringify(sorted(value));
114
+ };
115
+ const sha256 = (bytes: Uint8Array | string): string => createHash('sha256').update(bytes).digest('hex');
116
+ const isPoint = (v: unknown): v is Point => Array.isArray(v) && v.length === 2 && v.every(n => typeof n === 'number' && Number.isFinite(n));
117
+ const isName = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
118
+
119
+ /** Read one `value.chestLandmarks[i]` row; every problem it has is pushed, and null returned when any is. */
120
+ function readRow(raw: unknown, index: number, problems: Problem[]): ChestRow | null {
121
+ const at = `value.chestLandmarks[${index}]`;
122
+ const before = problems.length;
123
+ const fail = (object: string, detail: string): void => { problems.push({ code: 'BUST_LANDMARKS_ROW', object, detail }); };
124
+ if (!isObject(raw)) {
125
+ fail(at, `is ${show(raw)}; an object with edit and sha256 is required`);
126
+ return null;
127
+ }
128
+ const digest = raw.sha256;
129
+ const edit = raw.edit;
130
+ if (typeof digest !== 'string' || !SHA256_PATTERN.test(digest)) fail(`${at}.sha256`, `is ${show(digest)}; 64 lowercase hex digits are required`);
131
+ else if (isObject(edit)) {
132
+ const computed = sha256(canonicalJson(edit));
133
+ if (computed !== digest) fail(`${at}.sha256`, `is "${digest}"; "${computed}" is required, the digest of this row's edit by ${DIGEST_RULE} (Review's request digest): the edit is not the one the digest names`);
134
+ }
135
+ if (!isObject(edit)) {
136
+ fail(`${at}.edit`, `is ${show(edit)}; an object with slot, skin, attachment, basis, source and bust is required`);
137
+ return null;
138
+ }
139
+ for (const key of ['slot', 'skin', 'attachment'] as const) {
140
+ if (!isName(edit[key])) fail(`${at}.edit.${key}`, `is ${show(edit[key])}; a non-empty name is required`);
141
+ }
142
+ if (edit.basis !== 'setup') fail(`${at}.edit.basis`, `is ${show(edit.basis)}; "setup" is required: the points are setup-pose rig px`);
143
+ const source = edit.source;
144
+ let frame: { width: number; height: number } | null = null;
145
+ if (!isObject(source)) fail(`${at}.edit.source`, `is ${show(source)}; an object with hash and frame is required`);
146
+ else {
147
+ if (typeof source.hash !== 'string' || !SHA256_PATTERN.test(source.hash)) fail(`${at}.edit.source.hash`, `is ${show(source.hash)}; 64 lowercase hex digits are required`);
148
+ const f = source.frame;
149
+ const positive = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n > 0;
150
+ if (!isObject(f) || !positive(f.width) || !positive(f.height)) fail(`${at}.edit.source.frame`, `is ${show(f)}; {width, height} in positive finite rig px is required`);
151
+ else frame = { width: f.width, height: f.height };
152
+ }
153
+ const bust = edit.bust;
154
+ const shape: Partial<Shape> = {};
155
+ if (!isObject(bust)) fail(`${at}.edit.bust`, `is ${show(bust)}; an object with apex_r, apex_l and optional cleavage is required`);
156
+ else {
157
+ for (const key of Object.keys(bust)) {
158
+ if (!(BUST_KEYS as readonly string[]).includes(key)) fail(`${at}.edit.bust.${key}`, `is unknown; contour.bust takes ${BUST_KEYS.join(', ')}`);
159
+ }
160
+ for (const key of ['apex_r', 'apex_l', 'cleavage'] as const) {
161
+ if (key === 'cleavage' && !Object.hasOwn(bust, key)) continue;
162
+ if (!isPoint(bust[key])) fail(`${at}.edit.bust.${key}`, `is ${show(bust[key])}${nonFinite(bust[key]) ? ', a coordinate that is not finite' : ''}; a finite [x, y] point in rig px is required`);
163
+ }
164
+ for (const key of ['alpha', 'clearance', 'spacing'] as const) {
165
+ if (!Object.hasOwn(bust, key)) continue;
166
+ const n = bust[key];
167
+ if (typeof n !== 'number' || !Number.isFinite(n)) fail(`${at}.edit.bust.${key}`, `is ${show(n)}${nonFinite(n) ? ', not finite' : ''}; a finite number is required`);
168
+ else shape[key] = n;
169
+ }
170
+ for (const key of ['bone_r', 'bone_l'] as const) {
171
+ if (!Object.hasOwn(bust, key)) continue;
172
+ const name = bust[key];
173
+ if (!isName(name)) fail(`${at}.edit.bust.${key}`, `is ${show(name)}; a non-empty bone name is required`);
174
+ else shape[key] = name;
175
+ }
176
+ }
177
+ if (problems.length > before || !isObject(bust) || frame === null || !isObject(source)) return null;
178
+ const landmarks: BustLandmarksFile = { apex_r: [...(bust.apex_r as Point)], apex_l: [...(bust.apex_l as Point)] };
179
+ if (Object.hasOwn(bust, 'cleavage')) landmarks.cleavage = [...(bust.cleavage as Point)];
180
+ return {
181
+ index, slot: edit.slot as string, skin: edit.skin as string, attachment: edit.attachment as string,
182
+ hash: source.hash as string, frame, landmarks, shape, sha256: digest as string,
183
+ };
184
+ }
185
+
186
+ /** Read the act's envelope and rows: every problem pushed, the rows that read returned. */
187
+ function readAct(bytes: Buffer | string, path: string, problems: Problem[]): { actId: string; rows: ChestRow[] } | null {
188
+ if (typeof bytes === 'string') {
189
+ problems.push({ code: 'BUST_LANDMARKS_ACT', object: path, detail: `is not readable (${bytes}); a ${BUST_LANDMARKS_ACT_SCHEMA} JSON file is required` });
190
+ return null;
191
+ }
192
+ let raw: unknown;
193
+ try { raw = JSON.parse(bytes.toString('utf8')); }
194
+ catch (error) {
195
+ problems.push({ code: 'BUST_LANDMARKS_ACT', object: path, detail: `does not parse as JSON (${error instanceof Error ? error.message : String(error)}); a ${BUST_LANDMARKS_ACT_SCHEMA} JSON file is required` });
196
+ return null;
197
+ }
198
+ if (!isObject(raw)) {
199
+ problems.push({ code: 'BUST_LANDMARKS_ACT', object: path, detail: `is ${show(raw)}; a ${BUST_LANDMARKS_ACT_SCHEMA} act object is required` });
200
+ return null;
201
+ }
202
+ const before = problems.length;
203
+ if (raw.schema !== BUST_LANDMARKS_ACT_SCHEMA) problems.push({ code: 'BUST_LANDMARKS_ACT', object: `${path} schema`, detail: `is ${show(raw.schema)}; "${BUST_LANDMARKS_ACT_SCHEMA}" is required (the chest-landmarks act)` });
204
+ if (!isName(raw.actId)) problems.push({ code: 'BUST_LANDMARKS_ACT', object: `${path} actId`, detail: `is ${show(raw.actId)}; a non-empty act id is required` });
205
+ const value = raw.value;
206
+ const list = isObject(value) ? value.chestLandmarks : undefined;
207
+ if (!Array.isArray(list) || list.length === 0) {
208
+ problems.push({ code: 'BUST_LANDMARKS_ACT', object: `${path} value.chestLandmarks`, detail: `is ${Array.isArray(list) ? 'an empty list' : show(list)}; one chest-landmarks row is required` });
209
+ return null;
210
+ }
211
+ const rows = list.map((item, index) => readRow(item, index, problems)).filter((row): row is ChestRow => row !== null);
212
+ return problems.length > before ? null : { actId: raw.actId as string, rows };
213
+ }
214
+
215
+ /** One chest row: the landmarks file names no part, and `propose` drafts one chest carrier, so one row is required. */
216
+ function oneRow(rows: readonly ChestRow[], problems: Problem[]): ChestRow | null {
217
+ if (rows.length === 1) return rows[0];
218
+ const bySlot = new Map<string, number[]>();
219
+ for (const row of rows) bySlot.set(row.slot, [...(bySlot.get(row.slot) ?? []), row.index]);
220
+ for (const [slot, indices] of bySlot) {
221
+ if (indices.length > 1) {
222
+ problems.push({ code: 'BUST_LANDMARKS_PART_ROWS', object: `slot "${slot}"`, detail: `has ${indices.length} rows (value.chestLandmarks[${indices.join('], [')}]); one row per part is required` });
223
+ }
224
+ }
225
+ if (bySlot.size > 1) {
226
+ problems.push({ code: 'BUST_LANDMARKS_ROWS', object: 'value.chestLandmarks', detail: `names ${bySlot.size} parts (${[...bySlot.keys()].map(s => `"${s}"`).join(', ')}); one chest row is required, because propose drafts one chest carrier and the landmarks file names no part` });
227
+ }
228
+ return null;
229
+ }
230
+
231
+ /** Where one field of the shape the points are checked with came from (issue #1441). */
232
+ export type BustShapeSource = 'the config' | 'the pending record' | 'the default';
233
+ /** The shape the three points are checked with: each field's value and where it came from. */
234
+ export type EffectiveBustShape = { readonly [K in BustShapeKey]: { readonly value: unknown; readonly source: BustShapeSource } };
235
+
236
+ /**
237
+ * Issue #1441: the shape the points are checked with, the one the config write will hold. Each field is the pending
238
+ * record's where it names one, else the config's declared `contour.bust` field, else the default. The one rule, read
239
+ * by `propose --bust-landmarks` on both routes and by `bust-landmarks` before it writes the landmarks file.
240
+ */
241
+ export function effectiveBustShape(declared: Readonly<Record<string, unknown>> | undefined, pending: Readonly<Partial<Record<BustShapeKey, unknown>>> | undefined): EffectiveBustShape {
242
+ const pick = (key: BustShapeKey): { value: unknown; source: BustShapeSource } =>
243
+ pending !== undefined && Object.hasOwn(pending, key) && pending[key] !== undefined ? { value: pending[key], source: 'the pending record' }
244
+ : declared !== undefined && Object.hasOwn(declared, key) && declared[key] !== undefined ? { value: declared[key], source: 'the config' }
245
+ : { value: SHAPE_DEFAULTS[key], source: 'the default' };
246
+ return { alpha: pick('alpha'), clearance: pick('clearance'), bone_r: pick('bone_r'), bone_l: pick('bone_l'), spacing: pick('spacing') };
247
+ }
248
+
249
+ /** The two fields the clearance rule reads (`bustClearanceDetail`): the ones a refusal of the points names. */
250
+ export const BUST_POINT_SHAPE_FIELDS = ['alpha', 'clearance'] as const;
251
+
252
+ /** The clause a refusal of the points carries: the two fields the clearance rule reads, each with its source. */
253
+ export function bustShapeClause(shape: EffectiveBustShape): string {
254
+ return `the shape checked: alpha ${show(shape.alpha.value)} (${shape.alpha.source}), clearance ${show(shape.clearance.value)} (${shape.clearance.source})`;
255
+ }
256
+
257
+ /** The five shape fields after defaults, from a partial spec. */
258
+ const effective = (spec: Partial<Shape>): Shape => ({ ...SHAPE_DEFAULTS, ...spec });
259
+
260
+ /** One shape field `--write-config` writes into `contour.bust`: the act's value, or, with no value, the key removed. */
261
+ type ShapeField = { key: ShapeKey; value?: number | string };
262
+
263
+ /**
264
+ * Check the row against parts.json and the config: slot, frame and shape fields. Against a declared
265
+ * `contour.bust`, a shape field whose effective value differs is refused, or, with `writeConfig`, returned as a
266
+ * field to write: the act's value where the act spells it out, the key's removal where the act omits it. With no
267
+ * `contour.bust`, a field that differs from the default is returned as pending, for the sidecar.
268
+ */
269
+ /**
270
+ * Issue #1443: the act moves the points when apex_r or apex_l differs from the declared one in either coordinate, or
271
+ * when its cleavage differs from the declared one. An act with no cleavage moves the points too: propose derives one
272
+ * from a midline this command does not have, so it cannot be held equal, and the pending path loses nothing (propose
273
+ * writes the points and the shape in one staged write).
274
+ */
275
+ export function bustPointsMoved(act: { apex_r: readonly number[]; apex_l: readonly number[]; cleavage?: readonly number[] }, declared: { apex_r: readonly number[]; apex_l: readonly number[]; cleavage: readonly number[] }): boolean {
276
+ const same = (a: readonly number[], b: readonly number[]): boolean => a.length === b.length && a.every((v, i) => v === b[i]);
277
+ return !same(act.apex_r, declared.apex_r) || !same(act.apex_l, declared.apex_l) || act.cleavage === undefined || !same(act.cleavage, declared.cleavage);
278
+ }
279
+
280
+ function checkRow(row: ChestRow, parts: PartsFile | null, config: CharacterConfig | null, writeConfig: boolean, problems: Problem[]): { fields: ShapeField[]; pending: PendingBustShape['fields']; moved: boolean } {
281
+ const at = `value.chestLandmarks[${row.index}]`;
282
+ if (parts !== null) {
283
+ const [width, height] = parts.rig_size;
284
+ if (row.frame.width !== width || row.frame.height !== height) {
285
+ problems.push({ code: 'BUST_LANDMARKS_FRAME', object: `${at}.edit.source.frame`, detail: `is ${row.frame.width}x${row.frame.height}; parts.json's rig_size ${width}x${height} is required, the frame the points are rig px in` });
286
+ }
287
+ if (!parts.parts.some(p => p.name === row.slot)) {
288
+ problems.push({ code: 'BUST_LANDMARKS_SLOT', object: `${at}.edit.slot`, detail: `is "${row.slot}"; a part parts.json lists is required` });
289
+ }
290
+ }
291
+ if (row.attachment !== row.slot) {
292
+ problems.push({ code: 'BUST_LANDMARKS_SLOT', object: `${at}.edit.attachment`, detail: `is "${row.attachment}"; "${row.slot}" is required: a contour part's slot and attachment are both its part name` });
293
+ }
294
+ if (row.skin !== 'default') {
295
+ problems.push({ code: 'BUST_LANDMARKS_SLOT', object: `${at}.edit.skin`, detail: `is "${row.skin}"; "default" is required: this package writes every mesh into the default skin` });
296
+ }
297
+ if (config === null) return { fields: [], pending: {}, moved: false };
298
+ const mesh = Object.hasOwn(config.meshes, row.slot) ? config.meshes[row.slot] : undefined;
299
+ if (mesh === undefined || !('contour' in mesh)) {
300
+ const found = mesh === undefined ? 'no mesh in config.meshes' : `a ${['grid', 'auto', 'influence', 'explicit'].find(m => m in mesh) ?? 'non-contour'} mesh`;
301
+ problems.push({ code: 'BUST_LANDMARKS_SLOT', object: `${at}.edit.slot`, detail: `"${row.slot}" has ${found}; a part whose config.meshes entry is a contour mesh is required (the chest carrier propose drafts)` });
302
+ return { fields: [], pending: {}, moved: false };
303
+ }
304
+ // No contour.bust yet (a first draft made with --no-bust) reads as the defaults: propose drafts contour.bust from the
305
+ // three points alone, so the defaults are the values the redraft builds with.
306
+ const declared = mesh.contour.bust;
307
+ const configShape = effective(declared === undefined ? {} : {
308
+ ...(declared.alpha === undefined ? {} : { alpha: declared.alpha }),
309
+ ...(declared.clearance === undefined ? {} : { clearance: declared.clearance }),
310
+ ...(declared.spacing === undefined ? {} : { spacing: declared.spacing }),
311
+ ...(declared.bone_r === undefined ? {} : { bone_r: declared.bone_r }),
312
+ ...(declared.bone_l === undefined ? {} : { bone_l: declared.bone_l }),
313
+ });
314
+ const actShape = effective(row.shape);
315
+ // Issue #1443: with the points moved, the shape is not written against the config's old points: it waits in the
316
+ // sidecar like a first draft's, and propose writes it with the new points.
317
+ const moved = declared !== undefined && bustPointsMoved(row.landmarks, declared);
318
+ const fields: ShapeField[] = [];
319
+ const pending: PendingBustShape['fields'] = {};
320
+ for (const key of SHAPE_KEYS) {
321
+ if (actShape[key] === configShape[key]) continue;
322
+ const spelled = row.shape[key];
323
+ // No contour.bust yet: the field differs from the default, so the act spells it. It is left pending in the
324
+ // sidecar for propose --write-config to write with the three points (shape fields alone make no contour.bust).
325
+ // Points moved (issue #1443): the same, and a field the act leaves out where the config declares another value
326
+ // is pending as the default's value, since the record holds values and the act's shape is the default there.
327
+ if (declared === undefined || moved) {
328
+ pending[key] = spelled ?? SHAPE_DEFAULTS[key];
329
+ continue;
330
+ }
331
+ if (writeConfig) {
332
+ fields.push(spelled === undefined ? { key } : { key, value: spelled });
333
+ continue;
334
+ }
335
+ const from = declared[key] === undefined ? 'the default' : 'the config';
336
+ problems.push({
337
+ code: 'BUST_LANDMARKS_SHAPE', object: `${at}.edit.bust.${key}`,
338
+ detail: `is ${show(actShape[key])}${spelled === undefined ? ' (absent, the default)' : ''}; meshes.${row.slot}.contour.bust.${key} ${show(configShape[key])}, ${from}, is required: the landmarks file carries no such field; run again with --write-config to take the act's value into the config; propose --write-config keeps the config's shape fields on the redraft (#1428)`,
339
+ });
340
+ }
341
+ // Issue #1441: the points against the shape propose will check them with, so this command refuses what propose
342
+ // refuses. The config after this command: the act's fields with --write-config, else the declared ones. A cleavage
343
+ // the act leaves out is derived by propose from a midline this command does not have, so it is checked there.
344
+ const after = declared === undefined ? undefined : writeConfig && !moved ? { ...row.shape } : { ...declared };
345
+ const shape = effectiveBustShape(after, pending);
346
+ const { apex_r, apex_l, cleavage } = row.landmarks;
347
+ if (cleavage !== undefined && typeof shape.alpha.value === 'number' && typeof shape.clearance.value === 'number') {
348
+ const detail = bustClearanceDetail({ apex_r, apex_l, cleavage }, shape.alpha.value, shape.clearance.value);
349
+ if (detail !== null) problems.push({ code: 'CONFIG_BUST_CLEARANCE', object: `${at}.edit.bust`, detail: `${detail}; ${bustShapeClause(shape)}` });
350
+ }
351
+ return { fields, pending, moved };
352
+ }
353
+
354
+ /** A path's device and inode, or null when nothing is there. */
355
+ function identity(path: string): { dev: number; ino: number; file: boolean; directory: boolean } | null {
356
+ try {
357
+ const stat = statSync(path);
358
+ return { dev: stat.dev, ino: stat.ino, file: stat.isFile(), directory: stat.isDirectory() };
359
+ } catch (error) {
360
+ if (errorCode(error) === 'ENOENT') return null;
361
+ throw error;
362
+ }
363
+ }
364
+
365
+ /**
366
+ * Refuse an output that lands in the parts directory, over an input (by path, or as a hard link to it: same device
367
+ * and inode, compared where the output exists, as the staged config writer compares its target), over a directory,
368
+ * or over an existing file that is not writable.
369
+ */
370
+ function checkOut(out: string, inputs: { act: string; config: string; parts: string }, problems: Problem[]): void {
371
+ // Symlinks resolved where the path exists; a new file is its existing directory's real path plus its name.
372
+ const real = (p: string): string => {
373
+ if (existsSync(p)) return realpathSync(p);
374
+ return existsSync(dirname(p)) ? join(realpathSync(dirname(p)), basename(p)) : p;
375
+ };
376
+ const partsDir = real(inputs.parts);
377
+ const sources = [['--from-act', inputs.act], ['--config', inputs.config], ['--parts', join(inputs.parts, 'parts.json')]] as const;
378
+ for (const [flag, path] of [['--out', out], [`--out's provenance record`, out + BUST_LANDMARKS_PROVENANCE_SUFFIX]] as const) {
379
+ const refuse = (detail: string): void => { problems.push({ code: 'BUST_LANDMARKS_OUT', object: flag, detail: `is ${path}, ${detail}` }); };
380
+ const target = real(path);
381
+ if (target === partsDir || target.startsWith(partsDir + sep)) refuse(`inside --parts ${inputs.parts}; a path outside the parts directory is required`);
382
+ let found: ReturnType<typeof identity>;
383
+ try { found = identity(path); }
384
+ catch (error) {
385
+ refuse(`which cannot be read (${errorCode(error)}); a path that is no input is required`);
386
+ continue;
387
+ }
388
+ for (const [name, input] of sources) {
389
+ if (target === real(input)) {
390
+ if (name !== '--parts') refuse(`the ${name} input; a path that is no input is required`);
391
+ continue;
392
+ }
393
+ let source: ReturnType<typeof identity> = null;
394
+ try { source = identity(input); } catch { source = null; }
395
+ if (found !== null && source !== null && found.dev === source.dev && found.ino === source.ino) {
396
+ refuse(`a hard link to the ${name} input ${input} (the same device and inode); a path that is no input is required`);
397
+ }
398
+ }
399
+ if (found === null) continue;
400
+ if (!found.file) refuse(`an existing ${found.directory ? 'directory' : 'non-file'}; a file path is required`);
401
+ else {
402
+ try { accessSync(path, constants.W_OK); }
403
+ catch (error) { refuse(`an existing file that is not writable (${errorCode(error)}); a writable path is required, and the earlier file is kept`); }
404
+ }
405
+ }
406
+ }
407
+
408
+ /** Collect a reader's refusal into `problems` instead of throwing it. */
409
+ function collect<T>(read: () => T, problems: Problem[]): T | null {
410
+ try { return read(); }
411
+ catch (error) {
412
+ if (error instanceof PartsError) {
413
+ problems.push(...error.problems);
414
+ return null;
415
+ }
416
+ throw error;
417
+ }
418
+ }
419
+
420
+ /** The landmarks file's bytes: the keys `propose --bust-landmarks` reads, in its order. */
421
+ export function bustLandmarksText(landmarks: BustLandmarksFile): string {
422
+ const out: BustLandmarksFile = { apex_r: landmarks.apex_r, apex_l: landmarks.apex_l };
423
+ if (landmarks.cleavage !== undefined) out.cleavage = landmarks.cleavage;
424
+ return JSON.stringify(out, null, 2) + '\n';
425
+ }
426
+
427
+ /** What a checked act writes: the two files' bytes, and the config patch `--write-config` stages. */
428
+ export interface BustLandmarksPlan {
429
+ landmarks: BustLandmarksFile;
430
+ provenance: BustLandmarksProvenance;
431
+ out: string;
432
+ provenancePath: string;
433
+ /** The landmarks file's bytes, then the provenance record's. */
434
+ texts: readonly [string, string];
435
+ /** With `writeConfig`: the act's shape fields that differ from the config's `contour.bust`; null when none differs. */
436
+ configPatch: ConfigWritePatch | null;
437
+ /** Issue #1443: the config declares `contour.bust` and the act moves its points ({@link bustPointsMoved}), so a
438
+ * differing shape is pending in the record and the config is not written. */
439
+ moved: boolean;
440
+ }
441
+
442
+ /**
443
+ * Read the act, `parts.json` and the config and check the one chest row against them. Every problem, `prior`
444
+ * included, is collected and thrown once; nothing is written here.
445
+ */
446
+ export function planBustLandmarks(input: { act: string; parts: string; config: string; out: string; writeConfig?: boolean }, prior: readonly Problem[] = []): BustLandmarksPlan {
447
+ const problems: Problem[] = [...prior];
448
+ const actPath = resolve(input.act), partsDir = resolve(input.parts), configPath = resolve(input.config), out = resolve(input.out);
449
+ checkOut(out, { act: actPath, config: configPath, parts: partsDir }, problems);
450
+ let actBytes: Buffer | string;
451
+ try { actBytes = readFileSync(actPath); } catch (error) { actBytes = errorCode(error); }
452
+ const act = readAct(actBytes, input.act, problems);
453
+ const parts = collect(() => readParts(join(partsDir, 'parts.json')), problems);
454
+ const config = collect(() => loadConfig(configPath), problems);
455
+ const row = act === null ? null : oneRow(act.rows, problems);
456
+ const { fields, pending, moved } = row === null ? { fields: [], pending: {}, moved: false } : checkRow(row, parts, config, input.writeConfig === true, problems);
457
+ if (problems.length > 0 || act === null || row === null || typeof actBytes === 'string') throw new PartsError(problems);
458
+ const text = bustLandmarksText(row.landmarks);
459
+ const provenance: BustLandmarksProvenance = {
460
+ spec: BUST_LANDMARKS_PROVENANCE_SPEC,
461
+ act: { schema: BUST_LANDMARKS_ACT_SCHEMA, act_id: act.actId, file_sha256: sha256(actBytes) },
462
+ row_sha256: row.sha256,
463
+ slot: row.slot,
464
+ source: { hash: row.hash, frame: { width: row.frame.width, height: row.frame.height } },
465
+ landmarks_sha256: sha256(text),
466
+ ...(Object.keys(pending).length === 0 ? {} : { shape: { status: 'pending' as const, fields: pending } }),
467
+ };
468
+ return {
469
+ landmarks: row.landmarks, provenance, out, provenancePath: out + BUST_LANDMARKS_PROVENANCE_SUFFIX,
470
+ texts: [text, JSON.stringify(provenance, null, 2) + '\n'],
471
+ configPatch: fields.length === 0 ? null : { kind: 'bust-shape', part: row.slot, fields },
472
+ moved,
473
+ };
474
+ }
475
+
476
+ /** Narrow file operations, supplied only by failure controls; the command uses the real ones. */
477
+ export interface BustLandmarksFiles { replace?: (from: string, to: string) => void }
478
+
479
+ /** Both outputs staged beside their destinations: `commit` renames them in, `cancel` removes them, `undo` puts back what a commit replaced. */
480
+ export interface StagedBustLandmarks { commit(): void; cancel(): void; undo(): void }
481
+
482
+ /**
483
+ * Write both outputs to temporary siblings (`.<name>.rig-parts.tmp`, created exclusively, so a leftover is refused
484
+ * by name rather than overwritten). A destination that exists is written through its symlinks, and its bytes and
485
+ * mode are kept for `undo`. A failure at any step removes the temporaries and puts back every file it replaced.
486
+ */
487
+ export function stageBustLandmarks(plan: BustLandmarksPlan, files: BustLandmarksFiles = {}): StagedBustLandmarks {
488
+ return stageReplacements([[plan.out, plan.texts[0]], [plan.provenancePath, plan.texts[1]]], files);
489
+ }
490
+
491
+ /** {@link stageBustLandmarks} over any files: also the sidecar `propose` marks applied beside its staged config write. */
492
+ export function stageReplacements(writes: ReadonlyArray<readonly [string, string]>, files: BustLandmarksFiles = {}): StagedBustLandmarks {
493
+ const failure = (path: string, action: string, error: unknown): Problem => (
494
+ error instanceof PartsError ? error.problems[0] : { code: 'BUST_LANDMARKS_OUT', object: path, detail: `${action} (${errorCode(error)}); a writable path in an existing directory is required, and the earlier files are kept` });
495
+ // The planner refuses a directory or an unreadable destination by name; one that became so since is refused here, never thrown raw.
496
+ const slots = writes.map(([path, text]) => {
497
+ try {
498
+ const dest = existsSync(path) ? realpathSync(path) : path;
499
+ let previous: { bytes: Buffer; mode: number } | null = null;
500
+ if (existsSync(dest)) {
501
+ const stat = lstatSync(dest);
502
+ if (!stat.isFile()) throw new PartsError([{ code: 'BUST_LANDMARKS_OUT', object: path, detail: `is an existing ${stat.isDirectory() ? 'directory' : 'non-file'}; a file path is required, and nothing was written` }]);
503
+ previous = { bytes: readFileSync(dest), mode: stat.mode & 0o777 };
504
+ }
505
+ return { dest, text, temp: join(dirname(dest), `.${basename(dest)}.rig-parts.tmp`), previous, owned: false, placed: false };
506
+ } catch (error) { throw new PartsError([failure(path, 'could not be read before it is replaced', error)]); }
507
+ });
508
+ const cancel = (): void => {
509
+ const problems: Problem[] = [];
510
+ for (const slot of slots) {
511
+ if (!slot.owned) continue;
512
+ try { rmSync(slot.temp, { force: true }); slot.owned = false; }
513
+ catch (error) { problems.push(failure(slot.temp, 'the temporary could not be removed; remove it by hand', error)); }
514
+ }
515
+ if (problems.length > 0) throw new PartsError(problems);
516
+ };
517
+ const undo = (): void => {
518
+ const problems: Problem[] = [];
519
+ for (const slot of [...slots].reverse()) {
520
+ if (!slot.placed) continue;
521
+ try {
522
+ if (slot.previous === null) rmSync(slot.dest, { force: true });
523
+ else writeFileSync(slot.dest, slot.previous.bytes, { mode: slot.previous.mode });
524
+ slot.placed = false;
525
+ } catch (error) { problems.push(failure(slot.dest, 'the earlier file could not be put back', error)); }
526
+ }
527
+ if (problems.length > 0) throw new PartsError(problems);
528
+ };
529
+ /** Clean up after `error` at `path`, and throw it with every cleanup failure beside it. */
530
+ const fail = (path: string, action: string, error: unknown): never => {
531
+ const problems = [failure(path, action, error)];
532
+ for (const step of [undo, cancel]) {
533
+ try { step(); } catch (cleanup) { if (cleanup instanceof PartsError) problems.push(...cleanup.problems); else throw cleanup; }
534
+ }
535
+ throw new PartsError(problems);
536
+ };
537
+ for (const slot of slots) {
538
+ try {
539
+ writeFileSync(slot.temp, slot.text, { flag: 'wx', mode: slot.previous?.mode ?? 0o666 });
540
+ slot.owned = true;
541
+ } catch (error) {
542
+ // An exclusive create that failed made no file of ours; one that failed mid-write did.
543
+ if (errorCode(error) !== 'EEXIST' && existsSync(slot.temp)) slot.owned = true;
544
+ fail(slot.temp, `could not be staged${errorCode(error) === 'EEXIST' ? ': a leftover temporary is there; remove it' : ''}`, error);
545
+ }
546
+ }
547
+ return {
548
+ cancel,
549
+ undo,
550
+ commit(): void {
551
+ for (const slot of slots) {
552
+ try {
553
+ (files.replace ?? renameSync)(slot.temp, slot.dest);
554
+ slot.owned = false;
555
+ slot.placed = true;
556
+ } catch (error) { fail(slot.dest, 'could not be replaced', error); }
557
+ }
558
+ },
559
+ };
560
+ }
561
+
562
+ /**
563
+ * Plan, stage and commit without a config write: the outputs are written only when every check has passed, both
564
+ * or neither.
565
+ */
566
+ export function bustLandmarksFromAct(input: { act: string; parts: string; config: string; out: string }, files: BustLandmarksFiles = {}): BustLandmarksPlan {
567
+ const plan = planBustLandmarks(input);
568
+ stageBustLandmarks(plan, files).commit();
569
+ return plan;
570
+ }
571
+
572
+ /** The record beside a landmarks file `propose --bust-landmarks` reads, checked; `pending` is its shape still to write. */
573
+ export interface BustSidecar {
574
+ path: string;
575
+ provenance: BustLandmarksProvenance;
576
+ /** The reviewed shape still to write onto the chest carrier, or null (none recorded, or already applied). */
577
+ pending: PendingBustShape | null;
578
+ /** The record's bytes with its shape marked applied, written beside the config write that applies it. */
579
+ appliedText: string | null;
580
+ }
581
+
582
+ /**
583
+ * Issue #1382: read `<landmarks>.provenance.json` beside a landmarks file, if there is one. None there is null, and
584
+ * `propose` reads the landmarks file as before. One there must be a well-formed record of this spec whose
585
+ * `landmarks_sha256` is the landmarks file's own digest; anything else is refused by name, every problem at once.
586
+ */
587
+ export function readBustSidecar(landmarksPath: string, landmarksBytes: Uint8Array): BustSidecar | null {
588
+ const path = landmarksPath + BUST_LANDMARKS_PROVENANCE_SUFFIX;
589
+ try { lstatSync(path); }
590
+ catch (error) {
591
+ if (errorCode(error) === 'ENOENT') return null;
592
+ throw new PartsError([{ code: 'PROPOSE_BUST_SIDECAR', object: path, detail: `cannot be read (${errorCode(error)}); the provenance record bust-landmarks wrote, or no file at this path, is required` }]);
593
+ }
594
+ const problems: Problem[] = [];
595
+ const fail = (object: string, detail: string): void => { problems.push({ code: 'PROPOSE_BUST_SIDECAR', object, detail }); };
596
+ let raw: unknown;
597
+ try { raw = JSON.parse(readFileSync(path, 'utf8')); }
598
+ catch (error) {
599
+ const why = error instanceof SyntaxError ? `does not parse as JSON (${error.message})` : `cannot be read (${errorCode(error)})`;
600
+ throw new PartsError([{ code: 'PROPOSE_BUST_SIDECAR', object: path, detail: `${why}; the provenance record bust-landmarks wrote is required` }]);
601
+ }
602
+ if (!isObject(raw)) throw new PartsError([{ code: 'PROPOSE_BUST_SIDECAR', object: path, detail: `is ${show(raw)}; a ${BUST_LANDMARKS_PROVENANCE_SPEC} object is required` }]);
603
+ const keys = ['spec', 'act', 'row_sha256', 'slot', 'source', 'landmarks_sha256', 'shape'];
604
+ for (const key of Object.keys(raw)) if (!keys.includes(key)) fail(`${path} ${key}`, `is unknown; ${BUST_LANDMARKS_PROVENANCE_SPEC} takes ${keys.join(', ')}`);
605
+ if (raw.spec !== BUST_LANDMARKS_PROVENANCE_SPEC) fail(`${path} spec`, `is ${show(raw.spec)}; "${BUST_LANDMARKS_PROVENANCE_SPEC}" is required`);
606
+ const hex = (v: unknown): v is string => typeof v === 'string' && SHA256_PATTERN.test(v);
607
+ const act = raw.act;
608
+ if (!isObject(act) || act.schema !== BUST_LANDMARKS_ACT_SCHEMA || !isName(act.act_id) || !hex(act.file_sha256)) {
609
+ fail(`${path} act`, `is ${show(act)}; {schema: "${BUST_LANDMARKS_ACT_SCHEMA}", act_id, file_sha256} is required`);
610
+ }
611
+ if (!hex(raw.row_sha256)) fail(`${path} row_sha256`, `is ${show(raw.row_sha256)}; 64 lowercase hex digits are required`);
612
+ if (!isName(raw.slot)) fail(`${path} slot`, `is ${show(raw.slot)}; the chest carrier's part name is required`);
613
+ const source = raw.source;
614
+ const frame = isObject(source) ? source.frame : undefined;
615
+ if (!isObject(source) || !hex(source.hash) || !isObject(frame) || typeof frame.width !== 'number' || typeof frame.height !== 'number') {
616
+ fail(`${path} source`, `is ${show(source)}; {hash, frame: {width, height}} is required`);
617
+ }
618
+ if (!hex(raw.landmarks_sha256)) fail(`${path} landmarks_sha256`, `is ${show(raw.landmarks_sha256)}; 64 lowercase hex digits are required`);
619
+ let shape: BustLandmarksProvenance['shape'];
620
+ if (Object.hasOwn(raw, 'shape')) {
621
+ const s = raw.shape;
622
+ const fields = isObject(s) ? s.fields : undefined;
623
+ if (!isObject(s) || (s.status !== 'pending' && s.status !== 'applied') || !isObject(fields) || Object.keys(fields).length === 0) {
624
+ fail(`${path} shape`, `is ${show(s)}; {status: "pending" or "applied", fields: one or more of ${SHAPE_KEYS.join(', ')}} is required`);
625
+ } else {
626
+ const read: PendingBustShape['fields'] = {};
627
+ for (const key of Object.keys(fields)) if (!(SHAPE_KEYS as readonly string[]).includes(key)) fail(`${path} shape.fields.${key}`, `is unknown; contour.bust's shape fields are ${SHAPE_KEYS.join(', ')}`);
628
+ for (const key of SHAPE_KEYS) {
629
+ if (!Object.hasOwn(fields, key)) continue;
630
+ const v = fields[key];
631
+ const ok = key === 'bone_r' || key === 'bone_l' ? isName(v) : typeof v === 'number' && Number.isFinite(v);
632
+ if (!ok) fail(`${path} shape.fields.${key}`, `is ${show(v)}; ${key === 'bone_r' || key === 'bone_l' ? 'a non-empty bone name' : 'a finite number'} is required`);
633
+ else read[key] = v as number | string;
634
+ }
635
+ shape = { status: s.status, fields: read };
636
+ }
637
+ }
638
+ if (problems.length > 0) throw new PartsError(problems);
639
+ const computed = sha256(landmarksBytes);
640
+ if (raw.landmarks_sha256 !== computed) {
641
+ throw new PartsError([{ code: 'PROPOSE_BUST_SIDECAR_DIGEST', object: `${path} landmarks_sha256`, detail: `is "${raw.landmarks_sha256 as string}"; "${computed}" is required, the sha256 of ${landmarksPath}'s bytes: the landmarks file is not the one this record was written with` }]);
642
+ }
643
+ const a = act as Record<string, unknown>, src = source as Record<string, unknown>, f = frame as Record<string, unknown>;
644
+ const provenance: BustLandmarksProvenance = {
645
+ spec: BUST_LANDMARKS_PROVENANCE_SPEC,
646
+ act: { schema: BUST_LANDMARKS_ACT_SCHEMA, act_id: a.act_id as string, file_sha256: a.file_sha256 as string },
647
+ row_sha256: raw.row_sha256 as string,
648
+ slot: raw.slot as string,
649
+ source: { hash: src.hash as string, frame: { width: f.width as number, height: f.height as number } },
650
+ landmarks_sha256: computed,
651
+ ...(shape === undefined ? {} : { shape }),
652
+ };
653
+ const pending = shape?.status === 'pending' ? { part: provenance.slot, fields: shape.fields } : null;
654
+ const appliedText = pending === null ? null : JSON.stringify({ ...provenance, shape: { status: 'applied', fields: pending.fields } }, null, 2) + '\n';
655
+ return { path, provenance, pending, appliedText };
656
+ }