@rig-c/parts 2.40.0 → 2.42.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.
package/src/retune.ts CHANGED
@@ -38,7 +38,7 @@
38
38
  import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
39
39
  import { dirname, join, resolve, sep } from 'node:path';
40
40
  import { checkStage, gateThroughRigc, type Log, rigStage } from './build.ts';
41
- import { type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackShape, type PageEdges, rigcRanClause, type RigcRunner } from './check.ts';
41
+ import { type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackMode, type PackShape, type PageEdges, parsePageSize, rigcRanClause, type RigcRunner } from './check.ts';
42
42
  import { PartsError, type Problem, problemLine, refuseIfAny } from './errors.ts';
43
43
  import { type CheckSide, carryProvenance, type ParentProvenance, checkHeldProblems, checkSide, checkScope, type FileTree, firstDifference, type HashRow, hashRows, INPUT_CHECK_FILE, type InputCheckBinding, inputCheckHashes, inputCheckMovedProblems, inputCheckOf, inputCheckReusedLine, inputCheckText, inputTreeProblems, perturbed, pngsOf, readTree, sha256, textsOf } from './remesh.ts';
44
44
  import { DEFAULT_IDLE_KEYS, type IdleKeys, rigJsonText } from './rig.ts';
@@ -71,6 +71,7 @@ export interface RetuneInput {
71
71
  idleKeys?: IdleKeys;
72
72
  pageEdges?: PageEdges;
73
73
  packShape?: PackShape;
74
+ pageSize?: number;
74
75
  requirements?: string;
75
76
  /** Issue #617: a recorded input check (`input-check.json`, as `remesh` writes it) reused when it is bound to this run's input. */
76
77
  inputCheck?: string;
@@ -343,6 +344,8 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
343
344
  const idleKeys = input.idleKeys ?? DEFAULT_IDLE_KEYS;
344
345
  const pageEdges = input.pageEdges ?? DEFAULT_PAGE_EDGES;
345
346
  const packShape = input.packShape ?? DEFAULT_PACK_SHAPE;
347
+ const pageSize = parsePageSize(input.pageSize);
348
+ const mode: PackMode = { pageEdges, packShape, ...(pageSize === undefined ? {} : { pageSize }) };
346
349
  // 1. The input and the out.
347
350
  const outAt = resolve(input.out);
348
351
  const rigAt = resolve(input.rig);
@@ -351,13 +354,13 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
351
354
  if (outAt.startsWith(`${rigAt}${sep}`)) throw new PartsError([{ code: 'RETUNE_OUT_FRESH', object: input.out, detail: `is inside the input ${input.rig}; a revision is written beside the input, never into it` }]);
352
355
  const tree = readTree(rigAt);
353
356
  refuseIfAny(inputTreeProblems(tree, input.rig, 'retune', RETUNE_SPLICED));
354
- const recorded = inputCheckOf(input, rigAt, tree, pageEdges, packShape, versions.parts, rigc, 'retune');
357
+ const recorded = inputCheckOf(input, rigAt, tree, pageEdges, packShape, versions.parts, rigc, 'retune', pageSize);
355
358
  const inFiles = rigFiles(tree);
356
359
  // 2. The rebuild.
357
360
  log(`rig-parts retune: ${input.rig}, ${tree.size} file(s); the rebuild is the config as written`);
358
361
  const rebuiltAt = join(scratch, 'rebuild', 'rig');
359
362
  try {
360
- rigStage({ config: input.config, parts: input.parts, out: rebuiltAt, idleKeys, pageEdges, packShape }, rigc, join(scratch, 'rebuild', 'gate'), (l) => log(`[rebuild:rig] ${l}`));
363
+ rigStage({ config: input.config, parts: input.parts, out: rebuiltAt, idleKeys, pageEdges, packShape, ...(pageSize === undefined ? {} : { pageSize }) }, rigc, join(scratch, 'rebuild', 'gate'), (l) => log(`[rebuild:rig] ${l}`));
361
364
  } catch (err) {
362
365
  if (!(err instanceof PartsError)) throw err;
363
366
  throw new PartsError(err.problems.map((p) => ({ code: 'RETUNE_CONFIG_REFUSED', object: `${input.config} as written`, detail: `the rig stage refuses it, nothing is written: ${problemLine(p)}` })));
@@ -379,7 +382,7 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
379
382
  log(` idle: ${changed.idle.tracks_changed} track(s) changed, duration ${changed.idle.duration[0]} -> ${changed.idle.duration[1]}`);
380
383
  log(` preserved: ${identical.filter((p) => p !== RETUNE_FILE && !(input.recordInputCheck === true && p === INPUT_CHECK_FILE)).length} file(s) byte-identical to the input; rig.json identical outside constraints and invariants.detached; motion.json identical outside animations.idle`);
381
384
  // 6. The gate and check.
382
- const gate = gateThroughRigc(pngsOf(revision), textsOf(revision, plant.unfilteredGateTexts === true), rigc, join(scratch, 'gate'), { pageEdges, packShape });
385
+ const gate = gateThroughRigc(pngsOf(revision), textsOf(revision, plant.unfilteredGateTexts === true), rigc, join(scratch, 'gate'), mode);
383
386
  for (const g of gate) {
384
387
  log(` rigc ${g.label}, the revision: exit ${g.status}`);
385
388
  for (const l of g.lines) log(` ${l.trim()}`);
@@ -391,7 +394,7 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
391
394
  writeFileSync(join(staged, k), b);
392
395
  }
393
396
  const checkOf = (rig: string, name: string): CheckReport =>
394
- checkStage({ rig, parts: input.parts, out: join(scratch, name), pageEdges, packShape, ...(input.requirements === undefined ? {} : { requirements: input.requirements }) }, rigc, checkBin, (l) => log(`[${name}] ${l}`));
397
+ checkStage({ rig, parts: input.parts, out: join(scratch, name), pageEdges, packShape, ...(pageSize === undefined ? {} : { pageSize }), ...(input.requirements === undefined ? {} : { requirements: input.requirements }) }, rigc, checkBin, (l) => log(`[${name}] ${l}`));
395
398
  if (recorded.reused !== null) log(inputCheckReusedLine(input.inputCheck as string, recorded.binding as InputCheckBinding));
396
399
  let inSide: CheckSide;
397
400
  if (recorded.reused !== null) inSide = recorded.reused;
package/src/rig.ts CHANGED
@@ -177,7 +177,7 @@ import { skeletonLimbJoints } from './limbs.ts';
177
177
  import { coalesceLimbSlots } from './limbslots.ts';
178
178
  import { layoutAlias, placeLimbLayouts, type LayoutPlan } from './limblayout.ts';
179
179
  import { artCoverage, ART_ALPHA, latticeCells, latticeMesh, latticeStray, ONE_LOOP_PASSES, type LatticeMesh } from './mesh.ts';
180
- import { bindFaceSurfaceDeform, BLINK, blinkHoldMisses, blinkSpan, CONTROL_SUFFIX, controlledBones, IDLE_FPS, idleMotion, type MotionSpec, moveKeysToControls } from './motion.ts';
180
+ import { bindFaceSurfaceDeform, BLINK, blinkHoldMisses, blinkSpan, blinkTimes, CONTROL_SUFFIX, controlledBones, IDLE_FPS, idleMotion, type MotionSpec, moveKeysToControls } from './motion.ts';
181
181
  import { type PartRecord, type AlternateSetMap, FRONT_SUFFIX, PAINTING_RUN, type PartsFile, readFrom, tagOf } from './parts.ts';
182
182
  import { waistPairs, waistBand, waistInfluences } from './waist.ts';
183
183
  import { preserveWaistRest, refineWaistMesh, remapWaistDeforms, storedWorld, waistBottomMesh, waistBottomLayoutOf, type WaistMapping } from './waistmesh.ts';
@@ -1602,27 +1602,38 @@ export function buildWaistPairSource(
1602
1602
  // ---- motion ------------------------------------------------------------
1603
1603
  const bl = cfg.motion.blink;
1604
1604
  const span = bl === undefined ? 0 : blinkSpan(bl);
1605
- if (bl !== undefined && !(bl.t > 0 && bl.t + span < cfg.motion.duration)) {
1606
- fail(
1607
- 'RIG_BLINK_INSIDE_IDLE',
1608
- 'config.motion.blink.t',
1609
- `is ${bl.t} s; the blink's keys run from t to t + ${pyRound(span, 6)} s between the idle's first key at 0 and its last at ${cfg.motion.duration} s, so 0 < t < ${pyRound(cfg.motion.duration - span, 6)} is required`,
1610
- );
1605
+ if (bl !== undefined) {
1606
+ const times = blinkTimes(bl);
1607
+ times.forEach((time, i) => {
1608
+ const at = i === 0 ? 'config.motion.blink.t' : `config.motion.blink.more[${i - 1}]`;
1609
+ if (!(time > 0 && Math.max(time + span, pyRound(time + span, 6)) < cfg.motion.duration)) {
1610
+ fail('RIG_BLINK_INSIDE_IDLE', at,
1611
+ `is ${time} s; the blink's keys run from t to t + ${pyRound(span, 6)} s between the idle's first key at 0 and its last at ${cfg.motion.duration} s, so 0 < t < ${pyRound(cfg.motion.duration - span, 6)} is required`);
1612
+ }
1613
+ if (i > 0 && time <= Math.max(times[i - 1] + span, pyRound(times[i - 1] + span, 6))) {
1614
+ fail('RIG_BLINK_WINDOWS_DISJOINT', at,
1615
+ `starts at ${time} s; the preceding blink ends at ${pyRound(times[i - 1] + span, 6)} s, so a later start is required to keep the blink windows disjoint`);
1616
+ }
1617
+ problems.push(...blinkHoldProblems(BLINK.shut, BLINK.hold, IDLE_FPS).map(p => bl.more === undefined ? p : { ...p, object: `${at}: ${p.object}` }));
1618
+ });
1611
1619
  }
1612
- if (bl !== undefined) problems.push(...blinkHoldProblems(BLINK.shut, BLINK.hold, IDLE_FPS));
1613
1620
  // ---- blink.still: a blinking region cut at a row ----------------------
1614
1621
  const stills = bl?.still ?? {};
1615
1622
  const partNames = new Map(parts.parts.map((p) => [foldName(p.name), p.name]));
1623
+ const stillFail = (code: string, object: string, detail: string): void => {
1624
+ if (bl?.more === undefined) { fail(code, object, detail); return; }
1625
+ blinkTimes(bl).forEach((_, i) => fail(code, `${object} (${i === 0 ? 'config.motion.blink.t' : `config.motion.blink.more[${i - 1}]`})`, detail));
1626
+ };
1616
1627
  for (const [part, st] of Object.entries(stills)) {
1617
1628
  const at = `config.motion.blink.still.${part}`;
1618
1629
  const p = byPart.get(part);
1619
- if (!(part in cfg.regions)) fail('RIG_NAME_RESOLVES', at, `names "${part}", which config.regions does not attach; a region part is required`);
1620
- if (!B.has(st.bone)) fail('RIG_NAME_RESOLVES', `${at}.bone`, `names the bone "${st.bone}", which config.bones does not declare`);
1630
+ if (!(part in cfg.regions)) stillFail('RIG_NAME_RESOLVES', at, `names "${part}", which config.regions does not attach; a region part is required`);
1631
+ if (!B.has(st.bone)) stillFail('RIG_NAME_RESOLVES', `${at}.bone`, `names the bone "${st.bone}", which config.bones does not declare`);
1621
1632
  if (p === undefined) continue;
1622
1633
  const still = `${part}${STILL_SUFFIX}`;
1623
- if (partNames.has(foldName(still))) fail('RIG_STILL_NAME_FREE', at, `the still piece is drawn by the slot "${still}" ("${still}.png"), and parts.json already holds part "${partNames.get(foldName(still))}" ("${partNames.get(foldName(still))}.png"); rename that part`);
1634
+ if (partNames.has(foldName(still))) stillFail('RIG_STILL_NAME_FREE', at, `the still piece is drawn by the slot "${still}" ("${still}.png"), and parts.json already holds part "${partNames.get(foldName(still))}" ("${partNames.get(foldName(still))}.png"); rename that part`);
1624
1635
  if (!(st.row > p.y && st.row < p.y + p.h)) {
1625
- fail('RIG_STILL_ROW_INSIDE_PART', `${at}.row`, `is ${st.row}; "${part}" spans rows ${p.y}..${p.y + p.h - 1}, so a row with part rows on both sides, ${p.y + 1}..${p.y + p.h - 1}, is required`);
1636
+ stillFail('RIG_STILL_ROW_INSIDE_PART', `${at}.row`, `is ${st.row}; "${part}" spans rows ${p.y}..${p.y + p.h - 1}, so a row with part rows on both sides, ${p.y + 1}..${p.y + p.h - 1}, is required`);
1626
1637
  continue;
1627
1638
  }
1628
1639
  const img = images.get(part);
@@ -1631,7 +1642,7 @@ export function buildWaistPairSource(
1631
1642
  const crossing: number[] = [];
1632
1643
  for (let x = 0; x < img.width; x++) if (img.data[(r * img.width + x) * 4 + 3] > 0) crossing.push(x);
1633
1644
  if (crossing.length > 0) {
1634
- fail(
1645
+ stillFail(
1635
1646
  'RIG_STILL_ROW_CLEAR',
1636
1647
  `${at}.row`,
1637
1648
  `is ${st.row}, and "${part}" has ${crossing.length} pixel(s) with alpha above 0 on that row (the first at x = ${p.x + crossing[0]}); a row with no art across the part's whole width is required — two pieces cut through art are each resampled against their own transparent edge, so the render changes at rest, not only while the eye moves`,
@@ -1641,7 +1652,7 @@ export function buildWaistPairSource(
1641
1652
  const artAbove = alphaCount(img, 0, r);
1642
1653
  const artBelow = alphaCount(img, r, img.height);
1643
1654
  if (artAbove === 0 || artBelow === 0) {
1644
- fail('RIG_STILL_PIECES_HAVE_ART', `${at}.row`, `is ${st.row}; "${part}" has ${artAbove} art pixel(s) above it and ${artBelow} below; both pieces need art, or the cut holds nothing still (or nothing blinks)`);
1655
+ stillFail('RIG_STILL_PIECES_HAVE_ART', `${at}.row`, `is ${st.row}; "${part}" has ${artAbove} art pixel(s) above it and ${artBelow} below; both pieces need art, or the cut holds nothing still (or nothing blinks)`);
1645
1656
  }
1646
1657
  }
1647
1658
  refuseIfAny(problems);
package/src/runstamp.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { existsSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { existsSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
3
  import { basename, join, relative, resolve, sep } from 'node:path';
4
4
  import { type AssembleResult, FIGURE_MASK_FILE } from './assemble.ts';
5
5
  import { ERROR_MAP_FILE } from './build.ts';
@@ -16,8 +16,10 @@ import { SUPPORT_DOMAINS_FILE } from './supportdomains.ts';
16
16
 
17
17
  export const RUN_STAMP_SPEC = 'rig-run/1' as const;
18
18
  export const RUN_STAMP_FILE = 'run.json' as const;
19
+ export const RUN_STAMP_INPUT_ROLES = ['source', 'full', 'head'] as const;
19
20
 
20
21
  export type RunStampCommand = 'rig' | 'assemble';
22
+ export type RunStampInputRole = (typeof RUN_STAMP_INPUT_ROLES)[number];
21
23
 
22
24
  export interface RunStampPackage {
23
25
  name: string;
@@ -29,6 +31,19 @@ export interface RunStampFileEntry {
29
31
  sha256: string;
30
32
  }
31
33
 
34
+ export interface RunStampInputEntry {
35
+ role: RunStampInputRole;
36
+ path: string;
37
+ sha256: string;
38
+ }
39
+
40
+ export interface RunStampAssembleInputs {
41
+ cwd?: string;
42
+ source: string;
43
+ full: string;
44
+ head?: string | null;
45
+ }
46
+
32
47
  export interface RunStamp {
33
48
  spec: typeof RUN_STAMP_SPEC;
34
49
  package: RunStampPackage;
@@ -36,6 +51,7 @@ export interface RunStamp {
36
51
  started_at: string;
37
52
  finished_at: string;
38
53
  config: RunStampFileEntry;
54
+ inputs?: RunStampInputEntry[];
39
55
  outputs: RunStampFileEntry[];
40
56
  }
41
57
 
@@ -46,6 +62,7 @@ export interface RunStampInput {
46
62
  finishedAt: string;
47
63
  outDir: string;
48
64
  configPath: string;
65
+ inputs?: RunStampAssembleInputs;
49
66
  outputPaths: readonly string[];
50
67
  }
51
68
 
@@ -59,6 +76,40 @@ function relativeToOutRoot(outDir: string, targetPath: string): string {
59
76
  return relative(realOut, realTarget).split(sep).join('/');
60
77
  }
61
78
 
79
+ function relativeToCwd(cwd: string, targetPath: string): string {
80
+ const rel = relative(resolve(cwd), resolve(cwd, targetPath)).split(sep).join('/');
81
+ return rel === '' ? '.' : rel;
82
+ }
83
+
84
+ function inputSha256OnDisk(cwd: string, targetPath: string): string {
85
+ const resolved = resolve(cwd, targetPath);
86
+ const filePath = statSync(resolved).isDirectory() ? join(resolved, 'layers.json') : resolved;
87
+ return sha256OnDisk(filePath);
88
+ }
89
+
90
+ /**
91
+ * Build the ordered `inputs` list (`source`, `full`, and `head` when given) for an `assemble` run stamp:
92
+ * each entry records `role`, `path` relative to `cwd`, and `sha256` of the file or of `<dir>/layers.json`.
93
+ */
94
+ export function buildAssembleInputs(inputs: RunStampAssembleInputs): RunStampInputEntry[] {
95
+ const cwd = inputs.cwd ?? process.cwd();
96
+ const raw: ReadonlyArray<readonly [RunStampInputRole, string | null | undefined]> = [
97
+ ['source', inputs.source],
98
+ ['full', inputs.full],
99
+ ['head', inputs.head],
100
+ ];
101
+ const entries: RunStampInputEntry[] = [];
102
+ for (const [role, given] of raw) {
103
+ if (given === undefined || given === null) continue;
104
+ entries.push({
105
+ role,
106
+ path: relativeToCwd(cwd, given),
107
+ sha256: inputSha256OnDisk(cwd, given),
108
+ });
109
+ }
110
+ return entries;
111
+ }
112
+
62
113
  function sortCodeUnits(paths: readonly string[]): string[] {
63
114
  return [...new Set(paths.filter((p) => p !== RUN_STAMP_FILE))].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
64
115
  }
@@ -158,6 +209,7 @@ export function buildRunStamp(input: RunStampInput): RunStamp {
158
209
  path: rel,
159
210
  sha256: sha256OnDisk(join(input.outDir, ...rel.split('/'))),
160
211
  }));
212
+ const inputs = input.inputs === undefined ? undefined : buildAssembleInputs(input.inputs);
161
213
  return {
162
214
  spec: RUN_STAMP_SPEC,
163
215
  package: {
@@ -171,6 +223,7 @@ export function buildRunStamp(input: RunStampInput): RunStamp {
171
223
  path: relativeToOutRoot(input.outDir, input.configPath),
172
224
  sha256: sha256OnDisk(input.configPath),
173
225
  },
226
+ ...(inputs === undefined ? {} : { inputs }),
174
227
  outputs,
175
228
  };
176
229
  }
@@ -5,7 +5,7 @@
5
5
  import { closeSync, fchmodSync, linkSync, mkdirSync, lstatSync, openSync, readFileSync, realpathSync, statSync, renameSync, rmSync, writeFileSync } from 'node:fs';
6
6
  import { randomBytes } from 'node:crypto';
7
7
  import { basename, dirname, join, resolve } from 'node:path';
8
- import { loadConfigAndAnimations, loadEarlyConfig, repeatedKeys } from '../src/config.ts';
8
+ import { loadConfigAndAnimations, loadEarlyConfig, parseConfig, parseEarlyConfig, repeatedKeys } from '../src/config.ts';
9
9
  import { mergeConfigProposal, type ConfigWriteChange, type ConfigWritePatch } from '../src/configwrite.ts';
10
10
  import { PartsError, type Problem } from '../src/errors.ts';
11
11
  import { splicedEdits } from '../src/meshdraft.ts';
@@ -18,6 +18,8 @@ export interface ConfigWriteFiles {
18
18
  replace?: (from: string, to: string) => void;
19
19
  remove?: (path: string) => void;
20
20
  publish?: (from: string, to: string) => void;
21
+ /** Batch rollback is independent of the replacement failure being controlled. */
22
+ restore?: (from: string, to: string) => void;
21
23
  }
22
24
  export interface StagedConfigWrite {
23
25
  changes: readonly ConfigWriteChange[];
@@ -201,3 +203,83 @@ export function stageConfigWrite(target: ConfigWriteTarget | FreshConfigWrite, p
201
203
  export function configWriteLines(target: ConfigWriteTarget, changes: readonly ConfigWriteChange[]): string[] {
202
204
  return changes.length === 0 ? [`config ${target.path}: unchanged`] : changes.map((c) => `config ${target.path}: ${c.kind} ${c.path}${c.value === undefined ? '' : ` ${c.value}`}`);
203
205
  }
206
+
207
+ export interface ConfigWriteRequest { target: ConfigWriteTarget; patch: ConfigWritePatch }
208
+ export interface StagedConfigWriteBatch {
209
+ writes: ReadonlyArray<{ target: ConfigWriteTarget; changes: readonly ConfigWriteChange[] }>;
210
+ commit(): void;
211
+ cancel(): void;
212
+ }
213
+ /** Existing configs only: every candidate stages through stageConfigWrite before
214
+ * any destination commits. A later commit failure restores earlier originals.
215
+ * Backups whose restoration fails are retained and named, never deleted.
216
+ */
217
+ export function stageConfigWriteBatch(requests: readonly ConfigWriteRequest[], files: ConfigWriteFiles = {}): StagedConfigWriteBatch {
218
+ const entries: Array<{ target: ConfigWriteTarget; staged: StagedConfigWrite; backup: string | null; committed: boolean; restoreFailed: boolean }> = [];
219
+ const problemsOf = (error: unknown, path: string, action: string): Problem[] => error instanceof PartsError ? [...error.problems] : [ioProblem(path, action, error)];
220
+ const cancelAll = (): Problem[] => entries.flatMap(({ target, staged }) => {
221
+ try { staged.cancel(); return []; }
222
+ catch (error) { return problemsOf(error, target.path, 'removing the staged config failed'); }
223
+ });
224
+ try {
225
+ // Two names for one inode cannot be independent members of a write batch.
226
+ const identities = new Set<string>();
227
+ for (const { target } of requests) {
228
+ const stat = statSync(target.path), identity = `${stat.dev}:${stat.ino}`;
229
+ if (identities.has(identity)) refusal('CONFIG_WRITE_TARGET', target.path, 'names another config in the batch; distinct existing config files are required');
230
+ identities.add(identity);
231
+ }
232
+ // Candidate shape refusals precede even temporary writes. The existing
233
+ // stage loader then validates each real same-directory staged file, including
234
+ // relative sidecars. Edited receipts are full-config updates, not early drafts.
235
+ for (const { target, patch } of requests) {
236
+ const candidate = mergeConfigProposal(target.raw, patch).config;
237
+ if (patch.kind === 'head-box') parseEarlyConfig(candidate, 'layers');
238
+ else if (patch.kind === 'assemble-plan') parseEarlyConfig(candidate, 'assemble');
239
+ else parseConfig(candidate);
240
+ }
241
+ for (const { target, patch } of requests) entries.push({ target, staged: stageConfigWrite(target, patch, files), backup: null, committed: false, restoreFailed: false });
242
+ } catch (error) {
243
+ throw new PartsError([...problemsOf(error, 'config batch', 'staging configs failed'), ...cancelAll()]);
244
+ }
245
+ return {
246
+ writes: entries.map(({ target, staged }) => ({ target, changes: staged.changes })),
247
+ cancel(): void {
248
+ const problems = cancelAll();
249
+ if (problems.length > 0) throw new PartsError(problems);
250
+ },
251
+ commit(): void {
252
+ let problems: Problem[] = [];
253
+ try {
254
+ for (const entry of entries) {
255
+ unchanged(entry.target);
256
+ if (entry.staged.changes.length === 0) continue;
257
+ const path = entry.target.path;
258
+ const backup = join(dirname(path), `.${basename(path)}.rig-parts-${randomBytes(8).toString('hex')}.bak`);
259
+ linkSync(path, backup);
260
+ entry.backup = backup;
261
+ }
262
+ for (const entry of entries) {
263
+ entry.staged.commit();
264
+ entry.committed = entry.staged.changes.length > 0;
265
+ }
266
+ } catch (error) {
267
+ problems = problemsOf(error, 'config batch', 'committing configs failed');
268
+ for (const entry of entries.toReversed()) if (entry.committed && entry.backup !== null) {
269
+ try { (files.restore ?? renameSync)(entry.backup, entry.target.path); entry.backup = null; entry.committed = false; }
270
+ catch (restore) {
271
+ entry.restoreFailed = true;
272
+ problems.push(ioProblem(entry.target.path, `restoring original config failed; original retained at ${entry.backup}`, restore));
273
+ }
274
+ }
275
+ problems.push(...cancelAll());
276
+ }
277
+ for (const entry of entries) if (entry.backup !== null && !entry.restoreFailed) {
278
+ const backup = entry.backup;
279
+ try { (files.remove ?? ((path: string) => rmSync(path, { force: true })))(backup); entry.backup = null; }
280
+ catch (error) { problems.push(ioProblem(backup, 'removing the original-config backup failed', error)); }
281
+ }
282
+ if (problems.length > 0) throw new PartsError(problems);
283
+ },
284
+ };
285
+ }
@@ -0,0 +1,61 @@
1
+ /** Issue #1328: record file bytes, splice one receipt, then publish checked configs. */
2
+ import { createHash } from 'node:crypto';
3
+ import { readFileSync } from 'node:fs';
4
+ import { dirname, relative, resolve } from 'node:path';
5
+ import { parseConfig } from '../src/config.ts';
6
+ import type { EditedPartReceipt } from '../src/editedparts.ts';
7
+ import { PartsError } from '../src/errors.ts';
8
+ import { decodePngBytes } from '../src/raster/png.ts';
9
+ import { readConfigWriteTarget, stageConfigWriteBatch, type StagedConfigWriteBatch } from './configwrite.ts';
10
+
11
+ export interface EditedPartInput {
12
+ config: string;
13
+ rigConfig?: string;
14
+ part: string;
15
+ file: string;
16
+ from: string;
17
+ editor: string;
18
+ }
19
+ function refuse(code: string, object: string, detail: string): never {
20
+ throw new PartsError([{ code, object, detail }]);
21
+ }
22
+ function png(path: string, flag: string): { bytes: Buffer; width: number; height: number } {
23
+ let bytes: Buffer;
24
+ try { bytes = readFileSync(path); }
25
+ catch { return refuse('EDITED_PART_FILE', flag, `file ${JSON.stringify(path)} is not readable; a readable PNG is required`); }
26
+ try {
27
+ const { width, height } = decodePngBytes(bytes, path);
28
+ return { bytes, width, height };
29
+ } catch {
30
+ return refuse('EDITED_PART_PNG', flag, `file ${JSON.stringify(path)} is not a decodable PNG; a PNG is required`);
31
+ }
32
+ }
33
+ const hash = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
34
+ export interface EditedPartWriteResult { receipt: EditedPartReceipt; writes: StagedConfigWriteBatch['writes'] }
35
+
36
+ /** Prepare every replacement before even temporary files are written. No assembly or filename discovery. */
37
+ export function writeEditedPart(input: EditedPartInput): EditedPartWriteResult {
38
+ for (const [flag, value] of [
39
+ ['--config', input.config], ['--part', input.part], ['--file', input.file],
40
+ ['--from', input.from], ['--editor', input.editor],
41
+ ...(input.rigConfig === undefined ? [] : [['--rig-config', input.rigConfig]]),
42
+ ]) if (typeof value !== 'string' || value.trim() === '') refuse('EDITED_PART_ARGUMENT', flag, 'is missing or blank; a non-empty value is required');
43
+ const edited = png(input.file, '--file'), from = png(input.from, '--from');
44
+ if (edited.width !== from.width || edited.height !== from.height) refuse('EDITED_PART_SIZE', input.part,
45
+ `edited PNG is ${edited.width}x${edited.height}; --from PNG dimensions ${from.width}x${from.height} are required`);
46
+ const receipt = { part: input.part, file: input.file, sha256: hash(edited.bytes), from_sha256: hash(from.bytes), editor: input.editor };
47
+ const targets = [input.config, ...(input.rigConfig === undefined ? [] : [input.rigConfig])].map(readConfigWriteTarget);
48
+ const receipts: EditedPartReceipt[] = [];
49
+ const requests = targets.map(target => {
50
+ const config = parseConfig(target.raw as Parameters<typeof parseConfig>[0]);
51
+ const spec = config.assemble.edited_parts;
52
+ if (spec === undefined) return refuse('EDITED_PART_BLOCK', target.path, 'has no assemble.edited_parts; declare {dir, receipts: []} before recording an edited part');
53
+ const file = relative(resolve(dirname(target.path), spec.dir), resolve(input.file)).replaceAll('\\', '/');
54
+ const value: EditedPartReceipt = { ...receipt, file };
55
+ receipts.push(value);
56
+ return { target, patch: { kind: 'edited-part-receipt' as const, receipt: value } };
57
+ });
58
+ const staged = stageConfigWriteBatch(requests);
59
+ staged.commit();
60
+ return { receipt: receipts[0], writes: staged.writes };
61
+ }