@tora-editor/tora 0.1.0 → 0.3.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/README.md +107 -58
- package/assets/free-audio/arcade-pop/audio/loss.wav +0 -0
- package/assets/free-audio/arcade-pop/audio/reward.wav +0 -0
- package/assets/free-audio/arcade-pop/audio/win.wav +0 -0
- package/assets/free-audio/arcade-pop/source/INFO.txt +11 -11
- package/assets/kenney-food-starter/License.txt +28 -0
- package/assets/kenney-food-starter/burger.glb +0 -0
- package/assets/kenney-food-starter/frying-pan.glb +0 -0
- package/assets/kenney-food-starter/plan.json +61 -0
- package/assets/kenney-food-starter/plate.glb +0 -0
- package/assets/kenney-food-starter/pot.glb +0 -0
- package/assets/kenney-harvest/audio/victory.wav +0 -0
- package/assets/kenney-harvest/source/music-jingles/OGG/jingles_NES/jingles_NES03.ogg +0 -0
- package/assets/kenney-harvest/source/music-jingles/OGG/jingles_PIZZA/jingles_PIZZA03.ogg +0 -0
- package/assets/kenney-harvest/source/music-jingles/license.txt +14 -0
- package/bin/tora.mjs +322 -28
- package/crates/packer/trusted/native-3d-meta.json +4 -3
- package/crates/packer/trusted/native-3d.js +181 -181
- package/crates/packer/trusted/native-meta.json +3 -3
- package/crates/packer/trusted/native.js +5 -5
- package/crates/packer/trusted/release-manifest.json +17 -17
- package/crates/packer/trusted/review-runtime-meta.json +4 -3
- package/crates/packer/trusted/review-runtime.js +182 -182
- package/docs/MIGRATION_0_3.md +39 -0
- package/docs/NATIVE_AGENT_TOOLS.md +12 -363
- package/docs/TORA_AGENT_SETUP.md +24 -95
- package/docs/TORA_CREATION_API.md +63 -348
- package/docs/reference/CORE_AUTHORING.md +10 -3
- package/docs/reference/PLAYABLE_STARTERS.md +20 -0
- package/docs/reference/packs/3d.md +11 -3
- package/network-rules/mintegral-appgrowth-single-html.json +10 -10
- package/package.json +6 -6
- package/packages/creative-project/project-v21.schema.json +372 -9
- package/scripts/lean/editor/entry.js +11 -6
- package/scripts/lean/editor/project-launcher.js +116 -0
- package/scripts/lean/editor/quick-edit-panel.js +479 -0
- package/scripts/lean/editor/review-editor.css +256 -68
- package/scripts/lean/editor/review-editor.js +1834 -1086
- package/scripts/lean/editor-state.mjs +6 -0
- package/scripts/lean/editor.mjs +6 -3
- package/scripts/lean/matrix.mjs +5 -0
- package/scripts/lean/native/agent-tools.mjs +39 -62
- package/scripts/lean/native/api.mjs +161 -136
- package/scripts/lean/native/asset-catalog.mjs +7 -6
- package/scripts/lean/native/asset-lineage.mjs +54 -0
- package/scripts/lean/native/asset-prep.mjs +173 -40
- package/scripts/lean/native/assets.mjs +107 -11
- package/scripts/lean/native/audio-assets.mjs +30 -0
- package/scripts/lean/native/browser-pool.mjs +34 -0
- package/scripts/lean/native/build-cache.mjs +38 -7
- package/scripts/lean/native/cc0-inputs.mjs +24 -0
- package/scripts/lean/native/cc0-staging.mjs +28 -8
- package/scripts/lean/native/compiler.mjs +9 -3
- package/scripts/lean/native/contracts.mjs +16 -11
- package/scripts/lean/native/creative-qa.mjs +365 -128
- package/scripts/lean/native/demos.mjs +53 -18
- package/scripts/lean/native/document.mjs +50 -12
- package/scripts/lean/native/export-budget.mjs +75 -0
- package/scripts/lean/native/local-bundle.mjs +7 -3
- package/scripts/lean/native/mcp-server.mjs +42 -74
- package/scripts/lean/native/media-validate.mjs +124 -0
- package/scripts/lean/native/modules/harvest-restore.mjs +3 -284
- package/scripts/lean/native/modules/sort-puzzle.mjs +51 -0
- package/scripts/lean/native/modules/star-salvage.mjs +3 -368
- package/scripts/lean/native/native-bin.mjs +3 -3
- package/scripts/lean/native/outcome-playthrough.mjs +97 -0
- package/scripts/lean/native/project-bundle.mjs +6 -5
- package/scripts/lean/native/project-index.mjs +0 -2
- package/scripts/lean/native/qa-adapters.mjs +10 -0
- package/scripts/lean/native/quick-edit.mjs +328 -0
- package/scripts/lean/native/remote-cc0-fetcher.mjs +403 -197
- package/scripts/lean/native/review.mjs +205 -571
- package/scripts/lean/native/schema-vocabulary.mjs +10 -0
- package/scripts/lean/native/schema.mjs +7 -5
- package/scripts/lean/native/scope.mjs +45 -0
- package/scripts/lean/native/service.mjs +378 -79
- package/scripts/lean/native/starters.mjs +563 -0
- package/scripts/lean/native/variant-adapters.mjs +8 -0
- package/scripts/lean/native/variants-core.mjs +186 -0
- package/scripts/lean/native/variants.mjs +63 -0
- package/scripts/lean/native/win-cues.mjs +96 -0
- package/skills/tora-playables/SKILL.md +1 -1
- package/scripts/lean/editor/review-intake.js +0 -837
- package/scripts/lean/model-client.mjs +0 -119
- package/scripts/lean/native/author-expansion-proofs.mjs +0 -240
- package/scripts/lean/native/author-games.mjs +0 -160
- package/scripts/lean/native/author-harvest.mjs +0 -74
- package/scripts/lean/native/author-primitive-proofs.mjs +0 -874
- package/scripts/lean/native/author-salvage.mjs +0 -71
- package/scripts/lean/native/chat-compose.mjs +0 -287
- package/scripts/lean/native/check-harvest-outcome-audio.mjs +0 -191
- package/scripts/lean/native/check-salvage.mjs +0 -197
- package/scripts/lean/native/compatibility.mjs +0 -34
- package/scripts/lean/native/concept.mjs +0 -633
- package/scripts/lean/native/draw-stroke.mjs +0 -26
- package/scripts/lean/native/erase-mask.mjs +0 -18
- package/scripts/lean/native/harvest-recipe.mjs +0 -21
- package/scripts/lean/native/instance-steering.mjs +0 -24
- package/scripts/lean/native/intake-creator-agent.mjs +0 -98
- package/scripts/lean/native/intake-creator-tools.mjs +0 -165
- package/scripts/lean/native/interaction-gestures.mjs +0 -45
- package/scripts/lean/native/match-board.mjs +0 -138
- package/scripts/lean/native/modules/index.mjs +0 -54
- package/scripts/lean/native/modules/tap-collect.mjs +0 -54
- package/scripts/lean/native/path-network.mjs +0 -132
- package/scripts/lean/native/physics-2d.mjs +0 -154
- package/scripts/lean/native/physics-3d.mjs +0 -259
- package/scripts/lean/native/prepare-audio-collections.mjs +0 -112
- package/scripts/lean/native/prepare-game-audio.mjs +0 -372
- package/scripts/lean/native/prepare-golf-3d-assets.py +0 -177
- package/scripts/lean/native/prepare-golf-assets.py +0 -211
- package/scripts/lean/native/prepare-harvest-audio.mjs +0 -83
- package/scripts/lean/native/prepare-harvest-images.mjs +0 -31
- package/scripts/lean/native/prepare-primitive-images.py +0 -25
- package/scripts/lean/native/prepare-space-salvage-images.mjs +0 -89
- package/scripts/lean/native/prepare-traffic-assets.py +0 -329
- package/scripts/lean/native/presentation.mjs +0 -335
- package/scripts/lean/native/review-agent-tools.mjs +0 -561
- package/scripts/lean/native/review-connection.mjs +0 -303
- package/scripts/lean/native/review-fields.mjs +0 -24
- package/scripts/lean/native/review-intake.mjs +0 -385
- package/scripts/lean/native/review-intents.mjs +0 -217
- package/scripts/lean/native/review-provider.mjs +0 -580
- package/scripts/lean/native/review-receipts.mjs +0 -76
- package/scripts/lean/native/review-resolver.mjs +0 -429
- package/scripts/lean/native/review-targets.mjs +0 -35
- package/scripts/lean/native/runtime.mjs +0 -1623
- package/scripts/lean/native/salvage-recipe.mjs +0 -20
- package/scripts/lean/native/stage-3d.mjs +0 -818
- package/scripts/lean/native/verify.mjs +0 -4
- package/scripts/lean/scene-document.mjs +0 -48
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** Rust-backed faithful mechanical sprite preparation with hash-bound provenance receipts. */
|
|
1
|
+
/** Rust-backed faithful mechanical sprite & 3D model preparation with hash-bound provenance receipts. */
|
|
2
2
|
import {execFile} from 'node:child_process';
|
|
3
3
|
import {randomUUID} from 'node:crypto';
|
|
4
4
|
import {mkdir,mkdtemp,readFile,rm,writeFile} from 'node:fs/promises';
|
|
@@ -7,7 +7,8 @@ import {promisify} from 'node:util';
|
|
|
7
7
|
import {check} from './document.mjs';
|
|
8
8
|
import {hash} from './compiler.mjs';
|
|
9
9
|
import {readUploadFile,safeFile} from './assets.mjs';
|
|
10
|
-
import {resolveCc0SourceItem} from './cc0-staging.mjs';
|
|
10
|
+
import {compactAssetProvenance,resolveCc0SourceItem} from './cc0-staging.mjs';
|
|
11
|
+
import {pivotMode} from './cc0-inputs.mjs';
|
|
11
12
|
import {mapWithConcurrency} from './concurrency.mjs';
|
|
12
13
|
import {requireNativeTool} from './native-bin.mjs';
|
|
13
14
|
import {assertStorePath} from './store-path.mjs';
|
|
@@ -16,28 +17,21 @@ import {resolvePreparedAssetsRoot,resolveWorkspaceRoot} from '../runtime-paths.m
|
|
|
16
17
|
const run=promisify(execFile);
|
|
17
18
|
const PREP_MANIFEST_FORMAT='tora-prepared-assets-1';
|
|
18
19
|
const IMAGE_MIMES=new Set(['image/png','image/jpeg']);
|
|
20
|
+
const MODEL_EXTS=new Map([['.glb','model/gltf-binary'],['.gltf','model/gltf+json'],['.obj','model/obj']]);
|
|
21
|
+
const MODEL_MAX_SOURCE=32*1024*1024;
|
|
19
22
|
|
|
20
|
-
function
|
|
23
|
+
function inferAssetMime(path,bytes){
|
|
24
|
+
if(bytes.length>=12&&bytes[0]===0x67&&bytes[1]===0x6c&&bytes[2]===0x54&&bytes[3]===0x46)return 'model/gltf-binary';
|
|
21
25
|
if(bytes.length>=8&&bytes[0]===0x89&&bytes[1]===0x50&&bytes[2]===0x4e&&bytes[3]===0x47)return 'image/png';
|
|
22
26
|
if(bytes.length>=3&&bytes[0]===0xff&&bytes[1]===0xd8&&bytes[2]===0xff)return 'image/jpeg';
|
|
23
27
|
const ext=extname(path).toLowerCase();
|
|
28
|
+
if(MODEL_EXTS.has(ext))return MODEL_EXTS.get(ext);
|
|
24
29
|
if(ext==='.png')return 'image/png';
|
|
25
30
|
if(ext==='.jpg'||ext==='.jpeg')return 'image/jpeg';
|
|
26
31
|
throw Error('E_NATIVE_ASSET_MIME');
|
|
27
32
|
}
|
|
28
33
|
|
|
29
|
-
function
|
|
30
|
-
const full=JSON.stringify(payload);
|
|
31
|
-
if(full.length<=2048)return full;
|
|
32
|
-
const trimmed={...payload,prepOperations:(payload.prepOperations??[]).slice(0,4)};
|
|
33
|
-
const medium=JSON.stringify(trimmed);
|
|
34
|
-
if(medium.length<=2048)return medium;
|
|
35
|
-
delete trimmed.licenseEvidence;
|
|
36
|
-
delete trimmed.prepOperations;
|
|
37
|
-
return JSON.stringify(trimmed).slice(0,2048);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function normalizePrepOptions(item,index){
|
|
34
|
+
function normalizeImagePrepOptions(item,index){
|
|
41
35
|
const opts={
|
|
42
36
|
outputPrefix:item.outputPrefix??`prep_${String(index).padStart(2,'0')}`,
|
|
43
37
|
};
|
|
@@ -52,6 +46,25 @@ function normalizePrepOptions(item,index){
|
|
|
52
46
|
return opts;
|
|
53
47
|
}
|
|
54
48
|
|
|
49
|
+
function normalizeModelPrepOptions(item,index){
|
|
50
|
+
const opts={
|
|
51
|
+
outputPrefix:item.outputPrefix??`model_${String(index).padStart(2,'0')}`,
|
|
52
|
+
emitLosslessMaster:true,
|
|
53
|
+
};
|
|
54
|
+
if(item.mode!==undefined)opts.mode=item.mode;
|
|
55
|
+
if(item.maxTextureSide!==undefined)opts.maxTextureSide=item.maxTextureSide;
|
|
56
|
+
if(item.preserveGeometry!==undefined)opts.preserveGeometry=Boolean(item.preserveGeometry);
|
|
57
|
+
if(item.preserveResolution!==undefined)opts.preserveResolution=Boolean(item.preserveResolution);
|
|
58
|
+
if(item.preserveNamedNodes!==undefined)opts.preserveNamedNodes=Boolean(item.preserveNamedNodes);
|
|
59
|
+
if(item.preserveNodes!==undefined)opts.preserveNodes=item.preserveNodes;
|
|
60
|
+
if(item.targetTriangles!==undefined)opts.targetTriangles=item.targetTriangles;
|
|
61
|
+
if(item.targetBytes!==undefined)opts.targetBytes=item.targetBytes;
|
|
62
|
+
if(item.targetHeightMeters!==undefined)opts.targetHeightMeters=item.targetHeightMeters;
|
|
63
|
+
if(item.pivotMode!==undefined){check(pivotMode.enum.includes(item.pivotMode),'E_PREP_ARGUMENT');opts.pivotMode=item.pivotMode;}
|
|
64
|
+
if(item.upAxis!==undefined)opts.upAxis=item.upAxis;
|
|
65
|
+
return opts;
|
|
66
|
+
}
|
|
67
|
+
|
|
55
68
|
export async function prepAssets({workspaceRoot,items,catalog,remoteFetcher}){
|
|
56
69
|
check(Array.isArray(items)&&items.length>=1&&items.length<=16,'E_PREP_ARGUMENT');
|
|
57
70
|
const ws=resolveWorkspaceRoot(workspaceRoot);
|
|
@@ -60,7 +73,6 @@ export async function prepAssets({workspaceRoot,items,catalog,remoteFetcher}){
|
|
|
60
73
|
await mkdir(prepRoot,{recursive:true});
|
|
61
74
|
await assertStorePath(prepRoot);
|
|
62
75
|
|
|
63
|
-
const tool=requireNativeTool('prep');
|
|
64
76
|
const batchId='prep-'+randomUUID().slice(0,12);
|
|
65
77
|
const batchDir=resolve(prepRoot,batchId);
|
|
66
78
|
await mkdir(batchDir,{recursive:true});
|
|
@@ -76,10 +88,11 @@ export async function prepAssets({workspaceRoot,items,catalog,remoteFetcher}){
|
|
|
76
88
|
const hasSource=typeof item.sourceId==='string'&&item.sourceId.length>0;
|
|
77
89
|
check(hasFile!==hasSource,'E_PREP_ARGUMENT');
|
|
78
90
|
|
|
79
|
-
let bytes,mime,rights,provenance,sourceFile;
|
|
91
|
+
let bytes,mime,rights,provenance,sourceFile,sourceDependencies;
|
|
80
92
|
if(hasFile){
|
|
81
|
-
|
|
82
|
-
|
|
93
|
+
const isModelExt=MODEL_EXTS.has(extname(item.filePath).toLowerCase());
|
|
94
|
+
bytes=await readUploadFile(ws,item.filePath,isModelExt?MODEL_MAX_SOURCE:8_000_000);
|
|
95
|
+
mime=inferAssetMime(item.filePath,bytes);
|
|
83
96
|
sourceFile=item.filePath;
|
|
84
97
|
rights=typeof item.rights==='string'&&item.rights.trim().length>0
|
|
85
98
|
?item.rights.trim()
|
|
@@ -92,20 +105,86 @@ export async function prepAssets({workspaceRoot,items,catalog,remoteFetcher}){
|
|
|
92
105
|
};
|
|
93
106
|
}else{
|
|
94
107
|
const src=await resolveCc0SourceItem(item.sourceId,{catalog,remoteFetcher});
|
|
95
|
-
check(IMAGE_MIMES.has(src.mime),'E_NATIVE_ASSET_MIME');
|
|
96
|
-
bytes=src.bytes;
|
|
108
|
+
check(IMAGE_MIMES.has(src.mime)||src.mime==='model/gltf-binary','E_NATIVE_ASSET_MIME');
|
|
109
|
+
bytes=src.master?.bytes??src.bytes;
|
|
110
|
+
sourceDependencies=src.master?.dependencies;
|
|
97
111
|
mime=src.mime;
|
|
98
112
|
sourceFile=src.provenance?.sourceFile??item.sourceId;
|
|
99
113
|
rights=src.rights;
|
|
100
114
|
provenance={...src.provenance};
|
|
101
115
|
}
|
|
102
116
|
|
|
117
|
+
if(mime.startsWith('model/')){
|
|
118
|
+
const tool=requireNativeTool('prep-3d');
|
|
119
|
+
const stage=await mkdtemp(resolve(prepRoot,'.stage3d-'));
|
|
120
|
+
try{
|
|
121
|
+
const opts=normalizeModelPrepOptions(item,index);
|
|
122
|
+
let cliRoot=ws,inRel,outDirRel;
|
|
123
|
+
if(hasFile){
|
|
124
|
+
inRel=relative(ws,resolve(ws,item.filePath)).split(sep).join('/');
|
|
125
|
+
outDirRel=relative(ws,stage).split(sep).join('/');
|
|
126
|
+
check(!outDirRel.startsWith('..')&&!isAbsolute(outDirRel),'E_ASSET_PATH');
|
|
127
|
+
}else{
|
|
128
|
+
cliRoot=stage;
|
|
129
|
+
inRel='input.glb';
|
|
130
|
+
outDirRel='out';
|
|
131
|
+
await writeFile(resolve(stage,inRel),bytes,{flag:'wx'});
|
|
132
|
+
}
|
|
133
|
+
let report;
|
|
134
|
+
try{
|
|
135
|
+
const {stdout}=await run(tool.command,[...tool.prefixArgs,cliRoot,inRel,outDirRel,JSON.stringify(opts)],{timeout:120000,maxBuffer:2*1024*1024});
|
|
136
|
+
report=JSON.parse(stdout);
|
|
137
|
+
}catch(error){
|
|
138
|
+
const code=error.stderr?.match(/E_[A-Z_0-9]+/)?.[0]??'E_PREP_FAILED';
|
|
139
|
+
throw Error(code,{cause:error});
|
|
140
|
+
}
|
|
141
|
+
const outDirAbs=resolve(cliRoot,outDirRel);
|
|
142
|
+
const masterBytes=report.master?await readFile(resolve(outDirAbs,report.master.file)):null;
|
|
143
|
+
const itemFiles=[];
|
|
144
|
+
for(const out of report.outputs??[]){
|
|
145
|
+
const outBytes=await readFile(resolve(outDirAbs,out.file));
|
|
146
|
+
itemFiles.push({
|
|
147
|
+
kind:'model',
|
|
148
|
+
mime:'model/gltf-binary',
|
|
149
|
+
file:out.file,
|
|
150
|
+
bytes:outBytes,
|
|
151
|
+
bytesLen:out.bytesLen??outBytes.length,
|
|
152
|
+
sha256:out.sha256,
|
|
153
|
+
triangles:out.triangles,
|
|
154
|
+
vertices:out.vertices,
|
|
155
|
+
drawCalls:out.drawCalls,
|
|
156
|
+
materials:out.materials,
|
|
157
|
+
textures:out.textures,
|
|
158
|
+
subNodes:out.subNodes,
|
|
159
|
+
animations:out.animations??[],
|
|
160
|
+
boundsMin:out.boundsMin,
|
|
161
|
+
boundsMax:out.boundsMax,
|
|
162
|
+
geometryBytes:out.geometryBytes,
|
|
163
|
+
textureBytes:out.textureBytes,
|
|
164
|
+
decodedTextureBytes:out.decodedTextureBytes,
|
|
165
|
+
operations:out.operations,
|
|
166
|
+
warnings:out.warnings,
|
|
167
|
+
sourceHash:report.sourceSha256,
|
|
168
|
+
sourceFile,
|
|
169
|
+
rights,
|
|
170
|
+
provenance,
|
|
171
|
+
dependencies:sourceDependencies??report.dependencies??[],
|
|
172
|
+
master:report.master&&masterBytes?{file:report.master.file,sha256:report.master.sha256,bytes:masterBytes}:null,
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
return itemFiles;
|
|
176
|
+
}finally{
|
|
177
|
+
await rm(stage,{recursive:true,force:true});
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const tool=requireNativeTool('prep');
|
|
103
182
|
const stage=await mkdtemp(resolve(prepRoot,'.stage-'));
|
|
104
183
|
try{
|
|
105
184
|
const ext=mime==='image/jpeg'?'.jpg':'.png';
|
|
106
185
|
const inName='input'+ext;
|
|
107
186
|
await writeFile(resolve(stage,inName),bytes,{flag:'wx'});
|
|
108
|
-
const opts=
|
|
187
|
+
const opts=normalizeImagePrepOptions(item,index);
|
|
109
188
|
let report;
|
|
110
189
|
try{
|
|
111
190
|
const {stdout}=await run(tool.command,[...tool.prefixArgs,stage,inName,'out',JSON.stringify(opts)],{timeout:60000,maxBuffer:2*1024*1024});
|
|
@@ -118,6 +197,8 @@ export async function prepAssets({workspaceRoot,items,catalog,remoteFetcher}){
|
|
|
118
197
|
for(const out of report.outputs??[]){
|
|
119
198
|
const outBytes=await readFile(resolve(stage,'out',out.file));
|
|
120
199
|
itemFiles.push({
|
|
200
|
+
kind:'image',
|
|
201
|
+
mime:'image/png',
|
|
121
202
|
file:out.file,
|
|
122
203
|
bytes:outBytes,
|
|
123
204
|
width:out.width,
|
|
@@ -140,16 +221,29 @@ export async function prepAssets({workspaceRoot,items,catalog,remoteFetcher}){
|
|
|
140
221
|
|
|
141
222
|
for(const group of preparedItems){
|
|
142
223
|
for(const entry of group){
|
|
224
|
+
const ext=entry.kind==='model'?'.glb':'.png';
|
|
143
225
|
let finalName=entry.file;
|
|
144
226
|
if(usedFiles.has(finalName)){
|
|
145
|
-
const stem=finalName.replace(/\.png$/i,'');
|
|
227
|
+
const stem=finalName.replace(/\.(?:png|glb)$/i,'');
|
|
146
228
|
let n=2;
|
|
147
|
-
while(usedFiles.has(`${stem}_${n}
|
|
148
|
-
finalName=`${stem}_${n}
|
|
229
|
+
while(usedFiles.has(`${stem}_${n}${ext}`))n++;
|
|
230
|
+
finalName=`${stem}_${n}${ext}`;
|
|
149
231
|
}
|
|
150
232
|
usedFiles.add(finalName);
|
|
151
233
|
const outPath=resolve(batchDir,finalName);
|
|
152
234
|
await writeFile(outPath,entry.bytes,{flag:'wx'});
|
|
235
|
+
let masterFile=null;
|
|
236
|
+
if(entry.master){
|
|
237
|
+
masterFile=finalName.replace(/\.glb$/i,'.master.glb');
|
|
238
|
+
if(usedFiles.has(masterFile)){
|
|
239
|
+
const stem=masterFile.replace(/\.master\.glb$/i,'');
|
|
240
|
+
let n=2;
|
|
241
|
+
while(usedFiles.has(`${stem}_${n}.master.glb`))n++;
|
|
242
|
+
masterFile=`${stem}_${n}.master.glb`;
|
|
243
|
+
}
|
|
244
|
+
usedFiles.add(masterFile);
|
|
245
|
+
await writeFile(resolve(batchDir,masterFile),entry.master.bytes,{flag:'wx'});
|
|
246
|
+
}
|
|
153
247
|
const relPath=relative(ws,outPath).split(sep).join('/');
|
|
154
248
|
manifestEntries[finalName]={
|
|
155
249
|
outputSha256:entry.sha256,
|
|
@@ -158,21 +252,50 @@ export async function prepAssets({workspaceRoot,items,catalog,remoteFetcher}){
|
|
|
158
252
|
operations:entry.operations,
|
|
159
253
|
rights:entry.rights,
|
|
160
254
|
provenance:entry.provenance,
|
|
255
|
+
...(masterFile?{masterFile,masterSha256:entry.master.sha256,dependencies:entry.dependencies}:{}),
|
|
161
256
|
};
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
257
|
+
if(entry.kind==='model'){
|
|
258
|
+
outputs.push({
|
|
259
|
+
filePath:relPath,
|
|
260
|
+
file:finalName,
|
|
261
|
+
mime:'model/gltf-binary',
|
|
262
|
+
bytes:entry.bytesLen,
|
|
263
|
+
sha256:entry.sha256,
|
|
264
|
+
triangles:entry.triangles,
|
|
265
|
+
vertices:entry.vertices,
|
|
266
|
+
drawCalls:entry.drawCalls,
|
|
267
|
+
materials:entry.materials,
|
|
268
|
+
textures:entry.textures,
|
|
269
|
+
subNodes:entry.subNodes,
|
|
270
|
+
animations:entry.animations,
|
|
271
|
+
boundsMin:entry.boundsMin,
|
|
272
|
+
boundsMax:entry.boundsMax,
|
|
273
|
+
geometryBytes:entry.geometryBytes,
|
|
274
|
+
textureBytes:entry.textureBytes,
|
|
275
|
+
decodedTextureBytes:entry.decodedTextureBytes,
|
|
276
|
+
dependencies:entry.dependencies,
|
|
277
|
+
operations:entry.operations,
|
|
278
|
+
warnings:entry.warnings,
|
|
279
|
+
rights:entry.rights,
|
|
280
|
+
styleFamily:entry.provenance?.styleFamily??null,
|
|
281
|
+
sourceHash:entry.sourceHash,
|
|
282
|
+
});
|
|
283
|
+
}else{
|
|
284
|
+
outputs.push({
|
|
285
|
+
filePath:relPath,
|
|
286
|
+
file:finalName,
|
|
287
|
+
mime:'image/png',
|
|
288
|
+
width:entry.width,
|
|
289
|
+
height:entry.height,
|
|
290
|
+
bytes:entry.bytesLen,
|
|
291
|
+
sha256:entry.sha256,
|
|
292
|
+
hasAlpha:entry.hasAlpha,
|
|
293
|
+
operations:entry.operations,
|
|
294
|
+
rights:entry.rights,
|
|
295
|
+
styleFamily:entry.provenance?.styleFamily??null,
|
|
296
|
+
sourceHash:entry.sourceHash,
|
|
297
|
+
});
|
|
298
|
+
}
|
|
176
299
|
}
|
|
177
300
|
}
|
|
178
301
|
|
|
@@ -210,6 +333,15 @@ export async function resolvePreparedProvenance(workspaceRoot,filePath,bytes){
|
|
|
210
333
|
if(!entry||typeof entry.outputSha256!=='string')throw Error('E_PREP_PROVENANCE_MISMATCH');
|
|
211
334
|
if(hash(bytes)!==entry.outputSha256)throw Error('E_PREP_PROVENANCE_MISMATCH');
|
|
212
335
|
|
|
336
|
+
let master;
|
|
337
|
+
if(entry.masterFile){
|
|
338
|
+
const masterPath=resolve(batchDir,entry.masterFile);
|
|
339
|
+
await assertStorePath(masterPath);
|
|
340
|
+
const masterBytes=await safeFile(masterPath);
|
|
341
|
+
if(hash(masterBytes)!==entry.masterSha256)throw Error('E_PREP_PROVENANCE_MISMATCH');
|
|
342
|
+
master={bytes:masterBytes,sha256:entry.masterSha256,dependencies:entry.dependencies??[]};
|
|
343
|
+
}
|
|
344
|
+
|
|
213
345
|
const mergedProvenance={
|
|
214
346
|
...(entry.provenance&&typeof entry.provenance==='object'?entry.provenance:{}),
|
|
215
347
|
preparedFrom:entry.sourceHash,
|
|
@@ -218,7 +350,8 @@ export async function resolvePreparedProvenance(workspaceRoot,filePath,bytes){
|
|
|
218
350
|
};
|
|
219
351
|
return {
|
|
220
352
|
rights:entry.rights,
|
|
221
|
-
provenance:
|
|
353
|
+
provenance:compactAssetProvenance(mergedProvenance),
|
|
222
354
|
styleFamily:entry.provenance?.styleFamily??null,
|
|
355
|
+
...(master?{master}:{}),
|
|
223
356
|
};
|
|
224
357
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import {execFile} from 'node:child_process';
|
|
2
|
+
import {randomUUID} from 'node:crypto';
|
|
2
3
|
import {promisify} from 'node:util';
|
|
3
|
-
import {readFile,writeFile,mkdir,mkdtemp,rm,lstat} from 'node:fs/promises';
|
|
4
|
-
import {resolve,dirname,relative,isAbsolute} from 'node:path';
|
|
4
|
+
import {readFile,writeFile,link,mkdir,mkdtemp,rm,lstat,unlink} from 'node:fs/promises';
|
|
5
|
+
import {resolve,dirname,relative,isAbsolute,extname} from 'node:path';
|
|
5
6
|
import {Buffer} from 'node:buffer';
|
|
6
7
|
import process from 'node:process';
|
|
7
8
|
import {check,exact,identifier} from './document.mjs';
|
|
@@ -16,13 +17,24 @@ export const nativeDecoderPath=resolve(examples,process.platform==='win32'?'insp
|
|
|
16
17
|
export const nativeOptimizerPath=resolve(examples,process.platform==='win32'?'optimize_native.exe':'optimize_native');
|
|
17
18
|
async function noLinks(path){let p=resolve(path);while(p!==dirname(p)){try{check(!(await lstat(p)).isSymbolicLink(),'E_NATIVE_ASSET_PATH');}catch(e){if(e.code!=='ENOENT')throw e;}p=dirname(p);}}
|
|
18
19
|
export async function safeFile(path){await noLinks(path);return readFile(path);}
|
|
19
|
-
export
|
|
20
|
+
export const modelSourceTypes = new Map([['model/gltf-binary','.glb'],['model/gltf+json','.gltf'],['model/obj','.obj']]);
|
|
21
|
+
const modelSourceLimit = 32*1024*1024;
|
|
22
|
+
export async function readUploadFile(root,path,maxBytes=8_000_000){
|
|
20
23
|
check(typeof path==='string'&&path.length>0&&path.length<=4096&&!path.includes('\0'),'E_NATIVE_ASSET_PATH');
|
|
21
24
|
const base=resolve(root),candidate=resolve(base,path),rel=relative(base,candidate);check(rel&&!rel.startsWith('..')&&!isAbsolute(rel),'E_NATIVE_ASSET_PATH');
|
|
22
|
-
await noLinks(candidate);const info=await lstat(candidate);check(info.isFile()&&info.size>0&&info.size<=
|
|
25
|
+
await noLinks(candidate);const info=await lstat(candidate);check(info.isFile()&&info.size>0&&info.size<=maxBytes,'E_NATIVE_ASSET_SIZE');return readFile(candidate);
|
|
23
26
|
}
|
|
24
27
|
export async function readOriginal(root,digest){check(/^sha256:[a-f0-9]{64}$/.test(digest),'E_NATIVE_ASSET_PATH');return safeFile(resolve(root,'sources/assets/originals',digest.slice(7)));}
|
|
25
|
-
async function writeContent(path,bytes
|
|
28
|
+
async function writeContent(path,bytes,verifyExisting=existing=>check(hash(existing)===hash(bytes),'E_NATIVE_ASSET_HASH')){
|
|
29
|
+
const temp=path+'.'+randomUUID()+'.tmp';
|
|
30
|
+
try{
|
|
31
|
+
await writeFile(temp,bytes,{flag:'wx'});
|
|
32
|
+
try{await link(temp,path);}catch(error){
|
|
33
|
+
if(error.code!=='EEXIST')throw error;
|
|
34
|
+
verifyExisting(await safeFile(path));
|
|
35
|
+
}
|
|
36
|
+
}finally{await unlink(temp).catch(error=>{if(error.code!=='ENOENT')throw error;});}
|
|
37
|
+
}
|
|
26
38
|
async function inspectImage(stage,file,mime){let decoded;try{const tool=requireNativeTool('inspect');decoded=JSON.parse((await run(tool.command,[...tool.prefixArgs,stage,file],{timeout:10000,maxBuffer:16384})).stdout)[0];}catch{throw Error('E_NATIVE_ASSET_DECODE');}check(decoded?.source_mime===mime,'E_NATIVE_ASSET_MIME');return decoded;}
|
|
27
39
|
const PNG_SIG=[0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a];
|
|
28
40
|
const isPngBytes=b=>b.length>=24&&PNG_SIG.every((v,i)=>b[i]===v);
|
|
@@ -60,22 +72,76 @@ export function verifyImageSignature(bytes,mime){
|
|
|
60
72
|
}
|
|
61
73
|
throw Error('E_NATIVE_ASSET_DECODE');
|
|
62
74
|
}
|
|
75
|
+
async function runModelTool(kind,stage,args){
|
|
76
|
+
const tool=requireNativeTool(kind);
|
|
77
|
+
try{
|
|
78
|
+
const {stdout}=await run(tool.command,[...tool.prefixArgs,stage,...args],{timeout:120000,maxBuffer:1048576});
|
|
79
|
+
return JSON.parse(stdout);
|
|
80
|
+
}catch(cause){
|
|
81
|
+
throw Error(cause.stderr?.match(/E_[A-Z_0-9]+/)?.[0]??'E_NATIVE_ASSET_DECODE',{cause});
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export async function registerSourceFromFile(root,workspaceRoot,filePath,input,options={}){
|
|
85
|
+
const extension=modelSourceTypes.get(input.mime);
|
|
86
|
+
if(extension)check(extname(filePath).toLowerCase()===extension,'E_NATIVE_ASSET_MIME');
|
|
87
|
+
const bytes=await readUploadFile(workspaceRoot,filePath,extension?modelSourceLimit:8_000_000);
|
|
88
|
+
const prepared=await options.preparedProvenance?.(workspaceRoot,filePath,bytes);
|
|
89
|
+
const rights=prepared?.rights&&!prepared.provenance.includes('"studio-original"')?prepared.rights:input.rights;
|
|
90
|
+
return registerSourceBytes(root,{...input,rights},bytes,{...options,...(prepared?{provenance:prepared.provenance,master:prepared.master}: {})});
|
|
91
|
+
}
|
|
63
92
|
export async function registerSource(root,input,options={}){
|
|
64
|
-
check(
|
|
93
|
+
check(typeof input.data==='string'&&input.data.length<=11184812&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input.data),'E_NATIVE_ASSET');
|
|
94
|
+
const bytes=Buffer.from(input.data,'base64');
|
|
95
|
+
check(bytes.length<=8_000_000,'E_NATIVE_ASSET_SIZE');
|
|
96
|
+
const {data,...metadata}=input;void data;
|
|
97
|
+
return registerSourceBytes(root,metadata,bytes,options);
|
|
98
|
+
}
|
|
99
|
+
export async function registerSourceBytes(root,input,raw,options={}){
|
|
100
|
+
check(exact(input,['id','mime','rights','optimize','preserveResolution','maxTextureSide','preserveGeometry','targetTriangles'])&&identifier(input.id)&&typeof input.rights==='string'&&input.rights.trim().length>0&&input.rights.length<=2048,'E_NATIVE_ASSET');
|
|
65
101
|
const provenanceText=options.provenance!==undefined?options.provenance:'Public API upload; content hash and decoded media verified by Tora.';
|
|
66
102
|
check(typeof provenanceText==='string'&&provenanceText.length>0&&provenanceText.length<=2048,'E_NATIVE_ASSET');
|
|
67
103
|
const optimize=input.optimize??'auto',preserveResolution=input.preserveResolution??false;
|
|
68
104
|
check(['auto','lossless','none'].includes(optimize)&&typeof preserveResolution==='boolean','E_NATIVE_ASSET');
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
105
|
+
const modelExt=modelSourceTypes.get(input.mime);
|
|
106
|
+
check(modelExt||input.maxTextureSide===undefined&&input.preserveGeometry===undefined&&input.targetTriangles===undefined,'E_NATIVE_ASSET');
|
|
107
|
+
const optimizable=Boolean(modelExt)||['image/png','image/jpeg','audio/wav','audio/mpeg'].includes(input.mime);
|
|
108
|
+
const original=options.master?.bytes??raw;
|
|
109
|
+
const originalMime=options.master?'model/gltf-binary':input.mime;
|
|
110
|
+
check(Buffer.isBuffer(original)&&original.length>0&&original.length<=(modelExt?modelSourceLimit:optimizable?8_000_000:700_000),'E_NATIVE_ASSET_SIZE');
|
|
72
111
|
const originalHash=hash(original),folder=resolve(root,'sources/assets'),originals=resolve(folder,'originals');
|
|
112
|
+
if(options.master?.sha256)check(originalHash===options.master.sha256,'E_NATIVE_ASSET_HASH');
|
|
73
113
|
await noLinks(folder);await mkdir(originals,{recursive:true});const stage=await mkdtemp(resolve(folder,'.decode-'));
|
|
74
114
|
try{
|
|
75
115
|
let bytes=original,mime=input.mime,optimization,imageOptimized=false;
|
|
76
116
|
if(optimizable){
|
|
77
117
|
await writeContent(resolve(originals,originalHash.slice(7)),original);
|
|
78
|
-
if(
|
|
118
|
+
if(modelExt){
|
|
119
|
+
const modelOptions={mode:optimize,preserveResolution};
|
|
120
|
+
if(input.maxTextureSide!==undefined)modelOptions.maxTextureSide=input.maxTextureSide;
|
|
121
|
+
if(input.preserveGeometry!==undefined)modelOptions.preserveGeometry=input.preserveGeometry;
|
|
122
|
+
if(input.targetTriangles!==undefined)modelOptions.targetTriangles=input.targetTriangles;
|
|
123
|
+
let result;
|
|
124
|
+
if(options.master&&input.optimize===undefined&&input.maxTextureSide===undefined&&input.preserveGeometry===undefined&&input.preserveResolution===undefined&&input.targetTriangles===undefined){
|
|
125
|
+
bytes=raw;mime='model/gltf-binary';
|
|
126
|
+
await writeFile(resolve(stage,'prepared.glb'),raw);
|
|
127
|
+
result=await runModelTool('inspect-3d',stage,['prepared.glb']);
|
|
128
|
+
}else{
|
|
129
|
+
const name='input'+modelSourceTypes.get(originalMime);
|
|
130
|
+
await writeFile(resolve(stage,name),original);
|
|
131
|
+
result=await runModelTool('optimize-3d',stage,[name,'output.glb',JSON.stringify(modelOptions)]);
|
|
132
|
+
bytes=await readFile(resolve(stage,'output.glb'));mime='model/gltf-binary';
|
|
133
|
+
}
|
|
134
|
+
optimization={...result,originalHash,originalMime,originalBytes:original.length,mode:optimize,options:modelOptions,savedBytes:original.length-bytes.length,savedPercent:Number(((original.length-bytes.length)*100/original.length).toFixed(1))};
|
|
135
|
+
if(options.master?.dependencies){
|
|
136
|
+
const manifest=Buffer.from(JSON.stringify(options.master.dependencies)),digest=hash(manifest);
|
|
137
|
+
await writeContent(resolve(originals,digest.slice(7)),manifest);
|
|
138
|
+
optimization.dependencyManifestHash=digest;
|
|
139
|
+
}else if(options.dependencyManifestHash){
|
|
140
|
+
const manifest=await readOriginal(root,options.dependencyManifestHash);
|
|
141
|
+
check(hash(manifest)===options.dependencyManifestHash,'E_NATIVE_ASSET_HASH');
|
|
142
|
+
optimization.dependencyManifestHash=options.dependencyManifestHash;
|
|
143
|
+
}
|
|
144
|
+
}else if(mime==='audio/wav'||mime==='audio/mpeg'){
|
|
79
145
|
const result=await optimizeAudio(original,mime,{mode:optimize,stagingDir:stage});bytes=result.bytes;mime=result.mime;
|
|
80
146
|
optimization={mode:optimize,originalHash,originalMime:input.mime,originalBytes:original.length,savedBytes:original.length-bytes.length,savedPercent:Number(((original.length-bytes.length)*100/original.length).toFixed(1)),operations:result.operations,encoder:result.encoder};
|
|
81
147
|
}else{
|
|
@@ -93,6 +159,7 @@ export async function registerSource(root,input,options={}){
|
|
|
93
159
|
if(mime==='audio/wav')validateWav(bytes);
|
|
94
160
|
else if(mime==='audio/mpeg')validateMp3(bytes,'E_NATIVE_ASSET_DECODE');
|
|
95
161
|
else if(mime==='model/tora-mesh')validateToraMesh(bytes,'E_NATIVE_ASSET_DECODE');
|
|
162
|
+
else if(mime==='model/gltf-binary')check(Boolean(optimization),'E_NATIVE_ASSET_DECODE');
|
|
96
163
|
else{
|
|
97
164
|
check(['image/png','image/jpeg'].includes(mime),'E_NATIVE_ASSET_MIME');
|
|
98
165
|
if(imageOptimized){
|
|
@@ -102,7 +169,10 @@ export async function registerSource(root,input,options={}){
|
|
|
102
169
|
}
|
|
103
170
|
await writeContent(resolve(folder,file),bytes);
|
|
104
171
|
const metadata={mime,bytes:bytes.length,...(optimization?{optimization}:{})},path=resolve(folder,file+'.json');
|
|
105
|
-
|
|
172
|
+
await writeContent(path,JSON.stringify(metadata),bytes=>{
|
|
173
|
+
const existing=JSON.parse(bytes.toString());
|
|
174
|
+
check(existing.mime===metadata.mime&&existing.bytes===metadata.bytes,'E_NATIVE_ASSET_METADATA');
|
|
175
|
+
});
|
|
106
176
|
return {id:input.id,hash:digest,mime,bytes:bytes.length,rights:input.rights,provenance:provenanceText,...(optimization?{optimization}:{})};
|
|
107
177
|
}finally{await rm(stage,{recursive:true,force:true});}
|
|
108
178
|
}
|
|
@@ -113,3 +183,29 @@ export async function lowerAssets(root,assets){
|
|
|
113
183
|
return {...a,data:bytes.toString('base64')};
|
|
114
184
|
});
|
|
115
185
|
}
|
|
186
|
+
|
|
187
|
+
export async function storeVerifiedDeliveryAsset(root,{mime,bytes,expectedHash}){
|
|
188
|
+
check(Buffer.isBuffer(bytes)&&bytes.length>0&&bytes.length<=700000,'E_NATIVE_ASSET_SIZE');
|
|
189
|
+
check(hash(bytes)===expectedHash,'E_NATIVE_ASSET_HASH');
|
|
190
|
+
const folder=resolve(root,'sources/assets');
|
|
191
|
+
await noLinks(folder);await mkdir(folder,{recursive:true});
|
|
192
|
+
const stage=await mkdtemp(resolve(folder,'.import-'));
|
|
193
|
+
try{
|
|
194
|
+
if(mime==='model/tora-mesh')validateToraMesh(bytes,'E_NATIVE_ASSET_DECODE');
|
|
195
|
+
else if(mime==='audio/mpeg')validateMp3(bytes,'E_NATIVE_ASSET_DECODE');
|
|
196
|
+
else if(mime==='audio/wav')validateWav(bytes);
|
|
197
|
+
else{
|
|
198
|
+
const name=mime==='model/gltf-binary'?'delivery.glb':'delivery';
|
|
199
|
+
await writeFile(resolve(stage,name),bytes);
|
|
200
|
+
if(mime==='model/gltf-binary')await runModelTool('inspect-3d',stage,[name]);
|
|
201
|
+
else{
|
|
202
|
+
check(mime==='image/jpeg'||mime==='image/png','E_NATIVE_ASSET_MIME');
|
|
203
|
+
await inspectImage(stage,name,mime);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const name=expectedHash.slice(7);
|
|
207
|
+
await writeContent(resolve(folder,name),bytes);
|
|
208
|
+
const metadata={mime,bytes:bytes.length,importedDeliveryOnly:true},metaPath=resolve(folder,name+'.json');
|
|
209
|
+
try{await writeFile(metaPath,JSON.stringify(metadata),{flag:'wx'});}catch(e){if(e.code!=='EEXIST')throw e;const existing=JSON.parse((await safeFile(metaPath)).toString());check(existing.mime===metadata.mime&&existing.bytes===metadata.bytes,'E_NATIVE_ASSET_METADATA');}
|
|
210
|
+
}finally{await rm(stage,{recursive:true,force:true});}
|
|
211
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import {readFile} from 'node:fs/promises';
|
|
2
|
+
import {resolve} from 'node:path';
|
|
3
|
+
import {fileURLToPath,URL} from 'node:url';
|
|
4
|
+
import {check,exact,identifier} from './document.mjs';
|
|
5
|
+
import {registerSource} from './assets.mjs';
|
|
6
|
+
import {validateAssetPolicy} from './asset-policy.mjs';
|
|
7
|
+
import {loadCatalog} from './catalog-cache.mjs';
|
|
8
|
+
|
|
9
|
+
const root=fileURLToPath(new URL('../../../',import.meta.url));
|
|
10
|
+
export async function catalogAudio(){return (await loadCatalog()).audioFiles;}
|
|
11
|
+
|
|
12
|
+
export async function stageAudio(service,id,imports,{optimize}={}){
|
|
13
|
+
check(Array.isArray(imports)&&imports.length<=8,'E_REVIEW_IMPORT');
|
|
14
|
+
if(!imports.length)return [];
|
|
15
|
+
const catalog=await catalogAudio(),operations=[];
|
|
16
|
+
for(const item of imports){
|
|
17
|
+
check(exact(item,['catalogId','assetId'])&&identifier(item.assetId),'E_REVIEW_IMPORT');
|
|
18
|
+
const choice=catalog.find(cue=>cue.catalogId===item.catalogId);
|
|
19
|
+
check(choice,'E_REVIEW_IMPORT');
|
|
20
|
+
const {source,file}=choice;
|
|
21
|
+
const provenance={origin:'third-party-free',sourceId:source.id,sourceFile:file.path,sourceHash:file.sha256,author:source.author,license:source.license,sourceUrl:source.sourceUrl,styleFamily:source.styleFamily};
|
|
22
|
+
const data=(await readFile(resolve(root,file.file))).toString('base64');
|
|
23
|
+
const receipt=validateAssetPolicy({mime:file.mime,data,provenance},{role:'audio'});
|
|
24
|
+
const rights=[source.author+', '+source.license+'. '+source.sourceUrl,receipt.attribution].filter(Boolean).join('\n');
|
|
25
|
+
const asset=await registerSource(resolve(service.store.root,id),{id:item.assetId,mime:file.mime,data,rights,...(optimize?{optimize}:{})});
|
|
26
|
+
const record={...asset};delete record.optimization;
|
|
27
|
+
operations.push({kind:'registerAsset',asset:{...record,provenance:JSON.stringify(receipt)}});
|
|
28
|
+
}
|
|
29
|
+
return operations;
|
|
30
|
+
}
|
|
@@ -1,9 +1,22 @@
|
|
|
1
1
|
/** Lazy, crash-recovering Playwright Chromium manager for local authoring/QA. */
|
|
2
|
+
import {cpus} from 'node:os';
|
|
3
|
+
import process from 'node:process';
|
|
2
4
|
import {setTimeout,clearTimeout} from 'node:timers';
|
|
3
5
|
|
|
4
6
|
const IDLE_MS=5*60*1000;
|
|
5
7
|
let browser=null,launching=null,idleTimer=null;
|
|
6
8
|
|
|
9
|
+
export function defaultQaConcurrency(){
|
|
10
|
+
const override=process.env.TORA_QA_CONCURRENCY;
|
|
11
|
+
if(override!==undefined){
|
|
12
|
+
if(!/^[1-9][0-9]*$/.test(override))throw Error('E_QA_CONCURRENCY');
|
|
13
|
+
const value=Number(override);
|
|
14
|
+
if(!Number.isSafeInteger(value))throw Error('E_QA_CONCURRENCY');
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
return Math.min(4,Math.max(1,cpus().length-1));
|
|
18
|
+
}
|
|
19
|
+
|
|
7
20
|
function scheduleIdleClose(){
|
|
8
21
|
if(idleTimer)clearTimeout(idleTimer);
|
|
9
22
|
idleTimer=setTimeout(()=>{void closeSharedBrowser();},IDLE_MS);
|
|
@@ -43,3 +56,24 @@ export async function closeSharedBrowser(){
|
|
|
43
56
|
await current.close?.().catch(()=>{});
|
|
44
57
|
}
|
|
45
58
|
}
|
|
59
|
+
|
|
60
|
+
function isDisconnectFailure(instance,error){
|
|
61
|
+
if(instance?.isConnected?.()===false)return true;
|
|
62
|
+
return /(?:browser|context|target|connection).*(?:disconnect|closed)|(?:disconnect|closed).*(?:browser|context|target|connection)/i.test(error?.message??'');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function withBrowserContext(run,{launcher,contextOptions}={}){
|
|
66
|
+
let recovered=false;
|
|
67
|
+
while(true){
|
|
68
|
+
const instance=await getSharedBrowser(launcher);let context;
|
|
69
|
+
try{
|
|
70
|
+
context=await instance.newContext(contextOptions);
|
|
71
|
+
return await run(context,instance);
|
|
72
|
+
}catch(error){
|
|
73
|
+
if(recovered||!isDisconnectFailure(instance,error))throw error;
|
|
74
|
+
recovered=true;
|
|
75
|
+
}finally{
|
|
76
|
+
if(context)await context.close?.().catch(()=>{});
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -1,20 +1,24 @@
|
|
|
1
1
|
import {createHash,randomUUID} from 'node:crypto';
|
|
2
2
|
import {mkdir,readdir,rename,rm,stat,writeFile} from 'node:fs/promises';
|
|
3
|
-
import {resolve} from 'node:path';
|
|
3
|
+
import {isAbsolute,relative,resolve} from 'node:path';
|
|
4
4
|
import {canonical,projectContent} from '../../../packages/creative-project/src/canonical.mjs';
|
|
5
5
|
import {safeFile} from './assets.mjs';
|
|
6
6
|
import {assertStorePath} from './store-path.mjs';
|
|
7
7
|
|
|
8
8
|
const digest=value=>'sha256:'+createHash('sha256').update(value).digest('hex');
|
|
9
9
|
export const VERIFICATION_CACHE_VERSION='tora-verify-cache-1';
|
|
10
|
-
export function buildCacheKey({project,target,runtimeHash}){
|
|
11
|
-
return digest(canonical({format:'tora-build-cache-
|
|
10
|
+
export function buildCacheKey({project,target,runtimeHash,fitPolicyKey='standard',deliveredAssetHashes=project.assets.map(asset=>asset.hash)}){
|
|
11
|
+
return digest(canonical({format:'tora-build-cache-2',revisionId:project.revisionId,contentHash:digest('tora-v2-hash/1\ndocument-content\n'+canonical(projectContent(project))),target,runtimeHash,fitPolicyKey,deliveredAssetHashes}));
|
|
12
12
|
}
|
|
13
13
|
export class NativeBuildCache{
|
|
14
|
-
constructor({maxEntries=
|
|
14
|
+
constructor({maxEntries=64}={}){
|
|
15
15
|
if(!Number.isSafeInteger(maxEntries)||maxEntries<1)throw Error('E_NATIVE_CACHE_ARGUMENT');
|
|
16
16
|
this.maxEntries=maxEntries;this.entries=new Map();this.inFlight=new Map();this.counters={hits:0,misses:0,inFlightDedupes:0};
|
|
17
17
|
}
|
|
18
|
+
peek(key){
|
|
19
|
+
if(!this.entries.has(key))return null;
|
|
20
|
+
return {...this.entries.get(key),cacheHit:true};
|
|
21
|
+
}
|
|
18
22
|
async getOrBuild(key,buildFn){
|
|
19
23
|
if(this.entries.has(key)){
|
|
20
24
|
const value=this.entries.get(key);this.entries.delete(key);this.entries.set(key,value);this.counters.hits++;
|
|
@@ -35,12 +39,12 @@ export class NativeBuildCache{
|
|
|
35
39
|
stats(){return {...this.counters};}
|
|
36
40
|
}
|
|
37
41
|
export class VerificationReceiptCache{
|
|
38
|
-
constructor(storeRoot,{maxFiles=
|
|
42
|
+
constructor(storeRoot,{maxFiles=512}={}){
|
|
39
43
|
if(!Number.isSafeInteger(maxFiles)||maxFiles<1)throw Error('E_NATIVE_CACHE_ARGUMENT');
|
|
40
44
|
this.root=resolve(storeRoot,'.cache','verify');this.maxFiles=maxFiles;
|
|
41
45
|
}
|
|
42
|
-
receiptKey({artifactHash,checkerVersion,kind,viewport,host,scenario}){
|
|
43
|
-
return digest(canonical({format:VERIFICATION_CACHE_VERSION,artifactHash,checkerVersion,kind,viewport:viewport??'',host:host??'',scenario:scenario??''}));
|
|
46
|
+
receiptKey({artifactHash,checkerVersion,kind,viewport,host,scenario,qaTier='full',artifactCheckVersion}){
|
|
47
|
+
return digest(canonical({format:VERIFICATION_CACHE_VERSION,artifactHash,checkerVersion,kind,viewport:viewport??'',host:host??'',scenario:scenario??'',qaTier,artifactCheckVersion:artifactCheckVersion??''}));
|
|
44
48
|
}
|
|
45
49
|
path(key){
|
|
46
50
|
if(typeof key!=='string'||!/^sha256:[a-f0-9]{64}$/.test(key))throw Error('E_NATIVE_CACHE_KEY');
|
|
@@ -69,4 +73,31 @@ export class VerificationReceiptCache{
|
|
|
69
73
|
}
|
|
70
74
|
return payload;
|
|
71
75
|
}
|
|
76
|
+
async pruneOrphanedArtifactDirs(qaByArtifactRoot){
|
|
77
|
+
await assertStorePath(this.root);
|
|
78
|
+
let names;
|
|
79
|
+
try{names=(await readdir(this.root)).filter(name=>/^[a-f0-9]{64}\.json$/.test(name)).sort();}
|
|
80
|
+
catch(error){if(error.code!=='ENOENT')throw error;names=[];}
|
|
81
|
+
if(names.length>this.maxFiles)return [];
|
|
82
|
+
const referenced=[];
|
|
83
|
+
for(const name of names){
|
|
84
|
+
try{
|
|
85
|
+
const envelope=JSON.parse((await safeFile(resolve(this.root,name))).toString());
|
|
86
|
+
if(envelope?.format!==VERIFICATION_CACHE_VERSION||envelope.key!=='sha256:'+name.slice(0,-5)||typeof envelope.payload?.outputDir!=='string')continue;
|
|
87
|
+
referenced.push(resolve(envelope.payload.outputDir));
|
|
88
|
+
}catch{/* ignore invalid receipts */}
|
|
89
|
+
}
|
|
90
|
+
const root=resolve(qaByArtifactRoot);await assertStorePath(root);
|
|
91
|
+
let entries;
|
|
92
|
+
try{entries=await readdir(root,{withFileTypes:true});}
|
|
93
|
+
catch(error){if(error.code==='ENOENT')return [];throw error;}
|
|
94
|
+
const contains=(parent,child)=>{const rel=relative(parent,child);return rel===''||!rel.startsWith('..')&&!isAbsolute(rel);};
|
|
95
|
+
const removed=[];
|
|
96
|
+
for(const entry of entries.filter(entry=>entry.isDirectory()).sort((a,b)=>a.name.localeCompare(b.name)).slice(0,this.maxFiles)){
|
|
97
|
+
const path=resolve(root,entry.name);
|
|
98
|
+
if(referenced.some(output=>contains(path,output)||contains(output,path)))continue;
|
|
99
|
+
await rm(path,{recursive:true,force:true});removed.push(path);
|
|
100
|
+
}
|
|
101
|
+
return removed;
|
|
102
|
+
}
|
|
72
103
|
}
|