rig-parts 2.69.0 → 2.71.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.
@@ -39,7 +39,12 @@ export interface DepthConfig { zScale?: number; full?: DepthRunConfig; head?: De
39
39
  /** Explicit caller context; never inferred from a filename or sheet presence. */
40
40
  export interface DepthBinding { config: DepthConfig; run: 'full' | 'head'; base: string }
41
41
  /** Legacy metadata retained without file I/O or value validation until opt-in. */
42
- export interface DeferredDepthSource { filename: unknown; base: string }
42
+ export interface DeferredDepthSource {
43
+ filename: unknown;
44
+ base: string;
45
+ /** Bound to the original wrapper's receipt role, even if the layer is transformed. */
46
+ recordDecode?: (path: string, sha256: string) => void;
47
+ }
43
48
  export interface DepthSource {
44
49
  from: string;
45
50
  image: string;
@@ -173,7 +178,9 @@ export function registerDepthRun(set: LayerSet, run: 'full' | 'head', cfg: Depth
173
178
  const paths = [join(hint.base, file), join(hint.base, 'parts', `${layer.name}_depth.png`)];
174
179
  const found = paths.filter(p => existsSync(p));
175
180
  if (found.length === 2 && !readFileSync(found[0]).equals(readFileSync(found[1]))) throw new PartsError([{ code: 'DEPTH_SHEET_UNAMBIGUOUS', object: from, detail: `${paths.join(' and ')} differ; keep one source or identical bytes` }]);
176
- sheet = readSourceDepth(found[0] ?? paths[0], layer.pixels, layer.depth);
181
+ const selected = found[0] ?? paths[0];
182
+ sheet = readSourceDepth(selected, layer.pixels, layer.depth);
183
+ hint.recordDecode?.(selected, sheet.sha256);
177
184
  }
178
185
  if (sheet !== undefined && supplied !== undefined) throw new PartsError([{ code: 'DEPTH_SOURCE_AMBIGUOUS', object: from, detail: 'has both depth_filename and a user declaration; the writer file is authoritative — remove the unused fallback for this layer' }]);
179
186
  let near: DepthNear = sheet?.near ?? SEETHROUGH_DEPTH_NEAR, zScale = sheet?.zScale ?? cfg?.zScale;
@@ -1,23 +1,27 @@
1
1
  /** Explicit opt-in commands for provider maps on already assembled parts (#897).
2
2
  * No existing assembly/build path calls these stages. All inputs validate before
3
- * the first output is emitted; output directories must be absent or empty.
3
+ * the first output is emitted. A signed application publishes to an absent directory.
4
4
  */
5
5
  import { createHash } from 'node:crypto';
6
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs';
6
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
7
7
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
8
8
  import { refuseStaleAssembly } from './assembly-reading.ts';
9
- import { PartsError, type Problem } from './errors.ts';
9
+ import { foldName, PartsError, type Problem } from './errors.ts';
10
10
  import { loadConfigAndAnimations, parseConfig } from './config.ts';
11
11
  import { relocateConfigReferences } from './configrelocation.ts';
12
+ import { CUT_MATERIAL_SOURCES } from './cutmaterial.ts';
12
13
  import { depthReading, readSourceDepth } from './depthsheets.ts';
13
14
  import { readEditorReceipts } from './editreceipt.ts';
14
15
  import { alphaSupport, depthMapFail as fail, floatBox, integrateNormals, mapQuantile, mapToSheet, readNumericMap, type NumericMap } from './depthmaps.ts';
15
- import { depthImageReference, partImageReference, readParts } from './parts.ts';
16
+ import { depthImageReference, partImageReference, readParts, type PartsFile } from './parts.ts';
17
+ import { withinPartsPath, type PartsInventoryRow } from './partsfiles.ts';
16
18
  import { readPartSet, type PartSet } from './propose.ts';
17
19
  import { decodePngBytes, encodePngBytes } from './raster/png.ts';
18
20
  import { resize } from './raster/resize.ts';
19
21
  import { connectedComponents } from './raster/components.ts';
20
22
  import { newRaster, type Raster } from './raster/types.ts';
23
+ import { verifyReplacementRecord } from './replaceparts.ts';
24
+ import { captureReplacementTree, createDepthReplacementRecord, digestReplacementInventory, readBoundReplacementFile, replacementRecordPath } from './replacementrecord.ts';
21
25
 
22
26
  type Obj = Record<string, unknown>;
23
27
  interface PrepareOptions { longSide: number; paddingFraction: number; padding: number }
@@ -525,17 +529,160 @@ function groupSelection(recipe: DepthRecipe, groups: readonly string[] | undefin
525
529
  if (problems.length) throw new PartsError(problems);
526
530
  return declared.filter(g => seen.has(g));
527
531
  }
528
- export function applyDepth(input: { parts: string; manifest: string; config: string; rigConfig: string; out: string; groups?: readonly string[] }, log: (line: string) => void = console.warn): Obj {
532
+ interface ApplyDepthInput {
533
+ parts: string;
534
+ manifest: string;
535
+ config: string;
536
+ rigConfig: string;
537
+ out: string;
538
+ groups?: readonly string[];
539
+ sourceSha256?: string;
540
+ }
541
+
542
+ interface RecordedDepthSource {
543
+ root: string;
544
+ requestedOut: string;
545
+ out: string;
546
+ digest: string;
547
+ pointer: string;
548
+ inventory: ReadonlyMap<string, PartsInventoryRow>;
549
+ file: PartsFile;
550
+ manifest: Obj;
551
+ }
552
+
553
+ function depthBundlePath(path: string): string {
554
+ if (existsSync(path)) return realpathSync(path);
555
+ return join(depthBundlePath(dirname(path)), basename(path));
556
+ }
557
+
558
+ function depthBundleOutput(path: string, source: string, inputs: readonly string[]): string {
559
+ const target = resolve(path);
560
+ const refuse = (): never => fail('DEPTH_RECORD_OUTPUT', '--out', 'found an unavailable, occupied or overlapping path; required an absent directory disjoint from all inputs');
561
+ try {
562
+ if (lstatSync(target, { throwIfNoEntry: false }) !== undefined) return refuse();
563
+ const out = depthBundlePath(target);
564
+ if (withinPartsPath(source, out)) return refuse();
565
+ for (const input of [source, ...inputs]) {
566
+ const full = resolve(input);
567
+ if (withinPartsPath(target, full) || withinPartsPath(out, depthBundlePath(full))) return refuse();
568
+ }
569
+ return out;
570
+ } catch (error) {
571
+ if (error instanceof PartsError) throw error;
572
+ return refuse();
573
+ }
574
+ }
575
+
576
+ function recordedDepthSource(input: ApplyDepthInput, digest: string, paths: readonly string[]): RecordedDepthSource {
577
+ const path = resolve(input.parts);
578
+ if (!lstatSync(path, { throwIfNoEntry: false })?.isDirectory()) {
579
+ fail('REPLACE_PART_INPUT', '--parts', 'found a missing, linked or non-directory source; required a regular parts root');
580
+ }
581
+ const root = realpathSync(path);
582
+ const out = depthBundleOutput(input.out, root, paths);
583
+ if (lstatSync(join(root, CUT_MATERIAL_SOURCES), { throwIfNoEntry: false }) !== undefined) {
584
+ fail('DEPTH_RECORD_MANIFEST_BOUND', CUT_MATERIAL_SOURCES, 'found a source manifest binding; required a source set without cut_material_sources.json');
585
+ }
586
+ const inventory = captureReplacementTree(root), actual = digestReplacementInventory(inventory);
587
+ if (actual !== digest) {
588
+ fail('REPLACE_PART_SOURCE_HASH', 'recorded set', `found sha256 ${actual} — required sha256 ${digest}`);
589
+ }
590
+ const file = readParts(join(root, 'parts.json'));
591
+ const manifest = object(JSON.parse(readBoundReplacementFile(root, inventory, 'parts.json').toString('utf8')), 'parts.json');
592
+ if (text(file) !== text(manifest)) fail('REPLACE_PART_INPUT', 'parts.json', 'manifest changed while reading the source inventory');
593
+ verifyReplacementRecord(root, file);
594
+ const pointer = replacementRecordPath(digest);
595
+ if ([...inventory.keys()].some(path => foldName(path) === pointer)) {
596
+ fail('DEPTH_RECORD_OUTPUT', pointer, 'found an existing source receipt path; required a new active receipt path');
597
+ }
598
+ return { root, requestedOut: resolve(input.out), out, digest, pointer, inventory, file, manifest };
599
+ }
600
+
601
+ function writeDepthBundle(
602
+ source: RecordedDepthSource, parts: Obj, config: Obj, report: Obj,
603
+ writes: ReadonlyMap<string, Uint8Array>, removed: ReadonlySet<string>,
604
+ groups: ReadonlyMap<string, Group>, partGroups: ReadonlyMap<string, string | null>,
605
+ ): void {
606
+ const parent = dirname(source.out);
607
+ const refuse = (): never => fail('DEPTH_RECORD_OUTPUT', '--out', 'found an unavailable or occupied destination; required an absent directory in a writable, stable parent');
608
+ const available = (): boolean => realpathSync(parent) === parent && depthBundlePath(source.requestedOut) === source.out &&
609
+ lstatSync(source.out, { throwIfNoEntry: false }) === undefined;
610
+ let scratch: string;
611
+ try {
612
+ mkdirSync(parent, { recursive: true });
613
+ if (!available()) return refuse();
614
+ scratch = mkdtempSync(join(parent, '.depth-apply-'));
615
+ } catch (error) {
616
+ if (error instanceof PartsError) throw error;
617
+ return refuse();
618
+ }
619
+ try {
620
+ const stage = join(scratch, 'bundle');
621
+ const set = join(stage, 'set');
622
+ const emit = (path: string, bytes: Uint8Array | string): void => {
623
+ const target = join(set, path);
624
+ try {
625
+ mkdirSync(dirname(target), { recursive: true });
626
+ writeFileSync(target, bytes, { flag: 'wx' });
627
+ } catch (error) {
628
+ const code = (error as NodeJS.ErrnoException).code;
629
+ if (code === 'EEXIST' || code === 'ENOTDIR' || code === 'EISDIR') {
630
+ fail('DEPTH_RECORD_DELTA', path, 'found a file or directory alias in the staged set; required a unique owned path');
631
+ }
632
+ refuse();
633
+ }
634
+ };
635
+ for (const path of source.inventory.keys()) {
636
+ if (path !== 'parts.json' && !removed.has(path)) emit(path, readBoundReplacementFile(source.root, source.inventory, path));
637
+ }
638
+ for (const [file, bytes] of writes) emit(`parts/${file}`, bytes);
639
+ parts.replacement_record = source.pointer;
640
+ emit('parts.json', text(parts));
641
+ const record = createDepthReplacementRecord(source.root, set, groups, partGroups);
642
+ emit(source.pointer, text(record));
643
+ verifyReplacementRecord(set, readParts(join(set, 'parts.json')));
644
+ try {
645
+ writeFileSync(join(stage, 'config.json'), text(config), { flag: 'wx' });
646
+ writeFileSync(join(stage, 'depth-report.json'), text(report), { flag: 'wx' });
647
+ } catch { return refuse(); }
648
+
649
+ const actual = digestReplacementInventory(captureReplacementTree(source.root));
650
+ if (actual !== source.digest) {
651
+ fail('REPLACE_PART_SOURCE_HASH', 'recorded set', `found sha256 ${actual} before publication — required sha256 ${source.digest}`);
652
+ }
653
+ try {
654
+ if (!available()) return refuse();
655
+ renameSync(stage, source.out);
656
+ } catch (error) {
657
+ if (error instanceof PartsError) throw error;
658
+ return refuse();
659
+ }
660
+ } finally {
661
+ rmSync(scratch, { recursive: true, force: true });
662
+ }
663
+ }
664
+
665
+ export function applyDepth(input: ApplyDepthInput, log: (line: string) => void = console.warn): Obj {
529
666
  const recipe = parseDepthRecipe(readJson(input.config)), selection = groupSelection(recipe, input.groups), applied = (group: string): boolean => selection === undefined || selection.includes(group);
530
- const expected = preparedParts(input.parts, recipe);
667
+ const inputPaths = [input.config, input.manifest, input.rigConfig, ...Object.values(recipe.parts).flatMap(p => { const map = resolve(dirname(input.config), p.map); return [map, map + '.binding.json']; })];
668
+ const recorded = input.sourceSha256 === undefined ? undefined : recordedDepthSource(input, input.sourceSha256, [
669
+ ...inputPaths, ...Object.keys(recipe.parts).map(name => join(dirname(input.manifest), `${name}.png`)),
670
+ ]);
671
+ const source = recorded?.root ?? input.parts;
672
+ const expected = preparedParts(source, recipe);
673
+ if (recorded !== undefined && (expected.manifest.partsSha256 !== recorded.inventory.get('parts.json')?.sha256 ||
674
+ expected.manifest.parts.some(p => p.sourceSha256 !== recorded.inventory.get(`parts/${p.part}.png`)?.sha256))) {
675
+ fail('REPLACE_PART_INPUT', '--parts', 'manifest or art changed after capture of the source inventory');
676
+ }
531
677
  const supplied = readJson(input.manifest);
532
678
  if (text(supplied) !== text(expected.manifest)) fail('DEPTH_INPUT_BINDING', input.manifest, 'does not match the recipe, parts.json, art hashes, crop or padding; run depth-prepare again for these exact inputs');
533
679
  for (const p of expected.manifest.parts) {
534
680
  const file = join(dirname(input.manifest), p.input);
535
681
  if (!existsSync(file) || hash(readFileSync(file)) !== p.inputSha256) fail('DEPTH_INPUT_BINDING', p.part, 'prepared inference PNG is missing or changed; restore its exact bytes or prepare again');
536
682
  }
537
- emptyOutput(input.out, [input.parts, input.config, input.manifest, input.rigConfig, ...Object.values(recipe.parts).flatMap(p => { const map = resolve(dirname(input.config), p.map); return [map, map + '.binding.json']; })]);
538
- const rawParts = object(readJson(join(input.parts, 'parts.json')), 'parts.json'), file = readParts(join(input.parts, 'parts.json'));
683
+ if (recorded === undefined) emptyOutput(input.out, [source, ...inputPaths]);
684
+ const rawParts = recorded?.manifest ?? object(readJson(join(source, 'parts.json')), 'parts.json');
685
+ const file = recorded?.file ?? readParts(join(source, 'parts.json'));
539
686
  for (const p of file.parts) if (Object.hasOwn(recipe.parts, p.name) && applied(recipe.parts[p.name].group) && p.provenance?.depth?.kind === 'authored-unit') fail('DEPTH_AUTHORED_UNIT_CONFLICT', `part "${p.name}"`, 'has provenance.depth.kind "authored-unit"; a transported scalar reference cannot coexist with authored unit depth — retain the unit declaration or supply an explicitly reassembled scalar-compatible input; no automatic transition is made');
540
687
  const { config } = loadConfigAndAnimations(input.rigConfig);
541
688
  const receiptProblems = readEditorReceipts(config.assemble.editor_receipts, input.rigConfig).problems;
@@ -559,13 +706,15 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
559
706
  if (group.unitDepths !== undefined) target.unitDepths = group.unitDepths;
560
707
  }
561
708
  // Keep relative paths portable when relocating the output directory with its inputs.
562
- relocateConfigReferences(raw, dirname(input.rigConfig), input.out, 'relative');
563
- const relocatedConfig = parseConfig(raw), outConfig = join(input.out, 'config.json');
709
+ const configDir = recorded?.out ?? input.out;
710
+ relocateConfigReferences(raw, dirname(input.rigConfig), configDir, 'relative');
711
+ const relocatedConfig = parseConfig(raw), outConfig = join(configDir, 'config.json');
564
712
  const relocatedReceiptProblems = readEditorReceipts(relocatedConfig.assemble.editor_receipts, outConfig).problems;
565
713
  if (relocatedReceiptProblems.length) throw new PartsError(relocatedReceiptProblems);
566
714
  refuseStaleAssembly(outConfig, file, relocatedConfig);
567
715
  const warnings: string[] = [];
568
716
  const writes = new Map<string, Uint8Array>(), rows: Obj[] = [], recs = rawParts.parts as Obj[];
717
+ const removed = new Set<string>(), partGroups = new Map<string, string | null>();
569
718
  const groupMaxZ = new Map<string, number>();
570
719
  const clipped: { name: string; group: string; fraction: number; clipsHigh: boolean; median: number; minMedian?: number }[] = [];
571
720
  // Retain auxiliary art (including alternate sets) and diagnostics byte-for-byte.
@@ -579,16 +728,30 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
579
728
  else fail('DEPTH_INPUT_PRESENT', path, 'is not a regular owned file/directory; supply a self-contained assembled directory without symlinks');
580
729
  }
581
730
  };
582
- collect(input.parts, '');
731
+ if (recorded === undefined) collect(source, '');
583
732
  for (const p of file.parts) {
584
- const name = p.name, bytes = readFileSync(join(input.parts, partImageReference(p).path)), art = decodePngBytes(bytes, name), rec = recs.find(r => r.name === name) as Obj;
585
- writes.set(`${name}.png`, bytes);
733
+ const name = p.name, artPath = partImageReference(p).path;
734
+ const bytes = recorded === undefined ? readFileSync(join(source, artPath)) : readBoundReplacementFile(source, recorded.inventory, artPath);
735
+ const art = decodePngBytes(bytes, name), rec = recs.find(r => r.name === name) as Obj;
736
+ if (recorded === undefined) writes.set(`${name}.png`, bytes);
586
737
  const declaration = Object.hasOwn(recipe.parts, name) ? recipe.parts[name] : undefined;
738
+ const removeDepth = (group: string | null): void => {
739
+ if (p.depth !== undefined) {
740
+ const path = depthImageReference(p.depth).path;
741
+ if (recorded === undefined) retained.delete(path);
742
+ else removed.add(path);
743
+ }
744
+ if (recorded !== undefined && (p.depth !== undefined || group !== null)) partGroups.set(name, group);
745
+ };
587
746
  // A left-out group's part gets no new sheet, and any sheet it carried is dropped, never retained stale.
588
- if (declaration !== undefined && !applied(declaration.group)) { if (p.depth !== undefined) retained.delete(depthImageReference(p.depth).path); delete rec.depth; continue; }
747
+ if (declaration !== undefined && !applied(declaration.group)) { removeDepth(null); delete rec.depth; continue; }
589
748
  if (declaration === undefined) {
590
- if (recipe.clear.includes(name)) { if (p.depth !== undefined) retained.delete(depthImageReference(p.depth).path); delete rec.depth; }
591
- else if (p.depth !== undefined) { const depthPath = join(input.parts, depthImageReference(p.depth).path); readSourceDepth(depthPath, art, null); writes.set(p.depth.image, readFileSync(depthPath)); }
749
+ if (recipe.clear.includes(name)) { removeDepth(null); delete rec.depth; }
750
+ else if (p.depth !== undefined) {
751
+ const depthPath = join(source, depthImageReference(p.depth).path);
752
+ readSourceDepth(depthPath, art, null);
753
+ if (recorded === undefined) writes.set(p.depth.image, readFileSync(depthPath));
754
+ }
592
755
  continue;
593
756
  }
594
757
  const g = recipe.groups[declaration.group], target = declaration.group === 'head' ? turn : object(turn.body, 'config.turn.body');
@@ -618,9 +781,9 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
618
781
  continue;
619
782
  }
620
783
  const image = `${name}_depth.png`, sheetBytes = encodePngBytes(sheet);
621
- if (file.parts.some(p => `${p.name}.png` === image)) fail('DEPTH_GROUP_BINDING', name, `sheet filename ${image} collides with artwork; use noncolliding part names`);
784
+ if (recorded === undefined && file.parts.some(p => `${p.name}.png` === image)) fail('DEPTH_GROUP_BINDING', name, `sheet filename ${image} collides with artwork; use noncolliding part names`);
622
785
  writes.set(image, sheetBytes);
623
- if (p.depth !== undefined) retained.delete(depthImageReference(p.depth).path);
786
+ removeDepth(declaration.group);
624
787
  rec.depth = { image, near: g.near, zScale: g.zScale, sources: [{ from: p.from, image: basename(declaration.map), sha256: hash(mapBytes), crop: [0, 0, art.width, art.height], reading: depthReading(sheet, art, null) }] };
625
788
  rows.push({ part: name, group: declaration.group, source: declaration.source, frame: declaration.frame, sourceSha256: prepared.sourceSha256, mapSha256: hash(mapBytes), inputSha256: prepared.inputSha256, sheetSha256: hash(sheetBytes), median: declaration.median, relief: declaration.relief, near: g.near, zScale: g.zScale, pivot: g.pivot, ...reading, sign: normal?.sign ?? 1, ...(normal === undefined ? {} : { integration: { stride: 2, iterations: normal.iterations, residual: normal.residual, coreMinusRim: normal.coreMinusRim, maxIterations: 3000, atol: 1e-6, btol: 1e-6 } }) });
626
789
  }
