@rig-c/parts 1.60.1 → 1.60.2
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/README.md +4 -1
- package/cli.ts +7 -22
- package/docs/AUTHORING.md +122 -9
- package/docs/STABILITY.md +20 -3
- package/package.json +3 -1
- package/src/build.ts +16 -4
- package/src/check.ts +41 -30
- package/src/comfy/painting.ts +2 -1
- package/src/config.ts +74 -14
- package/src/configwrite.ts +56 -18
- package/src/diagnostics.ts +3 -2
- package/src/limblayout.ts +6 -4
- package/src/limbs.ts +18 -3
- package/src/limbslots.ts +17 -6
- package/src/propose.ts +4 -3
- package/src/remesh.ts +31 -7
- package/src/retune.ts +10 -8
- package/src/rig.ts +11 -5
- package/src/structure.ts +2 -1
- package/tools/alternate-cli.ts +25 -0
- package/tools/build-process.ts +206 -0
package/src/limbslots.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* ownership boundary: descendants belong to the first segment encountered up
|
|
5
5
|
* their parent graph, so a nested limb does not become its ancestor's rider.
|
|
6
6
|
*/
|
|
7
|
+
import { refuseIfAny } from './errors.ts';
|
|
7
8
|
import type { Limb } from './config.ts';
|
|
8
9
|
import type { RigSpec } from './rig.ts';
|
|
9
10
|
|
|
@@ -19,6 +20,8 @@ export interface LimbSlotOwner {
|
|
|
19
20
|
|
|
20
21
|
export interface LimbSlotLayout {
|
|
21
22
|
slots: RigSpec['slots'];
|
|
23
|
+
/** Explicitly retained generated families; omitted for historical output. */
|
|
24
|
+
ungathered?: readonly string[];
|
|
22
25
|
owners: LimbSlotOwner[];
|
|
23
26
|
/** First segment SLOT encountered in setup order, not anatomical segment 0. */
|
|
24
27
|
anchors: Array<{ limb: string; slot: string | null }>;
|
|
@@ -33,18 +36,20 @@ export interface LimbSlotLayout {
|
|
|
33
36
|
* Even a listed zero-weight reference is read, as in meshBoundBones: there is
|
|
34
37
|
* no epsilon or first-weight rule. Mixed/outside/empty bindings stay outside
|
|
35
38
|
* the gathered blocks, with their classification returned for inspection.
|
|
39
|
+
* Declared opt-outs retain their authored family without changing ownership.
|
|
36
40
|
* Their mutual order is preserved; complete closure is not promised across a
|
|
37
|
-
* nonexclusive segment or rider.
|
|
41
|
+
* nonexclusive segment or rider. An opt-out on a non-rider is refused by name.
|
|
38
42
|
*/
|
|
39
43
|
export function coalesceLimbSlots(
|
|
40
44
|
limbs: Readonly<Record<string, Limb>> | undefined,
|
|
41
45
|
bones: RigSpec['bones'],
|
|
42
46
|
slots: RigSpec['slots'],
|
|
43
47
|
skin: RigSpec['skins']['default'],
|
|
48
|
+
retain: readonly { part: string; object: string; slots: readonly string[] }[] = [],
|
|
44
49
|
): LimbSlotLayout {
|
|
45
|
-
if (limbs === undefined || Object.keys(limbs).length === 0) return { slots, owners: [], anchors: [] };
|
|
50
|
+
if (retain.length === 0 && (limbs === undefined || Object.keys(limbs).length === 0)) return { slots, owners: [], anchors: [] };
|
|
46
51
|
const seeds = new Map<string, string[]>();
|
|
47
|
-
for (const [name, limb] of Object.entries(limbs)) {
|
|
52
|
+
for (const [name, limb] of Object.entries(limbs ?? {})) {
|
|
48
53
|
for (const s of limb.segments) {
|
|
49
54
|
const names = seeds.get(s.bone) ?? [];
|
|
50
55
|
if (!names.includes(name)) names.push(name);
|
|
@@ -83,7 +88,13 @@ export function coalesceLimbSlots(
|
|
|
83
88
|
const kind = exclusive && mine.size === 1 && outside.size === 0 ? 'exclusive' : mine.size > 0 ? 'nonexclusive' : bindings.some((b) => b.bones.length > 0) ? 'outside' : 'unbound';
|
|
84
89
|
return { slot: slot.name, kind, limb: kind === 'exclusive' ? [...mine][0] : null, bindings, limbs: [...mine], outside: [...outside] };
|
|
85
90
|
});
|
|
86
|
-
const
|
|
91
|
+
const segments = new Set(Object.values(limbs ?? {}).flatMap((limb) => limb.segments.map((s) => s.part)));
|
|
92
|
+
refuseIfAny(retain.flatMap((r) => {
|
|
93
|
+
const owner = owners.find((o) => o.slot === r.part);
|
|
94
|
+
return owner?.kind === 'exclusive' && !segments.has(r.part) ? [] : [{ code: 'RIG_GATHER_RIDER', object: r.object, detail: `part "${r.part}" is ${segments.has(r.part) ? 'a declared limb segment' : owner?.kind ?? 'absent'}; an exclusively bound non-segment limb rider is required to opt out of gathering — remove gather or bind this rider exclusively to one declared limb` }];
|
|
95
|
+
}));
|
|
96
|
+
const ungathered = new Set(retain.flatMap((r) => [...r.slots]));
|
|
97
|
+
const anchors = Object.entries(limbs ?? {}).map(([name, limb]) => ({ limb: name, slot: slots.find((s) => limb.segments.some((sg) => sg.part === s.name))?.name ?? null }));
|
|
87
98
|
const at = new Map<string, string[]>();
|
|
88
99
|
const anchored = new Set<string>();
|
|
89
100
|
for (const anchor of anchors) {
|
|
@@ -91,7 +102,7 @@ export function coalesceLimbSlots(
|
|
|
91
102
|
at.set(anchor.slot, [...(at.get(anchor.slot) ?? []), anchor.limb]);
|
|
92
103
|
anchored.add(anchor.limb);
|
|
93
104
|
}
|
|
94
|
-
const owned = new Map(owners.map((o) => [o.slot, o.limb !== null && anchored.has(o.limb) ? o.limb : null]));
|
|
105
|
+
const owned = new Map(owners.map((o) => [o.slot, o.limb !== null && anchored.has(o.limb) && !ungathered.has(o.slot) ? o.limb : null]));
|
|
95
106
|
const gathered = new Map<string, RigSpec['slots']>();
|
|
96
107
|
for (const slot of slots) {
|
|
97
108
|
const name = owned.get(slot.name);
|
|
@@ -102,5 +113,5 @@ export function coalesceLimbSlots(
|
|
|
102
113
|
for (const name of at.get(slot.name) ?? []) reordered.push(...(gathered.get(name) ?? []));
|
|
103
114
|
if (owned.get(slot.name) === null) reordered.push(slot);
|
|
104
115
|
}
|
|
105
|
-
return { slots: reordered.every((s, i) => s === slots[i]) ? slots : reordered, owners, anchors };
|
|
116
|
+
return { slots: reordered.every((s, i) => s === slots[i]) ? slots : reordered, owners, anchors, ...(ungathered.size === 0 ? {} : { ungathered: [...ungathered] }) };
|
|
106
117
|
}
|
package/src/propose.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { regionBone, type RegionSpec } from './config.ts';
|
|
1
2
|
/**
|
|
2
3
|
* The propose stage: bone origins, mesh candidate lists, regions and a default
|
|
3
4
|
* idle, read off the assembled parts — and the overlay a person or an agent
|
|
@@ -4885,7 +4886,7 @@ export function coverageOutcome(c: BoneCoverage): CoverageOutcome {
|
|
|
4885
4886
|
*/
|
|
4886
4887
|
export function lint(
|
|
4887
4888
|
P: PartSet,
|
|
4888
|
-
spec: { bones: readonly BoneEntry[]; meshes: Readonly<Record<string, MeshSpec>>; regions?: Readonly<Record<string,
|
|
4889
|
+
spec: { bones: readonly BoneEntry[]; meshes: Readonly<Record<string, MeshSpec>>; regions?: Readonly<Record<string, RegionSpec>>; motion?: SkeletonSections['motion']; constraints?: readonly ConfigConstraint[]; limbs?: Readonly<Record<string, Limb>>; stops?: readonly ConfigStop[] },
|
|
4889
4890
|
joints?: RigJoints,
|
|
4890
4891
|
drafted: readonly DraftLintFinding[] = [],
|
|
4891
4892
|
): LintResult {
|
|
@@ -5391,7 +5392,7 @@ function findingBones(f: LintFinding, bones: readonly BoneEntry[]): string[] {
|
|
|
5391
5392
|
* art by design: its role is the reason, never a finding.
|
|
5392
5393
|
*/
|
|
5393
5394
|
function lintCoverage(
|
|
5394
|
-
spec: { bones: readonly BoneEntry[]; meshes: Readonly<Record<string, MeshSpec>>; regions?: Readonly<Record<string,
|
|
5395
|
+
spec: { bones: readonly BoneEntry[]; meshes: Readonly<Record<string, MeshSpec>>; regions?: Readonly<Record<string, RegionSpec>>; motion?: SkeletonSections['motion']; constraints?: readonly ConfigConstraint[] },
|
|
5395
5396
|
byName: ReadonlyMap<string, ExpandedBone>,
|
|
5396
5397
|
read: ReadonlyMap<string, string[]>,
|
|
5397
5398
|
findings: readonly LintFinding[],
|
|
@@ -5433,7 +5434,7 @@ function lintCoverage(
|
|
|
5433
5434
|
else if (chain !== null && sp === chain && unknownMeshes.includes(mname)) partless.push(`${at} (mesh ${JSON.stringify(mname)})`);
|
|
5434
5435
|
});
|
|
5435
5436
|
}
|
|
5436
|
-
const regions = Object.entries(spec.regions ?? {}).filter(([, b]) => b === bone).map(([part]) => `regions.${part}`);
|
|
5437
|
+
const regions = Object.entries(spec.regions ?? {}).filter(([, b]) => regionBone(b) === bone).map(([part]) => `regions.${part}`);
|
|
5437
5438
|
const stills = Object.entries(spec.motion?.blink?.still ?? {}).filter(([, st]) => st.bone === bone).map(([part]) => `motion.blink.still.${part}`);
|
|
5438
5439
|
const s = (list: readonly string[], one: string, many: string): string => (list.length === 1 ? one : many);
|
|
5439
5440
|
if (single.length > 0) why.push(`named as a single bone by ${single.join(', ')}: a single bone has no links, and the off-art check reads only the links <segment><digits> of a chain`);
|
package/src/remesh.ts
CHANGED
|
@@ -183,7 +183,7 @@ export interface RemeshProvenance {
|
|
|
183
183
|
| { part: string; mesh: unknown; mesh_sha256: string; idle_keys: IdleKeys; page_edges: PageEdges; pack_shape: PackShape }
|
|
184
184
|
| { part: string; delta: MeshEditDocument; delta_sha256: string; ops: number; applied: Omit<DeltaApplied, 'ops'>; idle_keys: IdleKeys; page_edges: PageEdges; pack_shape: PackShape };
|
|
185
185
|
versions: RemeshVersions;
|
|
186
|
-
input: { rig: HashRow[]; config_sha256: string; parts_json_sha256: string };
|
|
186
|
+
input: { rig: HashRow[]; config_sha256: string; parts_json_sha256: string; provenance?: ParentProvenance[] };
|
|
187
187
|
baseline: { reproduced: string[]; not_compared: string };
|
|
188
188
|
target: { before: MeshCounts; after: MeshCounts };
|
|
189
189
|
preserved: { identical: string[]; spliced: string[] };
|
|
@@ -223,6 +223,28 @@ export function hashRows(tree: FileTree): HashRow[] {
|
|
|
223
223
|
return [...tree].map(([path, bytes]) => ({ path, bytes: bytes.length, sha256: sha256(bytes) }));
|
|
224
224
|
}
|
|
225
225
|
|
|
226
|
+
/** A previous root record, recoverable byte for byte at its content-addressed path (issue #531). */
|
|
227
|
+
export interface ParentProvenance extends HashRow { source: 'remesh.json' | 'retune.json' }
|
|
228
|
+
|
|
229
|
+
/** Keep prior records before replacing the current root record; no rig, motion or hold input is changed. */
|
|
230
|
+
export function carryProvenance(input: FileTree, revision: FileTree, replacing: 'remesh.json' | 'retune.json'): { revision: FileTree; parents: ParentProvenance[] } {
|
|
231
|
+
const next = new Map(revision), parents: ParentProvenance[] = [];
|
|
232
|
+
for (const source of ['remesh.json', 'retune.json'] as const) {
|
|
233
|
+
const bytes = input.get(source);
|
|
234
|
+
if (bytes === undefined) continue;
|
|
235
|
+
const digest = sha256(bytes), path = `provenance/${source.slice(0, -5)}-${digest}.json`;
|
|
236
|
+
const existing = next.get(path);
|
|
237
|
+
if (existing !== undefined && !bytesEqual(existing, bytes)) {
|
|
238
|
+
throw new PartsError([{ code: replacing === 'remesh.json' ? 'REMESH_PRESERVED' : 'RETUNE_PRESERVED', object: path,
|
|
239
|
+
detail: `already holds ${existing.length} bytes sha256 ${sha256(existing)}; preserving parent ${source} requires ${bytes.length} bytes sha256 ${digest} at that path, so nothing is written` }]);
|
|
240
|
+
}
|
|
241
|
+
next.set(path, bytes);
|
|
242
|
+
parents.push({ source, path, bytes: bytes.length, sha256: digest });
|
|
243
|
+
}
|
|
244
|
+
next.delete(replacing); // The new root record cannot list a hash of itself.
|
|
245
|
+
return { revision: new Map([...next].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)), parents };
|
|
246
|
+
}
|
|
247
|
+
|
|
226
248
|
const text = (b: Uint8Array): string => new TextDecoder().decode(b);
|
|
227
249
|
const bytesOf = (s: string): Uint8Array => new TextEncoder().encode(s);
|
|
228
250
|
|
|
@@ -986,7 +1008,7 @@ export function remeshStage(input: RemeshInput, rigc: RigcRunner, checkBin: stri
|
|
|
986
1008
|
const spliced = ['rig.json', 'mesh_report.json'];
|
|
987
1009
|
const identical = [...tree.keys()].filter((k) => !spliced.includes(k));
|
|
988
1010
|
log(` ${part}: v=${before.vertices} t=${before.triangles} hull=${before.hull} -> v=${after.vertices} t=${after.triangles} hull=${after.hull}`);
|
|
989
|
-
log(` preserved: ${identical.length} file(s) byte-identical to the input; rig.json identical outside skins.default.${part}.${part}; mesh_report.json identical but the "${part}" row`);
|
|
1011
|
+
log(` preserved: ${identical.filter((p) => p !== PROVENANCE_FILE && !(input.recordInputCheck === true && p === INPUT_CHECK_FILE)).length} file(s) byte-identical to the input; rig.json identical outside skins.default.${part}.${part}; mesh_report.json identical but the "${part}" row`);
|
|
990
1012
|
// 7. The gate and check.
|
|
991
1013
|
const gate = gateThroughRigc(pngsOf(revision), textsOf(revision), rigc, join(scratch, 'gate'), { pageEdges, packShape });
|
|
992
1014
|
for (const g of gate) {
|
|
@@ -1014,18 +1036,22 @@ export function remeshStage(input: RemeshInput, rigc: RigcRunner, checkBin: stri
|
|
|
1014
1036
|
refuseIfAny(checkHeldProblems(sides.input, sides.revision, revCheck.problems));
|
|
1015
1037
|
const scope = checkScope(sides.revision.physics);
|
|
1016
1038
|
log(` check: input ${sides.input.pass ? 'PASS' : `FAIL (${sides.input.not_met.join(', ')})`}, revision ${sides.revision.pass ? 'PASS' : `FAIL (${sides.revision.not_met.join(', ')})`}, the same ${sides.revision.measured.length} bar(s) measured; ${scope}`);
|
|
1017
|
-
// 8. The write.
|
|
1039
|
+
// 8. The write. Previous root records are metadata, preserved separately after the rig hold.
|
|
1040
|
+
const lineage = carryProvenance(tree, revision, PROVENANCE_FILE);
|
|
1041
|
+
revision = lineage.revision;
|
|
1042
|
+
if (input.recordInputCheck === true) revision.set(INPUT_CHECK_FILE, new TextEncoder().encode(inputCheckText(recorded.binding as InputCheckBinding, sides.input)));
|
|
1043
|
+
revision = new Map([...revision].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
1018
1044
|
const provenance: RemeshProvenance = {
|
|
1019
1045
|
spec: REMESH_SPEC,
|
|
1020
1046
|
request: deltaRequest ?? { part, mesh: (meshReq as { entry: Json }).entry, mesh_sha256: sha256((meshReq as { bytes: Uint8Array }).bytes), idle_keys: idleKeys, page_edges: pageEdges, pack_shape: packShape },
|
|
1021
1047
|
versions,
|
|
1022
|
-
input: { rig: hashRows(tree), config_sha256: sha256(bytesOf(configText)), parts_json_sha256: sha256(new Uint8Array(readFileSync(join(input.parts, 'parts.json')))) },
|
|
1048
|
+
input: { rig: hashRows(tree), config_sha256: sha256(bytesOf(configText)), parts_json_sha256: sha256(new Uint8Array(readFileSync(join(input.parts, 'parts.json')))), ...(lineage.parents.length === 0 ? {} : { provenance: lineage.parents }) },
|
|
1023
1049
|
baseline: {
|
|
1024
1050
|
reproduced,
|
|
1025
1051
|
not_compared: 'every other attachment, image and report row: carried over from the input as bytes, whether or not the config reproduces it',
|
|
1026
1052
|
},
|
|
1027
1053
|
target: { before, after },
|
|
1028
|
-
preserved: { identical, spliced },
|
|
1054
|
+
preserved: { identical: identical.filter((p) => p !== PROVENANCE_FILE && !(input.recordInputCheck === true && p === INPUT_CHECK_FILE)), spliced },
|
|
1029
1055
|
revision: hashRows(revision),
|
|
1030
1056
|
check: { ...sides, scope },
|
|
1031
1057
|
};
|
|
@@ -1039,8 +1065,6 @@ export function remeshStage(input: RemeshInput, rigc: RigcRunner, checkBin: stri
|
|
|
1039
1065
|
writeFileSync(join(outAt, PROVENANCE_FILE), rigJsonText(provenance));
|
|
1040
1066
|
written.push(PROVENANCE_FILE);
|
|
1041
1067
|
if (input.recordInputCheck === true) {
|
|
1042
|
-
writeFileSync(join(outAt, INPUT_CHECK_FILE), inputCheckText(recorded.binding as InputCheckBinding, sides.input));
|
|
1043
|
-
written.push(INPUT_CHECK_FILE);
|
|
1044
1068
|
log(` recorded: the input's check in ${INPUT_CHECK_FILE}, bound by ${inputCheckHashes(recorded.binding as InputCheckBinding)} sha256 row(s); pass it as --input-check to a later remesh or retune of ${input.rig}`);
|
|
1045
1069
|
}
|
|
1046
1070
|
log(' file sha256 (input) sha256 (revision)');
|
package/src/retune.ts
CHANGED
|
@@ -40,7 +40,7 @@ import { dirname, join, resolve, sep } from 'node:path';
|
|
|
40
40
|
import { checkStage, gateThroughRigc, type Log, rigStage } from './build.ts';
|
|
41
41
|
import { type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackShape, type PageEdges, rigcRanClause, type RigcRunner } from './check.ts';
|
|
42
42
|
import { PartsError, type Problem, problemLine, refuseIfAny } from './errors.ts';
|
|
43
|
-
import { type CheckSide, checkHeldProblems, checkSide, checkScope, type FileTree, firstDifference, type HashRow, hashRows, INPUT_CHECK_FILE, type InputCheckBinding, inputCheckHashes, inputCheckMovedProblems, inputCheckOf, inputCheckReusedLine, inputCheckText, inputTreeProblems, perturbed, readTree, sha256 } from './remesh.ts';
|
|
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, readTree, sha256 } from './remesh.ts';
|
|
44
44
|
import { DEFAULT_IDLE_KEYS, type IdleKeys, rigJsonText } from './rig.ts';
|
|
45
45
|
|
|
46
46
|
/** The provenance file's spec. */
|
|
@@ -103,7 +103,7 @@ export interface RetuneProvenance {
|
|
|
103
103
|
spec: typeof RETUNE_SPEC;
|
|
104
104
|
request: { idle_keys: IdleKeys; page_edges: PageEdges; pack_shape: PackShape };
|
|
105
105
|
versions: { parts: string; rigc: string };
|
|
106
|
-
input: { rig: HashRow[]; config_sha256: string; parts_json_sha256: string };
|
|
106
|
+
input: { rig: HashRow[]; config_sha256: string; parts_json_sha256: string; provenance?: ParentProvenance[] };
|
|
107
107
|
held: { compared: string[]; not_compared: string };
|
|
108
108
|
changed: { constraints: ConstraintChange[]; added: string[]; removed: string[]; idle: { tracks_changed: number; duration: [number, number] } };
|
|
109
109
|
preserved: { identical: string[]; spliced: string[] };
|
|
@@ -375,7 +375,7 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
|
|
|
375
375
|
if (changed.added.length > 0) log(` constraints added: ${changed.added.join(', ')}`);
|
|
376
376
|
if (changed.removed.length > 0) log(` constraints removed: ${changed.removed.join(', ')}`);
|
|
377
377
|
log(` idle: ${changed.idle.tracks_changed} track(s) changed, duration ${changed.idle.duration[0]} -> ${changed.idle.duration[1]}`);
|
|
378
|
-
log(` preserved: ${identical.length} file(s) byte-identical to the input; rig.json identical outside constraints and invariants.detached; motion.json identical outside animations.idle`);
|
|
378
|
+
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`);
|
|
379
379
|
// 6. The gate and check.
|
|
380
380
|
const pngs = [...revision].filter(([k]) => k.startsWith('images/')).map(([k, b]) => [k.slice('images/'.length), b] as const);
|
|
381
381
|
const texts = [...revision].filter(([k]) => !k.startsWith('images/')).map(([k, b]) => [k, text(b)] as const);
|
|
@@ -405,15 +405,19 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
|
|
|
405
405
|
refuseIfAny(checkHeldProblems(sides.input, sides.revision, revCheck.problems, 'retune'));
|
|
406
406
|
const scope = checkScope(sides.revision.physics);
|
|
407
407
|
log(` check: input ${sides.input.pass ? 'PASS' : `FAIL (${sides.input.not_met.join(', ')})`}, revision ${sides.revision.pass ? 'PASS' : `FAIL (${sides.revision.not_met.join(', ')})`}, the same ${sides.revision.measured.length} bar(s) measured; ${scope}`);
|
|
408
|
-
// 7. The write.
|
|
408
|
+
// 7. The write. The hold above still compares the original rig and motion bytes.
|
|
409
|
+
const lineage = carryProvenance(tree, revision, RETUNE_FILE);
|
|
410
|
+
revision = lineage.revision;
|
|
411
|
+
if (input.recordInputCheck === true) revision.set(INPUT_CHECK_FILE, new TextEncoder().encode(inputCheckText(recorded.binding as InputCheckBinding, sides.input)));
|
|
412
|
+
revision = new Map([...revision].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
409
413
|
const provenance: RetuneProvenance = {
|
|
410
414
|
spec: RETUNE_SPEC,
|
|
411
415
|
request: { idle_keys: idleKeys, page_edges: pageEdges, pack_shape: packShape },
|
|
412
416
|
versions,
|
|
413
|
-
input: { rig: hashRows(tree), config_sha256: sha256(new Uint8Array(readFileSync(input.config))), parts_json_sha256: sha256(new Uint8Array(readFileSync(join(input.parts, 'parts.json')))) },
|
|
417
|
+
input: { rig: hashRows(tree), config_sha256: sha256(new Uint8Array(readFileSync(input.config))), parts_json_sha256: sha256(new Uint8Array(readFileSync(join(input.parts, 'parts.json')))), ...(lineage.parents.length === 0 ? {} : { provenance: lineage.parents }) },
|
|
414
418
|
held: { compared: [...RETUNE_HELD], not_compared: RETUNE_NOT_COMPARED },
|
|
415
419
|
changed,
|
|
416
|
-
preserved: { identical, spliced },
|
|
420
|
+
preserved: { identical: identical.filter((p) => p !== RETUNE_FILE && !(input.recordInputCheck === true && p === INPUT_CHECK_FILE)), spliced },
|
|
417
421
|
revision: hashRows(revision),
|
|
418
422
|
check: { ...sides, scope },
|
|
419
423
|
};
|
|
@@ -427,8 +431,6 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
|
|
|
427
431
|
writeFileSync(join(outAt, RETUNE_FILE), rigJsonText(provenance));
|
|
428
432
|
written.push(RETUNE_FILE);
|
|
429
433
|
if (input.recordInputCheck === true) {
|
|
430
|
-
writeFileSync(join(outAt, INPUT_CHECK_FILE), inputCheckText(recorded.binding as InputCheckBinding, sides.input));
|
|
431
|
-
written.push(INPUT_CHECK_FILE);
|
|
432
434
|
log(` recorded: the input's check in ${INPUT_CHECK_FILE}, bound by ${inputCheckHashes(recorded.binding as InputCheckBinding)} sha256 row(s); pass it as --input-check to a later remesh or retune of ${input.rig}`);
|
|
433
435
|
}
|
|
434
436
|
log(' file sha256 (input) sha256 (revision)');
|
package/src/rig.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { regionBone } from './config.ts';
|
|
1
2
|
/**
|
|
2
3
|
* The rig stage: a character config and its assembled parts in, a rig spec
|
|
3
4
|
* and a motion spec in rig-c's format out.
|
|
@@ -1413,7 +1414,8 @@ export function buildRig(
|
|
|
1413
1414
|
: '';
|
|
1414
1415
|
const where = (part: string): string => `parts.json holds ${parts.parts.length} part(s): ${parts.parts.map((p) => p.name).join(', ')}`;
|
|
1415
1416
|
for (const part of Object.keys(cfg.meshes)) if (!byPart.has(part)) fail('RIG_PART_PRESENT', `config.meshes.${part}`, `names the part "${part}", which is not in parts.json; ${where(part)}`);
|
|
1416
|
-
for (const [part,
|
|
1417
|
+
for (const [part, region] of Object.entries(cfg.regions)) {
|
|
1418
|
+
const bone = regionBone(region);
|
|
1417
1419
|
if (!byPart.has(part)) fail('RIG_PART_PRESENT', `config.regions.${part}`, `names the part "${part}", which is not in parts.json; ${where(part)}`);
|
|
1418
1420
|
if (!B.has(bone)) fail('RIG_NAME_RESOLVES', `config.regions.${part}`, `names the bone "${bone}", which config.bones does not declare`);
|
|
1419
1421
|
}
|
|
@@ -2259,7 +2261,7 @@ export function buildRig(
|
|
|
2259
2261
|
outImages.push([file, img]);
|
|
2260
2262
|
const mesh = cfg.meshes[p.name];
|
|
2261
2263
|
if (mesh === undefined) {
|
|
2262
|
-
const bone = B.get(cfg.regions[p.name]) as Bone;
|
|
2264
|
+
const bone = B.get(regionBone(cfg.regions[p.name])) as Bone;
|
|
2263
2265
|
const cx = p.x + p.w / 2;
|
|
2264
2266
|
const st = stills[p.name];
|
|
2265
2267
|
if (st !== undefined) {
|
|
@@ -2463,7 +2465,7 @@ export function buildRig(
|
|
|
2463
2465
|
coveredBones = new Set<string>();
|
|
2464
2466
|
for (const slotName of Object.keys(alt.slots)) {
|
|
2465
2467
|
const pName = declaredFront.has(slotName) && altFront.has(slotName.slice(0, -FRONT_SUFFIX.length)) ? slotName.slice(0, -FRONT_SUFFIX.length) : slotName;
|
|
2466
|
-
if (pName in cfg.regions) coveredBones.add(cfg.regions[pName]);
|
|
2468
|
+
if (pName in cfg.regions) coveredBones.add(regionBone(cfg.regions[pName]));
|
|
2467
2469
|
for (const s of meshSegments.get(pName) ?? []) coveredBones.add(s.bone);
|
|
2468
2470
|
const m = cfg.meshes[pName];
|
|
2469
2471
|
if (m !== undefined) {
|
|
@@ -2528,7 +2530,7 @@ export function buildRig(
|
|
|
2528
2530
|
outImages.push([file, img]);
|
|
2529
2531
|
const mesh = cfg.meshes[p.name];
|
|
2530
2532
|
if (mesh === undefined) {
|
|
2531
|
-
const bone = B.get(cfg.regions[p.name]) as Bone;
|
|
2533
|
+
const bone = B.get(regionBone(cfg.regions[p.name])) as Bone;
|
|
2532
2534
|
skin[skinSlot][attName] = altRegion(file, bone.name, p.x + p.w / 2, p.y + p.h / 2);
|
|
2533
2535
|
continue;
|
|
2534
2536
|
}
|
|
@@ -2676,7 +2678,11 @@ export function buildRig(
|
|
|
2676
2678
|
const hasAlternateFaceSet = sets !== undefined && Object.values(sets.sets).some((e) => Object.hasOwn(e.slots, 'face'));
|
|
2677
2679
|
// Read every base/alternate binding before rebinds; publish only the slot
|
|
2678
2680
|
// permutation below, after stops/turn have used the original enumeration.
|
|
2679
|
-
const
|
|
2681
|
+
const ungathered = [
|
|
2682
|
+
...Object.entries(cfg.meshes).filter(([, spec]) => spec.gather === false).map(([part]) => ({ part, object: `config.meshes.${part}.gather`, slots: slotFamilies.get(part) ?? [part] })),
|
|
2683
|
+
...Object.entries(cfg.regions).filter(([, spec]) => typeof spec !== 'string' && spec.gather === false).map(([part]) => ({ part, object: `config.regions.${part}.gather`, slots: slotFamilies.get(part) ?? [part] })),
|
|
2684
|
+
];
|
|
2685
|
+
const limbLayout = coalesceLimbSlots(cfg.limbs, bones, slots, skin, ungathered);
|
|
2680
2686
|
const explicitLayout = placeLimbLayouts(cfg.limbs, bones, limbLayout, skin, slotFamilies);
|
|
2681
2687
|
// ---- leg stops (issue #404) --------------------------------------------
|
|
2682
2688
|
// Only when the config has `stops`: each link after the first (and any bone hanging from a stopped link) hangs
|
package/src/structure.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { regionBone } from './config.ts';
|
|
1
2
|
/**
|
|
2
3
|
* A structural comparison of two skeletons (issue #85).
|
|
3
4
|
*
|
|
@@ -193,7 +194,7 @@ export function configRoles(s: SkeletonSections & { constraints?: readonly Confi
|
|
|
193
194
|
if (weightsABone(rg)) push(bound, rg.bone, `meshes.${part}.auto.regions[${i}]`);
|
|
194
195
|
});
|
|
195
196
|
}
|
|
196
|
-
for (const [part, bone] of Object.entries(s.regions)) push(bound, bone, `regions.${part}`);
|
|
197
|
+
for (const [part, bone] of Object.entries(s.regions)) push(bound, regionBone(bone), `regions.${part}`);
|
|
197
198
|
for (const [part, st] of Object.entries(s.motion.blink?.still ?? {})) push(bound, st.bone, `motion.blink.still.${part}`);
|
|
198
199
|
const keyed = new Map<string, string[]>();
|
|
199
200
|
s.motion.tracks.forEach((t, i) => {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AlternateCliInput } from '../src/build.ts';
|
|
2
|
+
|
|
3
|
+
/** Parse `--alt <name>=<source>:<full>[:<head>]` (issue #454), or return a usage message. */
|
|
4
|
+
export function parseAltArg(value: string): AlternateCliInput | string {
|
|
5
|
+
const eq = value.indexOf('=');
|
|
6
|
+
if (eq <= 0) return `--alt "${value}" is not <name>=<source>:<full>[:<head>]`;
|
|
7
|
+
const name = value.slice(0, eq);
|
|
8
|
+
if (name.startsWith('.') || name.includes('/') || name.includes('\\')) return `--alt set name "${name}" may not start with "." or hold a slash`;
|
|
9
|
+
const rest = value.slice(eq + 1);
|
|
10
|
+
const parts: string[] = [];
|
|
11
|
+
const drivePrefix = /^[A-Za-z]:[\\/]/;
|
|
12
|
+
let start = 0;
|
|
13
|
+
for (let at = 0; at < rest.length; at++) {
|
|
14
|
+
if (rest[at] !== ':') continue;
|
|
15
|
+
// Only the leading drive colon of this segment belongs to its path.
|
|
16
|
+
if (at === start + 1 && drivePrefix.test(rest.slice(start))) continue;
|
|
17
|
+
parts.push(rest.slice(start, at));
|
|
18
|
+
start = at + 1;
|
|
19
|
+
}
|
|
20
|
+
parts.push(rest.slice(start));
|
|
21
|
+
if (parts.length < 2 || parts.length > 3 || parts[0].length === 0 || parts[1].length === 0 || (parts.length === 3 && parts[2].length === 0)) {
|
|
22
|
+
return `--alt "${value}" is not <name>=<source>:<full>[:<head>]`;
|
|
23
|
+
}
|
|
24
|
+
return { name, source: parts[0], full: parts[1], ...(parts.length === 3 ? { head: parts[2] } : {}) };
|
|
25
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/** Ordinary build stage processes. No public option selects this internal protocol. */
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { assembleStage, checkStage, rigStage, type AssembleOutputs, type AssembleStageInput, type CheckStageInput, type RigStageInput } from '../src/build.ts';
|
|
6
|
+
import { rigcRunnerAt, type CheckReport, type RigcRunner } from '../src/check.ts';
|
|
7
|
+
import { PartsError, type Problem } from '../src/errors.ts';
|
|
8
|
+
|
|
9
|
+
/** Preserve native/custom executables; adapt only a proven package-manager script shim. */
|
|
10
|
+
export function selectedRigcCommand(bin: string, platform: NodeJS.Platform = process.platform): { command: string; prefix: string[] } {
|
|
11
|
+
if (platform !== 'win32' || extname(bin).toLowerCase() === '.exe') return { command: bin, prefix: [] };
|
|
12
|
+
const fail = (detail: string): never => { throw new Error('RIGC_LAUNCHER_IDENTITY: ' + bin + ' — ' + detail + '; the selected executable must keep its own launcher'); };
|
|
13
|
+
try {
|
|
14
|
+
const selected = resolve(bin);
|
|
15
|
+
// findRigc selected this exact local .bin path; do not resolve an ambient package.
|
|
16
|
+
if (basename(selected) !== 'rigc' || basename(dirname(selected)) !== '.bin') return fail('unknown or custom script shim');
|
|
17
|
+
const packageRoot = join(dirname(dirname(selected)), 'rig-c');
|
|
18
|
+
const manifest = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')) as { name?: unknown; bin?: unknown };
|
|
19
|
+
const binMap = manifest.bin;
|
|
20
|
+
const declared = typeof binMap === 'string' ? binMap : binMap !== null && typeof binMap === 'object' ? (binMap as Record<string, unknown>).rigc : undefined;
|
|
21
|
+
if (manifest.name !== 'rig-c' || typeof declared !== 'string') return fail('the selected package does not declare rigc');
|
|
22
|
+
const entry = resolve(packageRoot, declared);
|
|
23
|
+
const within = relative(realpathSync.native(packageRoot), realpathSync.native(entry));
|
|
24
|
+
if (within === '..' || within.startsWith('..' + sep) || isAbsolute(within) || !statSync(entry).isFile()) return fail('bin target is outside the selected package');
|
|
25
|
+
const launcher = readFileSync(entry, 'utf8');
|
|
26
|
+
if (launcher.split(/\r?\n/, 1)[0] !== '#!/usr/bin/env node') return fail('declared bin is not a Node launcher');
|
|
27
|
+
if (realpathSync.native(selected) !== realpathSync.native(entry)) {
|
|
28
|
+
// npm cmd-shim's shell companion is checked in full, including both forwarding branches.
|
|
29
|
+
// Extra custom commands, another target or an unknown shim format are refused, never bypassed.
|
|
30
|
+
const reference = relative(dirname(selected), entry).split(sep).join('/');
|
|
31
|
+
if (/["$\x60\r\n]/.test(reference)) return fail('target cannot be identified literally in the package shim');
|
|
32
|
+
const expected = [
|
|
33
|
+
'#!/bin/sh', 'basedir=$(dirname "$(echo "$0" | sed -e \'s,\\\\,/,g\')")',
|
|
34
|
+
'case \x60uname\x60 in', '*CYGWIN*|*MINGW*|*MSYS*)', 'if command -v cygpath > /dev/null 2>&1; then',
|
|
35
|
+
'basedir=\x60cygpath -w "$basedir"\x60', 'fi', ';;', 'esac',
|
|
36
|
+
'if [ -x "$basedir/node" ]; then', 'exec "$basedir/node" "$basedir/' + reference + '" "$@"',
|
|
37
|
+
'else', 'exec node "$basedir/' + reference + '" "$@"', 'fi',
|
|
38
|
+
];
|
|
39
|
+
const actual = readFileSync(selected, 'utf8').split(/\r?\n/).map(line => line.trim()).filter(Boolean);
|
|
40
|
+
const equal = actual.length === expected.length && actual.every((line, i) => line === expected[i] ||
|
|
41
|
+
(i === 10 && line === expected[i].replace('node" ', 'node" ')) || (i === 12 && line === expected[i].replace('exec node ', 'exec node ')));
|
|
42
|
+
if (!equal) return fail('selected shim is not the declared launcher forwarding wrapper');
|
|
43
|
+
}
|
|
44
|
+
return { command: 'node', prefix: [entry] };
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (error instanceof Error && error.message.startsWith('RIGC_LAUNCHER_IDENTITY:')) throw error;
|
|
47
|
+
return fail(error instanceof Error ? error.message : String(error));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function childStarted(child: { status: number | null; signal: string | null }): boolean {
|
|
52
|
+
return typeof child.status === 'number' || (typeof child.signal === 'string' && child.signal !== '');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function processRigcRunner(bin: string): RigcRunner {
|
|
56
|
+
return rigcRunnerAt(bin, (b, args) => {
|
|
57
|
+
let launch: { command: string; prefix: string[] };
|
|
58
|
+
try { launch = selectedRigcCommand(b); }
|
|
59
|
+
catch (error) { return { status: 127, out: error instanceof Error ? error.message : String(error) }; }
|
|
60
|
+
const r = spawnSync(launch.command, [...launch.prefix, ...args], { shell: false, windowsHide: true, encoding: 'utf8', maxBuffer: 1 << 28 });
|
|
61
|
+
if (!childStarted(r)) return { status: 127, out: 'could not start ' + b + ': ' + (r.error?.message ?? 'no exit status or signal was reported') };
|
|
62
|
+
return { status: r.status ?? 1, out: (r.stdout ?? '') + (r.stderr ?? '') };
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
type Stage = 'assemble' | 'rig' | 'check';
|
|
67
|
+
export type BuildProcessJob =
|
|
68
|
+
| { stage: 'assemble'; bin: string; input: AssembleStageInput; outputs: AssembleOutputs }
|
|
69
|
+
| { stage: 'rig'; bin: string; input: Omit<RigStageInput, 'reduce'>; scratch: string }
|
|
70
|
+
| { stage: 'check'; bin: string; input: CheckStageInput };
|
|
71
|
+
|
|
72
|
+
function record(value: unknown): value is Record<string, unknown> {
|
|
73
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
74
|
+
}
|
|
75
|
+
function problems(value: unknown): value is Problem[] {
|
|
76
|
+
return Array.isArray(value) && value.length > 0 && value.every((p) => record(p) && typeof p.code === 'string' && typeof p.object === 'string' && typeof p.detail === 'string');
|
|
77
|
+
}
|
|
78
|
+
function resultError(stage: Stage, detail: string): never {
|
|
79
|
+
throw new Error('BUILD_STAGE_RESULT: ' + stage + ' child — ' + detail + '; a matching complete receipt is required');
|
|
80
|
+
}
|
|
81
|
+
function checkReport(value: unknown): value is CheckReport {
|
|
82
|
+
if (!record(value) || !record(value.figures) || typeof value.figures.PASS !== 'boolean') return false;
|
|
83
|
+
const arrays = ['gateHtml', 'pack', 'packOpaque', 'problems', 'written', 'besideIdle'];
|
|
84
|
+
if (!arrays.every((key) => Array.isArray(value[key]))) return false;
|
|
85
|
+
if (!record(value.bars) || !Array.isArray(value.bars.measured) || !Array.isArray(value.bars.skipped)) return false;
|
|
86
|
+
if (!record(value.motionSeam) || !record(value.cloth)) return false;
|
|
87
|
+
if (!['idle', 'loopPhysics', 'seamViewport', 'requirements'].every((key) => Object.hasOwn(value, key))) return false;
|
|
88
|
+
return (value.pack as unknown[]).every((p) => record(p) && typeof p.line === 'string' && typeof p.page === 'string' &&
|
|
89
|
+
['width', 'height', 'regions', 'coveredPct', 'padding'].every((key) => typeof p[key] === 'number') &&
|
|
90
|
+
(p.pageEdges === 'free' || p.pageEdges === 'pot') && (p.packShape === 'rect' || p.packShape === 'polygon')) &&
|
|
91
|
+
(value.problems as unknown[]).every((p) => record(p) && typeof p.code === 'string' && typeof p.object === 'string' && typeof p.detail === 'string');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Decode only a matching successful stage or its original named input refusal. */
|
|
95
|
+
export function readBuildReceipt(stage: 'check', status: number | null, signal: string | null, text: string): CheckReport;
|
|
96
|
+
export function readBuildReceipt(stage: 'assemble' | 'rig', status: number | null, signal: string | null, text: string): void;
|
|
97
|
+
export function readBuildReceipt(stage: Stage, status: number | null, signal: string | null, text: string): CheckReport | void;
|
|
98
|
+
export function readBuildReceipt(stage: Stage, status: number | null, signal: string | null, text: string): CheckReport | void {
|
|
99
|
+
if (signal !== null || status === null || (status !== 0 && status !== 1) || (status !== 0 && text === '')) {
|
|
100
|
+
throw new Error('BUILD_STAGE_CHILD: ' + stage + ' child — exit ' + status + ', signal ' + signal + '; no later stage ran');
|
|
101
|
+
}
|
|
102
|
+
let row: unknown;
|
|
103
|
+
try { row = JSON.parse(text); } catch { return resultError(stage, 'missing or malformed JSON'); }
|
|
104
|
+
if (!record(row) || row.version !== 1 || row.stage !== stage) return resultError(stage, 'wrong version or stage');
|
|
105
|
+
if (row.kind === 'refused') {
|
|
106
|
+
if (status !== 1 || !problems(row.problems)) return resultError(stage, 'refusal must exit 1 and name at least one complete problem');
|
|
107
|
+
throw new PartsError(row.problems);
|
|
108
|
+
}
|
|
109
|
+
if (row.kind !== 'done') return resultError(stage, 'unknown receipt kind');
|
|
110
|
+
if (status !== 0) throw new Error('BUILD_STAGE_CHILD: ' + stage + ' child — exit ' + status + ' with a completion receipt; no later stage ran');
|
|
111
|
+
if (stage !== 'check') {
|
|
112
|
+
if (Object.hasOwn(row, 'report') || Object.hasOwn(row, 'sweepSteps')) return resultError(stage, 'a void stage returned an invented check report');
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (!checkReport(row.report)) return resultError(stage, 'check report is incomplete');
|
|
116
|
+
if (row.sweepSteps !== null && (!Array.isArray(row.sweepSteps) || !row.sweepSteps.every((p) =>
|
|
117
|
+
Array.isArray(p) && p.length === 2 && typeof p[0] === 'string' && record(p[1]) && typeof p[1].left === 'number' && typeof p[1].right === 'number'))) {
|
|
118
|
+
return resultError(stage, 'sweepSteps must be null or the original map entries');
|
|
119
|
+
}
|
|
120
|
+
const report = row.report;
|
|
121
|
+
if (row.sweepSteps !== null) report.sweepSteps = new Map(row.sweepSteps as Array<[string, { left: number; right: number }]>);
|
|
122
|
+
return report;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The check's one optional Map is carried as entries; every other field is the original report. */
|
|
126
|
+
export function encodeCheckReceipt(report: CheckReport): string {
|
|
127
|
+
return JSON.stringify({ version: 1, stage: 'check', kind: 'done', report: { ...report, sweepSteps: undefined },
|
|
128
|
+
sweepSteps: report.sweepSteps === undefined ? null : [...report.sweepSteps] });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Minimum Bun may attach error to an ordinary nonzero exit; only an unstarted child is a launch failure. */
|
|
132
|
+
export function readBuildChild(stage: Stage, child: { status: number | null; signal: string | null; error?: Error }, text: string): CheckReport | void {
|
|
133
|
+
if (!childStarted(child) && child.error !== undefined) throw new Error('BUILD_STAGE_CHILD: ' + stage + ' could not start — ' + child.error.message);
|
|
134
|
+
return readBuildReceipt(stage, child.status ?? null, child.signal ?? null, text);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Inherited descriptors keep stdout/stderr write order; no shell parses paths or flags. */
|
|
138
|
+
export function launchBuildChild(argv: readonly string[]): { status: number | null; signal: string | null; error?: Error } {
|
|
139
|
+
const [command, ...args] = argv;
|
|
140
|
+
if (command === undefined) throw new Error('BUILD_STAGE_CHILD: executable is required');
|
|
141
|
+
return spawnSync(command, args, { shell: false, windowsHide: true, stdio: ['ignore', 'inherit', 'inherit'] });
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function runBuildProcess(job: Extract<BuildProcessJob, { stage: 'check' }>, home: string): CheckReport;
|
|
145
|
+
export function runBuildProcess(job: Exclude<BuildProcessJob, { stage: 'check' }>, home: string): void;
|
|
146
|
+
export function runBuildProcess(job: BuildProcessJob, home: string): CheckReport | void {
|
|
147
|
+
mkdirSync(home, { recursive: true });
|
|
148
|
+
const request = join(home, job.stage + '.request.json');
|
|
149
|
+
const result = join(home, job.stage + '.result.json');
|
|
150
|
+
rmSync(result, { force: true });
|
|
151
|
+
writeFileSync(request, JSON.stringify(job));
|
|
152
|
+
try {
|
|
153
|
+
const child = launchBuildChild([process.execPath, import.meta.path, request, result]);
|
|
154
|
+
return readBuildChild(job.stage, child, existsSync(result) ? readFileSync(result, 'utf8') : '');
|
|
155
|
+
} finally {
|
|
156
|
+
rmSync(request, { force: true });
|
|
157
|
+
rmSync(result, { force: true });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function requestError(detail: string): never {
|
|
162
|
+
throw new PartsError([{ code: 'BUILD_STAGE_REQUEST', object: 'internal build worker', detail: detail + '; a complete assemble, rig or check request is required' }]);
|
|
163
|
+
}
|
|
164
|
+
function readJob(path: string): BuildProcessJob {
|
|
165
|
+
let job: unknown;
|
|
166
|
+
try { job = JSON.parse(readFileSync(path, 'utf8')); } catch { return requestError('request file is missing or malformed'); }
|
|
167
|
+
if (!record(job) || typeof job.bin !== 'string' || !record(job.input)) return requestError('request must name its runner and typed input');
|
|
168
|
+
const input = job.input;
|
|
169
|
+
const strings = (keys: string[]): boolean => keys.every((key) => typeof input[key] === 'string');
|
|
170
|
+
if (job.stage === 'assemble') {
|
|
171
|
+
if (!strings(['config', 'source', 'full', 'seam', 'project']) || !(input.head === null || typeof input.head === 'string') ||
|
|
172
|
+
!record(job.outputs) || !['partsJson', 'partsDir', 'recomposite', 'errorMap'].every((key) => typeof (job.outputs as Record<string, unknown>)[key] === 'string')) return requestError('assemble input or output paths are incomplete');
|
|
173
|
+
} else if (job.stage === 'rig') {
|
|
174
|
+
if (!strings(['config', 'parts', 'out']) || typeof job.scratch !== 'string' || Object.hasOwn(input, 'reduce')) return requestError('rig input or scratch is incomplete, or contains a nonserializable reducer');
|
|
175
|
+
} else if (job.stage === 'check') {
|
|
176
|
+
if (!strings(['rig', 'out'])) return requestError('check input paths are incomplete');
|
|
177
|
+
} else return requestError('unknown stage ' + JSON.stringify(job.stage));
|
|
178
|
+
return job as unknown as BuildProcessJob;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function worker(args: string[]): number {
|
|
182
|
+
if (args.length !== 2 || args.some((a) => a === '' || a.startsWith('--'))) return requestError('expected exactly one request path and one result path');
|
|
183
|
+
const job = readJob(args[0]);
|
|
184
|
+
const runner = processRigcRunner(job.bin);
|
|
185
|
+
const log = (line: string): void => { console.log('[' + job.stage + '] ' + line); };
|
|
186
|
+
try {
|
|
187
|
+
let report: CheckReport | undefined;
|
|
188
|
+
if (job.stage === 'assemble') assembleStage(job.input, job.outputs, log);
|
|
189
|
+
else if (job.stage === 'rig') rigStage(job.input, runner, job.scratch, log);
|
|
190
|
+
else report = checkStage(job.input, runner, job.bin, log);
|
|
191
|
+
writeFileSync(args[1], report === undefined ? JSON.stringify({ version: 1, stage: job.stage, kind: 'done' }) : encodeCheckReceipt(report));
|
|
192
|
+
return 0;
|
|
193
|
+
} catch (err) {
|
|
194
|
+
if (!(err instanceof PartsError)) throw err;
|
|
195
|
+
writeFileSync(args[1], JSON.stringify({ version: 1, stage: job.stage, kind: 'refused', problems: err.problems }));
|
|
196
|
+
return 1;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (import.meta.main) {
|
|
200
|
+
try { process.exit(worker(process.argv.slice(2))); }
|
|
201
|
+
catch (err) {
|
|
202
|
+
if (!(err instanceof PartsError)) throw err;
|
|
203
|
+
console.error(err.message);
|
|
204
|
+
process.exit(1);
|
|
205
|
+
}
|
|
206
|
+
}
|