@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.
Files changed (131) hide show
  1. package/README.md +107 -58
  2. package/assets/free-audio/arcade-pop/audio/loss.wav +0 -0
  3. package/assets/free-audio/arcade-pop/audio/reward.wav +0 -0
  4. package/assets/free-audio/arcade-pop/audio/win.wav +0 -0
  5. package/assets/free-audio/arcade-pop/source/INFO.txt +11 -11
  6. package/assets/kenney-food-starter/License.txt +28 -0
  7. package/assets/kenney-food-starter/burger.glb +0 -0
  8. package/assets/kenney-food-starter/frying-pan.glb +0 -0
  9. package/assets/kenney-food-starter/plan.json +61 -0
  10. package/assets/kenney-food-starter/plate.glb +0 -0
  11. package/assets/kenney-food-starter/pot.glb +0 -0
  12. package/assets/kenney-harvest/audio/victory.wav +0 -0
  13. package/assets/kenney-harvest/source/music-jingles/OGG/jingles_NES/jingles_NES03.ogg +0 -0
  14. package/assets/kenney-harvest/source/music-jingles/OGG/jingles_PIZZA/jingles_PIZZA03.ogg +0 -0
  15. package/assets/kenney-harvest/source/music-jingles/license.txt +14 -0
  16. package/bin/tora.mjs +322 -28
  17. package/crates/packer/trusted/native-3d-meta.json +4 -3
  18. package/crates/packer/trusted/native-3d.js +181 -181
  19. package/crates/packer/trusted/native-meta.json +3 -3
  20. package/crates/packer/trusted/native.js +5 -5
  21. package/crates/packer/trusted/release-manifest.json +17 -17
  22. package/crates/packer/trusted/review-runtime-meta.json +4 -3
  23. package/crates/packer/trusted/review-runtime.js +182 -182
  24. package/docs/MIGRATION_0_3.md +39 -0
  25. package/docs/NATIVE_AGENT_TOOLS.md +12 -363
  26. package/docs/TORA_AGENT_SETUP.md +24 -95
  27. package/docs/TORA_CREATION_API.md +63 -348
  28. package/docs/reference/CORE_AUTHORING.md +10 -3
  29. package/docs/reference/PLAYABLE_STARTERS.md +20 -0
  30. package/docs/reference/packs/3d.md +11 -3
  31. package/network-rules/mintegral-appgrowth-single-html.json +10 -10
  32. package/package.json +6 -6
  33. package/packages/creative-project/project-v21.schema.json +372 -9
  34. package/scripts/lean/editor/entry.js +11 -6
  35. package/scripts/lean/editor/project-launcher.js +116 -0
  36. package/scripts/lean/editor/quick-edit-panel.js +479 -0
  37. package/scripts/lean/editor/review-editor.css +256 -68
  38. package/scripts/lean/editor/review-editor.js +1834 -1086
  39. package/scripts/lean/editor-state.mjs +6 -0
  40. package/scripts/lean/editor.mjs +6 -3
  41. package/scripts/lean/matrix.mjs +5 -0
  42. package/scripts/lean/native/agent-tools.mjs +39 -62
  43. package/scripts/lean/native/api.mjs +161 -136
  44. package/scripts/lean/native/asset-catalog.mjs +7 -6
  45. package/scripts/lean/native/asset-lineage.mjs +54 -0
  46. package/scripts/lean/native/asset-prep.mjs +173 -40
  47. package/scripts/lean/native/assets.mjs +107 -11
  48. package/scripts/lean/native/audio-assets.mjs +30 -0
  49. package/scripts/lean/native/browser-pool.mjs +34 -0
  50. package/scripts/lean/native/build-cache.mjs +38 -7
  51. package/scripts/lean/native/cc0-inputs.mjs +24 -0
  52. package/scripts/lean/native/cc0-staging.mjs +28 -8
  53. package/scripts/lean/native/compiler.mjs +9 -3
  54. package/scripts/lean/native/contracts.mjs +16 -11
  55. package/scripts/lean/native/creative-qa.mjs +365 -128
  56. package/scripts/lean/native/demos.mjs +53 -18
  57. package/scripts/lean/native/document.mjs +50 -12
  58. package/scripts/lean/native/export-budget.mjs +75 -0
  59. package/scripts/lean/native/local-bundle.mjs +7 -3
  60. package/scripts/lean/native/mcp-server.mjs +42 -74
  61. package/scripts/lean/native/media-validate.mjs +124 -0
  62. package/scripts/lean/native/modules/harvest-restore.mjs +3 -284
  63. package/scripts/lean/native/modules/sort-puzzle.mjs +51 -0
  64. package/scripts/lean/native/modules/star-salvage.mjs +3 -368
  65. package/scripts/lean/native/native-bin.mjs +3 -3
  66. package/scripts/lean/native/outcome-playthrough.mjs +97 -0
  67. package/scripts/lean/native/project-bundle.mjs +6 -5
  68. package/scripts/lean/native/project-index.mjs +0 -2
  69. package/scripts/lean/native/qa-adapters.mjs +10 -0
  70. package/scripts/lean/native/quick-edit.mjs +328 -0
  71. package/scripts/lean/native/remote-cc0-fetcher.mjs +403 -197
  72. package/scripts/lean/native/review.mjs +205 -571
  73. package/scripts/lean/native/schema-vocabulary.mjs +10 -0
  74. package/scripts/lean/native/schema.mjs +7 -5
  75. package/scripts/lean/native/scope.mjs +45 -0
  76. package/scripts/lean/native/service.mjs +378 -79
  77. package/scripts/lean/native/starters.mjs +563 -0
  78. package/scripts/lean/native/variant-adapters.mjs +8 -0
  79. package/scripts/lean/native/variants-core.mjs +186 -0
  80. package/scripts/lean/native/variants.mjs +63 -0
  81. package/scripts/lean/native/win-cues.mjs +96 -0
  82. package/skills/tora-playables/SKILL.md +1 -1
  83. package/scripts/lean/editor/review-intake.js +0 -837
  84. package/scripts/lean/model-client.mjs +0 -119
  85. package/scripts/lean/native/author-expansion-proofs.mjs +0 -240
  86. package/scripts/lean/native/author-games.mjs +0 -160
  87. package/scripts/lean/native/author-harvest.mjs +0 -74
  88. package/scripts/lean/native/author-primitive-proofs.mjs +0 -874
  89. package/scripts/lean/native/author-salvage.mjs +0 -71
  90. package/scripts/lean/native/chat-compose.mjs +0 -287
  91. package/scripts/lean/native/check-harvest-outcome-audio.mjs +0 -191
  92. package/scripts/lean/native/check-salvage.mjs +0 -197
  93. package/scripts/lean/native/compatibility.mjs +0 -34
  94. package/scripts/lean/native/concept.mjs +0 -633
  95. package/scripts/lean/native/draw-stroke.mjs +0 -26
  96. package/scripts/lean/native/erase-mask.mjs +0 -18
  97. package/scripts/lean/native/harvest-recipe.mjs +0 -21
  98. package/scripts/lean/native/instance-steering.mjs +0 -24
  99. package/scripts/lean/native/intake-creator-agent.mjs +0 -98
  100. package/scripts/lean/native/intake-creator-tools.mjs +0 -165
  101. package/scripts/lean/native/interaction-gestures.mjs +0 -45
  102. package/scripts/lean/native/match-board.mjs +0 -138
  103. package/scripts/lean/native/modules/index.mjs +0 -54
  104. package/scripts/lean/native/modules/tap-collect.mjs +0 -54
  105. package/scripts/lean/native/path-network.mjs +0 -132
  106. package/scripts/lean/native/physics-2d.mjs +0 -154
  107. package/scripts/lean/native/physics-3d.mjs +0 -259
  108. package/scripts/lean/native/prepare-audio-collections.mjs +0 -112
  109. package/scripts/lean/native/prepare-game-audio.mjs +0 -372
  110. package/scripts/lean/native/prepare-golf-3d-assets.py +0 -177
  111. package/scripts/lean/native/prepare-golf-assets.py +0 -211
  112. package/scripts/lean/native/prepare-harvest-audio.mjs +0 -83
  113. package/scripts/lean/native/prepare-harvest-images.mjs +0 -31
  114. package/scripts/lean/native/prepare-primitive-images.py +0 -25
  115. package/scripts/lean/native/prepare-space-salvage-images.mjs +0 -89
  116. package/scripts/lean/native/prepare-traffic-assets.py +0 -329
  117. package/scripts/lean/native/presentation.mjs +0 -335
  118. package/scripts/lean/native/review-agent-tools.mjs +0 -561
  119. package/scripts/lean/native/review-connection.mjs +0 -303
  120. package/scripts/lean/native/review-fields.mjs +0 -24
  121. package/scripts/lean/native/review-intake.mjs +0 -385
  122. package/scripts/lean/native/review-intents.mjs +0 -217
  123. package/scripts/lean/native/review-provider.mjs +0 -580
  124. package/scripts/lean/native/review-receipts.mjs +0 -76
  125. package/scripts/lean/native/review-resolver.mjs +0 -429
  126. package/scripts/lean/native/review-targets.mjs +0 -35
  127. package/scripts/lean/native/runtime.mjs +0 -1623
  128. package/scripts/lean/native/salvage-recipe.mjs +0 -20
  129. package/scripts/lean/native/stage-3d.mjs +0 -818
  130. package/scripts/lean/native/verify.mjs +0 -4
  131. package/scripts/lean/scene-document.mjs +0 -48
