@tora-editor/tora 0.1.0 → 0.2.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 +108 -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 +77 -9
- package/crates/packer/trusted/native-3d-meta.json +3 -2
- package/crates/packer/trusted/native-3d.js +181 -181
- package/crates/packer/trusted/native-meta.json +2 -2
- 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 +3 -2
- package/crates/packer/trusted/review-runtime.js +182 -182
- package/docs/TORA_AGENT_SETUP.md +24 -13
- package/docs/TORA_CREATION_API.md +29 -12
- package/docs/reference/CORE_AUTHORING.md +2 -1
- package/docs/reference/PLAYABLE_STARTERS.md +20 -0
- package/docs/reference/packs/3d.md +9 -3
- package/network-rules/mintegral-appgrowth-single-html.json +10 -10
- package/package.json +6 -6
- package/packages/creative-project/project-v21.schema.json +264 -8
- package/scripts/lean/editor/review-editor.css +10 -0
- package/scripts/lean/editor/review-editor.js +117 -1
- package/scripts/lean/native/agent-tools.mjs +7 -7
- package/scripts/lean/native/api.mjs +16 -5
- 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/author-expansion-proofs.mjs +2 -99
- package/scripts/lean/native/author-fps.mjs +545 -0
- package/scripts/lean/native/author-primitive-proofs.mjs +5 -4
- package/scripts/lean/native/build-cache.mjs +2 -2
- package/scripts/lean/native/cc0-inputs.mjs +24 -0
- package/scripts/lean/native/cc0-staging.mjs +28 -8
- package/scripts/lean/native/check-harvest-outcome-audio.mjs +7 -8
- package/scripts/lean/native/check-salvage.mjs +8 -5
- package/scripts/lean/native/compiler.mjs +9 -3
- package/scripts/lean/native/contracts.mjs +11 -8
- package/scripts/lean/native/creative-qa.mjs +305 -122
- package/scripts/lean/native/demos.mjs +47 -3
- package/scripts/lean/native/document.mjs +36 -10
- package/scripts/lean/native/export-budget.mjs +75 -0
- package/scripts/lean/native/glb-loader.mjs +468 -0
- package/scripts/lean/native/intake-creator-tools.mjs +83 -30
- package/scripts/lean/native/local-bundle.mjs +5 -3
- package/scripts/lean/native/mcp-server.mjs +33 -46
- package/scripts/lean/native/media-validate.mjs +124 -0
- package/scripts/lean/native/native-bin.mjs +3 -3
- package/scripts/lean/native/outcome-playthrough.mjs +97 -0
- package/scripts/lean/native/prepare-fps-assets.mjs +330 -0
- package/scripts/lean/native/project-bundle.mjs +3 -3
- package/scripts/lean/native/remote-cc0-fetcher.mjs +403 -197
- package/scripts/lean/native/review-agent-tools.mjs +2 -2
- package/scripts/lean/native/review.mjs +3 -0
- package/scripts/lean/native/runtime.mjs +242 -56
- package/scripts/lean/native/schema.mjs +7 -5
- package/scripts/lean/native/service.mjs +159 -32
- package/scripts/lean/native/stage-3d.mjs +343 -40
- package/scripts/lean/native/starters.mjs +436 -0
- package/scripts/lean/native/verify.mjs +1 -1
- package/scripts/lean/native/win-cues.mjs +96 -0
- package/skills/tora-playables/SKILL.md +1 -1
|
@@ -4,20 +4,31 @@ import {execFile} from 'node:child_process';
|
|
|
4
4
|
import {createHash,randomUUID} from 'node:crypto';
|
|
5
5
|
import {mkdir,mkdtemp,readdir,readFile,rename,rm,writeFile} from 'node:fs/promises';
|
|
6
6
|
import {lookup as dnsLookup} from 'node:dns/promises';
|
|
7
|
+
import {request as httpsRequest} from 'node:https';
|
|
7
8
|
import {isIP} from 'node:net';
|
|
8
|
-
import {
|
|
9
|
+
import {dirname,extname,resolve} from 'node:path';
|
|
9
10
|
import {URL} from 'node:url';
|
|
10
11
|
import {setTimeout,clearTimeout} from 'node:timers';
|
|
11
12
|
import {promisify} from 'node:util';
|
|
12
13
|
import {inflateRawSync} from 'node:zlib';
|
|
13
14
|
import {registerSource,safeFile} from './assets.mjs';
|
|
14
15
|
import {AssetCatalog,inspectMedia} from './asset-catalog.mjs';
|
|
16
|
+
import {mapWithConcurrency} from './concurrency.mjs';
|
|
17
|
+
import {validateGlbHeader} from './media-validate.mjs';
|
|
18
|
+
import {requireNativeTool} from './native-bin.mjs';
|
|
15
19
|
import {assertStorePath} from './store-path.mjs';
|
|
16
20
|
import {PACKAGE_ROOT,resolveRemoteCacheRoot} from '../runtime-paths.mjs';
|
|
17
21
|
|
|
18
22
|
const run=promisify(execFile);
|
|
19
|
-
const maxZipBytes=
|
|
20
|
-
const
|
|
23
|
+
const maxZipBytes=64_000_000,maxSingleModelBytes=32_000_000,maxSingleBytes=8_000_000,maxPageBytes=2_000_000,maxUncompressedBytes=64_000_000,maxZipEntries=4096,maxArchiveDeclaredBytes=512_000_000;
|
|
24
|
+
const archiveRootPrefix='archive-root/';
|
|
25
|
+
const mediaExtensions=new Map([
|
|
26
|
+
['.png','image/png'],['.jpg','image/jpeg'],['.jpeg','image/jpeg'],['.wav','audio/wav'],['.mp3','audio/mpeg'],['.ogg','audio/ogg'],
|
|
27
|
+
['.glb','model/gltf-binary'],['.gltf','model/gltf+json'],['.obj','model/obj'],
|
|
28
|
+
]);
|
|
29
|
+
const modelExtensions=new Set(['.glb','.gltf','.obj']);
|
|
30
|
+
const companionExtensions=new Set(['.mtl','.bin','.png','.jpg','.jpeg']);
|
|
31
|
+
const recoverableModelErrors=new Set(['E_MODEL_UNSUPPORTED','E_MODEL_CORRUPT','E_MODEL_BOUNDS','E_MODEL_GRAPH','E_MODEL_TEXTURE','E_MODEL_EXTERNAL_DEPS','E_NATIVE_ASSET_SIZE','E_NATIVE_ASSET_DECODE','E_NATIVE_ASSET_MIME','E_ASSET_LICENSE_UNVERIFIED','E_ASSET_READ','E_ASSET_TOO_LARGE','E_ASSET_PATH']);
|
|
21
32
|
const crcTable=Array.from({length:256},(_,n)=>{
|
|
22
33
|
let value=n;for(let bit=0;bit<8;bit++)value=value&1?0xedb88320^(value>>>1):value>>>1;return value>>>0;
|
|
23
34
|
});
|
|
@@ -29,108 +40,227 @@ function sha256Prefixed(value){return 'sha256:'+sha256Hex(value);}
|
|
|
29
40
|
function remoteId(value){return 'remote-'+sha256Hex(value).slice(0,32);}
|
|
30
41
|
function computePackKey(sourceHref){return sha256Hex(sourceHref);}
|
|
31
42
|
function computeCacheKey(sourceHref,packId,fileFilter){return sha256Hex(sourceHref+'\0'+(packId??'')+'\0'+JSON.stringify(fileFilter??''));}
|
|
43
|
+
function computeCacheKeyV2(sourceHref,packId,fileFilter,{fileFilters=[],kind,modelOptions}={}){return sha256Hex('v2\0'+sourceHref+'\0'+(packId??'')+'\0'+JSON.stringify({fileFilter:fileFilter??'',fileFilters,kind:kind??null,modelOptions}));}
|
|
32
44
|
function cleanPath(name){
|
|
33
|
-
if(
|
|
34
|
-
const parts=name.split('/');
|
|
35
|
-
|
|
45
|
+
if(typeof name!=='string'||!name||name.length>512||name.includes('\0')||/[<>:"\\|?*]/.test(name))throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
46
|
+
const parts=name.split('/');
|
|
47
|
+
if(parts.some(part=>!part||part==='.'||part==='..'||/[. ]$/.test(part)||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part)))throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
48
|
+
return name;
|
|
36
49
|
}
|
|
37
|
-
|
|
50
|
+
function isLicensePath(name){return /(?:^|\/)(?:license|copying)(?:[-_][^/.]+)*(?:\.txt|\.md)?$/i.test(name);}
|
|
51
|
+
function isZip(bytes){return bytes.length>=4&&[0x04034b50,0x06054b50].includes(bytes.readUInt32LE(0));}
|
|
52
|
+
export function readZipEntries(archive,entryFilter,metadataOnly=false){
|
|
38
53
|
if(archive.length<22||archive.length>maxZipBytes)throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
39
54
|
let eocd=-1;
|
|
40
55
|
for(let offset=archive.length-22;offset>=Math.max(0,archive.length-65_557);offset--){
|
|
41
|
-
if(archive.readUInt32LE(offset)===0x06054b50){eocd=offset;break;}
|
|
56
|
+
if(archive.readUInt32LE(offset)===0x06054b50&&offset+22+archive.readUInt16LE(offset+20)===archive.length){eocd=offset;break;}
|
|
42
57
|
}
|
|
43
58
|
if(eocd<0)throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
44
59
|
const count=archive.readUInt16LE(eocd+10),centralSize=archive.readUInt32LE(eocd+12),centralOffset=archive.readUInt32LE(eocd+16);
|
|
45
|
-
if(count>
|
|
46
|
-
|
|
60
|
+
if(count>maxZipEntries||count===0xffff||centralOffset===0xffffffff||centralSize===0xffffffff||centralOffset+centralSize>eocd)throw Error('E_REMOTE_ASSET_ARCHIVE_LIMIT');
|
|
61
|
+
if(archive.readUInt16LE(eocd+4)||archive.readUInt16LE(eocd+6)||archive.readUInt16LE(eocd+8)!==count)throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
62
|
+
const centralEnd=centralOffset+centralSize,entries=[],paths=new Map();let offset=centralOffset,total=0;
|
|
47
63
|
for(let index=0;index<count;index++){
|
|
48
|
-
if(offset+46>
|
|
64
|
+
if(offset+46>centralEnd||archive.readUInt32LE(offset)!==0x02014b50)throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
49
65
|
const flags=archive.readUInt16LE(offset+8),method=archive.readUInt16LE(offset+10),expectedCrc=archive.readUInt32LE(offset+16),compressedSize=archive.readUInt32LE(offset+20),uncompressedSize=archive.readUInt32LE(offset+24);
|
|
50
66
|
const nameLength=archive.readUInt16LE(offset+28),extraLength=archive.readUInt16LE(offset+30),commentLength=archive.readUInt16LE(offset+32),externalAttributes=archive.readUInt32LE(offset+38),localOffset=archive.readUInt32LE(offset+42);
|
|
51
|
-
if(offset+46+nameLength+extraLength+commentLength>
|
|
52
|
-
const rawName=archive.toString('utf8',offset+46,offset+46+nameLength);
|
|
53
|
-
const unixMode=(externalAttributes>>>16)&0xffff;
|
|
67
|
+
if(offset+46+nameLength+extraLength+commentLength>centralEnd||compressedSize===0xffffffff||uncompressedSize===0xffffffff||localOffset===0xffffffff)throw Error('E_REMOTE_ASSET_ARCHIVE_LIMIT');
|
|
68
|
+
const rawName=archive.toString('utf8',offset+46,offset+46+nameLength),unixMode=(externalAttributes>>>16)&0xffff;
|
|
54
69
|
if(flags&1||![0,8].includes(method)||(unixMode&0o170000)===0o120000)throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
55
|
-
total+=uncompressedSize;if(total>
|
|
70
|
+
total+=uncompressedSize;if(total>maxArchiveDeclaredBytes)throw Error('E_REMOTE_ASSET_ARCHIVE_LIMIT');
|
|
56
71
|
offset+=46+nameLength+extraLength+commentLength;
|
|
57
72
|
const trimmed=rawName.replace(/\/+$/,'');
|
|
58
73
|
if(!trimmed&&rawName.endsWith('/')&&uncompressedSize===0)continue;
|
|
59
74
|
const name=cleanPath(trimmed);
|
|
60
75
|
if(rawName.endsWith('/')&&uncompressedSize===0)continue;
|
|
76
|
+
const pathKey=name.normalize('NFC').toLowerCase();
|
|
77
|
+
if(rawName.endsWith('/')||paths.has(pathKey))throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
78
|
+
paths.set(pathKey,name);
|
|
61
79
|
entries.push({name,flags,method,expectedCrc,compressedSize,uncompressedSize,localOffset});
|
|
62
80
|
}
|
|
81
|
+
if(offset!==centralEnd)throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
82
|
+
const directories=new Map();
|
|
83
|
+
for(const path of paths.values()){
|
|
84
|
+
for(let dir=parentPath(path);dir;dir=parentPath(dir)){
|
|
85
|
+
const dirKey=dir.normalize('NFC').toLowerCase(),previous=directories.get(dirKey);
|
|
86
|
+
if(paths.has(dirKey)||previous!==undefined&&previous!==dir)throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
87
|
+
directories.set(dirKey,dir);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
63
90
|
const selected=entryFilter?entries.filter(entry=>entryFilter(entry.name)):entries;
|
|
91
|
+
if(metadataOnly)return selected;
|
|
92
|
+
if(selected.reduce((sum,entry)=>sum+entry.uncompressedSize,0)>maxUncompressedBytes)throw Error('E_REMOTE_ASSET_ARCHIVE_LIMIT');
|
|
64
93
|
return selected.map(entry=>{
|
|
65
|
-
if(entry.localOffset+30>
|
|
66
|
-
const
|
|
67
|
-
if(end>archive.
|
|
94
|
+
if(entry.localOffset+30>centralOffset||archive.readUInt32LE(entry.localOffset)!==0x04034b50)throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
95
|
+
const nameStart=entry.localOffset+30,nameEnd=nameStart+archive.readUInt16LE(entry.localOffset+26),start=nameEnd+archive.readUInt16LE(entry.localOffset+28),end=start+entry.compressedSize;
|
|
96
|
+
if(end>centralOffset||archive.toString('utf8',nameStart,nameEnd)!==entry.name||archive.readUInt16LE(entry.localOffset+6)!==entry.flags||archive.readUInt16LE(entry.localOffset+8)!==entry.method)throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
68
97
|
let bytes;
|
|
69
98
|
try{bytes=entry.method===0?archive.subarray(start,end):inflateRawSync(archive.subarray(start,end),{maxOutputLength:entry.uncompressedSize+1});}catch{throw Error('E_REMOTE_ASSET_ARCHIVE');}
|
|
70
99
|
if(bytes.length!==entry.uncompressedSize||crc32(bytes)!==entry.expectedCrc)throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
71
100
|
return {...entry,bytes};
|
|
72
101
|
});
|
|
73
102
|
}
|
|
74
|
-
function
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
103
|
+
function isPublicAddress(address){
|
|
104
|
+
const family=typeof address==='string'?isIP(address):0;
|
|
105
|
+
if(family===6){
|
|
106
|
+
const [first,second]=address.split(':').map(part=>Number.parseInt(part||'0',16));
|
|
107
|
+
return first>=0x2000&&first<0x4000&&first!==0x2002&&first!==0x3fff&&!(first===0x2001&&(second<0x200||second===0xdb8))&&!address.includes('%');
|
|
108
|
+
}
|
|
109
|
+
if(family!==4)return false;
|
|
110
|
+
const [a,b,c]=address.split('.').map(Number);
|
|
111
|
+
return !(a===0||a===10||a===127||a>=224||a===100&&b>=64&&b<=127||a===169&&b===254||a===172&&b>=16&&b<=31||a===192&&(b===168||b===0&&(c===0||c===2))||a===198&&(b===18||b===19||b===51&&c===100)||a===203&&b===0&&c===113);
|
|
112
|
+
}
|
|
113
|
+
function requestPublicUrl(url,{addresses,headers,signal}){
|
|
114
|
+
return new Promise((resolve,reject)=>{
|
|
115
|
+
const request=httpsRequest(url,{headers,signal,agent:false,lookup(_host,options,callback){
|
|
116
|
+
const matches=addresses.filter(item=>!options.family||item.family===options.family);
|
|
117
|
+
if(!matches.length){callback(Error('E_REMOTE_ASSET_ORIGIN'));return;}
|
|
118
|
+
if(options.all)callback(null,matches);else callback(null,matches[0].address,matches[0].family);
|
|
119
|
+
}},body=>{
|
|
120
|
+
const status=body.statusCode;
|
|
121
|
+
resolve({status,ok:status>=200&&status<300,headers:{get:name=>body.headers[name]},body,cancel:()=>body.destroy()});
|
|
122
|
+
});
|
|
123
|
+
request.once('error',reject);request.end();
|
|
124
|
+
});
|
|
81
125
|
}
|
|
126
|
+
function deriveProvider(value){const host=new URL(value).hostname.toLowerCase();return host==='kenney.nl'||host.endsWith('.kenney.nl')?'kenney':host==='quaternius.com'||host.endsWith('.quaternius.com')?'quaternius':'opengameart';}
|
|
82
127
|
export function assertRemoteUrl(value){
|
|
83
128
|
let url;try{url=new URL(value);}catch{throw Error('E_REMOTE_ASSET_ORIGIN');}
|
|
84
129
|
const host=url.hostname.toLowerCase();
|
|
85
|
-
const allowed=url.protocol==='https:'&&!url.username&&!url.password&&(host==='kenney.nl'||host.endsWith('.kenney.nl')||host==='opengameart.org'||host.endsWith('.opengameart.org'));
|
|
130
|
+
const allowed=url.protocol==='https:'&&!url.username&&!url.password&&!url.port&&(host==='kenney.nl'||host.endsWith('.kenney.nl')||host==='quaternius.com'||host.endsWith('.quaternius.com')||host==='opengameart.org'||host.endsWith('.opengameart.org'));
|
|
86
131
|
if(!allowed||isIP(host))throw Error('E_REMOTE_ASSET_ORIGIN');
|
|
87
132
|
return url;
|
|
88
133
|
}
|
|
89
134
|
function htmlText(html,pattern){const match=pattern.exec(html);return match?.[1]?.replace(/&/g,'&').replace(/"/g,'"').replace(/'/g,"'").trim();}
|
|
90
|
-
function
|
|
91
|
-
return [...html.matchAll(
|
|
92
|
-
|
|
135
|
+
function anchorLinks(html,base){
|
|
136
|
+
return [...html.matchAll(/<a\b[^>]*href\s*=\s*["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>(?:\s*<div\b[^>]*class=["']PackText["'][^>]*>([^<]+))?/gi)].map(match=>{
|
|
137
|
+
const anchorText=match[2].replace(/<img\b[^>]*\balt=["']([^"']*)["'][^>]*>/gi,' $1 ').replace(/<[^>]+>/g,' ');
|
|
138
|
+
const text=(anchorText+' '+(match[3]??'')).replace(/&(?:amp|nbsp);/g,' ').replace(/\s+/g,' ').trim();
|
|
139
|
+
try{return {href:new URL(match[1].replace(/&/g,'&'),base).href,text,attachment:/^<a\b[^>]*\sdownload(?:\s|=|>)/i.test(match[0])};}catch{return null;}
|
|
93
140
|
}).filter(Boolean);
|
|
94
141
|
}
|
|
95
142
|
function verifyCc0Evidence(text){
|
|
96
|
-
|
|
143
|
+
const cc0=/\bCC0(?:\s| |<|\/|-)*1\.0\b|\bCreative Commons Zero\b|(?:^|[\s<"'(]|https?:\/\/)(?:www\.)?creativecommons\.org\/publicdomain\/zero\/1\.0(?=[/"'\s<]|$)/i;
|
|
144
|
+
const conflictingLicense=/\b(?:Non[ -]?Commercial|CC[ -]+BY\b|GNU GPL|GPL v\d|MIT License)\b|creativecommons\.org\/licenses\/(?:by|by-nc|by-sa|by-nd)\//i;
|
|
145
|
+
const restrictions=text.replace(/^\s*Commercial and non-commercial use\.\s*$/gim,'');
|
|
146
|
+
if(!cc0.test(text)||conflictingLicense.test(restrictions))throw Error('E_ASSET_LICENSE_UNVERIFIED');
|
|
147
|
+
}
|
|
148
|
+
function verifyPageLicense(provider,pageHtml){
|
|
149
|
+
const licenseIcons=provider==='opengameart'?[...pageHtml.matchAll(/<div\s+class=["']license-icon["']>[\s\S]*?<\/a>/gi)]:[];
|
|
150
|
+
if(licenseIcons.length){for(const icon of licenseIcons)verifyCc0Evidence(icon[0]);}
|
|
151
|
+
else if(provider==='opengameart'&&/field-name-field-art-licenses/.test(pageHtml))throw Error('E_ASSET_LICENSE_UNVERIFIED');
|
|
152
|
+
else verifyCc0Evidence(pageHtml);
|
|
97
153
|
}
|
|
98
154
|
function mimeFor(path){return mediaExtensions.get(extname(path).toLowerCase());}
|
|
155
|
+
function mediaKindFor(path){const mime=mimeFor(path);return mime?.startsWith('model/')?'mesh':mime?.startsWith('image/')?'sprite':mime?'audio':null;}
|
|
156
|
+
function decodePath(path){try{return decodeURIComponent(path);}catch{return path;}}
|
|
99
157
|
function fileMatches(path,filter){
|
|
100
|
-
if(!filter)return true;const values=Array.isArray(filter)?filter:[filter];return values.some(value=>path.toLowerCase().includes(String(value).toLowerCase().slice(0,128)));
|
|
158
|
+
if(!filter||Array.isArray(filter)&&!filter.length)return true;const values=Array.isArray(filter)?filter:[filter];return values.some(value=>path.toLowerCase().includes(String(value).toLowerCase().slice(0,128)));
|
|
159
|
+
}
|
|
160
|
+
function deriveAuthor(provider,pageHtml,legacy=false){
|
|
161
|
+
if(provider==='kenney')return 'Kenney';
|
|
162
|
+
if(provider==='quaternius')return 'Quaternius';
|
|
163
|
+
const fallback=htmlText(pageHtml,/(?:submitted by|author)[\s\S]{0,200}?>([A-Za-z0-9 _.-]{2,80})</i)??'OpenGameArt contributor';
|
|
164
|
+
return legacy?fallback:htmlText(pageHtml,/<span[^>]+class=["']username["'][^>]*>[\s\S]{0,300}?<a[^>]*>([^<]+)/i)??fallback;
|
|
165
|
+
}
|
|
166
|
+
function parentPath(path){const index=path.lastIndexOf('/');return index<0?'':path.slice(0,index);}
|
|
167
|
+
function buildLicenseIndex(entries){
|
|
168
|
+
const index=new Map();
|
|
169
|
+
for(const entry of entries.filter(item=>isLicensePath(item.name))){const dir=parentPath(entry.name).normalize('NFC').toLowerCase();if(!index.has(dir))index.set(dir,[]);index.get(dir).push(entry);}
|
|
170
|
+
return index;
|
|
171
|
+
}
|
|
172
|
+
function resolveScopedLicense(filePath,licenseIndex,{provider,pageHtmlVerified,isArchive=true}={}){
|
|
173
|
+
let dir=parentPath(filePath).normalize('NFC').toLowerCase();
|
|
174
|
+
while(true){
|
|
175
|
+
const entries=licenseIndex.get(dir);
|
|
176
|
+
if(entries?.length){
|
|
177
|
+
for(const entry of entries)verifyCc0Evidence(entry.bytes.toString('utf8'));
|
|
178
|
+
return entries.map(entry=>entry.name).sort()[0];
|
|
179
|
+
}
|
|
180
|
+
if(!dir)break;
|
|
181
|
+
dir=parentPath(dir);
|
|
182
|
+
}
|
|
183
|
+
if(pageHtmlVerified&&(!isArchive||provider!=='kenney'))return 'page.html';
|
|
184
|
+
throw Error('E_ASSET_LICENSE_UNVERIFIED');
|
|
185
|
+
}
|
|
186
|
+
function externalDownloadError(externalDownloadUrl,provider){
|
|
187
|
+
const error=Error('E_REMOTE_ASSET_ORIGIN');error.detail={externalDownloadUrl,provider,downloadMode:'manual-workspace-import',guidance:'Download this CC0 pack manually into your workspace and run tora_prep_assets / tora_upload_assets.'};return error;
|
|
188
|
+
}
|
|
189
|
+
function isExternalHttps(url){
|
|
190
|
+
if(url.protocol!=='https:'||url.username||url.password||url.port||isIP(url.hostname.replace(/^\[|\]$/g,'')))return false;
|
|
191
|
+
try{assertRemoteUrl(url.href);return false;}catch{return true;}
|
|
192
|
+
}
|
|
193
|
+
function abortError(signal,cause){return Error(signal?.aborted?'E_BUILD_CANCELLED':'E_REMOTE_ASSET_TIMEOUT',{cause});}
|
|
194
|
+
async function abortableLookup(lookup,signal,requestSignal){
|
|
195
|
+
if(requestSignal.aborted)throw abortError(signal);
|
|
196
|
+
let onAbort;
|
|
197
|
+
const abort=new Promise((_,reject)=>{onAbort=()=>reject(abortError(signal));requestSignal.addEventListener('abort',onAbort,{once:true});});
|
|
198
|
+
try{return await Promise.race([lookup(),abort]);}finally{requestSignal.removeEventListener('abort',onAbort);}
|
|
101
199
|
}
|
|
102
|
-
function
|
|
103
|
-
|
|
200
|
+
function normalizeModelFetchOptions(input){
|
|
201
|
+
const kind=input.kind===undefined?null:input.kind;
|
|
202
|
+
if(input.kind!==undefined&&!['sprite','audio','mesh'].includes(kind))throw Error('E_NATIVE_ARGUMENT');
|
|
203
|
+
const fileFilters=input.fileFilters===undefined?[]:input.fileFilters;
|
|
204
|
+
if(!Array.isArray(fileFilters)||fileFilters.length>64||fileFilters.some(value=>typeof value!=='string'||!value.length||value.length>128))throw Error('E_NATIVE_ARGUMENT');
|
|
205
|
+
if(input.fileFilter!==undefined&&typeof input.fileFilter!=='string')throw Error('E_NATIVE_ARGUMENT');
|
|
206
|
+
if(input.packId!==undefined&&typeof input.packId!=='string')throw Error('E_NATIVE_ARGUMENT');
|
|
207
|
+
const options={mode:input.mode===undefined?'auto':input.mode,preserveNamedNodes:input.preserveNamedNodes===undefined?true:input.preserveNamedNodes};
|
|
208
|
+
if(!['auto','lossless','none'].includes(options.mode)||typeof options.preserveNamedNodes!=='boolean')throw Error('E_NATIVE_ARGUMENT');
|
|
209
|
+
const integer=(name,min,max)=>{if(input[name]===undefined)return;if(!Number.isInteger(input[name])||input[name]<min||input[name]>max)throw Error('E_NATIVE_ARGUMENT');options[name]=input[name];};
|
|
210
|
+
integer('maxTextureSide',16,1024);integer('targetTriangles',32,50000);integer('targetBytes',4096,700000);integer('maxFiles',1,64);
|
|
211
|
+
if(input.targetHeightMeters!==undefined){if(typeof input.targetHeightMeters!=='number'||!Number.isFinite(input.targetHeightMeters)||input.targetHeightMeters<.01||input.targetHeightMeters>1000)throw Error('E_NATIVE_ARGUMENT');options.targetHeightMeters=input.targetHeightMeters;}
|
|
212
|
+
if(input.pivotMode!==undefined){if(!['origin','center','bottom-center'].includes(input.pivotMode))throw Error('E_NATIVE_ARGUMENT');options.pivotMode=input.pivotMode;}
|
|
213
|
+
if(input.upAxis!==undefined){if(!['auto','y','z'].includes(input.upAxis))throw Error('E_NATIVE_ARGUMENT');options.upAxis=input.upAxis;}
|
|
214
|
+
for(const name of ['preserveGeometry','preserveResolution']){if(input[name]!==undefined){if(typeof input[name]!=='boolean')throw Error('E_NATIVE_ARGUMENT');options[name]=input[name];}}
|
|
215
|
+
return {kind,fileFilters,modelOptions:options};
|
|
216
|
+
}
|
|
217
|
+
function publicModelOptions(options){const result={...options};delete result.maxFiles;return result;}
|
|
218
|
+
function modelCliOptions(options){return {...publicModelOptions(options),outputPrefix:'model',emitLosslessMaster:true};}
|
|
219
|
+
function modelRank(path){return ({'.glb':0,'.gltf':1,'.obj':2})[extname(path).toLowerCase()]??99;}
|
|
220
|
+
function previewPath(path){return /(?:^|\/)(?:preview\.png|sample\.png)$/i.test(path)||/(?:^|\/)previews\//i.test(path);}
|
|
221
|
+
function compactFile(file){
|
|
222
|
+
const {storedPath,masterStoredPath,...metadata}=file;void storedPath;void masterStoredPath;return metadata;
|
|
104
223
|
}
|
|
105
224
|
|
|
106
225
|
export class RemoteCc0Fetcher{
|
|
107
|
-
constructor({root,workspaceRoot,cacheRoot,fetchImpl
|
|
226
|
+
constructor({root,workspaceRoot,cacheRoot,fetchImpl,lookup=async host=>dnsLookup(host,{all:true,verbatim:true}),catalog}={}){
|
|
108
227
|
const catalogRoot=root??PACKAGE_ROOT;
|
|
109
228
|
this.cacheRoot=resolve(cacheRoot??(root?resolve(root,'.tora/remote-asset-cache'):resolveRemoteCacheRoot(workspaceRoot)));
|
|
110
229
|
this.fetchImpl=fetchImpl;this.lookup=lookup;this.catalog=catalog??new AssetCatalog({root:catalogRoot});
|
|
111
230
|
}
|
|
112
231
|
async assertPublicHost(url){
|
|
113
|
-
let addresses;try{addresses=await this.lookup(url.hostname);}catch{throw Error('E_REMOTE_ASSET_FETCH');}
|
|
114
|
-
|
|
115
|
-
if(!
|
|
232
|
+
let addresses;try{addresses=await this.lookup(url.hostname);}catch(error){throw Error('E_REMOTE_ASSET_FETCH',{cause:error});}
|
|
233
|
+
const resolved=(Array.isArray(addresses)?addresses:[addresses]).map(item=>item?.address??item);
|
|
234
|
+
if(!resolved.length||resolved.some(address=>!isPublicAddress(address)))throw Error('E_REMOTE_ASSET_ORIGIN');
|
|
235
|
+
return resolved.map(address=>({address,family:isIP(address)}));
|
|
116
236
|
}
|
|
117
|
-
async download(value,{maxBytes=maxSingleBytes,signal}={}){
|
|
118
|
-
let url=assertRemoteUrl(value);const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),15_000);
|
|
237
|
+
async download(value,{maxBytes=maxSingleBytes,signal,referer,manualProvider}={}){
|
|
238
|
+
let url=assertRemoteUrl(value);const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),maxBytes>maxPageBytes?45_000:15_000);
|
|
119
239
|
const abort=()=>controller.abort();signal?.addEventListener('abort',abort,{once:true});
|
|
240
|
+
if(signal?.aborted)abort();
|
|
120
241
|
try{
|
|
121
242
|
for(let redirects=0;redirects<=5;redirects++){
|
|
122
|
-
await this.assertPublicHost(url);
|
|
123
|
-
|
|
243
|
+
const addresses=await abortableLookup(()=>this.assertPublicHost(url),signal,controller.signal);
|
|
244
|
+
const headers={'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Tora-CC0-Asset-Fetcher/2.0'};
|
|
245
|
+
if(referer)headers.Referer=referer;
|
|
246
|
+
let response;
|
|
247
|
+
try{response=this.fetchImpl?await this.fetchImpl(url.href,{redirect:'manual',signal:controller.signal,headers}):await requestPublicUrl(url,{addresses,headers,signal:controller.signal});}
|
|
248
|
+
catch(error){throw controller.signal.aborted?abortError(signal,error):Error('E_REMOTE_ASSET_FETCH',{cause:error});}
|
|
249
|
+
const cancel=async()=>{if(response.cancel)response.cancel();else await response.body?.cancel().catch(()=>{});};
|
|
124
250
|
if([301,302,303,307,308].includes(response.status)){
|
|
125
|
-
const location=response.headers.get('location');await
|
|
126
|
-
if(!location||redirects===5)throw Error('E_REMOTE_ASSET_ORIGIN');
|
|
251
|
+
const location=response.headers.get('location');await cancel();
|
|
252
|
+
if(!location||redirects===5)throw Error('E_REMOTE_ASSET_ORIGIN');
|
|
253
|
+
let next;try{next=new URL(location,url);}catch{throw Error('E_REMOTE_ASSET_ORIGIN');}
|
|
254
|
+
if(manualProvider&&isExternalHttps(next))throw externalDownloadError(next.href,manualProvider);
|
|
255
|
+
url=assertRemoteUrl(next.href);continue;
|
|
127
256
|
}
|
|
128
|
-
if(!response.ok){await
|
|
129
|
-
const declared=Number(response.headers.get('content-length')??0);if(declared>maxBytes){await
|
|
257
|
+
if(!response.ok){await cancel();throw Error('E_REMOTE_ASSET_FETCH');}
|
|
258
|
+
const declared=Number(response.headers.get('content-length')??0);if(declared>maxBytes){await cancel();throw Error('E_REMOTE_ASSET_SIZE');}
|
|
130
259
|
const chunks=[];let size=0;
|
|
131
260
|
try{
|
|
132
|
-
for await(const chunk of response.body){size+=chunk.length;if(size>maxBytes)
|
|
133
|
-
}catch(error){if(error.message==='E_REMOTE_ASSET_SIZE')throw error;throw Error('E_REMOTE_ASSET_FETCH',{cause:error});}
|
|
261
|
+
for await(const chunk of response.body??[]){size+=chunk.length;if(size>maxBytes)throw Error('E_REMOTE_ASSET_SIZE');chunks.push(chunk);}
|
|
262
|
+
}catch(error){if(error.message==='E_REMOTE_ASSET_SIZE')throw error;throw controller.signal.aborted?abortError(signal,error):Error('E_REMOTE_ASSET_FETCH',{cause:error});}
|
|
263
|
+
if(controller.signal.aborted)throw abortError(signal);
|
|
134
264
|
return {bytes:Buffer.concat(chunks),contentType:response.headers.get('content-type')??'',finalUrl:url.href};
|
|
135
265
|
}
|
|
136
266
|
throw Error('E_REMOTE_ASSET_ORIGIN');
|
|
@@ -140,53 +270,62 @@ export class RemoteCc0Fetcher{
|
|
|
140
270
|
if(typeof key!=='string'||!/^[a-f0-9]{64}$/.test(key))return null;
|
|
141
271
|
try{await assertStorePath(this.cacheRoot);}catch{return null;}
|
|
142
272
|
let receipt;try{receipt=JSON.parse((await safeFile(resolve(this.cacheRoot,key,'receipt.json'))).toString('utf8'));}catch{return null;}
|
|
143
|
-
if(
|
|
273
|
+
if(!['tora-remote-cc0-1','tora-remote-cc0-2'].includes(receipt?.format)||receipt.license!=='CC0-1.0'||!Array.isArray(receipt.files))return null;
|
|
274
|
+
const v2=receipt.format==='tora-remote-cc0-2';
|
|
144
275
|
try{
|
|
145
|
-
const source=assertRemoteUrl(receipt.sourceUrl);
|
|
146
|
-
const expectedCacheKey=computeCacheKey(source.href,receipt.packId??'',receipt.fileFilter??'');
|
|
276
|
+
const source=assertRemoteUrl(receipt.sourceUrl),expectedCacheKey=v2?computeCacheKeyV2(source.href,receipt.packId??'',receipt.fileFilter??'',{fileFilters:receipt.fileFilters??[],kind:receipt.kind??null,modelOptions:receipt.cacheModelOptions??receipt.modelOptions}):computeCacheKey(source.href,receipt.packId??'',receipt.fileFilter??'');
|
|
147
277
|
if(expectedCacheKey!==key)return null;
|
|
148
|
-
const expectedPackKey=computePackKey(source.href);
|
|
149
|
-
const expectedProvider=source.hostname.endsWith('kenney.nl')?'kenney':'opengameart';
|
|
150
|
-
const expectedSourceId='remote-'+expectedPackKey.slice(0,24);
|
|
151
|
-
const expectedStyleFamily='remote-'+expectedPackKey.slice(0,16);
|
|
278
|
+
const expectedPackKey=computePackKey(source.href),expectedProvider=deriveProvider(source.href),expectedSourceId='remote-'+expectedPackKey.slice(0,24),expectedStyleFamily='remote-'+expectedPackKey.slice(0,16);
|
|
152
279
|
if(receipt.provider!==expectedProvider||receipt.sourceId!==expectedSourceId)return null;
|
|
153
280
|
if(receipt.packKey&&receipt.packKey!==expectedPackKey)return null;
|
|
154
|
-
|
|
155
281
|
const archive=await safeFile(resolve(this.cacheRoot,key,'archive.bin'));
|
|
156
282
|
if(sha256Prefixed(archive)!==receipt.archiveSha256)return null;
|
|
157
|
-
|
|
158
|
-
let pageHtml='',verifiedEvidence=false;
|
|
283
|
+
let pageHtml='',pageHtmlVerified=false;
|
|
159
284
|
if(receipt.pageSha256){
|
|
160
|
-
const pageBytes=await safeFile(resolve(this.cacheRoot,key,'page.html'));
|
|
161
|
-
|
|
162
|
-
pageHtml=pageBytes.toString('utf8');
|
|
163
|
-
verifyCc0Evidence(pageHtml);
|
|
164
|
-
verifiedEvidence=true;
|
|
165
|
-
}
|
|
166
|
-
if(deriveAuthor(expectedProvider,pageHtml)!==receipt.author)return null;
|
|
167
|
-
|
|
168
|
-
if(receipt.archiveLicenseEntry){
|
|
169
|
-
const entries=readZipEntries(archive,name=>name===receipt.archiveLicenseEntry);
|
|
170
|
-
if(entries.length!==1)return null;
|
|
171
|
-
verifyCc0Evidence(entries[0].bytes.toString('utf8'));
|
|
172
|
-
verifiedEvidence=true;
|
|
173
|
-
}else if(expectedProvider==='kenney'&&archive.length>=4&&archive.readUInt32LE(0)===0x04034b50){
|
|
174
|
-
return null;
|
|
285
|
+
const pageBytes=await safeFile(resolve(this.cacheRoot,key,'page.html'));if(sha256Prefixed(pageBytes)!==receipt.pageSha256)return null;
|
|
286
|
+
pageHtml=pageBytes.toString('utf8');verifyPageLicense(expectedProvider,pageHtml);pageHtmlVerified=true;
|
|
175
287
|
}
|
|
176
|
-
if(
|
|
177
|
-
|
|
288
|
+
if(deriveAuthor(expectedProvider,pageHtml,!v2)!==receipt.author)return null;
|
|
289
|
+
const isArchive=isZip(archive),archivePaths=isArchive?new Set(readZipEntries(archive,undefined,true).map(entry=>entry.name)):null;
|
|
290
|
+
const licenseIndex=isArchive?buildLicenseIndex(readZipEntries(archive,isLicensePath)):new Map();
|
|
291
|
+
if(!v2){
|
|
292
|
+
let verifiedEvidence=pageHtmlVerified;
|
|
293
|
+
if(receipt.archiveLicenseEntry){
|
|
294
|
+
const entries=readZipEntries(archive,name=>name===receipt.archiveLicenseEntry);if(entries.length!==1)return null;
|
|
295
|
+
verifyCc0Evidence(entries[0].bytes.toString('utf8'));verifiedEvidence=true;
|
|
296
|
+
}else if(expectedProvider==='kenney'&&isArchive)return null;
|
|
297
|
+
if(!verifiedEvidence)return null;
|
|
298
|
+
}else if(!pageHtmlVerified&&!licenseIndex.size)return null;
|
|
178
299
|
for(const file of receipt.files){
|
|
179
|
-
if(!/^files\/\d{3}\.(?:png|jpg|wav|mp3)$/.test(file.storedPath))return null;
|
|
300
|
+
if(!/^files\/\d{3}\.(?:png|jpg|wav|mp3|glb)$/.test(file.storedPath))return null;
|
|
180
301
|
if(file.styleFamily!==expectedStyleFamily||file.sourceId!==expectedSourceId)return null;
|
|
181
|
-
|
|
182
|
-
|
|
302
|
+
if(cleanPath(file.path)!==file.path||isArchive&&!archivePaths.has(file.path))return null;
|
|
303
|
+
const isModel=file.kind==='mesh',expectedId=remoteId(source.href+'\0'+file.path+(isModel?'\0'+key:''));
|
|
304
|
+
if(file.id!==expectedId)return null;
|
|
305
|
+
const binding=resolveScopedLicense(file.path,licenseIndex,{provider:expectedProvider,pageHtmlVerified,isArchive});
|
|
306
|
+
if(v2){
|
|
307
|
+
if(binding!==file.licenseEntry)return null;
|
|
308
|
+
if(isModel&&!file.dependencies?.some(dependency=>dependency.path===file.path))return null;
|
|
309
|
+
for(const dependency of file.dependencies??[]){
|
|
310
|
+
if(cleanPath(dependency.path)!==dependency.path||(isArchive?!archivePaths.has(dependency.path):dependency.path!==file.path))return null;
|
|
311
|
+
resolveScopedLicense(dependency.path,licenseIndex,{provider:expectedProvider,pageHtmlVerified,isArchive});
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
const expectedKind=file.mime.startsWith('image/')?'sprite':file.mime.startsWith('audio/')?'audio':file.mime==='model/gltf-binary'?'mesh':null;
|
|
315
|
+
const bytes=await safeFile(resolve(this.cacheRoot,key,file.storedPath));if(expectedKind!==file.kind||inspectMedia(bytes,file.mime).sha256!==file.sha256)return null;
|
|
316
|
+
if(isModel){
|
|
317
|
+
if(!file.masterStoredPath||!/^masters\/\d{3}\.master\.glb$/.test(file.masterStoredPath)||!file.masterSha256)return null;
|
|
318
|
+
const master=await safeFile(resolve(this.cacheRoot,key,file.masterStoredPath));
|
|
319
|
+
validateGlbHeader(master,'E_MODEL_CORRUPT',maxSingleModelBytes);
|
|
320
|
+
if(sha256Prefixed(master)!==file.masterSha256)return null;
|
|
321
|
+
}
|
|
183
322
|
}
|
|
184
323
|
return {...receipt,cacheKey:key,cached:true};
|
|
185
324
|
}catch{return null;}
|
|
186
325
|
}
|
|
187
|
-
async normalize({path,bytes,mime,temp,rights}){
|
|
326
|
+
async normalize({path,bytes,mime,temp,rights,signal}){
|
|
327
|
+
if(bytes.length===0||bytes.length>maxSingleBytes)return null;
|
|
188
328
|
if(mime==='image/png'||mime==='image/jpeg'){
|
|
189
|
-
if(bytes.length===0||bytes.length>8_000_000)return null;
|
|
190
329
|
const id=remoteId(path+sha256Hex(bytes).slice(0,16));
|
|
191
330
|
try{
|
|
192
331
|
const registered=await registerSource(temp,{id,mime,data:bytes.toString('base64'),rights});
|
|
@@ -200,12 +339,10 @@ export class RemoteCc0Fetcher{
|
|
|
200
339
|
let normalized=bytes,outputMime=mime,inputPath=resolve(temp,'input'+extname(path));
|
|
201
340
|
await writeFile(inputPath,bytes);
|
|
202
341
|
if(mime==='audio/ogg'||bytes.length>700000){
|
|
203
|
-
outputMime='audio/wav';
|
|
204
|
-
|
|
205
|
-
const args=['-v','error','-y','-i',inputPath,'-t','120','-ac','1','-ar','44100','-c:a','pcm_s16le',outputPath];
|
|
206
|
-
try{await run('ffmpeg',args,{timeout:15000,maxBuffer:16384});normalized=await readFile(outputPath);}catch{return null;}
|
|
342
|
+
outputMime='audio/wav';const outputPath=resolve(temp,'output.wav'),args=['-v','error','-y','-i',inputPath,'-t','120','-ac','1','-ar','44100','-c:a','pcm_s16le',outputPath];
|
|
343
|
+
try{await run('ffmpeg',args,{timeout:15000,maxBuffer:16384,signal});normalized=await readFile(outputPath);}catch(error){if(signal?.aborted)throw abortError(signal,error);return null;}
|
|
207
344
|
}
|
|
208
|
-
if(normalized.length>
|
|
345
|
+
if(normalized.length>maxSingleBytes)return null;
|
|
209
346
|
const id=remoteId(path+sha256Hex(normalized).slice(0,16));
|
|
210
347
|
try{
|
|
211
348
|
const registered=await registerSource(temp,{id,mime:outputMime,data:normalized.toString('base64'),rights});
|
|
@@ -217,162 +354,231 @@ export class RemoteCc0Fetcher{
|
|
|
217
354
|
}
|
|
218
355
|
}
|
|
219
356
|
async persist(key,receipt,archive,pageHtml,files){
|
|
220
|
-
await assertStorePath(this.cacheRoot);
|
|
221
|
-
await mkdir(this.cacheRoot,{recursive:true});
|
|
222
|
-
await assertStorePath(this.cacheRoot);
|
|
357
|
+
await assertStorePath(this.cacheRoot);await mkdir(this.cacheRoot,{recursive:true});await assertStorePath(this.cacheRoot);
|
|
223
358
|
const folder=resolve(this.cacheRoot,key),temporary=resolve(this.cacheRoot,'.staging-'+randomUUID());
|
|
224
|
-
await mkdir(resolve(temporary,'files'),{recursive:true});
|
|
359
|
+
await mkdir(resolve(temporary,'files'),{recursive:true});await mkdir(resolve(temporary,'masters'),{recursive:true});
|
|
225
360
|
try{
|
|
226
|
-
await writeFile(resolve(temporary,'archive.bin'),archive,{flag:'wx'});
|
|
227
|
-
if(pageHtml){
|
|
228
|
-
await writeFile(resolve(temporary,'page.html'),pageHtml,{flag:'wx'});
|
|
229
|
-
}
|
|
361
|
+
await writeFile(resolve(temporary,'archive.bin'),archive,{flag:'wx'});if(pageHtml)await writeFile(resolve(temporary,'page.html'),pageHtml,{flag:'wx'});
|
|
230
362
|
const publicFiles=[];
|
|
231
363
|
for(let index=0;index<files.length;index++){
|
|
232
|
-
const file=files[index],
|
|
364
|
+
const file=files[index],extension=file.kind==='mesh'?'.glb':file.mime==='image/png'?'.png':file.mime==='image/jpeg'?'.jpg':file.mime==='audio/wav'?'.wav':'.mp3',storedPath='files/'+String(index).padStart(3,'0')+extension;
|
|
233
365
|
await writeFile(resolve(temporary,storedPath),file.data,{flag:'wx'});
|
|
234
|
-
const metadata={...file};delete metadata.data;
|
|
366
|
+
const metadata={...file};delete metadata.data;
|
|
367
|
+
if(file.kind==='mesh'){
|
|
368
|
+
const masterStoredPath='masters/'+String(index).padStart(3,'0')+'.master.glb';await writeFile(resolve(temporary,masterStoredPath),file.masterBytes,{flag:'wx'});delete metadata.masterBytes;metadata.masterStoredPath=masterStoredPath;
|
|
369
|
+
}
|
|
370
|
+
publicFiles.push({...metadata,storedPath});
|
|
235
371
|
}
|
|
236
372
|
const finalReceipt={...receipt,cacheKey:key,files:publicFiles};await writeFile(resolve(temporary,'receipt.json'),JSON.stringify(finalReceipt),{flag:'wx'});
|
|
237
373
|
try{await rename(temporary,folder);}catch(error){await rm(temporary,{recursive:true,force:true});if(error.code!=='EEXIST'&&error.code!=='ENOTEMPTY')throw error;}
|
|
238
|
-
|
|
374
|
+
const verified=await this.cached(key);
|
|
375
|
+
if(!verified)throw Error('E_REMOTE_ASSET_CACHE');
|
|
376
|
+
return verified;
|
|
239
377
|
}finally{await rm(temporary,{recursive:true,force:true});}
|
|
240
378
|
}
|
|
241
|
-
async
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
379
|
+
async resolveDownload(source,first,kind,filters,signal){
|
|
380
|
+
const firstUrl=new URL(first.finalUrl);
|
|
381
|
+
if(isZip(first.bytes)||mimeFor(firstUrl.pathname)&&!first.contentType.includes('text/html'))return {archive:first.bytes,pageHtml:'',downloadUrl:first.finalUrl};
|
|
382
|
+
if(/\.zip$/i.test(firstUrl.pathname))throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
383
|
+
const pageHtml=first.bytes.toString('utf8'),provider=deriveProvider(source.href);
|
|
384
|
+
verifyPageLicense(provider,pageHtml);
|
|
385
|
+
const anchors=anchorLinks(pageHtml,first.finalUrl),onclick=[...pageHtml.matchAll(/<(?:a|button)\b[^>]*\bonclick=["'][^<>]*?window\.open\(\s*(['"])([^'"]+)\1[^<>]*>([\s\S]*?)<\/(?:a|button)>/gi)]
|
|
386
|
+
.flatMap(match=>{try{return [{href:new URL(match[2].replace(/&/g,'&'),first.finalUrl).href,text:match[3].replace(/<[^>]+>/g,' '),attachment:false}];}catch{return [];}});
|
|
387
|
+
const all=[...anchors,...onclick],allowlisted=[];
|
|
388
|
+
for(const link of all){try{allowlisted.push({...link,url:assertRemoteUrl(link.href)});}catch{continue;}}
|
|
389
|
+
let selected=allowlisted.find(link=>/\.zip$/i.test(link.url.pathname))?.href;
|
|
390
|
+
if(!selected&&provider==='kenney'){
|
|
391
|
+
const downloadId=htmlText(pageHtml,/data-download-id=["']([a-z0-9]+)["']/i);
|
|
392
|
+
if(downloadId){
|
|
393
|
+
const endpoint='https://kenney.nl/download-link/'+downloadId,response=await this.download(endpoint,{maxBytes:maxPageBytes,signal,referer:source.href,manualProvider:provider});
|
|
394
|
+
let url;try{url=new URL(JSON.parse(response.bytes.toString('utf8')).url,first.finalUrl);}catch(error){throw Error('E_REMOTE_ASSET_FETCH',{cause:error});}
|
|
395
|
+
if(isExternalHttps(url))throw externalDownloadError(url.href,provider);
|
|
396
|
+
selected=assertRemoteUrl(url.href).href;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
if(!selected){
|
|
400
|
+
const direct=allowlisted.filter(({url})=>{const mediaKind=mediaKindFor(url.pathname);return mediaKind&&(!kind||mediaKind===kind)&&fileMatches(decodePath(url.pathname).split('/').pop(),filters);});
|
|
401
|
+
selected=(direct.find(link=>link.attachment)??direct.find(link=>mediaKindFor(link.url.pathname)==='mesh')??direct[0])?.href;
|
|
402
|
+
}
|
|
403
|
+
if(!selected){
|
|
404
|
+
const external=all.find(({href,text,attachment})=>{const url=new URL(href);return isExternalHttps(url)&&(attachment||/\bdownload\b/i.test(text)||/\.zip$/i.test(url.pathname)||Boolean(mimeFor(url.pathname))||url.hostname==='drive.google.com');});
|
|
405
|
+
if(external)throw externalDownloadError(external.href,provider);
|
|
406
|
+
throw Error('E_REMOTE_ASSET_NOT_FOUND');
|
|
253
407
|
}
|
|
254
|
-
const
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
408
|
+
const path=new URL(selected).pathname,isModel=modelExtensions.has(extname(path).toLowerCase()),isZipPath=/\.zip$/i.test(path),downloaded=await this.download(selected,{maxBytes:isZipPath?maxZipBytes:isModel?maxSingleModelBytes:maxSingleBytes,signal,referer:source.href,manualProvider:provider});
|
|
409
|
+
if(isZipPath&&!isZip(downloaded.bytes))throw Error('E_REMOTE_ASSET_ARCHIVE');
|
|
410
|
+
return {archive:downloaded.bytes,pageHtml,downloadUrl:mimeFor(new URL(downloaded.finalUrl).pathname)?downloaded.finalUrl:selected};
|
|
411
|
+
}
|
|
412
|
+
async prepModel({entry,index,temp,key,source,sourceId,styleFamily,licenseEntry,licenseScope,stagedEntries,modelOptions,signal}){
|
|
413
|
+
const tool=requireNativeTool('prep-3d'),inputRel=archiveRootPrefix+entry.name,outRel='out-'+index;
|
|
414
|
+
let report;
|
|
415
|
+
try{const {stdout}=await run(tool.command,[...tool.prefixArgs,temp,inputRel,outRel,JSON.stringify(modelCliOptions(modelOptions))],{timeout:120000,maxBuffer:4*1024*1024,signal});report=JSON.parse(stdout);}
|
|
416
|
+
catch(error){if(signal?.aborted)throw abortError(signal,error);if(error.code==='ENOENT'||error.code==='EACCES')throw Error('E_NATIVE_BIN_UNAVAILABLE',{cause:error});const code=error.stderr?.match(/E_[A-Z_0-9]+/)?.[0]??'E_NATIVE_ASSET_DECODE';throw Error(code,{cause:error});}
|
|
417
|
+
const dependencies=(report.dependencies??[]).map(dependency=>{
|
|
418
|
+
if(!dependency.path.startsWith(archiveRootPrefix))throw Error('E_MODEL_EXTERNAL_DEPS');
|
|
419
|
+
const path=dependency.path.slice(archiveRootPrefix.length),source=stagedEntries.get(path);
|
|
420
|
+
if(!source||dependency.bytes!==source.bytes.length||dependency.sha256!==sha256Prefixed(source.bytes))throw Error('E_MODEL_EXTERNAL_DEPS');
|
|
421
|
+
return {...dependency,path};
|
|
422
|
+
});
|
|
423
|
+
const reportedPaths=dependencies.map(dependency=>dependency.path);
|
|
424
|
+
try{for(const path of reportedPaths)resolveScopedLicense(path,licenseScope.index,licenseScope);}
|
|
425
|
+
catch(error){error.dependencyPaths=reportedPaths;throw error;}
|
|
426
|
+
const output=report.outputs?.[0];if(!output)throw Error('E_NATIVE_ASSET_DECODE');
|
|
427
|
+
const bytes=await readFile(resolve(temp,outRel,output.file)),masterBytes=report.master?await readFile(resolve(temp,outRel,report.master.file)):null;
|
|
428
|
+
if(!masterBytes||bytes.length>700000||masterBytes.length>maxSingleModelBytes)throw Error('E_NATIVE_ASSET_SIZE');
|
|
429
|
+
const info=inspectMedia(bytes,'model/gltf-binary'),masterSha256=sha256Prefixed(masterBytes);
|
|
430
|
+
if(masterSha256!==report.master.sha256||info.sha256!==output.sha256)throw Error('E_NATIVE_ASSET_DECODE');
|
|
431
|
+
return {
|
|
432
|
+
id:remoteId(source.href+'\0'+entry.name+'\0'+key),source:'remote',sourceId,path:entry.name,name:entry.name.split('/').pop(),kind:'mesh',styleFamily,tags:entry.name.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean),data:bytes,...info,
|
|
433
|
+
triangles:output.triangles,vertices:output.vertices,drawCalls:output.drawCalls,materials:output.materials,textures:output.textures,subNodes:output.subNodes??[],animations:output.animations??[],boundsMin:output.boundsMin,boundsMax:output.boundsMax,geometryBytes:output.geometryBytes,textureBytes:output.textureBytes,decodedTextureBytes:output.decodedTextureBytes,operations:output.operations??[],warnings:output.warnings??[],dependencies,licenseEntry,masterBytes,masterSha256,modelOptions:publicModelOptions(modelOptions),
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
async fetchPack(input){
|
|
437
|
+
const {sourceUrl,packId,fileFilter,signal}=input,source=assertRemoteUrl(sourceUrl),normalized=normalizeModelFetchOptions(input),{kind,fileFilters,modelOptions}=normalized;
|
|
438
|
+
if(signal?.aborted)throw abortError(signal);
|
|
439
|
+
modelOptions.maxFiles??=kind==='sprite'||kind==='audio'?100:32;
|
|
440
|
+
const mediaMaxFiles=input.maxFiles??100,filters=fileFilters.length?fileFilters:fileFilter;
|
|
441
|
+
const key=computeCacheKeyV2(source.href,packId,fileFilter,normalized),packKey=computePackKey(source.href),cached=await this.cached(key);
|
|
442
|
+
if(signal?.aborted)throw abortError(signal);
|
|
443
|
+
if(cached)return cached;
|
|
444
|
+
const sourcePathExt=extname(source.pathname).toLowerCase(),first=await this.download(source.href,{maxBytes:sourcePathExt==='.zip'?maxZipBytes:modelExtensions.has(sourcePathExt)?maxSingleModelBytes:mimeFor(source.pathname)?maxSingleBytes:maxPageBytes,signal});
|
|
445
|
+
const resolved=await this.resolveDownload(source,first,kind,filters,signal),archive=resolved.archive,pageHtml=resolved.pageHtml,provider=deriveProvider(source.href),title=htmlText(pageHtml,/<meta[^>]+property=["']og:title["'][^>]+content=["']([^"']+)/i)??htmlText(pageHtml,/<title>([^<]+)/i)??source.pathname.split('/').filter(Boolean).pop()??'CC0 pack',author=deriveAuthor(provider,pageHtml);
|
|
446
|
+
const pageHtmlVerified=Boolean(pageHtml),isArchive=isZip(archive);
|
|
447
|
+
let entries,licenseIndex=new Map(),allModels=[],standalone=[],companions=[];
|
|
448
|
+
if(isArchive){
|
|
449
|
+
const directory=readZipEntries(archive,undefined,true),licenses=directory.filter(entry=>isLicensePath(entry.name));
|
|
450
|
+
if(!licenses.length&&(provider==='kenney'||!pageHtmlVerified))throw Error('E_ASSET_LICENSE_UNVERIFIED');
|
|
451
|
+
const candidates=directory.filter(entry=>mediaKindFor(entry.name)==='mesh'&&fileMatches(entry.name,filters)&&kind!=='sprite'&&kind!=='audio'),groups=new Map();
|
|
452
|
+
for(const entry of candidates){const stem=entry.name.slice(0,-extname(entry.name).length).toLowerCase();if(!groups.has(stem))groups.set(stem,[]);groups.get(stem).push(entry);}
|
|
453
|
+
allModels=[...groups.values()].map(group=>group.sort((a,b)=>modelRank(a.name)-modelRank(b.name))[0]).sort((a,b)=>a.name.localeCompare(b.name));
|
|
454
|
+
if(allModels.length)companions=directory.filter(entry=>entry.uncompressedSize<=maxSingleModelBytes&&companionExtensions.has(extname(entry.name).toLowerCase()));
|
|
455
|
+
standalone=directory.filter(entry=>{
|
|
456
|
+
const mediaKind=mediaKindFor(entry.name);
|
|
457
|
+
return mediaKind&&mediaKind!=='mesh'&&(!kind||mediaKind===kind)&&fileMatches(entry.name,filters)&&entry.uncompressedSize<=maxSingleBytes&&!(allModels.length&&previewPath(entry.name));
|
|
458
|
+
}).slice(0,mediaMaxFiles);
|
|
459
|
+
const modelEntries=allModels.slice(0,modelOptions.maxFiles).filter(entry=>entry.uncompressedSize<=maxSingleModelBytes);
|
|
460
|
+
const wanted=new Set([...licenses,...companions,...modelEntries,...standalone].map(entry=>entry.name));
|
|
461
|
+
entries=readZipEntries(archive,name=>wanted.has(name));
|
|
462
|
+
licenseIndex=buildLicenseIndex(entries.filter(entry=>isLicensePath(entry.name)));
|
|
463
|
+
const archiveHasCc0=[...licenseIndex.values()].flat().some(entry=>{try{verifyCc0Evidence(entry.bytes.toString('utf8'));return true;}catch{return false;}});
|
|
464
|
+
if(licenses.length&&!archiveHasCc0&&(licenseIndex.has('')||provider==='kenney'||!pageHtmlVerified))throw Error('E_ASSET_LICENSE_UNVERIFIED');
|
|
263
465
|
}else{
|
|
264
|
-
if(!
|
|
265
|
-
const
|
|
466
|
+
const path=new URL(resolved.downloadUrl).pathname,mediaKind=mediaKindFor(path);if(!mediaKind)throw Error('E_REMOTE_ASSET_MIME');
|
|
467
|
+
const entry={name:cleanPath(decodePath(path.split('/').pop())),bytes:archive};
|
|
468
|
+
if((!kind||kind===mediaKind)&&fileMatches(entry.name,filters)){
|
|
469
|
+
if(mediaKind==='mesh')allModels=[entry];else standalone=[entry];
|
|
470
|
+
}
|
|
471
|
+
entries=[entry];
|
|
472
|
+
if(!pageHtmlVerified)throw Error('E_ASSET_LICENSE_UNVERIFIED');
|
|
266
473
|
}
|
|
267
|
-
const sourceId='remote-'+packKey.slice(0,24),styleFamily='remote-'+packKey.slice(0,16);
|
|
268
|
-
|
|
474
|
+
const sourceId='remote-'+packKey.slice(0,24),styleFamily='remote-'+packKey.slice(0,16),licenseScope={index:licenseIndex,provider,pageHtmlVerified,isArchive};
|
|
475
|
+
await assertStorePath(this.cacheRoot);await mkdir(this.cacheRoot,{recursive:true});await assertStorePath(this.cacheRoot);
|
|
476
|
+
const temp=await mkdtemp(resolve(this.cacheRoot,'.verify-')),files=[];
|
|
477
|
+
let skippedModels;
|
|
269
478
|
try{
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
const
|
|
274
|
-
|
|
479
|
+
const byName=new Map(entries.map(entry=>[entry.name,entry])),models=allModels.slice(0,modelOptions.maxFiles),stagedEntries=new Map();
|
|
480
|
+
for(const descriptor of [...models,...companions]){
|
|
481
|
+
if(signal?.aborted)throw abortError(signal);
|
|
482
|
+
const entry=byName.get(descriptor.name);if(!entry)continue;
|
|
483
|
+
const target=resolve(temp,archiveRootPrefix+entry.name);await mkdir(dirname(target),{recursive:true});await writeFile(target,entry.bytes,{flag:'wx'});stagedEntries.set(entry.name,entry);
|
|
484
|
+
}
|
|
485
|
+
const prepared=await mapWithConcurrency(models,4,async(descriptor,index)=>{
|
|
486
|
+
try{
|
|
487
|
+
if(signal?.aborted)throw abortError(signal);
|
|
488
|
+
const licenseEntry=resolveScopedLicense(descriptor.name,licenseIndex,licenseScope),entry=stagedEntries.get(descriptor.name);
|
|
489
|
+
if(!entry)throw Error('E_NATIVE_ASSET_SIZE');
|
|
490
|
+
return {file:await this.prepModel({entry,index,temp,key,source,sourceId,styleFamily,licenseEntry,licenseScope,stagedEntries,modelOptions,signal})};
|
|
491
|
+
}catch(error){
|
|
492
|
+
if(!recoverableModelErrors.has(error.message))throw error;
|
|
493
|
+
const code=['E_ASSET_READ','E_ASSET_TOO_LARGE','E_ASSET_PATH'].includes(error.message)?'E_MODEL_EXTERNAL_DEPS':error.message;
|
|
494
|
+
const reason=error.cause?.stderr?.replaceAll(temp,'archive').trim().slice(0,512)||error.message;
|
|
495
|
+
return {skipped:{path:descriptor.name,code,reason},dependencyPaths:error.dependencyPaths??[]};
|
|
496
|
+
}
|
|
497
|
+
});
|
|
498
|
+
files.push(...prepared.flatMap(result=>result.file?[result.file]:[]));
|
|
499
|
+
skippedModels=prepared.flatMap(result=>result.skipped?[result.skipped]:[]);
|
|
500
|
+
const dependencyPaths=new Set(prepared.flatMap(result=>result.dependencyPaths??result.file.dependencies.map(dependency=>dependency.path)));
|
|
501
|
+
for(const descriptor of standalone){
|
|
502
|
+
if(signal?.aborted)throw abortError(signal);
|
|
503
|
+
const entry=byName.get(descriptor.name),originalMime=mimeFor(entry.name);if(dependencyPaths.has(entry.name))continue;
|
|
504
|
+
try{
|
|
505
|
+
const licenseEntry=resolveScopedLicense(entry.name,licenseIndex,licenseScope),rights=`${author}, CC0-1.0. ${source.href}`,normalizedMedia=await this.normalize({path:entry.name,bytes:entry.bytes,mime:originalMime,temp,rights,signal});if(!normalizedMedia)continue;
|
|
506
|
+
const info=inspectMedia(normalizedMedia.bytes,normalizedMedia.mime),id=remoteId(source.href+'\0'+entry.name);
|
|
507
|
+
files.push({id,source:'remote',sourceId,path:entry.name,name:entry.name.split('/').pop(),kind:info.mime.startsWith('image/')?'sprite':'audio',styleFamily,tags:entry.name.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean),data:normalizedMedia.bytes,...info,licenseEntry});
|
|
508
|
+
}catch(error){if(error.message!=='E_ASSET_LICENSE_UNVERIFIED')throw error;}
|
|
275
509
|
}
|
|
276
510
|
}finally{await rm(temp,{recursive:true,force:true});}
|
|
277
|
-
if(
|
|
511
|
+
if(signal?.aborted)throw abortError(signal);
|
|
512
|
+
if(!files.length){const error=Error('E_REMOTE_ASSET_NO_SUPPORTED_MEDIA');error.detail={skippedModels};throw error;}
|
|
513
|
+
const totalMatchingModels=allModels.length,truncated=totalMatchingModels>modelOptions.maxFiles,remainingModelPaths=allModels.slice(modelOptions.maxFiles,modelOptions.maxFiles+64).map(entry=>entry.name),licenseEvidence=[pageHtml?'page:'+source.href:'',...new Set(files.map(file=>file.licenseEntry==='page.html'?'':'archive:'+file.licenseEntry))].filter(Boolean).join('; ');
|
|
278
514
|
const receipt={
|
|
279
|
-
format:'tora-remote-cc0-1',
|
|
280
|
-
|
|
281
|
-
packId:packId??'',
|
|
282
|
-
fileFilter:fileFilter??'',
|
|
283
|
-
sourceId,
|
|
284
|
-
provider,
|
|
285
|
-
packTitle:title,
|
|
286
|
-
author,
|
|
287
|
-
license:'CC0-1.0',
|
|
288
|
-
licenseEvidence,
|
|
289
|
-
...(archiveLicenseEntry?{archiveLicenseEntry}:{}),
|
|
290
|
-
...(pageHtml?{pageSha256:sha256Prefixed(Buffer.from(pageHtml,'utf8'))}:{}),
|
|
291
|
-
sourceUrl:source.href,
|
|
292
|
-
fetchedAt:new Date().toISOString(),
|
|
293
|
-
archiveSha256:sha256Prefixed(archive),
|
|
294
|
-
files,
|
|
515
|
+
format:'tora-remote-cc0-2',packKey,packId:packId??'',fileFilter:fileFilter??'',fileFilters,kind,modelOptions:publicModelOptions(modelOptions),cacheModelOptions:modelOptions,sourceId,provider,packTitle:title,author,license:'CC0-1.0',licenseEvidence,
|
|
516
|
+
...(pageHtml?{pageSha256:sha256Prefixed(Buffer.from(pageHtml,'utf8'))}:{}),sourceUrl:source.href,fetchedAt:new Date().toISOString(),archiveSha256:sha256Prefixed(archive),files,skippedModels,totalMatchingModels,truncated,remainingModelPaths,
|
|
295
517
|
};
|
|
296
518
|
return this.persist(key,receipt,archive,pageHtml,files);
|
|
297
519
|
}
|
|
298
520
|
async listCached({query='',kind,styleFamily,limit=40}={}){
|
|
299
521
|
try{await assertStorePath(this.cacheRoot);}catch{return [];}
|
|
300
|
-
let dirs;
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
if(!receipt)continue;
|
|
522
|
+
let dirs;try{dirs=await readdir(this.cacheRoot);}catch(e){if(e.code==='ENOENT')return [];throw e;}
|
|
523
|
+
const receipts=[];for(const key of dirs.sort()){if(/^[a-f0-9]{64}$/.test(key)){const receipt=await this.cached(key);if(receipt)receipts.push(receipt);}}
|
|
524
|
+
receipts.sort((a,b)=>(b.format==='tora-remote-cc0-2')-(a.format==='tora-remote-cc0-2')||a.cacheKey.localeCompare(b.cacheKey));
|
|
525
|
+
const v2Packs=new Set(receipts.filter(receipt=>receipt.format==='tora-remote-cc0-2').map(receipt=>receipt.packKey)),byId=new Map();
|
|
526
|
+
for(const receipt of receipts){
|
|
527
|
+
if(receipt.format==='tora-remote-cc0-1'&&v2Packs.has(receipt.packKey??computePackKey(receipt.sourceUrl)))continue;
|
|
307
528
|
for(const file of receipt.files){
|
|
308
529
|
if(byId.has(file.id))continue;
|
|
309
|
-
byId.set(file.id,{
|
|
310
|
-
id:file.id,
|
|
311
|
-
source:'remote',
|
|
312
|
-
sourceId:receipt.sourceId,
|
|
313
|
-
packTitle:receipt.packTitle,
|
|
314
|
-
author:receipt.author,
|
|
315
|
-
license:receipt.license,
|
|
316
|
-
sourceUrl:receipt.sourceUrl,
|
|
317
|
-
path:file.path,
|
|
318
|
-
name:file.name,
|
|
319
|
-
kind:file.kind,
|
|
320
|
-
styleFamily:file.styleFamily,
|
|
321
|
-
tags:file.tags??[],
|
|
322
|
-
mime:file.mime,
|
|
323
|
-
bytes:file.bytes,
|
|
324
|
-
sha256:file.sha256,
|
|
325
|
-
...(file.width!==undefined?{width:file.width,height:file.height}:{}),
|
|
326
|
-
...(file.durationSec!==undefined?{durationSec:file.durationSec}:{}),
|
|
327
|
-
cached:true,
|
|
328
|
-
});
|
|
530
|
+
byId.set(file.id,{...compactFile(file),source:'remote',sourceId:receipt.sourceId,packTitle:receipt.packTitle,author:receipt.author,license:receipt.license,sourceUrl:receipt.sourceUrl,cached:true,...(receipt.skippedModels?.length?{skippedModels:receipt.skippedModels}:{})});
|
|
329
531
|
}
|
|
330
532
|
}
|
|
331
533
|
const words=String(query).toLowerCase().split(/\s+/).filter(Boolean);
|
|
332
534
|
return [...byId.values()].filter(entry=>
|
|
333
535
|
(!kind||entry.kind===kind)&&(!styleFamily||entry.styleFamily===styleFamily)&&
|
|
334
|
-
words.every(word=>(entry.name+' '+entry.tags.join(' ')+' '+entry.packTitle+' '+entry.sourceId).toLowerCase().includes(word))
|
|
536
|
+
words.every(word=>(entry.name+' '+(entry.tags??[]).join(' ')+' '+entry.packTitle+' '+entry.sourceId+' '+(entry.subNodes??[]).join(' ')+' '+(entry.animations??[]).join(' ')).toLowerCase().includes(word))
|
|
335
537
|
).sort((a,b)=>a.styleFamily.localeCompare(b.styleFamily)||a.name.localeCompare(b.name)).slice(0,Math.min(100,Math.max(1,limit)));
|
|
336
538
|
}
|
|
337
539
|
async getCachedFile(remoteAssetId){
|
|
338
540
|
if(typeof remoteAssetId!=='string'||!remoteAssetId.startsWith('remote-'))return null;
|
|
339
541
|
try{await assertStorePath(this.cacheRoot);}catch{return null;}
|
|
340
|
-
let dirs;
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
const receipt
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
if(
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
542
|
+
let dirs;try{dirs=await readdir(this.cacheRoot);}catch(e){if(e.code==='ENOENT')return null;throw e;}
|
|
543
|
+
const receipts=[];for(const key of dirs.sort()){if(/^[a-f0-9]{64}$/.test(key)){const receipt=await this.cached(key);if(receipt)receipts.push(receipt);}}
|
|
544
|
+
receipts.sort((a,b)=>(b.format==='tora-remote-cc0-2')-(a.format==='tora-remote-cc0-2'));
|
|
545
|
+
for(const receipt of receipts){
|
|
546
|
+
const file=receipt.files.find(entry=>entry.id===remoteAssetId);if(!file)continue;
|
|
547
|
+
const bytes=await safeFile(resolve(this.cacheRoot,receipt.cacheKey,file.storedPath));if(inspectMedia(bytes,file.mime).sha256!==file.sha256)continue;
|
|
548
|
+
let master;
|
|
549
|
+
if(file.kind==='mesh'){
|
|
550
|
+
const masterBytes=await safeFile(resolve(this.cacheRoot,receipt.cacheKey,file.masterStoredPath));
|
|
551
|
+
if(sha256Prefixed(masterBytes)!==file.masterSha256)continue;
|
|
552
|
+
master={bytes:masterBytes,sha256:file.masterSha256,dependencies:file.dependencies};
|
|
553
|
+
}
|
|
554
|
+
return {receipt,file,bytes,...(master?{master}:{})};
|
|
351
555
|
}
|
|
352
556
|
return null;
|
|
353
557
|
}
|
|
354
558
|
async search({query,includeRemote=false,kind,styleFamily,limit=40,signal}={}){
|
|
559
|
+
if(signal?.aborted)throw abortError(signal);
|
|
355
560
|
await this.catalog.load();
|
|
356
|
-
const localMatches=this.catalog.list({query,kind,styleFamily,limit});
|
|
357
|
-
|
|
358
|
-
const fallbackLocalMatches=[...localMatches,...cachedRemoteMatches].slice(0,Math.min(100,Math.max(1,limit)));
|
|
561
|
+
const localMatches=this.catalog.list({query,kind,styleFamily,limit}),cachedRemoteMatches=await this.listCached({query,kind,styleFamily,limit}),fallbackLocalMatches=[...localMatches,...cachedRemoteMatches].slice(0,Math.min(100,Math.max(1,limit)));
|
|
562
|
+
if(signal?.aborted)throw abortError(signal);
|
|
359
563
|
if(!includeRemote)return {online:false,assets:fallbackLocalMatches,cachedRemoteMatches,remotePacks:[],fallbackLocalMatches};
|
|
360
564
|
const packs=[],seen=new Set(),failures=[];let reachedAny=false;
|
|
361
|
-
const sources=[
|
|
362
|
-
{provider:'kenney',url
|
|
363
|
-
{provider:'opengameart',url:`https://opengameart.org/art-search-advanced?keys=${encodeURIComponent(query??'')}&field_art_licenses_tid%5B%5D=
|
|
565
|
+
const mesh=kind==='mesh',sources=[
|
|
566
|
+
{provider:'kenney',url:mesh?`https://kenney.nl/assets/category:3D?q=${encodeURIComponent(query??'')}`:`https://kenney.nl/assets?q=${encodeURIComponent(query??'')}`,match:href=>/^https:\/\/(?:www\.)?kenney\.nl\/assets\/[a-z0-9-]+(?:\/)?$/i.test(href)},
|
|
567
|
+
{provider:'opengameart',url:`https://opengameart.org/art-search-advanced?keys=${encodeURIComponent(query??'')}${mesh?'&field_art_type_tid%5B%5D=10':''}&field_art_licenses_tid%5B%5D=4`,match:href=>/^https:\/\/(?:www\.)?opengameart\.org\/content\/[a-z0-9-]+/i.test(href)},
|
|
364
568
|
];
|
|
569
|
+
if(kind===undefined||mesh)sources.push({provider:'quaternius',url:'https://quaternius.com/',match:href=>/^https:\/\/(?:www\.)?quaternius\.com\/packs\/[a-z0-9_-]+\.html$/i.test(href)});
|
|
570
|
+
const words=String(query??'').toLowerCase().split(/\s+/).filter(Boolean);
|
|
365
571
|
for(const source of sources){
|
|
366
572
|
try{
|
|
367
|
-
const page=await this.download(source.url,{signal}),html=page.bytes.toString('utf8')
|
|
573
|
+
const page=await this.download(source.url,{maxBytes:maxPageBytes,signal}),html=page.bytes.toString('utf8');reachedAny=true;
|
|
368
574
|
let added=0;
|
|
369
|
-
for(const
|
|
370
|
-
const clean=href.split('#')[0];
|
|
371
|
-
if(!source.match(clean)||seen.has(clean))continue;
|
|
372
|
-
seen.add(clean);packs.push({sourceUrl:clean,provider:source.provider,license:'CC0-1.0',licenseVerified:false,isRemotePack:true});
|
|
575
|
+
for(const anchor of anchorLinks(html,page.finalUrl)){
|
|
576
|
+
const clean=anchor.href.split('#')[0],haystack=(clean+' '+anchor.text).toLowerCase();
|
|
577
|
+
if(!source.match(clean)||seen.has(clean)||source.provider==='quaternius'&&!words.every(word=>haystack.includes(word)))continue;
|
|
578
|
+
seen.add(clean);packs.push({sourceUrl:clean,provider:source.provider,kindHint:mesh||source.provider==='quaternius'?'mesh':undefined,license:'CC0-1.0',licenseVerified:false,isRemotePack:true});
|
|
373
579
|
if(++added>=6)break;
|
|
374
580
|
}
|
|
375
|
-
}catch{failures.push(source.provider);}
|
|
581
|
+
}catch(error){if(error.message==='E_BUILD_CANCELLED')throw error;failures.push(source.provider);}
|
|
376
582
|
}
|
|
377
583
|
if(!reachedAny)return {online:false,warning:'Remote CC0 sources are unavailable; using the verified local catalog.',assets:fallbackLocalMatches,cachedRemoteMatches,remotePacks:[],fallbackLocalMatches};
|
|
378
584
|
const warning=failures.length?`Some remote CC0 sources were unavailable (${failures.join(', ')}); returning available remote packs and local CC0 matches.`:undefined;
|
|
@@ -380,10 +586,10 @@ export class RemoteCc0Fetcher{
|
|
|
380
586
|
}
|
|
381
587
|
async fetchPackWithFallback(options){
|
|
382
588
|
try{return await this.fetchPack(options);}catch(error){
|
|
383
|
-
if(['
|
|
384
|
-
|
|
385
|
-
const fallbackLocalMatches=[...this.catalog.list({query
|
|
386
|
-
return {online:false,warning:'Remote asset could not be
|
|
589
|
+
if(!['E_REMOTE_ASSET_FETCH','E_REMOTE_ASSET_NOT_FOUND'].includes(error.message))throw error;
|
|
590
|
+
const query=options.fileFilter??options.fileFilters?.[0],kind=options.kind;
|
|
591
|
+
await this.catalog.load();const fallbackLocalMatches=[...this.catalog.list({query,kind}),...await this.listCached({query,kind})];
|
|
592
|
+
return {online:false,warning:'Remote asset could not be downloaded; use these local CC0 matches instead.',error:error.message,fallbackLocalMatches,files:[]};
|
|
387
593
|
}
|
|
388
594
|
}
|
|
389
595
|
}
|