rig-review 2.8.0 → 2.10.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/docs/PARTS_VIEW.md +103 -66
- package/docs/REVIEW_PACKAGE.md +143 -9
- package/docs/STABILITY.md +6 -1
- package/package.json +3 -3
- package/src/build.ts +10 -2
- package/src/cli.ts +4 -5
- package/src/correction-handoff.ts +27 -4
- package/src/feedback-export.ts +1 -1
- package/src/front.ts +2 -1
- package/src/handoff.ts +1 -1
- package/src/job-act.ts +43 -23
- package/src/job-api.ts +23 -9
- package/src/job-checkpoint-evidence.ts +113 -0
- package/src/job-cli.ts +6 -2
- package/src/job-contract.ts +110 -13
- package/src/job-front.ts +123 -9
- package/src/job-host.ts +7 -0
- package/src/job-session.ts +73 -8
- package/src/job-source.ts +52 -7
- package/src/manifest.ts +9 -0
- package/src/open-workspace-launch.ts +2 -2
- package/src/open.ts +2 -1
- package/src/parts-comment-crops.ts +126 -31
- package/src/parts-comment.ts +321 -28
- package/src/parts-view.ts +485 -89
- package/src/stage-comment.ts +9 -1
- package/src/stage-parts.ts +5 -1
- package/src/versions.ts +7 -7
- package/web/catalog-en.ts +45 -1
- package/web/catalog-ko.ts +45 -1
- package/web/job-session.ts +682 -134
- package/web/parts-page.ts +217 -0
- package/web/parts-render.ts +26 -19
- package/web/parts-viewport-provider.ts +13 -1
- package/web/parts.css +13 -1
- package/web/parts.html +4 -38
- package/web/parts.ts +649 -267
- package/web/stage-comments.ts +79 -25
- package/web/styles.css +27 -5
- package/web/viewport-controller.ts +13 -4
package/src/job-source.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {checkpointEvidenceFields, checkpointEvidenceMetadata} from './job-checkpoint-evidence.ts';
|
|
1
2
|
import { randomUUID } from 'node:crypto';
|
|
2
3
|
import { type Dirent, lstatSync, readdirSync, realpathSync, type Stats } from 'node:fs';
|
|
3
4
|
import { mkdir, open, rm, writeFile } from 'node:fs/promises';
|
|
@@ -8,7 +9,7 @@ import {
|
|
|
8
9
|
JOB_PARTS_ENUMERATOR_RANGE,
|
|
9
10
|
} from './job-contract.ts';
|
|
10
11
|
import type {
|
|
11
|
-
JobFileIdentity, JobImageSetInput, JobInterviewDiagnostics, JobInterviewRecord, JobModelSourceBinding, JobPartsEnumerator, JobPartsFileReference, JobPartsIdentity, JobPlanIdentity, JobPublishRequest,
|
|
12
|
+
JobCheckpointEvidence, JobFileIdentity, JobImageSetInput, JobInterviewDiagnostics, JobInterviewRecord, JobModelSourceBinding, JobPartsEnumerator, JobPartsFileReference, JobPartsIdentity, JobPlanIdentity, JobPublishRequest,
|
|
12
13
|
JobSelector, JobSourceBinding, JobSubject,
|
|
13
14
|
OptionContext, OptionSource, PackageResultV3, PlanContext, PlanSource, ProjectRecord, PublishRequestV3,
|
|
14
15
|
RecordFreeze, RecordOptionResult, RecordPlanResult, RecordPublicationReader, RecordPublishedContext,
|
|
@@ -55,6 +56,7 @@ export interface JobRootIdentity {
|
|
|
55
56
|
* referenced-image enumeration belongs to the public Parts #1163 surface.
|
|
56
57
|
*/
|
|
57
58
|
export interface JobPublishedContext {
|
|
59
|
+
readonly checkpointEvidence?: readonly JobCheckpointEvidence[];
|
|
58
60
|
readonly imageSet?: JobImageSetInput;
|
|
59
61
|
readonly selector: JobSelector | null;
|
|
60
62
|
readonly plan: JobPlanIdentity | null;
|
|
@@ -71,6 +73,8 @@ export type JobPublicationReader = (input: {
|
|
|
71
73
|
}) => Promise<JobPublishedContext>;
|
|
72
74
|
|
|
73
75
|
export interface JobRetainedSource {
|
|
76
|
+
/** Private base preimage for evidence-aware durable validation, absent historically. */
|
|
77
|
+
readonly checkpointEvidencePackageHash?: string;
|
|
74
78
|
readonly root: JobRootIdentity;
|
|
75
79
|
readonly record: JobFileIdentity | null;
|
|
76
80
|
readonly seals: readonly JobFileIdentity[];
|
|
@@ -859,6 +863,7 @@ export async function prepareJobRecordSource(options: {
|
|
|
859
863
|
if (inventory.files.length > maxSourceFiles) {
|
|
860
864
|
throw new JobError('JOB_SOURCE_UNRETAINABLE');
|
|
861
865
|
}
|
|
866
|
+
checkpointEvidenceMetadata(root.path, inventory.checkpointEvidence);
|
|
862
867
|
const snapshotRoot = join(options.stateRoot, 'snapshots', randomUUID());
|
|
863
868
|
const seals: JobFileIdentity[] = [];
|
|
864
869
|
let snapshotIdentity: { dev: number; ino: number } | null = null;
|
|
@@ -910,6 +915,7 @@ export async function prepareJobRecordSource(options: {
|
|
|
910
915
|
assertRetainedSnapshotIntact(snapshotRoot, seals, snapshotIdentity, 'JOB_SOURCE_UNRETAINABLE');
|
|
911
916
|
assertEqualRecordContexts(inventory, retainedContext);
|
|
912
917
|
const decoded = decodeRetainedRecordProject(snapshotRoot, seals, result, retainedContext);
|
|
918
|
+
checkpointEvidenceMetadata(snapshotRoot, retainedContext.checkpointEvidence);
|
|
913
919
|
const source = parseRecordSource(
|
|
914
920
|
result.kind === 'option-set'
|
|
915
921
|
? buildRecordSource({
|
|
@@ -1052,6 +1058,14 @@ export async function verifyJobRecordSourceFresh(options: {
|
|
|
1052
1058
|
return freshSource;
|
|
1053
1059
|
}
|
|
1054
1060
|
|
|
1061
|
+
/** Preserve the existing composite preimage, conditionally appending the declaration. */
|
|
1062
|
+
function packageSourceDigest(packageSourceHash: string, record: JobFileIdentity | null,
|
|
1063
|
+
source: Pick<JobModelSourceBinding, 'selector' | 'plan' | 'parts'>, files: readonly JobFileIdentity[],
|
|
1064
|
+
evidence: {readonly checkpointEvidence?: readonly JobCheckpointEvidence[]}): string {
|
|
1065
|
+
return jobHash(JSON.stringify({schema: 'rig-review-job-source/2', packageSourceHash, record,
|
|
1066
|
+
selector: source.selector, plan: source.plan, parts: source.parts, files, ...evidence}));
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1055
1069
|
export async function prepareJobSource(options: {
|
|
1056
1070
|
readonly root: JobRootIdentity;
|
|
1057
1071
|
readonly stateRoot: string;
|
|
@@ -1168,6 +1182,10 @@ export async function prepareJobSource(options: {
|
|
|
1168
1182
|
}
|
|
1169
1183
|
if (requestDigest(context.selector) !== requestDigest(request.result.selector)) throw new JobError('JOB_SOURCE_MISMATCH');
|
|
1170
1184
|
const declared = publishedIdentities(context);
|
|
1185
|
+
const evidence = checkpointEvidenceFields(context, context.plan, context.subjects, declared);
|
|
1186
|
+
if (evidence.checkpointEvidence && context.imageSet !== undefined) throw new JobError(
|
|
1187
|
+
'JOB_SOURCE_MISMATCH', 'CHECKPOINT_EVIDENCE_INVALID');
|
|
1188
|
+
checkpointEvidenceMetadata(root.path, evidence.checkpointEvidence);
|
|
1171
1189
|
let review: Awaited<ReturnType<typeof loadReview>>;
|
|
1172
1190
|
try {
|
|
1173
1191
|
const target = checkedPath(root.path, request.result.path, lstatSync(join(root.path, request.result.path)).isDirectory());
|
|
@@ -1243,11 +1261,10 @@ export async function prepareJobSource(options: {
|
|
|
1243
1261
|
const originalIdentity = (file: { path: string; sha256: string } | null): JobFileIdentity | null => file && ({
|
|
1244
1262
|
path: rootRelative(root.path, resolve(review.root, file.path)), sha256: file.sha256,
|
|
1245
1263
|
});
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
})) : review.sourceHash,
|
|
1264
|
+
checkpointEvidenceMetadata(snapshotRoot, evidence.checkpointEvidence);
|
|
1265
|
+
const modelSource: Omit<JobModelSourceBinding, 'checkpointEvidence'> = {
|
|
1266
|
+
sourceHash: project || context.plan || context.parts ? packageSourceDigest(review.sourceHash, record,
|
|
1267
|
+
{selector: context.selector, plan: context.plan, parts: parts.identity}, seals, evidence) : review.sourceHash,
|
|
1251
1268
|
projectHash: project?.hash ?? null,
|
|
1252
1269
|
package: { id: review.manifest.id, revision: review.manifest.revision },
|
|
1253
1270
|
selector: context.selector,
|
|
@@ -1255,7 +1272,7 @@ export async function prepareJobSource(options: {
|
|
|
1255
1272
|
direction: originalIdentity(review.direction?.file ?? null),
|
|
1256
1273
|
optionSet: null, appliedResult: null, plan: context.plan, parts: parts.identity,
|
|
1257
1274
|
};
|
|
1258
|
-
let source: JobSourceBinding = modelSource;
|
|
1275
|
+
let source: JobSourceBinding = {...modelSource, ...evidence};
|
|
1259
1276
|
if (imageSet) {
|
|
1260
1277
|
if (modelSource.model || modelSource.selector) throw new JobError('JOB_IMAGE_SET_INVALID');
|
|
1261
1278
|
const {model, selector, ...common} = modelSource;
|
|
@@ -1282,6 +1299,7 @@ export async function prepareJobSource(options: {
|
|
|
1282
1299
|
: null;
|
|
1283
1300
|
const prepared: JobRetainedSource = {
|
|
1284
1301
|
root, record, seals, snapshotRoot, snapshotIdentity,
|
|
1302
|
+
...(evidence.checkpointEvidence ? {checkpointEvidencePackageHash: review.sourceHash} : {}),
|
|
1285
1303
|
manifestPath: retained.manifestPath,
|
|
1286
1304
|
source,
|
|
1287
1305
|
instanceKey: openKey({ mode: 'single', p: boundReview, inputs: { input: review.manifestPath },
|
|
@@ -1303,6 +1321,7 @@ export async function prepareJobSource(options: {
|
|
|
1303
1321
|
};
|
|
1304
1322
|
await options.afterSnapshot?.();
|
|
1305
1323
|
assertJobSourceCurrent(prepared);
|
|
1324
|
+
if (source.checkpointEvidence) assertRetainedSnapshotIntact(snapshotRoot, seals, snapshotIdentity);
|
|
1306
1325
|
return prepared;
|
|
1307
1326
|
} catch (error) {
|
|
1308
1327
|
if (snapshotIdentity) await removeOwnedJobSnapshot(options.stateRoot, {snapshotRoot, ...snapshotIdentity});
|
|
@@ -1310,3 +1329,29 @@ export async function prepareJobSource(options: {
|
|
|
1310
1329
|
throw new JobError('JOB_SOURCE_MISMATCH');
|
|
1311
1330
|
}
|
|
1312
1331
|
}
|
|
1332
|
+
|
|
1333
|
+
/** Authenticate the optional extension without opening live files or reclaimed snapshots. */
|
|
1334
|
+
export function assertStoredCheckpointEvidence(retained: JobRetainedSourceV3): void {
|
|
1335
|
+
if (!retained.source || typeof retained.source !== 'object' || Array.isArray(retained.source)) {
|
|
1336
|
+
throw new JobError('JOB_SOURCE_MISMATCH');
|
|
1337
|
+
}
|
|
1338
|
+
const hasEvidence = 'checkpointEvidence' in retained.source;
|
|
1339
|
+
if (isRetainedRecordSource(retained)) {
|
|
1340
|
+
const parsed = parseRecordSource(retained.source);
|
|
1341
|
+
if (!hasEvidence && !('checkpointEvidence' in retained.context)) return;
|
|
1342
|
+
const context = parseRecordPublishedContext(retained.context, retained.result, retained.record);
|
|
1343
|
+
if (requestDigest(parsed.checkpointEvidence ?? null) !== requestDigest(context.checkpointEvidence ?? null) ||
|
|
1344
|
+
requestDigest(parsed.subjects) !== requestDigest(retained.subjects) ||
|
|
1345
|
+
requestDigest(parsed.files) !== requestDigest(retained.seals)) throw new JobError('JOB_SOURCE_MISMATCH');
|
|
1346
|
+
return;
|
|
1347
|
+
}
|
|
1348
|
+
if (!hasEvidence && !('checkpointEvidencePackageHash' in retained)) return;
|
|
1349
|
+
const source = retained.source;
|
|
1350
|
+
if (!hasEvidence || source.subject === 'image-set' || !retained.record) throw new JobError('JOB_SOURCE_MISMATCH');
|
|
1351
|
+
const evidence = checkpointEvidenceFields(source, source.plan, retained.subjects, retained.seals);
|
|
1352
|
+
const packageSourceHash = jobSha(retained.checkpointEvidencePackageHash);
|
|
1353
|
+
const expected = packageSourceDigest(packageSourceHash, retained.record, source, retained.seals, evidence);
|
|
1354
|
+
if (expected !== source.sourceHash || requestDigest(evidence.checkpointEvidence) !== requestDigest(source.checkpointEvidence)) {
|
|
1355
|
+
throw new JobError('JOB_SOURCE_MISMATCH');
|
|
1356
|
+
}
|
|
1357
|
+
}
|
package/src/manifest.ts
CHANGED
|
@@ -9,6 +9,8 @@ import { readFile, realpath, stat, lstat, readdir } from 'node:fs/promises';
|
|
|
9
9
|
import { createReadStream } from 'node:fs';
|
|
10
10
|
import { basename, dirname, isAbsolute, relative, resolve, posix } from 'node:path';
|
|
11
11
|
import { isBuildRoot, parseHandoffDeclaration, resolveHandoff, type Handoff, type HandoffDeclaration, type HandoffFlags, type HandoffRecord } from './handoff.ts';
|
|
12
|
+
import { parsePanelComposition, type JobPanelComposition } from './job-contract.ts';
|
|
13
|
+
export { isPanelComponent, parsePanelComposition } from './job-contract.ts';
|
|
12
14
|
|
|
13
15
|
export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
|
|
14
16
|
export interface Reference { id: string; label: string; type: 'image' | 'video' | 'pose'; path: string; width?: number; height?: number }
|
|
@@ -22,6 +24,7 @@ export interface ReviewManifest {
|
|
|
22
24
|
audio: { clips: { id: string; label?: string; path: string }[]; cues: { id: string; clip: string; time: number; animation?: string }[] };
|
|
23
25
|
/** Optional producer handoff (#101): package-relative literal paths; checked when the package loads. */
|
|
24
26
|
producer?: HandoffDeclaration;
|
|
27
|
+
panels?: JobPanelComposition;
|
|
25
28
|
}
|
|
26
29
|
export interface ReviewedSource { readonly packageRevision:string; readonly viewerVersion:string; readonly runtimeVersion:string; readonly rig:{readonly path:string;readonly sha256:string}|null; readonly motion:{readonly path:string;readonly sha256:string}|null; readonly handoff?:HandoffRecord }
|
|
27
30
|
export interface ReviewPackage { direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; root: string; manifestPath: string; manifest: ReviewManifest; sourceHash: string; reviewedSource:ReviewedSource; files: Set<string>; report:ReportSeeds|null; feedbackCatalog:FeedbackCatalog;
|
|
@@ -64,6 +67,11 @@ export async function safeFile(root: string, path: string): Promise<string> {
|
|
|
64
67
|
export function parseManifest(input: unknown): ReviewManifest {
|
|
65
68
|
const m = object(input, 'review'); if (m.schema !== 'rig-review/1') fail('schema', 'rig-review/1');
|
|
66
69
|
const audio = m.audio === undefined ? {} : object(m.audio, 'audio');
|
|
70
|
+
let panels: JobPanelComposition | undefined;
|
|
71
|
+
if (m.panels !== undefined) {
|
|
72
|
+
try { panels = parsePanelComposition(m.panels); }
|
|
73
|
+
catch { panels = undefined; }
|
|
74
|
+
}
|
|
67
75
|
const manifest: ReviewManifest = {
|
|
68
76
|
schema: 'rig-review/1', id: id(m.id, 'id'), title: string(m.title, 'title'), revision: string(m.revision, 'revision'),
|
|
69
77
|
model: m.model === undefined ? undefined : packagePath(m.model, 'model'),
|
|
@@ -76,6 +84,7 @@ export function parseManifest(input: unknown): ReviewManifest {
|
|
|
76
84
|
authoring:list(m.authoring,'authoring',(v,f)=>({label:string(v.label,f+'.label'),path:packagePath(v.path,f+'.path')})),
|
|
77
85
|
axes:list(m.axes,'axes',(v,f)=>({id:id(v.id,f+'.id'),label:string(v.label,f+'.label'),animation:string(v.animation,f+'.animation'),min:number(v.min,f+'.min',-Number.MAX_VALUE),max:number(v.max,f+'.max',-Number.MAX_VALUE)})),
|
|
78
86
|
...(m.producer===undefined?{}:{producer:parseHandoffDeclaration(m.producer)}),
|
|
87
|
+
...(panels===undefined?{}:{panels}),
|
|
79
88
|
audio:{clips:list(audio.clips,'audio.clips',(v,f)=>({id:id(v.id,f+'.id'),label:optionalString(v.label,f+'.label'),path:packagePath(v.path,f+'.path')})),cues:list(audio.cues,'audio.cues',(v,f)=>({id:id(v.id,f+'.id'),clip:string(v.clip,f+'.clip'),time:number(v.time,f+'.time'),animation:optionalString(v.animation,f+'.animation')}))}
|
|
80
89
|
};
|
|
81
90
|
if(manifest.model&&!manifest.model.endsWith('.model.json'))fail('model','compiled model path ending .model.json (the play runtime input)');
|
|
@@ -2,7 +2,7 @@ import {spawn} from 'node:child_process';
|
|
|
2
2
|
import {randomUUID} from 'node:crypto';
|
|
3
3
|
import {open, readFile, unlink} from 'node:fs/promises';
|
|
4
4
|
import {join} from 'node:path';
|
|
5
|
-
import {appRoot} from './build.ts';
|
|
5
|
+
import {appRoot, playBuildConditions} from './build.ts';
|
|
6
6
|
import {frontPort} from './front.ts';
|
|
7
7
|
import {acquireClaim, defaultStateDir, openFingerprint, prepareOpenTarget, readOpenStatus, releaseClaim,
|
|
8
8
|
type OpenInputs, type OpenOptions} from './open.ts';
|
|
@@ -61,7 +61,7 @@ export async function openWorkspace(inputs: readonly OpenInputs[], options: Open
|
|
|
61
61
|
const logPath = join(directory, nonce + '.log');
|
|
62
62
|
const log = await open(logPath, 'a', 0o600);
|
|
63
63
|
try {
|
|
64
|
-
child = spawn(process.execPath, [join(appRoot, 'src/open-workspace-worker.ts'), request],
|
|
64
|
+
child = spawn(process.execPath, [...playBuildConditions().map(c => `--conditions=${c}`), join(appRoot, 'src/open-workspace-worker.ts'), request],
|
|
65
65
|
{cwd: directory, detached: true, stdio: ['ignore', log.fd, log.fd], env: process.env});
|
|
66
66
|
child.unref();
|
|
67
67
|
} finally {await log.close();}
|
package/src/open.ts
CHANGED
|
@@ -16,6 +16,7 @@ import {startCompareServer} from './compare-server.ts';
|
|
|
16
16
|
import {selectAnimation,AnimationSelectionError,type AnimationSelection} from './animation-selection.ts';
|
|
17
17
|
import {capabilityHeader,capabilityPattern,type OpenIdentity} from './open-protocol.ts';
|
|
18
18
|
import {ensureFront,frontPort} from './front.ts';
|
|
19
|
+
import {playBuildConditions} from './build.ts';
|
|
19
20
|
import {playPackagePath} from './versions.ts';
|
|
20
21
|
import {HandoffError,HANDOFF_FLAGS,isBuildRoot,type HandoffFlags,type HandoffRecord} from './handoff.ts';
|
|
21
22
|
import {stateDirInside,stateRoots} from './state-dir.ts';
|
|
@@ -160,7 +161,7 @@ async function ensureWorker(p:OpenPackage,key:string,fingerprint:string,stateDir
|
|
|
160
161
|
const row=await reuse();if(row)return {row,reused:true};
|
|
161
162
|
const identity:OpenIdentity={key,contentHash:p.contentHash,nonce,fingerprint};request=join(canonicalControl,`${key}.${nonce}.request.json`);const log=join(canonicalControl,`${key}.${nonce}.log`);
|
|
162
163
|
const spec:WorkerRequest={schema:'rig-review-open-request/1',inputs:p.inputs,identity,stateDir,registry,request,idleMs,...(graceMs!==undefined?{graceMs}:{}),cwd,...(viewOnly?{viewOnly:true}:{}),...(p.inputs.control?{controlToken:randomUUID()}:{} )};await writeFile(request,JSON.stringify(spec),{mode:0o600,flag:'wx'});
|
|
163
|
-
const logHandle=await openFile(log,'a',0o600);let child;try{child=spawn(process.execPath,[join(appRoot,'src/open-worker.ts'),request],{cwd:canonicalControl,detached:true,stdio:['ignore',logHandle.fd,logHandle.fd],env:process.env});spawned=child;child.unref();}finally{await logHandle.close();}
|
|
164
|
+
const logHandle=await openFile(log,'a',0o600);let child;try{child=spawn(process.execPath,[...playBuildConditions().map(c=>`--conditions=${c}`),join(appRoot,'src/open-worker.ts'),request],{cwd:canonicalControl,detached:true,stdio:['ignore',logHandle.fd,logHandle.fd],env:process.env});spawned=child;child.unref();}finally{await logHandle.close();}
|
|
164
165
|
let exited:string|undefined;child.on('error',error=>{exited=error.message;});child.on('exit',(code,signal)=>{exited=`exit ${code} ${signal??''}`;});
|
|
165
166
|
while(performance.now()<deadline){const record=await reuse();if(record){handedOff=true;return {row:record,reused:false};}if(exited)throw new Error(`OPEN_START: ${exited}; worker log ${log}`);await sleep(30);}throw new Error(`OPEN_TIMEOUT: worker did not become ready; log ${log}`);
|
|
166
167
|
}finally{if(spawned&&!handedOff&&spawned.exitCode===null&&spawned.signalCode===null)spawned.kill('SIGTERM');await releaseClaim(claim,nonce);if(request)await unlink(request).catch(e=>{if(e.code!=='ENOENT')throw e;});}
|
|
@@ -1,33 +1,128 @@
|
|
|
1
1
|
/** Native evidence is cut from the bound original PNG, never from a displayed alpha mask. */
|
|
2
|
-
import {createHash} from 'node:crypto';
|
|
3
|
-
import {readFile} from 'node:fs/promises';
|
|
4
|
-
import {PNG} from 'pngjs';
|
|
5
|
-
import {
|
|
6
|
-
import {validatePngCrop,storePngCrop,readPngCrop} from './comment-crops.ts';
|
|
7
|
-
import {assertPartsUnchanged,partsDifference,verdictSource,type PartsViewPackage} from './parts-view.ts';
|
|
8
|
-
|
|
9
|
-
export
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
return
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { PNG } from 'pngjs';
|
|
5
|
+
import { parsePartsIssue, assertPartsIssueBinding, type PartsIssue } from './parts-comment.ts';
|
|
6
|
+
import { validatePngCrop, storePngCrop, readPngCrop, type PngCrop } from './comment-crops.ts';
|
|
7
|
+
import { assertPartsUnchanged, partsDifference, verdictSource, type PartsViewPackage } from './parts-view.ts';
|
|
8
|
+
|
|
9
|
+
export interface PartsCommentBindingOptions {
|
|
10
|
+
readonly sourceHash?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function preparePartsComment(
|
|
14
|
+
pkg: PartsViewPackage,
|
|
15
|
+
raw: unknown,
|
|
16
|
+
requireNative = false,
|
|
17
|
+
options?: PartsCommentBindingOptions,
|
|
18
|
+
): Promise<PartsIssue> {
|
|
19
|
+
return resolvePartsComment(pkg, raw, requireNative, true, false, options);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function validateStoredPartsComment(
|
|
23
|
+
pkg: PartsViewPackage,
|
|
24
|
+
raw: unknown,
|
|
25
|
+
allowLegacy = false,
|
|
26
|
+
options?: PartsCommentBindingOptions,
|
|
27
|
+
): Promise<PartsIssue> {
|
|
28
|
+
return resolvePartsComment(pkg, raw, true, false, allowLegacy, options);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function resolvePartsComment(
|
|
32
|
+
pkg: PartsViewPackage,
|
|
33
|
+
raw: unknown,
|
|
34
|
+
requireNative: boolean,
|
|
35
|
+
persist: boolean,
|
|
36
|
+
allowLegacy = false,
|
|
37
|
+
options?: PartsCommentBindingOptions,
|
|
38
|
+
): Promise<PartsIssue> {
|
|
39
|
+
const c = parsePartsIssue(raw, requireNative, allowLegacy, persist && !requireNative);
|
|
40
|
+
if (pkg.mode !== 'parts') {
|
|
41
|
+
throw new Error('PARTS_COMMENT_UNAVAILABLE: original part image required');
|
|
42
|
+
}
|
|
43
|
+
const itemMap = new Map<
|
|
44
|
+
string,
|
|
45
|
+
{ name: string; index: number; x: number; y: number; w: number; h: number; imageHash: string; path: string }
|
|
46
|
+
>();
|
|
47
|
+
for (const item of pkg.items) {
|
|
48
|
+
const path = pkg.imagePaths[item.index];
|
|
49
|
+
const file = path ? pkg.files.find(f => f.abs === path) : undefined;
|
|
50
|
+
if (!path || !file) {
|
|
51
|
+
throw new Error('PARTS_COMMENT_UNAVAILABLE: bound original PNG required');
|
|
52
|
+
}
|
|
53
|
+
itemMap.set(item.name, { ...item, imageHash: file.sha256, path });
|
|
54
|
+
}
|
|
55
|
+
const expectedSourceHash = options?.sourceHash ?? verdictSource(pkg).sha256;
|
|
56
|
+
assertPartsIssueBinding(c, itemMap, expectedSourceHash);
|
|
57
|
+
if (c.view.comparison?.mode === 'overlay' && !pkg.painting) {
|
|
58
|
+
throw new Error('PARTS_COMPARISON_UNAVAILABLE: original painting required');
|
|
59
|
+
}
|
|
60
|
+
if (c.view.comparison?.mode === 'difference') {
|
|
61
|
+
for (const part of c.parts) {
|
|
62
|
+
const item = itemMap.get(part.name)!;
|
|
63
|
+
await partsDifference(pkg, item.index, c.view.comparison.threshold, c.view.footprints);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const partBuffers = new Map<string, Buffer>();
|
|
67
|
+
for (const part of c.parts) {
|
|
68
|
+
const item = itemMap.get(part.name)!;
|
|
69
|
+
const bytes = await readFile(item.path);
|
|
70
|
+
if (createHash('sha256').update(bytes).digest('hex') !== item.imageHash) {
|
|
71
|
+
throw new Error('PARTS_COMMENT_STALE_SOURCE: original PNG changed');
|
|
72
|
+
}
|
|
73
|
+
partBuffers.set(part.name, bytes);
|
|
74
|
+
}
|
|
75
|
+
await assertPartsUnchanged(pkg);
|
|
76
|
+
if (c.crop.png !== undefined) {
|
|
77
|
+
validatePngCrop(c.crop as PngCrop);
|
|
78
|
+
}
|
|
79
|
+
if (c.view.mode !== 'item') {
|
|
80
|
+
if (persist && c.crop.png !== undefined) {
|
|
81
|
+
await storePngCrop(c.crop as PngCrop);
|
|
82
|
+
} else {
|
|
83
|
+
await readPngCrop(c.crop);
|
|
84
|
+
}
|
|
85
|
+
await assertPartsUnchanged(pkg);
|
|
86
|
+
return { ...c, nativeCrop: null };
|
|
87
|
+
}
|
|
88
|
+
const primary = itemMap.get(c.parts[0]!.name)!;
|
|
89
|
+
const r = c.imageRegion!;
|
|
90
|
+
if (r.width * r.height > 16777216) {
|
|
91
|
+
throw new Error('PARTS_COMMENT_CROP_LIMIT: native crop exceeds 16 million pixels');
|
|
92
|
+
}
|
|
93
|
+
const bytes = partBuffers.get(primary.name)!;
|
|
94
|
+
const original = PNG.sync.read(bytes);
|
|
95
|
+
if (original.width !== primary.w || original.height !== primary.h) {
|
|
96
|
+
throw new Error('PARTS_COMMENT_IMAGE_SIZE: original dimensions differ from placement');
|
|
97
|
+
}
|
|
98
|
+
const native = new PNG({ width: r.width, height: r.height });
|
|
99
|
+
for (let y = 0; y < r.height; y++) {
|
|
100
|
+
original.data.copy(
|
|
101
|
+
native.data,
|
|
102
|
+
y * r.width * 4,
|
|
103
|
+
((r.y + y) * original.width + r.x) * 4,
|
|
104
|
+
((r.y + y) * original.width + r.x + r.width) * 4,
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
if (requireNative) {
|
|
108
|
+
const stored = await readPngCrop(c.nativeCrop!);
|
|
109
|
+
const decoded = PNG.sync.read(stored);
|
|
110
|
+
if (decoded.width !== r.width || decoded.height !== r.height || !decoded.data.equals(native.data)) {
|
|
111
|
+
throw new Error('PARTS_COMMENT_NATIVE_CROP_TAMPERED: native crop differs from bound original');
|
|
112
|
+
}
|
|
113
|
+
if (persist && c.crop.png !== undefined) {
|
|
114
|
+
await storePngCrop(c.crop as PngCrop);
|
|
115
|
+
} else {
|
|
116
|
+
await readPngCrop(c.crop);
|
|
117
|
+
}
|
|
118
|
+
await assertPartsUnchanged(pkg);
|
|
119
|
+
return c;
|
|
120
|
+
}
|
|
121
|
+
const png = PNG.sync.write(native);
|
|
122
|
+
const sha256 = createHash('sha256').update(png).digest('hex');
|
|
123
|
+
const nativeCrop = { path: `comment-crops/${sha256}.png`, sha256, width: r.width, height: r.height };
|
|
124
|
+
await storePngCrop(c.crop as PngCrop);
|
|
125
|
+
await storePngCrop({ ...nativeCrop, png: 'data:image/png;base64,' + png.toString('base64') });
|
|
126
|
+
await assertPartsUnchanged(pkg);
|
|
127
|
+
return { ...c, nativeCrop };
|
|
33
128
|
}
|