@@ -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 {resolve,extname} from 'node:path';
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=25_000_000,maxSingleBytes=2_000_000,maxUncompressedBytes=64_000_000;
20
- const mediaExtensions=new Map([['.png','image/png'],['.jpg','image/jpeg'],['.jpeg','image/jpeg'],['.wav','audio/wav'],['.mp3','audio/mpeg'],['.ogg','audio/ogg']]);
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(!name||name.length>512||name.includes('\0')||name.includes('\\')||name.startsWith('/')||/^[a-z]:/i.test(name))throw Error('E_REMOTE_ASSET_ARCHIVE');
34
- const parts=name.split('/');if(parts.some(part=>part==='..'||part===''))throw Error('E_REMOTE_ASSET_ARCHIVE');
35
- return parts.join('/');
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
- export function readZipEntries(archive,entryFilter){
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>2000||count===0xffff||centralOffset===0xffffffff||centralSize===0xffffffff||centralOffset+centralSize>eocd)throw Error('E_REMOTE_ASSET_ARCHIVE_LIMIT');
46
- const entries=[];let offset=centralOffset,total=0;
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>archive.length||archive.readUInt32LE(offset)!==0x02014b50)throw Error('E_REMOTE_ASSET_ARCHIVE');
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>archive.length||compressedSize===0xffffffff||uncompressedSize===0xffffffff||localOffset===0xffffffff)throw Error('E_REMOTE_ASSET_ARCHIVE_LIMIT');
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>maxUncompressedBytes)throw Error('E_REMOTE_ASSET_ARCHIVE_LIMIT');
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>archive.length||archive.readUInt32LE(entry.localOffset)!==0x04034b50)throw Error('E_REMOTE_ASSET_ARCHIVE');
66
- const start=entry.localOffset+30+archive.readUInt16LE(entry.localOffset+26)+archive.readUInt16LE(entry.localOffset+28),end=start+entry.compressedSize;
67
- if(end>archive.length)throw Error('E_REMOTE_ASSET_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 privateAddress(address){
75
- if(address==='::'||address==='::1'||address==='0.0.0.0')return true;
76
- const normalized=address.toLowerCase().split('%')[0];
77
- if(/^f[cd]/.test(normalized)||/^fe[89ab]/.test(normalized)||normalized.startsWith('::ffff:127.')||normalized.startsWith('::ffff:10.')||normalized.startsWith('::ffff:192.168.'))return true;
78
- const mapped=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(normalized);if(mapped)return privateAddress(mapped[1]);
79
- const parts=normalized.split('.').map(Number);if(parts.length!==4||parts.some(part=>!Number.isInteger(part)||part<0||part>255))return false;
80
- const [a,b]=parts;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||a===198&&(b===18||b===19)||a===192&&b===0||a===198&&b===51||a===203&&b===0;
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(/&amp;/g,'&').replace(/&quot;/g,'"').replace(/&#39;/g,"'").trim();}
90
- function links(html,base){
91
- return [...html.matchAll(/href\s*=\s*["']([^"']+)["']/gi)].map(match=>{
92
- try{return new URL(match[1].replace(/&amp;/g,'&'),base).href;}catch{return null;}
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(/&amp;/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
- if(!/CC0(?:\s|&nbsp;|<|\/|-)*1\.0|CC0 1\.0 Universal|Creative Commons Zero|public domain/i.test(text)||/(?:NonCommercial|Non-Commercial|CC BY-NC|CC BY-SA|CC BY-ND|GNU GPL|GPL v\d)/i.test(text))throw Error('E_ASSET_LICENSE_UNVERIFIED');
143
+ const cc0=/\bCC0(?:\s|&nbsp;|<|\/|-)*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 deriveAuthor(provider,pageHtml){
103
- return provider==='kenney'?'Kenney':htmlText(pageHtml,/(?:submitted by|author)[\s\S]{0,200}?>([A-Za-z0-9 _.-]{2,80})</i)??'OpenGameArt contributor';
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=globalThis.fetch,lookup=async host=>dnsLookup(host,{all:true,verbatim:true}),catalog}={}){
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
- if(!Array.isArray(addresses))addresses=[{address:addresses.address??addresses,family:addresses.family}];
115
- if(!addresses.length||addresses.some(item=>privateAddress(item.address)))throw Error('E_REMOTE_ASSET_ORIGIN');
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
- let response;try{response=await this.fetchImpl(url.href,{redirect:'manual',signal:controller.signal,headers:{'User-Agent':'Tora-CC0-Asset-Fetcher/1.0'}});}catch(error){if(signal?.aborted)throw Error('E_BUILD_CANCELLED',{cause:error});throw Error(error.name==='AbortError'?'E_REMOTE_ASSET_TIMEOUT':'E_REMOTE_ASSET_FETCH',{cause:error});}
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 response.body?.cancel().catch(()=>{});
126
- if(!location||redirects===5)throw Error('E_REMOTE_ASSET_ORIGIN');url=assertRemoteUrl(new URL(location,url).href);continue;
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 response.body?.cancel().catch(()=>{});throw Error('E_REMOTE_ASSET_FETCH');}
129
- const declared=Number(response.headers.get('content-length')??0);if(declared>maxBytes){await response.body?.cancel().catch(()=>{});throw Error('E_REMOTE_ASSET_SIZE');}
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){await response.body.cancel().catch(()=>{});throw Error('E_REMOTE_ASSET_SIZE');}chunks.push(chunk);}
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(receipt?.format!=='tora-remote-cc0-1'||receipt.license!=='CC0-1.0'||!Array.isArray(receipt.files))return null;
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
- if(sha256Prefixed(pageBytes)!==receipt.pageSha256)return null;
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(!verifiedEvidence)return null;
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
- const bytes=await safeFile(resolve(this.cacheRoot,key,file.storedPath));
182
- if(inspectMedia(bytes,file.mime).sha256!==file.sha256)return null;
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
- const outputPath=resolve(temp,'output.wav');
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>8_000_000)return null;
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],storedPath='files/'+String(index).padStart(3,'0')+(file.mime==='image/png'?'.png':file.mime==='image/jpeg'?'.jpg':file.mime==='audio/wav'?'.wav':'.mp3');
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;publicFiles.push({...metadata,storedPath});
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
- return await this.cached(key)??{...finalReceipt,cached:false};
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 fetchPack({sourceUrl,packId,fileFilter,signal}){
242
- const source=assertRemoteUrl(sourceUrl),key=computeCacheKey(source.href,packId,fileFilter),packKey=computePackKey(source.href);
243
- const cached=await this.cached(key);if(cached)return cached;
244
- const first=await this.download(source.href,{maxBytes:/\.zip(?:$|\?)/i.test(source.pathname)?maxZipBytes:maxSingleBytes,signal});
245
- let archive=first.bytes,pageHtml='',evidenceUrl=source.href,downloadUrl=source.href;
246
- const isZip=archive.length>=4&&archive.readUInt32LE(0)===0x04034b50;
247
- if(!isZip){
248
- pageHtml=archive.toString('utf8');verifyCc0Evidence(pageHtml);
249
- const candidates=links(pageHtml,source.href),provider=source.hostname.endsWith('kenney.nl')?'kenney':'opengameart';
250
- const selected=candidates.find(url=>/\.zip(?:$|\?)/i.test(url))??(provider==='opengameart'?candidates.find(url=>mimeFor(new URL(url).pathname)):null);
251
- if(!selected)throw Error('E_REMOTE_ASSET_NOT_FOUND');downloadUrl=assertRemoteUrl(selected).href;
252
- const downloaded=await this.download(downloadUrl,{maxBytes:/\.zip(?:$|\?)/i.test(downloadUrl)?maxZipBytes:maxSingleBytes,signal});archive=downloaded.bytes;
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(/&amp;/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 provider=source.hostname.endsWith('kenney.nl')?'kenney':'opengameart',title=htmlText(pageHtml,/<meta[^>]+property=["']og:title["'][^>]+content=["']([^"']+)/i)??htmlText(pageHtml,/<title>([^<]+)/i)??source.pathname.split('/').filter(Boolean).pop()??'CC0 pack';
255
- const author=deriveAuthor(provider,pageHtml);
256
- let licenseEvidence=pageHtml?evidenceUrl:'',archiveLicenseEntry=null,selected;
257
- if(archive.length>=4&&archive.readUInt32LE(0)===0x04034b50){
258
- const isLicense=name=>/(?:^|\/)(?:license|copying)(?:\.txt)?$/i.test(name);
259
- const entries=readZipEntries(archive,name=>isLicense(name)||Boolean(mimeFor(name)&&fileMatches(name,fileFilter)));
260
- const licenseEntry=entries.find(entry=>isLicense(entry.name));
261
- if(licenseEntry){verifyCc0Evidence(licenseEntry.bytes.toString('utf8'));archiveLicenseEntry=licenseEntry.name;licenseEvidence+=(licenseEvidence?'; ':'')+'archive:'+licenseEntry.name;}else if(provider==='kenney'||!pageHtml)throw Error('E_ASSET_LICENSE_UNVERIFIED');
262
- selected=entries.filter(entry=>mimeFor(entry.name)&&fileMatches(entry.name,fileFilter));
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(!pageHtml)throw Error('E_ASSET_LICENSE_UNVERIFIED');
265
- const path=new URL(downloadUrl).pathname;if(!mimeFor(path))throw Error('E_REMOTE_ASSET_MIME');selected=[{name:path.split('/').pop(),bytes:archive}];
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
- const temp=await (async()=>{await assertStorePath(this.cacheRoot);await mkdir(this.cacheRoot,{recursive:true});return mkdtemp(resolve(this.cacheRoot,'.verify-'));})(),files=[];
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
- for(const entry of selected.slice(0,100)){
271
- const originalMime=mimeFor(entry.name),rights=`${author}, CC0-1.0. ${source.href}`;
272
- const normalized=await this.normalize({path:entry.name,bytes:entry.bytes,mime:originalMime,temp,rights});if(!normalized)continue;
273
- const info=inspectMedia(normalized.bytes,normalized.mime),id=remoteId(source.href+'\0'+entry.name);
274
- 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:normalized.bytes,...info});
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(!files.length)throw Error('E_REMOTE_ASSET_NO_SUPPORTED_MEDIA');
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
- packKey,
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
- try{dirs=await readdir(this.cacheRoot);}catch(e){if(e.code==='ENOENT')return [];throw e;}
302
- const byId=new Map();
303
- for(const key of dirs.sort()){
304
- if(!/^[a-f0-9]{64}$/.test(key))continue;
305
- const receipt=await this.cached(key);
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
- try{dirs=await readdir(this.cacheRoot);}catch(e){if(e.code==='ENOENT')return null;throw e;}
342
- for(const key of dirs.sort()){
343
- if(!/^[a-f0-9]{64}$/.test(key))continue;
344
- const receipt=await this.cached(key);
345
- if(!receipt)continue;
346
- const file=receipt.files.find(entry=>entry.id===remoteAssetId);
347
- if(!file)continue;
348
- const bytes=await safeFile(resolve(this.cacheRoot,key,file.storedPath));
349
- if(inspectMedia(bytes,file.mime).sha256!==file.sha256)continue;
350
- return {receipt,file,bytes};
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
- const cachedRemoteMatches=await this.listCached({query,kind,styleFamily,limit});
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:`https://kenney.nl/assets?q=${encodeURIComponent(query??'')}`,match:href=>/^https:\/\/(?:www\.)?kenney\.nl\/assets\/[a-z0-9-]+(?:\/)?$/i.test(href)},
363
- {provider:'opengameart',url:`https://opengameart.org/art-search-advanced?keys=${encodeURIComponent(query??'')}&field_art_licenses_tid%5B%5D=17981`,match:href=>/^https:\/\/(?:www\.)?opengameart\.org\/content\/[a-z0-9-]+/i.test(href)},
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'),base=new URL(source.url);reachedAny=true;
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 href of links(html,base)){
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(['E_REMOTE_ASSET_ORIGIN','E_BUILD_CANCELLED','E_REMOTE_ASSET_SIZE','E_REMOTE_ASSET_ARCHIVE','E_REMOTE_ASSET_ARCHIVE_LIMIT'].includes(error.message))throw error;
384
- await this.catalog.load();
385
- const fallbackLocalMatches=[...this.catalog.list({query:options.fileFilter}),...await this.listCached({query:options.fileFilter})];
386
- return {online:false,warning:'Remote asset could not be verified or downloaded; use these local CC0 matches instead.',error:error.message,fallbackLocalMatches,files:[]};
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
  }