@@ -647,6 +810,12 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
647
810
  }
648
811
  const report = { spec: 'rig-parts-depth-report/1', partsSha256: expected.manifest.partsSha256, recipeSha256: expected.manifest.recipeSha256, manifestSha256: hash(readFileSync(input.manifest)), rigConfigSha256: hash(readFileSync(input.rigConfig)), alpha: 128, normalization: 'median, linear p5..p95', extension: 'nearest alpha>=128, row-major ties', cleared: recipe.clear,
649
812
  ...(selection === undefined ? {} : { selection: { groups: selection, leftOut: file.parts.filter(p => Object.hasOwn(recipe.parts, p.name) && !applied(recipe.parts[p.name].group)).map(p => p.name) } }), parts: rows };
813
+ if (recorded !== undefined) {
814
+ const groups = new Map(Object.entries(recipe.groups).filter(([name]) => applied(name)));
815
+ writeDepthBundle(recorded, rawParts, raw, report, writes, removed, groups, partGroups);
816
+ for (const warning of warnings) log(warning);
817
+ return report;
818
+ }
650
819
  mkdirSync(join(input.out, 'parts'), { recursive: true });
651
820
  for (const [file, bytes] of retained) {
652
821
  if (['parts.json', 'config.json', 'depth-report.json'].includes(file)) continue;
package/src/layers.ts CHANGED
@@ -33,6 +33,7 @@ import type { TakenLayerSource } from './takesource.ts';
33
33
  * role, and its place in the draw order is read like any other layer's.
34
34
  */
35
35
  import { bindDepthRun, type DepthBinding, type DeferredDepthSource, type SourceDepthSheet } from './depthsheets.ts';
36
+ import { createHash } from 'node:crypto';
36
37
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
37
38
  import { basename, dirname, join } from 'node:path';
38
39
  import { initializeCanvas, type Layer as PsdLayer, readPsd, writePsd } from 'ag-psd';
@@ -199,6 +200,18 @@ const MANIFEST_REQUIRED = ['layers', 'width', 'height'] as const;
199
200
  const LAYER_KEYS = ['name', 'filename', 'left', 'top', 'right', 'bottom', 'depth_median', 'depth_filename'] as const;
200
201
  const LAYER_REQUIRED = ['name', 'filename', 'left', 'top', 'right', 'bottom', 'depth_median'] as const;
201
202
 
203
+ export interface WrapperManifestReading {
204
+ path: string;
205
+ sha256: string;
206
+ givenAsDirectory: boolean;
207
+ }
208
+
209
+ /** Optional capture of consumed files for a primary assemble input. Paths retain their reader spelling. */
210
+ export interface WrapperReadings {
211
+ manifest?: WrapperManifestReading;
212
+ pngs: Array<{ path: string; sha256: string }>;
213
+ }
214
+
202
215
  /**
203
216
  * What the wrapper form's `depth_median` may be, as a refusal quotes it. A
204
217
  * See-through run writes a number; an input with no depth — a PSD exported by
@@ -227,10 +240,15 @@ const DEPTH_RULE = 'a finite number (See-through\'s depth, larger = further back
227
240
  export function readWrapperLayers(
228
241
  path: string, binding?: DepthBinding,
229
242
  sealedFiles?: ReadonlyMap<string, Buffer>,
243
+ readings?: WrapperReadings,
230
244
  ): LayerSet {
231
245
  const bytesOf = (file: string): Buffer => sealedFiles?.get(file) ?? readFileSync(file);
232
- const manifestPath = existsSync(path) && statSync(path).isDirectory() ? join(path, 'layers.json') : path;
246
+ const givenAsDirectory = existsSync(path) && statSync(path).isDirectory();
247
+ const manifestPath = givenAsDirectory ? join(path, 'layers.json') : path;
233
248
  const dir = dirname(manifestPath);
249
+ const recordDecode = readings === undefined ? undefined : (file: string, sha256: string): void => {
250
+ readings.pngs.push({ path: file, sha256 });
251
+ };
234
252
  const problems: Problem[] = [];
235
253
  const refuse = (code: string, object: string, detail: string): void => {
236
254
  problems.push({ code, object, detail });
@@ -241,7 +259,11 @@ export function readWrapperLayers(
241
259
  }
242
260
  let manifest: unknown;
243
261
  try {
244
- manifest = JSON.parse(bytesOf(manifestPath).toString('utf8'));
262
+ const bytes = bytesOf(manifestPath);
263
+ manifest = JSON.parse(bytes.toString('utf8'));
264
+ if (readings !== undefined) {
265
+ readings.manifest = { path: manifestPath, sha256: createHash('sha256').update(bytes).digest('hex'), givenAsDirectory };
266
+ }
245
267
  } catch (err) {
246
268
  refuse('LAYERS_MANIFEST_IS_JSON', manifestPath, `does not parse as JSON: ${(err as Error).message}`);
247
269
  refuseIfAny(problems);
@@ -371,6 +393,7 @@ export function readWrapperLayers(
371
393
  refuse('LAYERS_PNG_DECODES', `layer "${name}"`, (err as Error).message);
372
394
  return;
373
395
  }
396
+ recordDecode?.(present[0], createHash('sha256').update(bytes[0]).digest('hex'));
374
397
  if (pixels.width !== right - left || pixels.height !== bottom - top) {
375
398
  refuse(
376
399
  'LAYERS_PNG_MATCHES_BBOX',
@@ -379,8 +402,13 @@ export function readWrapperLayers(
379
402
  );
380
403
  return;
381
404
  }
405
+ const depthHint: DeferredDepthSource | undefined = !('depth_filename' in e) ? undefined : {
406
+ filename: e.depth_filename,
407
+ base: dir,
408
+ ...(recordDecode === undefined ? {} : { recordDecode }),
409
+ };
382
410
  if (hiddenOf !== null) {
383
- hidden.push({ name, of: hiddenOf.of, file: present[0], pixels, left, top, right, bottom, opaquePx: opaque(pixels), ...(!('depth_filename' in e) ? {} : { depthHint: { filename: e.depth_filename, base: dir } }) });
411
+ hidden.push({ name, of: hiddenOf.of, file: present[0], pixels, left, top, right, bottom, opaquePx: opaque(pixels), ...(depthHint === undefined ? {} : { depthHint }) });
384
412
  return;
385
413
  }
386
414
  read.push({
@@ -388,7 +416,7 @@ export function readWrapperLayers(
388
416
  tag: tag as LayerTagReading,
389
417
  file: present[0],
390
418
  pixels,
391
- ...(!('depth_filename' in e) ? {} : { depthHint: { filename: e.depth_filename, base: dir } }),
419
+ ...(depthHint === undefined ? {} : { depthHint }),
392
420
  left,
393
421
  top,
394
422
  right,
@@ -576,9 +604,9 @@ export function readPsdLayers(path: string): LayerSet {
576
604
  }
577
605
 
578
606
  /** Read whichever form `path` is: a `.psd` file, or a wrapper directory / `layers.json`. */
579
- export function readLayers(path: string, binding?: DepthBinding): LayerSet {
607
+ export function readLayers(path: string, binding?: DepthBinding, readings?: WrapperReadings): LayerSet {
580
608
  if (/\.psd$/i.test(path)) { const set = readPsdLayers(path); return binding === undefined ? set : bindDepthRun(set, binding.run, binding.config, binding.base); }
581
- if (existsSync(path) && (statSync(path).isDirectory() || basename(path) === 'layers.json')) return readWrapperLayers(path, binding);
609
+ if (existsSync(path) && (statSync(path).isDirectory() || basename(path) === 'layers.json')) return readWrapperLayers(path, binding, undefined, readings);
582
610
  refuseIfAny([
583
611
  {
584
612
  code: 'LAYERS_INPUT_KIND',