@tora-editor/tora 0.2.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 (107) hide show
  1. package/README.md +5 -6
  2. package/bin/tora.mjs +255 -29
  3. package/crates/packer/trusted/native-3d-meta.json +3 -3
  4. package/crates/packer/trusted/native-3d.js +180 -180
  5. package/crates/packer/trusted/native-meta.json +3 -3
  6. package/crates/packer/trusted/native.js +5 -5
  7. package/crates/packer/trusted/release-manifest.json +17 -17
  8. package/crates/packer/trusted/review-runtime-meta.json +3 -3
  9. package/crates/packer/trusted/review-runtime.js +182 -182
  10. package/docs/MIGRATION_0_3.md +39 -0
  11. package/docs/NATIVE_AGENT_TOOLS.md +12 -363
  12. package/docs/TORA_AGENT_SETUP.md +24 -106
  13. package/docs/TORA_CREATION_API.md +63 -365
  14. package/docs/reference/CORE_AUTHORING.md +8 -2
  15. package/docs/reference/PLAYABLE_STARTERS.md +1 -1
  16. package/docs/reference/packs/3d.md +2 -0
  17. package/package.json +6 -6
  18. package/packages/creative-project/project-v21.schema.json +108 -1
  19. package/scripts/lean/editor/entry.js +11 -6
  20. package/scripts/lean/editor/project-launcher.js +116 -0
  21. package/scripts/lean/editor/quick-edit-panel.js +479 -0
  22. package/scripts/lean/editor/review-editor.css +246 -68
  23. package/scripts/lean/editor/review-editor.js +1731 -1099
  24. package/scripts/lean/editor-state.mjs +6 -0
  25. package/scripts/lean/editor.mjs +6 -3
  26. package/scripts/lean/matrix.mjs +5 -0
  27. package/scripts/lean/native/agent-tools.mjs +35 -58
  28. package/scripts/lean/native/api.mjs +148 -134
  29. package/scripts/lean/native/audio-assets.mjs +30 -0
  30. package/scripts/lean/native/browser-pool.mjs +34 -0
  31. package/scripts/lean/native/build-cache.mjs +36 -5
  32. package/scripts/lean/native/contracts.mjs +8 -6
  33. package/scripts/lean/native/creative-qa.mjs +66 -12
  34. package/scripts/lean/native/demos.mjs +11 -20
  35. package/scripts/lean/native/document.mjs +14 -2
  36. package/scripts/lean/native/local-bundle.mjs +4 -2
  37. package/scripts/lean/native/mcp-server.mjs +16 -35
  38. package/scripts/lean/native/modules/harvest-restore.mjs +3 -284
  39. package/scripts/lean/native/modules/sort-puzzle.mjs +51 -0
  40. package/scripts/lean/native/modules/star-salvage.mjs +3 -368
  41. package/scripts/lean/native/project-bundle.mjs +3 -2
  42. package/scripts/lean/native/project-index.mjs +0 -2
  43. package/scripts/lean/native/qa-adapters.mjs +10 -0
  44. package/scripts/lean/native/quick-edit.mjs +328 -0
  45. package/scripts/lean/native/review.mjs +203 -572
  46. package/scripts/lean/native/schema-vocabulary.mjs +10 -0
  47. package/scripts/lean/native/schema.mjs +1 -1
  48. package/scripts/lean/native/scope.mjs +45 -0
  49. package/scripts/lean/native/service.mjs +242 -70
  50. package/scripts/lean/native/starters.mjs +135 -8
  51. package/scripts/lean/native/variant-adapters.mjs +8 -0
  52. package/scripts/lean/native/variants-core.mjs +186 -0
  53. package/scripts/lean/native/variants.mjs +63 -0
  54. package/scripts/lean/native/win-cues.mjs +1 -1
  55. package/skills/tora-playables/SKILL.md +1 -1
  56. package/scripts/lean/editor/review-intake.js +0 -837
  57. package/scripts/lean/model-client.mjs +0 -119
  58. package/scripts/lean/native/author-expansion-proofs.mjs +0 -143
  59. package/scripts/lean/native/author-fps.mjs +0 -545
  60. package/scripts/lean/native/author-games.mjs +0 -160
  61. package/scripts/lean/native/author-harvest.mjs +0 -74
  62. package/scripts/lean/native/author-primitive-proofs.mjs +0 -875
  63. package/scripts/lean/native/author-salvage.mjs +0 -71
  64. package/scripts/lean/native/chat-compose.mjs +0 -287
  65. package/scripts/lean/native/check-harvest-outcome-audio.mjs +0 -190
  66. package/scripts/lean/native/check-salvage.mjs +0 -200
  67. package/scripts/lean/native/compatibility.mjs +0 -34
  68. package/scripts/lean/native/concept.mjs +0 -633
  69. package/scripts/lean/native/draw-stroke.mjs +0 -26
  70. package/scripts/lean/native/erase-mask.mjs +0 -18
  71. package/scripts/lean/native/glb-loader.mjs +0 -468
  72. package/scripts/lean/native/harvest-recipe.mjs +0 -21
  73. package/scripts/lean/native/instance-steering.mjs +0 -24
  74. package/scripts/lean/native/intake-creator-agent.mjs +0 -98
  75. package/scripts/lean/native/intake-creator-tools.mjs +0 -218
  76. package/scripts/lean/native/interaction-gestures.mjs +0 -45
  77. package/scripts/lean/native/match-board.mjs +0 -138
  78. package/scripts/lean/native/modules/index.mjs +0 -54
  79. package/scripts/lean/native/modules/tap-collect.mjs +0 -54
  80. package/scripts/lean/native/path-network.mjs +0 -132
  81. package/scripts/lean/native/physics-2d.mjs +0 -154
  82. package/scripts/lean/native/physics-3d.mjs +0 -259
  83. package/scripts/lean/native/prepare-audio-collections.mjs +0 -112
  84. package/scripts/lean/native/prepare-fps-assets.mjs +0 -330
  85. package/scripts/lean/native/prepare-game-audio.mjs +0 -372
  86. package/scripts/lean/native/prepare-golf-3d-assets.py +0 -177
  87. package/scripts/lean/native/prepare-golf-assets.py +0 -211
  88. package/scripts/lean/native/prepare-harvest-audio.mjs +0 -83
  89. package/scripts/lean/native/prepare-harvest-images.mjs +0 -31
  90. package/scripts/lean/native/prepare-primitive-images.py +0 -25
  91. package/scripts/lean/native/prepare-space-salvage-images.mjs +0 -89
  92. package/scripts/lean/native/prepare-traffic-assets.py +0 -329
  93. package/scripts/lean/native/presentation.mjs +0 -335
  94. package/scripts/lean/native/review-agent-tools.mjs +0 -561
  95. package/scripts/lean/native/review-connection.mjs +0 -303
  96. package/scripts/lean/native/review-fields.mjs +0 -24
  97. package/scripts/lean/native/review-intake.mjs +0 -385
  98. package/scripts/lean/native/review-intents.mjs +0 -217
  99. package/scripts/lean/native/review-provider.mjs +0 -580
  100. package/scripts/lean/native/review-receipts.mjs +0 -76
  101. package/scripts/lean/native/review-resolver.mjs +0 -429
  102. package/scripts/lean/native/review-targets.mjs +0 -35
  103. package/scripts/lean/native/runtime.mjs +0 -1809
  104. package/scripts/lean/native/salvage-recipe.mjs +0 -20
  105. package/scripts/lean/native/stage-3d.mjs +0 -1121
  106. package/scripts/lean/native/verify.mjs +0 -4
  107. package/scripts/lean/scene-document.mjs +0 -48
@@ -1,340 +1,3 @@
1
- import {createHash} from 'node:crypto';
2
- import {Buffer} from 'node:buffer';
3
- import {isDeepStrictEqual} from 'node:util';
4
- import {canonical} from '../../../../packages/creative-project/src/canonical.mjs';
5
- import {validateAssetPolicy} from '../asset-policy.mjs';
6
- import {component} from '../document.mjs';
7
- import {assertValue,fieldLimits,layout,record,standardText} from '../review-fields.mjs';
8
- import {salvageRecipe} from '../salvage-recipe.mjs';
9
- import {isAudioMime} from '../media-validate.mjs';
10
-
11
- const moments=[
12
- {id:'opening',label:'Opening'},
13
- {id:'first-catch',label:'First core catch'},
14
- {id:'end-card',label:'End card'},
15
- {id:'timeout',label:'Timeout'},
16
- ];
17
- const timeoutCaptionId='salvage.timeout.caption';
18
- const timeoutLayoutId='salvage.timeout.layout';
19
- const timeoutBindingId='salvage.timeout.caption.show';
20
- const targetDefinitions=[
21
- {id:'opening',label:'Opening instruction',moment:'opening',componentIds:['salvage.instruction'],fields:[['instruction','Instruction'],['hint-delay','Time before opening hint (s)']]},
22
- {id:'first-catch',label:'First station repair',moment:'first-catch',componentIds:['salvage.station.stage.1','salvage.instruction'],fields:[['reveal-duration','Reveal duration (s)'],['message','Reward message']]},
23
- {id:'cta',label:'Install button',moment:'end-card',componentIds:['salvage.cta'],fields:[['text','Button wording'],['payoff-hold','Time to enjoy the restored station before showing the button (s)']]},
24
- {id:'ending',label:'Final payoff',moment:'end-card',componentIds:['salvage.reward.title','salvage.reward.caption'],fields:[['payoff-hold','Hold before install button (s)']]},
25
- ];
26
- const playfieldLayout=Object.freeze({x:345,y:-155,scaleX:.78,scaleY:.78});
27
- const lanes=Object.freeze([52,134,216,298]);
28
- const check=(value,code)=>{if(!value)throw Error(code);};
29
- const message=binding=>binding?.actions.find(action=>action.kind==='set'&&action.variableId==='salvage.message');
30
- const payoff=binding=>binding?.condition?.all?.find(part=>part.variableId==='salvage.payoff'&&part.op==='gte');
31
-
32
- function condition(binding,variableId,op,value){
33
- const parts=[binding.condition,...binding.condition?.all??[],...binding.condition?.any??[]].filter(Boolean);
34
- return parts.some(part=>part.variableId===variableId&&part.op===op&&part.value===value);
35
- }
36
- function setsPhase(binding,value){return binding?.actions.some(action=>action.kind==='set'&&action.variableId==='salvage.phase'&&action.value===value);}
37
- function audioCue(index,binding){
38
- const actions=binding?.actions.filter(action=>action.kind==='playAudio')??[];
39
- if(actions.length!==1)return {unresolved:actions.length?'multiple-cues':'missing-cue'};
40
- const behavior=index.behavior(actions[0].behaviorId),target=behavior&&index.component(behavior.componentId);
41
- const assetId=target?.assetSlots[0]?.assetId,asset=assetId&&index.asset(assetId);
42
- if(behavior?.kind!=='audio'||!target||!isAudioMime(asset?.mime))return {unresolved:'invalid-cue'};
43
- return {behaviorId:behavior.id,componentId:target.id,assetId,assetHash:asset.hash};
44
- }
45
- function outcome(index,{bindingId,eventKind,eventReference,phase}){
46
- const binding=index.binding(bindingId),event=binding&&index.event(binding.eventId);
47
- if(!binding||event?.kind!==eventKind||event[eventReference.key]!==eventReference.value||!setsPhase(binding,phase))return {unresolved:'invalid-binding'};
48
- const duplicate=index.bindingsForEvent(event.id).filter(other=>other.id!==binding.id&&isDeepStrictEqual(other.condition,binding.condition)&&setsPhase(other,phase));
49
- if(duplicate.length)return {unresolved:'ambiguous-binding'};
50
- return {bindingId,eventId:event.id,cue:audioCue(index,binding)};
51
- }
52
- export function resolveSalvageRoles(index){
53
- const unresolved=[],rules=index.behavior('salvage.rules');
54
- if(rules?.kind!=='drag'||rules.componentId!=='salvage.ship')return {status:'unsupported',module:null,unresolved:['module']};
55
- const win=outcome(index,{bindingId:'salvage.restore.3',eventKind:'variableChange',eventReference:{key:'variableId',value:'salvage.catches'},phase:'payoff'});
56
- if(!condition(index.binding('salvage.restore.3')??{},'salvage.catches','eq',3))win.unresolved??='invalid-condition';
57
- const loss=outcome(index,{bindingId:'salvage.deadline.cta',eventKind:'timer',eventReference:{key:'behaviorId',value:'salvage.deadline'},phase:'cta'});
58
- const cta=index.component('salvage.cta'),label=index.component('salvage.cta.label'),click=index.binding('salvage.cta.click'),event=click&&index.event(click.eventId);
59
- const primaryCta=cta?.contract==='native.button.v1'&&label?.parentId===cta.id&&label.contract==='native.text.v1'&&event?.kind==='click'&&event.componentId===cta.id&&click.actions.some(action=>action.kind==='store')
60
- ?{componentId:cta.id,labelId:label.id,bindingId:click.id}:{unresolved:'invalid-cta'};
61
- const panel=index.component('salvage.panel'),hand=index.behavior('salvage.hand'),payoffFinish=index.binding('salvage.payoff.finish');
62
- const outcomePanel=panel?.contract==='native.rectangle.v1'?{componentId:panel.id}:{unresolved:'missing-panel'};
63
- const hintTiming=hand?.kind==='tutorial-hand'?{behaviorId:hand.id}:{unresolved:'missing-hint'};
64
- const payoffTiming=payoff(payoffFinish)?{bindingId:'salvage.payoff.finish'}:{unresolved:'missing-payoff'};
65
- const roles={winEvent:win,timeoutEvent:loss,primaryCta,outcomePanel,rewardCue:win.cue??{unresolved:win.unresolved??'invalid-cue'},hintTiming,payoffTiming};
66
- for(const [role,value]of Object.entries(roles))if(value.unresolved)unresolved.push(role+':'+value.unresolved);
67
- if(index.component(timeoutCaptionId))roles.timeoutCaption={componentId:timeoutCaptionId};
68
- if(win.bindingId&&win.bindingId===loss.bindingId)unresolved.push('outcomes:shared-binding');
69
- return {status:unresolved.length?'unresolved':'resolved',module:'star-salvage',version:1,roles,unresolved};
70
- }
71
-
72
- function endingFields(project,resolution){
73
- const panel=record(project,'components','salvage.panel'),cta=record(project,'components','salvage.cta');
74
- const winAudio=record(project,'components',resolution.roles?.rewardCue?.componentId);
75
- if(!panel||!cta||!layout(project,'salvage.playfield.layout')||!record(project,'eventBindings','salvage.cta.show'))return [];
76
- const descriptions={};
77
- for(const [cue,description]of Object.entries({catch:'short core collection cue',repair:'short station restoration cue',complete:'current warp completion cue'})){
78
- const assetId=record(project,'components','salvage.audio.'+cue)?.assetSlots[0]?.assetId;
79
- if(assetId&&project.assets.some(asset=>asset.id===assetId&&isAudioMime(asset.mime)))descriptions[assetId]=description;
80
- }
81
- return [
82
- {id:'timeout-caption',label:'Centered text on the timeout end card',value:record(project,'components',timeoutCaptionId)?.parameters?.text??'',...standardText},
83
- ...(winAudio?[{id:'win-cue',label:'Sound played when the third core restores the station',value:winAudio.assetSlots[0]?.assetId,choices:Object.keys(descriptions),descriptions}]:[]),
84
- ];
85
- }
86
- function values(project){
87
- return {
88
- instruction:record(project,'variables','salvage.message')?.initial,
89
- 'hint-delay':record(project,'gameplay','salvage.hand')?.parameters.idleDelaySeconds,
90
- 'reveal-duration':record(project,'gameplay','salvage.station.stage.1.reveal')?.parameters.seconds,
91
- message:message(record(project,'eventBindings','salvage.restore.1'))?.value,
92
- text:record(project,'components','salvage.cta.label')?.parameters.text,
93
- 'payoff-hold':payoff(record(project,'eventBindings','salvage.payoff.finish'))?.value,
94
- };
95
- }
96
- function sharedArtTargets(project){
97
- const targets=[];
98
- for(const [prefix,label]of [['core','Star Core'],['hazard','Meteor']]){
99
- const proto=record(project,'components','salvage.'+prefix+'.image'),assetId=proto?.assetSlots[0]?.assetId;
100
- if(!assetId)continue;
101
- const uses=project.components.filter(item=>item.assetSlots.some(slot=>slot.assetId===assetId));
102
- if(uses.some(item=>item.assetSlots.length!==1||item.assetSlots[0].slotId!=='source'))continue;
103
- const otherAssets=new Set(project.components.filter(item=>item.id.startsWith('salvage.'+(prefix==='core'?'hazard':'core'))).flatMap(item=>item.assetSlots.map(slot=>slot.assetId)));
104
- const imageChoices=project.assets.filter(asset=>asset.mime.startsWith('image/')&&!otherAssets.has(asset.id)).map(asset=>asset.id);
105
- targets.push({id:prefix+'-art',label:label+' artwork',moment:'opening',componentIds:uses.map(item=>item.id),uses:uses.map(item=>item.id),imageChoices,
106
- fields:[{id:'shared-art',label:'Replace all '+uses.length+' uses of this source asset',confirm:true,value:assetId}]});
107
- }
108
- return targets;
109
- }
110
- function reviewTargets(project,resolution){
111
- const current=values(project);
112
- if(!record(project,'gameplay','salvage.rules')||!message(record(project,'eventBindings','salvage.music.start'))||Object.values(current).some(value=>value===undefined)||targetDefinitions.some(target=>target.componentIds.some(id=>!record(project,'components',id))))
113
- return {module:'star-salvage',moments:[],targets:[]};
114
- const targets=targetDefinitions.map(target=>({...target,fields:target.fields.map(([id,label])=>({id,label,value:current[id],...fieldLimits[id]}))}));
115
- const ending=endingFields(project,resolution);
116
- targets.find(target=>target.id==='ending').fields.push(...ending);
117
- if(ending.length)targets.push({id:'timeout-card',label:'Timeout end card',moment:'timeout',componentIds:['salvage.panel',timeoutCaptionId],fields:[
118
- ...ending.filter(field=>field.id!=='win-cue'),
119
- ...(record(project,'components',timeoutCaptionId)?[{id:'caption-alignment',label:'Caption alignment within the panel',choices:['center']}]:[]),
120
- ]});
121
- return {module:'star-salvage',moments,targets:[...targets,...sharedArtTargets(project)],
122
- momentRules:{phaseVariable:'salvage.phase',progressVariable:'salvage.catches',goal:3,progressMoment:'first-catch'}};
123
- }
124
- function reviewOperations(project,targetId,fields,changes,baseline,resolution){
125
- if(!changes||typeof changes!=='object'||Array.isArray(changes))throw Error('E_REVIEW_ARGUMENT');
126
- const keys=Object.keys(changes);
127
- if(!keys.length||keys.some(key=>!fields.includes(key)))throw Error('E_REVIEW_SCOPE');
128
- const operations=[],expected=globalThis.structuredClone(project);
129
- function update(collection,id,kind,key,change){const next=record(expected,collection,id);if(!next)throw Error('E_REVIEW_ROLE_UNRESOLVED');change(next);operations.push({kind,[key]:globalThis.structuredClone(next)});}
130
- const binding=(id,change)=>update('eventBindings',id,'putBinding','binding',change);
131
- for(const field of keys){
132
- const value=changes[field];
133
- if(field==='shared-art'){
134
- const target=sharedArtTargets(baseline).find(item=>item.id===targetId);
135
- if(!target?.imageChoices.includes(value))throw Error('E_REVIEW_ASSET_CHOICE');
136
- for(const id of target.uses){record(expected,'components',id).assetSlots=[{slotId:'source',assetId:value}];operations.push({kind:'replaceAsset',id,assetId:value});}
137
- continue;
138
- }
139
- if(field==='win-cue'){
140
- const cue=endingFields(baseline,resolution).find(item=>item.id===field),id=resolution.roles?.rewardCue?.componentId;
141
- if(!cue?.choices.includes(value))throw Error('E_REVIEW_ASSET_CHOICE');
142
- if(!id)throw Error('E_REVIEW_ROLE_UNRESOLVED');
143
- record(expected,'components',id).assetSlots=[{slotId:'source',assetId:value}];operations.push({kind:'replaceAsset',id,assetId:value});continue;
144
- }
145
- assertValue(field,value);
146
- switch(field){
147
- case 'timeout-caption':{
148
- const existing=record(expected,'components',timeoutCaptionId);
149
- if(existing){existing.parameters.text=value;operations.push({kind:'setParameter',id:timeoutCaptionId,key:'text',value});break;}
150
- const title=record(expected,'components','salvage.reward.title'),panel=record(expected,'components','salvage.panel'),button=record(expected,'components','salvage.cta');
151
- if(!title||!panel||!button)throw Error('E_REVIEW_ROLE_UNRESOLVED');
152
- const group=component({id:timeoutLayoutId,label:'Timeout caption layout',contract:'native.group.v1',parentId:'salvage.playfield.layout',sceneId:title.sceneId,order:title.order});
153
- const caption=component({...title,id:timeoutCaptionId,label:'Timeout caption',parentId:group.id,transform:[1,0,0,1,title.transform[4],(panel.transform[5]+button.transform[5]-title.parameters.height)/2],parameters:{...title.parameters,text:value,visible:false,fontSize:22}});
154
- const show={id:timeoutBindingId,eventId:record(expected,'eventBindings','salvage.cta.show').eventId,condition:{all:[{variableId:'salvage.phase',op:'eq',value:'cta'},{variableId:'salvage.catches',op:'lt',value:3}]},actions:[{kind:'setComponent',componentId:timeoutCaptionId,key:'visible',value:true}]};
155
- expected.components.push(group,caption);expected.eventBindings.push(show);
156
- operations.push({kind:'createComponent',component:group},{kind:'createComponent',component:caption},{kind:'putBinding',binding:show});break;
157
- }
158
- case 'caption-alignment':{
159
- const caption=record(expected,'components',timeoutCaptionId),panel=record(expected,'components','salvage.panel'),button=record(expected,'components','salvage.cta'),title=record(expected,'components','salvage.reward.title'),group=caption&&record(expected,'components',caption.parentId);
160
- if(targetId!=='timeout-card'||!caption||!panel||!button||group?.id!==timeoutLayoutId||caption.parentId!==group.id||group.parentId!=='salvage.playfield.layout'||![caption,panel,group,button].every(item=>item.transform.slice(0,4).join(',')==='1,0,0,1'))throw Error('E_REVIEW_ROLE_UNRESOLVED');
161
- const top=title&&title.transform[5]+title.parameters.height<button.transform[5]?Math.max(panel.transform[5],title.transform[5]+title.parameters.height):panel.transform[5];
162
- const transform=[...caption.transform];transform[4]=panel.transform[4]+(panel.parameters.width-caption.parameters.width)/2-group.transform[4];transform[5]=(top+button.transform[5]-caption.parameters.height)/2-group.transform[5];
163
- if(transform.some((entry,index)=>Math.abs(entry-caption.transform[index])>.001))operations.push({kind:'setTransform',id:caption.id,transform});
164
- if(caption.parameters.align!=='center')operations.push({kind:'setParameter',id:caption.id,key:'align',value:'center'});
165
- caption.transform=transform;caption.parameters.align='center';break;
166
- }
167
- case 'text':{
168
- const label=record(expected,'components',resolution.roles?.primaryCta?.labelId);
169
- if(!label)throw Error('E_REVIEW_ROLE_UNRESOLVED');
170
- label.parameters.text=value;operations.push({kind:'setParameter',id:label.id,key:'text',value});break;
171
- }
172
- case 'instruction':
173
- update('variables','salvage.message','putVariable','variable',entry=>{entry.initial=value;});
174
- binding('salvage.music.start',entry=>{message(entry).value=value;});break;
175
- case 'hint-delay':update('gameplay','salvage.hand','putBehavior','behavior',entry=>{entry.parameters.idleDelaySeconds=value;});break;
176
- case 'reveal-duration':update('gameplay','salvage.station.stage.1.reveal','putBehavior','behavior',entry=>{entry.parameters.seconds=value;});break;
177
- case 'message':binding('salvage.restore.1',entry=>{message(entry).value=value;});break;
178
- case 'payoff-hold':binding('salvage.payoff.finish',entry=>{payoff(entry).value=value;});break;
179
- default:throw Error('E_REVIEW_SCOPE');
180
- }
181
- }
182
- return {operations,expected};
183
- }
184
-
185
- function waveLanes(seed){
186
- let state=seed>>>0;
187
- const random=()=>{state+=0x6d2b79f5;let value=state;value=Math.imul(value^value>>>15,value|1);value^=value+Math.imul(value^value>>>7,value|61);return ((value^value>>>14)>>>0)/4294967296;};
188
- let previous=-1;
189
- return Array.from({length:6},(_,index)=>{
190
- let core=Math.floor(random()*4);if(core===previous)core=(core+1+Math.floor(random()*3))%4;previous=core;
191
- const offset=1+Math.floor(random()*3),hazard=(core+offset)%4;
192
- return {core:lanes[core],hazard:index%2?lanes[hazard]:undefined};
193
- });
194
- }
195
- function compose(concept,studioAssets){
196
- const operations=[],assets=[],assetPolicy=[],plan=concept.salvage,{treatment,receipt:recipe}=salvageRecipe(plan),palette=concept.presentation.palette;
197
- const arc=Object.fromEntries(concept.experience.arc.map(step=>[step.phase,step]));
198
- const add=(id,kind,x,y,width,height,parameters={},extra={})=>operations.push({kind:'createComponent',component:{id,label:id,order:operations.length,contract:'native.'+kind+'.v1',transform:[1,0,0,1,x,y],parameters:{width,height,...parameters},...extra}});
199
- const behavior=(id,componentId,kind,parameters)=>operations.push({kind:'putBehavior',behavior:{id,componentId,kind,parameters}});
200
- const bind=(id,event,actions,condition)=>operations.push({kind:'putBinding',binding:{id,event,actions,...(condition?{condition}:{})}});
201
- const property=(componentId,key,value)=>({kind:'setComponent',componentId,key,value});
202
- const set=(variableId,value)=>({kind:'set',variableId,value});
203
- const is=(variableId,value)=>({variableId,op:'eq',value});
204
- const variable=(id,type,initial)=>operations.push({kind:'putVariable',variable:{id,label:id,type,initial}});
205
- const assetById=new Map(plan.assets.map(asset=>[asset.id,asset]));
206
- check(assetById.size===plan.assets.length,'E_CONCEPT_ASSET_DUPLICATE');
207
- const styleFamily=plan.assets.find(asset=>asset.mime.startsWith('image/'))?.provenance.styleFamily;
208
- for(const source of plan.assets){
209
- let receipt;
210
- if(source.provenance.origin==='studio-original'){
211
- const original=studioAssets?.get(source.id);
212
- check(original&&canonical(original)===canonical(source),'E_ASSET_POLICY_STUDIO_SOURCE');
213
- check(source.provenance.styleFamily===styleFamily||isAudioMime(source.mime),'E_ASSET_POLICY_STYLE');receipt=source.provenance;
214
- }else receipt=validateAssetPolicy(source,{role:isAudioMime(source.mime)?'audio':'visual',styleFamily});
215
- assetPolicy.push({id:source.id,...receipt});
216
- const bytes=Buffer.from(source.data,'base64');check(bytes.length<=700000,'E_CONCEPT_ASSET_SIZE');
217
- const rights=source.rights+(receipt.attribution?'\n'+receipt.attribution:'');check(rights.length<=2048,'E_CONCEPT_ASSET_RIGHTS');
218
- assets.push({id:source.id,mime:source.mime,data:source.data,rights});
219
- operations.push({kind:'registerAsset',asset:{id:source.id,hash:'sha256:'+createHash('sha256').update(bytes).digest('hex'),mime:source.mime,bytes:bytes.length,rights,provenance:JSON.stringify(receipt)}});
220
- }
221
- const imageReference=id=>check(assetById.get(id)?.mime.startsWith('image/'),'E_CONCEPT_VISUAL_REFERENCE');
222
- Object.values(plan.sprites).forEach(imageReference);
223
- const coreVariants=plan.coreVariants??[plan.sprites.core],hazardVariants=plan.hazardVariants??[plan.sprites.hazard];
224
- check(coreVariants[0]===plan.sprites.core&&hazardVariants[0]===plan.sprites.hazard,'E_CONCEPT_VISUAL_REFERENCE');
225
- check(new Set(coreVariants).size===coreVariants.length&&new Set(hazardVariants).size===hazardVariants.length,'E_CONCEPT_VISUAL_REFERENCE');
226
- coreVariants.forEach(imageReference);hazardVariants.forEach(imageReference);
227
- check(plan.bay.length===4&&new Set(plan.bay.map(object=>object.id)).size===4,'E_CONCEPT_BAY_STATE');
228
- for(let stage=0;stage<=3;stage++)check(plan.bay.filter(object=>object.unlockAt===stage).length===1,'E_CONCEPT_BAY_STATE');
229
- for(const object of plan.bay)imageReference(object.assetId);
230
- for(const id of Object.values(plan.audio))check(isAudioMime(assetById.get(id)?.mime),'E_CONCEPT_AUDIO_REFERENCE');
231
- variable('salvage.catches','number',0);variable('salvage.phase','string','first-seconds');variable('salvage.message','string',concept.experience.instruction);
232
- variable('salvage.wave','number',0);variable('salvage.spawn.lock','boolean',false);variable('salvage.payoff','number',0);variable('salvage.hits','number',0);
233
- add('salvage.background','rectangle',0,0,700,700,{fill:palette.background,radius:0});
234
- add('salvage.backdrop','image',0,0,700,700,{fit:'cover'},{assetSlots:[{slotId:'source',assetId:plan.sprites.backdrop}]});
235
- add('salvage.station.layout','group',0,0,390,260);behavior('salvage.station.layout.responsive','salvage.station.layout','responsive-layout',{x:5,y:55,scaleX:.85,scaleY:.85});
236
- add('salvage.brand','text',60,14,186,34,{text:concept.presentation.title,fontSize:24,color:palette.text,align:'center',wrap:false},{parentId:'salvage.station.layout'});
237
- add('salvage.progress','text',254,14,76,34,{text:'{{salvage.catches}} / 3',fontSize:21,color:palette.accent,align:'center',wrap:false},{parentId:'salvage.station.layout'});
238
- const bayPositions=[{x:145,y:96,width:100,height:100},{x:173,y:188,width:44,height:32},{x:126,y:77,width:138,height:138},{x:112,y:63,width:166,height:166}];
239
- for(const object of plan.bay){
240
- const stage=object.unlockAt,stageId='salvage.station.stage.'+stage;
241
- if(!plan.bay.slice(0,plan.bay.indexOf(object)).some(item=>item.unlockAt===stage))add(stageId,'group',195,146,0,0,{visible:stage===0},{parentId:'salvage.station.layout'});
242
- const position=bayPositions[stage];
243
- add('salvage.bay.'+object.id,'image',position.x-195,position.y-146,position.width,position.height,{fit:'contain'},{parentId:stageId,assetSlots:[{slotId:'source',assetId:object.assetId}]});
244
- if(stage===3&&assetById.has('salvage-spark'))add('salvage.bay.beacon','image',-22,-22,44,44,{fit:'contain'},{parentId:stageId,assetSlots:[{slotId:'source',assetId:'salvage-spark'}]});
245
- if(stage)behavior(stageId+'.reveal',stageId,'animation',{property:'scale',from:stage===3?treatment.revealFrom:.82,to:1,seconds:stage===3?treatment.revealSeconds:.42,loop:false,easing:stage===3?treatment.easing:'back-out'});
246
- }
247
- add('salvage.playfield.layout','group',0,0,390,700);behavior('salvage.playfield.layout.responsive','salvage.playfield.layout','responsive-layout',playfieldLayout);
248
- add('salvage.playfield.background','rectangle',1,241,388,398,{fill:'#0d162999',stroke:'#31466d',strokeWidth:1,radius:0},{parentId:'salvage.playfield.layout'});
249
- add('salvage.instruction','text',15,246,360,38,{text:'{{salvage.message}}',fontSize:18,color:palette.text},{parentId:'salvage.playfield.layout'});
250
- add('salvage.rail','rectangle',20,632,350,3,{fill:'#6384b8',radius:0},{parentId:'salvage.playfield.layout'});
251
- add('salvage.ship','group',163,560,64,64,{},{parentId:'salvage.playfield.layout'});
252
- add('salvage.ship.thruster','image',24,49,16,28,{fit:'contain'},{parentId:'salvage.ship',assetSlots:[{slotId:'source',assetId:assetById.has('salvage-thruster')?'salvage-thruster':plan.sprites.ship}]});
253
- add('salvage.ship.image','image',0,0,64,64,{fit:'contain'},{parentId:'salvage.ship',assetSlots:[{slotId:'source',assetId:plan.sprites.ship}]});
254
- add('salvage.ship.shield','image',-6,-6,76,76,{fit:'contain',opacity:0},{parentId:'salvage.ship',assetSlots:[{slotId:'source',assetId:assetById.has('salvage-shield-1')?'salvage-shield-1':plan.sprites.ship}]});
255
- behavior('salvage.rules','salvage.ship','drag',{axis:'x',minX:20,maxX:306});
256
- behavior('salvage.ship.collider','salvage.ship','collider',{shape:'box'});
257
- behavior('salvage.ship.press','salvage.ship','press-feedback',{scaleDown:.94,springBackSeconds:.18,liftShadow:true});
258
- behavior('salvage.shield.flash','salvage.ship.shield','animation',{property:'opacity',from:.85,to:0,seconds:.45,loop:false,easing:'ease-out'});
259
- add('salvage.drag.destination','group',216,560,64,64,{visible:false},{parentId:'salvage.playfield.layout'});
260
- add('salvage.director','group',0,0,0,0);
261
- behavior('salvage.hand','salvage.director','tutorial-hand',{targetId:'salvage.ship',destinationId:'salvage.drag.destination',mode:'drag',idleDelaySeconds:plan.firstHintSeconds??.8,hideOnFirstInput:true});
262
- const prototypes={cores:[],hazards:[]};
263
- for(const [kind,variants]of [['core',coreVariants],['hazard',hazardVariants]])for(const [index,assetId]of variants.entries()){
264
- const id='salvage.'+kind+(index?'.alt.'+index:'');prototypes[kind+'s'].push(id);
265
- add(id,'group',0,0,48,48,{},{prototype:true});
266
- add(id+'.image','image',0,0,48,48,{fit:'contain'},{parentId:id,assetSlots:[{slotId:'source',assetId}]});
267
- behavior(id+'.motion',id,'motion',{vx:0,vy:kind==='core'?165:185,gravity:kind==='core'?28:20});
268
- behavior(id+'.collider',id,'collider',{shape:'circle'});
269
- behavior(id+'.responsive',id,'responsive-layout',playfieldLayout);
270
- behavior(id+'.burst',id,'emitter',{count:kind==='core'?18:14,color:kind==='core'?palette.accent:'#ff796c',speed:kind==='core'?145:110,lifetime:.65,gravity:80});
271
- bind(id+'.exit',{kind:'boundaryExit',componentId:id},[{kind:'despawn'}]);
272
- }
273
- const clearPlayfield=[...prototypes.cores,...prototypes.hazards].map(id=>property(id,'visible',false));
274
- behavior('salvage.spawn.timer','salvage.director','timer',{seconds:.95,repeat:true});
275
- const active={all:[{variableId:'salvage.phase',op:'ne',value:'payoff'},{variableId:'salvage.phase',op:'ne',value:'cta'}]};
276
- const waves=waveLanes(plan.seed);
277
- waves.forEach((wave,index)=>{
278
- const actions=[{kind:'spawn',prototypeId:prototypes.cores[index%prototypes.cores.length],x:wave.core,y:240}];
279
- if(wave.hazard!==undefined)actions.push({kind:'spawn',prototypeId:prototypes.hazards[index%prototypes.hazards.length],x:wave.hazard,y:220});
280
- actions.push(index===waves.length-1?set('salvage.wave',0):{kind:'add',variableId:'salvage.wave',value:1},set('salvage.spawn.lock',true));
281
- bind('salvage.wave.'+index,{kind:'timer',behaviorId:'salvage.spawn.timer'},actions,{all:[is('salvage.wave',index),is('salvage.spawn.lock',false),...active.all]});
282
- });
283
- for(const [cue,assetId]of Object.entries(plan.audio)){
284
- const target='salvage.audio.'+cue;add(target,'group',0,0,0,0,{},{assetSlots:[{slotId:'source',assetId}]});
285
- const role={complete:'win',loss:'loss',reject:'reject',ambient:'ambient'}[cue];
286
- behavior(target+'.play',target,'audio',{loop:cue==='ambient',volume:{ambient:.08,catch:.22,repair:.28,complete:treatment.gain,loss:.32,reject:.12}[cue],frequency:660,seconds:.2,bus:cue==='ambient'?'music':['complete','loss'].includes(cue)?'stinger':'sfx',...(cue==='catch'?{pitchVariableId:'salvage.catches',pitchStep:1.5}:{}),...(role?{role}:{})});
287
- }
288
- const sound=cue=>({kind:'playAudio',behaviorId:'salvage.audio.'+cue+'.play'});
289
- bind('salvage.music.start',{kind:'click',componentId:'salvage.ship'},[sound('ambient'),set('salvage.message',concept.experience.instruction),property('salvage.instruction','visible',false)],active);
290
- for(const id of prototypes.cores)bind(id+'.catch',{kind:'contactBegin',componentId:id,otherId:'salvage.ship'},[
291
- {kind:'add',variableId:'salvage.catches',value:1},property('salvage.instruction','visible',false),sound('catch'),{kind:'emit',behaviorId:id+'.burst'},
292
- {kind:'floatingText',text:'+1',componentId:id,color:palette.accent,fontSize:22,risePx:36,seconds:.7},{kind:'despawn'},
293
- ],{all:[{variableId:'salvage.catches',op:'lt',value:3},...active.all]});
294
- for(const id of prototypes.hazards)bind(id+'.hit',{kind:'contactBegin',componentId:id,otherId:'salvage.ship'},[
295
- {kind:'add',variableId:'salvage.hits',value:1},set('salvage.message','Dodge meteors!'),sound('reject'),
296
- property('salvage.ship.shield','opacity',.85),{kind:'animate',behaviorId:'salvage.shield.flash'},
297
- {kind:'emit',behaviorId:id+'.burst'},{kind:'floatingText',text:'HIT!',componentId:id,color:'#ff9b91',fontSize:22,risePx:32,seconds:.7},
298
- {kind:'cameraShake',intensity:4,seconds:.18},{kind:'screenFlash',color:'#ff394f',opacity:.2,seconds:.2},{kind:'despawn'},
299
- ],active);
300
- const milestones=['Thrusters online!','Shield online!',concept.presentation.rewardCopy];
301
- for(const stage of [1,2,3]){
302
- const station='salvage.station.stage.'+stage,actions=[
303
- property(station,'visible',true),{kind:'animate',behaviorId:station+'.reveal'},set('salvage.message',milestones[stage-1]),property('salvage.instruction','visible',false),
304
- set('salvage.phase',stage===3?'payoff':stage===1?'agency':'escalation'),sound(stage===3?'complete':plan.audio.repair?'repair':'catch'),
305
- ...(stage===3?[]:[{kind:'floatingText',text:'+1 PART',componentId:station,color:palette.accent,fontSize:20,risePx:34,seconds:.8}]),
306
- {kind:'cameraShake',intensity:stage===3?treatment.shakeIntensity:3,seconds:stage===3?.25:.12},
307
- ];
308
- if(stage===3)actions.push(property('salvage.ship','visible',false),property('salvage.rail','visible',false),...clearPlayfield,property('salvage.panel','visible',true),property('salvage.reward.title','visible',true),property('salvage.reward.caption','visible',true),{kind:'emit',behaviorId:'salvage.celebration'},{kind:'screenFlash',color:palette.accent,opacity:.18,seconds:.22});
309
- bind('salvage.restore.'+stage,{kind:'variableChange',variableId:'salvage.catches'},actions,{all:[is('salvage.catches',stage),{variableId:'salvage.phase',op:'ne',value:'cta'}]});
310
- }
311
- behavior('salvage.celebration','salvage.station.stage.3','emitter',{shape:'confetti',coverage:'screen',count:Math.min(128,treatment.particles*2),color:palette.accent,color2:'#4ecdc4',color3:'#fff3b0',speed:treatment.speed,lifetime:treatment.lifetime+.6,gravity:65,spread:360});
312
- add('salvage.panel','rectangle',35,310,320,280,{visible:false,fill:'#1b2b4bf5',stroke:palette.accent,strokeWidth:3,radius:22},{parentId:'salvage.playfield.layout'});
313
- add('salvage.reward.title','text',55,354,280,48,{visible:false,text:'WARP READY!',fontSize:30,color:palette.accent},{parentId:'salvage.playfield.layout'});
314
- add('salvage.reward.caption','text',55,410,280,36,{visible:false,text:concept.presentation.rewardCopy,fontSize:19,color:palette.text},{parentId:'salvage.playfield.layout'});
315
- add(timeoutLayoutId,'group',0,0,0,0,{},{parentId:'salvage.playfield.layout'});
316
- add(timeoutCaptionId,'text',55,410,280,42,{visible:false,text:'Catch 3 to launch',fontSize:21,color:palette.text},{parentId:timeoutLayoutId});
317
- add('salvage.cta','button',65,482,260,68,{visible:false,presentation:'shiny-cta',fill:palette.accent,hoverFill:'#ffe29a',pressedFill:'#e5a93c',stroke:'#0e2830',strokeWidth:3,radius:16},{parentId:'salvage.playfield.layout'});
318
- add('salvage.cta.label','text',8,0,244,68,{text:concept.experience.ctaLabel,fontSize:22,color:palette.background},{parentId:'salvage.cta'});
319
- behavior('salvage.cta.pulse','salvage.cta','animation',{property:'y',from:479,to:485,seconds:.95,loop:true,easing:'ease-in-out'});
320
- bind('salvage.cta.click',{kind:'click',componentId:'salvage.cta'},[{kind:'store'}],is('salvage.phase','cta'));
321
- bind('salvage.cta.show',{kind:'variableChange',variableId:'salvage.phase'},[property('salvage.instruction','visible',false),property('salvage.rail','visible',false),property('salvage.cta','visible',true),{kind:'animate',behaviorId:'salvage.cta.pulse'}],is('salvage.phase','cta'));
322
- behavior('salvage.clock','salvage.director','timer',{seconds:.1,repeat:true});
323
- bind('salvage.spawn.unlock',{kind:'timer',behaviorId:'salvage.clock'},[set('salvage.spawn.lock',false)]);
324
- bind('salvage.payoff.tick',{kind:'timer',behaviorId:'salvage.clock'},[{kind:'add',variableId:'salvage.payoff',value:.1}],is('salvage.phase','payoff'));
325
- bind('salvage.payoff.finish',{kind:'variableChange',variableId:'salvage.payoff'},[set('salvage.message',arc.cta.description),set('salvage.phase','cta')],{all:[is('salvage.phase','payoff'),{variableId:'salvage.payoff',op:'gte',value:arc.payoff.seconds}]});
326
- behavior('salvage.deadline','salvage.director','timer',{seconds:arc['first-seconds'].seconds+arc.agency.seconds+arc.escalation.seconds,repeat:false});
327
- bind('salvage.deadline.cta',{kind:'timer',behaviorId:'salvage.deadline'},[
328
- set('salvage.message','Time is up'),property('salvage.instruction','visible',false),property('salvage.ship','visible',false),property('salvage.rail','visible',false),...clearPlayfield,property('salvage.panel','visible',true),property('salvage.reward.title','text','TIME IS UP!'),property('salvage.reward.title','visible',true),
329
- property('salvage.reward.caption','visible',false),property(timeoutCaptionId,'visible',true),
330
- ...(plan.audio.loss?[sound('loss')]:[]),set('salvage.phase','cta'),
331
- ],{all:[{variableId:'salvage.phase',op:'ne',value:'payoff'},{variableId:'salvage.phase',op:'ne',value:'cta'}]});
332
- operations.push({kind:'setStore',url:concept.product.storeUrl});
333
- check(operations.length<=256,'E_CONCEPT_OPERATION_LIMIT');
334
- const effects={'catch-rule':['salvage.ship','salvage.rules','salvage.core.catch'],'world-transformation':['salvage.restore.1','salvage.restore.2','salvage.restore.3'],recovery:['salvage.hazard.hit','salvage.hand'],continuity:['salvage.cta','salvage.cta.click']};
335
- return {operations,assets,assetPolicy,recipe,requirements:concept.requirements.map(requirement=>({...requirement,records:effects[requirement.effect]}))};
336
- }
337
-
338
1
  async function prepareTimeout(page){
339
2
  const points=await page.evaluate(()=>{
340
3
  const state=globalThis.toraRuntime?.state?.(),canvas=globalThis.document.querySelector('canvas'),embedded=globalThis.document.getElementById('project');
@@ -392,36 +55,8 @@ async function playToEndCard(page,project){
392
55
  return {available:phase==='cta',mode:'real-play'};
393
56
  }
394
57
 
395
- export const starSalvageModule=Object.freeze({
396
- id:'star-salvage',version:1,supportsIntake:true,outcomeAssetId:'salvage.audio.victory.source',supportsLandscapeReview:true,outcomeKind:'salvage-outcome-audio',
397
- outcomeAudio:async()=>{const module=await import('../check-salvage.mjs');return {exercise:module.exerciseSalvageOutcomeAudio,checkerVersion:module.SALVAGE_OUTCOME_CHECKER_VERSION};},
398
- matches:index=>Boolean(index.behavior('salvage.rules')),
399
- resolveRoles:resolveSalvageRoles,reviewTargets,reviewOperations,compose,
400
- canTransferOutcomeCue:(index,resolution)=>resolution.status==='resolved'&&resolution.roles.timeoutEvent.cue?.unresolved==='missing-cue'&&!index.asset('salvage.audio.victory.source'),
401
- timingFields:()=>({
402
- 'hint-delay':{target:'opening',targets:['opening'],moment:'opening',label:'opening hint delay'},
403
- 'reveal-duration':{target:'first-catch',targets:['first-catch'],moment:'first-catch',label:'reveal duration'},
404
- 'payoff-hold':{target:'ending',targets:['ending','cta'],moment:'end-card',label:'payoff hold'},
405
- }),
406
- intake:{
407
- validateMedia(assets,concept){
408
- const images=new Set(assets.filter(asset=>asset.mime.startsWith('image/')).map(asset=>asset.hash));
409
- if(images.size<4||!assets.some(asset=>isAudioMime(asset.mime)))throw Error('E_INTAKE_SALVAGE_MEDIA');
410
- if(concept){
411
- const sprites=Object.values(concept.salvage.sprites).map(id=>assets.find(asset=>asset.id===id));
412
- if(sprites.length!==4||sprites.some(asset=>!asset?.mime.startsWith('image/'))||new Set(sprites.map(asset=>asset.hash)).size!==4)throw Error('E_INTAKE_SALVAGE_MEDIA');
413
- }
414
- },
415
- validateConcept(concept){
416
- const audio=concept?.salvage?.audio,keys=Object.keys(concept?.salvage??{}).sort();
417
- const allowed=['assets','audio','bay','coreVariants','firstHintSeconds','hazardVariants','rewardRecipe','seed','sprites'];
418
- if(concept?.experience?.mechanic!=='star-salvage'||!concept.salvage||keys.some(key=>!allowed.includes(key)||key==='assets')||
419
- !['audio','bay','seed','sprites'].every(key=>keys.includes(key))||JSON.stringify(Object.keys(concept.salvage.sprites??{}).sort())!==JSON.stringify(['backdrop','core','hazard','ship'])||
420
- !Array.isArray(concept.salvage.bay)||concept.salvage.bay.length!==4||!audio||!['ambient','catch','complete','reject'].every(key=>typeof audio[key]==='string')||
421
- Object.keys(audio).some(key=>!['ambient','catch','complete','loss','reject','repair'].includes(key)))throw Error('E_INTAKE_ARGUMENT');
422
- return [...Object.values(concept.salvage.sprites),...(concept.salvage.coreVariants??[]),...(concept.salvage.hazardVariants??[]),...Object.values(audio),...concept.salvage.bay.map(object=>object?.assetId)];
423
- },
424
- hydrateConcept(concept,assets){return {...concept,salvage:{...concept.salvage,assets}};},
425
- },
58
+
59
+ export const salvageQaAdapter=Object.freeze({
60
+ id:'star-salvage',matches:index=>Boolean(index.behavior('salvage.rules')),
426
61
  qa:{phaseVariable:'salvage.phase',progressVariable:'salvage.catches',goalValue:3,deadlineBehaviorId:'salvage.deadline',playToEndCard,prepareTimeout,validateTimeout},
427
62
  });
@@ -1,10 +1,11 @@
1
1
  import {validateDocument,check,exact,identifier} from './document.mjs';
2
2
  import {validateGlbHeader,validateMp3,validateToraMesh} from './media-validate.mjs';
3
+ import {assertVariantStore} from './variants-core.mjs';
3
4
  export const BUNDLE_LIMIT=64*1024*1024;
4
5
  export async function hash(value){const bytes=typeof value==='string'?new globalThis.TextEncoder().encode(value):value;return 'sha256:'+Array.from(new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256',bytes)),b=>b.toString(16).padStart(2,'0')).join('');}
5
6
  async function browserDecodeImage(bytes,mime){check(typeof globalThis.createImageBitmap==='function','Image decoder required');const image=await globalThis.createImageBitmap(new globalThis.Blob([bytes],{type:mime}));try{check(image.width>0&&image.height>0&&image.width<=4096&&image.height<=4096,'Image dimensions exceed 4096 pixels');}finally{image.close();}}
6
- export function projectBundle(project,assets){validateDocument(project);const data={};for(const asset of project.assets){check(typeof assets[asset.hash]==='string','Missing project asset');data[asset.hash]=assets[asset.hash];}const text=JSON.stringify({format:'tora-project-bundle',version:1,project,assets:data});check(new globalThis.TextEncoder().encode(text).length<=BUNDLE_LIMIT,'Project file exceeds 64 MiB');return text;}
7
- export async function readProjectBundle(text,options={}){check(typeof text==='string'&&new globalThis.TextEncoder().encode(text).length<=BUNDLE_LIMIT,'Project file exceeds 64 MiB');let bundle;try{bundle=JSON.parse(text);}catch{throw Error('Invalid project JSON');}check(exact(bundle,['format','version','project','assets'])&&bundle.format==='tora-project-bundle'&&bundle.version===1,'Unsupported project bundle');const project=validateDocument(globalThis.structuredClone(bundle.project));check(/^[a-z][a-z0-9-]{1,47}$/.test(project.projectId)&&project.projectId!=='compose','Invalid project ID');check(bundle.assets&&typeof bundle.assets==='object'&&!Array.isArray(bundle.assets),'Missing project assets');const expected=new Set(project.assets.map(a=>a.hash));check(Object.keys(bundle.assets).length===expected.size&&Object.keys(bundle.assets).every(key=>expected.has(key)),'Unexpected project assets');for(const asset of project.assets){const result=await validateAssetData({id:asset.id,mime:asset.mime,rights:asset.rights,data:bundle.assets[asset.hash]},options);check(result.hash===asset.hash&&result.bytes===asset.bytes,'Asset hash or byte count mismatch');}project.revisionId='initial';return {project,assets:globalThis.structuredClone(bundle.assets)};}
7
+ export function projectBundle(project,assets,variants){validateDocument(project);if(variants?.variants?.length)assertVariantStore(variants,project);const data={};for(const asset of project.assets){check(typeof assets[asset.hash]==='string','Missing project asset');data[asset.hash]=assets[asset.hash];}const text=JSON.stringify({format:'tora-project-bundle',version:variants?.variants?.length?2:1,project,assets:data,...(variants?.variants?.length?{variants}:{})});check(new globalThis.TextEncoder().encode(text).length<=BUNDLE_LIMIT,'Project file exceeds 64 MiB');return text;}
8
+ export async function readProjectBundle(text,options={}){check(typeof text==='string'&&new globalThis.TextEncoder().encode(text).length<=BUNDLE_LIMIT,'Project file exceeds 64 MiB');let bundle;try{bundle=JSON.parse(text);}catch{throw Error('Invalid project JSON');}check(exact(bundle,['format','version','project','assets','variants'])&&bundle.format==='tora-project-bundle'&&(bundle.version===1&&!Object.hasOwn(bundle,'variants')||bundle.version===2&&Object.hasOwn(bundle,'variants')),'Unsupported project bundle');const project=validateDocument(globalThis.structuredClone(bundle.project));if(bundle.version===2)assertVariantStore(bundle.variants,project);check(/^[a-z][a-z0-9-]{1,47}$/.test(project.projectId)&&project.projectId!=='compose','Invalid project ID');check(bundle.assets&&typeof bundle.assets==='object'&&!Array.isArray(bundle.assets),'Missing project assets');const expected=new Set(project.assets.map(a=>a.hash));check(Object.keys(bundle.assets).length===expected.size&&Object.keys(bundle.assets).every(key=>expected.has(key)),'Unexpected project assets');for(const asset of project.assets){const result=await validateAssetData({id:asset.id,mime:asset.mime,rights:asset.rights,data:bundle.assets[asset.hash]},options);check(result.hash===asset.hash&&result.bytes===asset.bytes,'Asset hash or byte count mismatch');}project.revisionId='initial';return {project,assets:globalThis.structuredClone(bundle.assets),...(bundle.version===2?{variants:globalThis.structuredClone(bundle.variants)}:{})};}
8
9
  export async function validateAssetData(input,{decodeImage=browserDecodeImage}={}){check(exact(input,['id','mime','data','rights'])&&identifier(input.id)&&typeof input.rights==='string'&&input.rights.trim()&&input.rights.length<=2048,'Describe the asset rights');check(typeof input.data==='string'&&input.data.length<=933336&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input.data),'Invalid asset encoding');const bytes=Uint8Array.from(globalThis.atob(input.data),c=>c.charCodeAt(0));check(bytes.length>0&&bytes.length<=700000,'Asset exceeds 700,000 bytes');check(['image/png','image/jpeg','audio/wav','audio/mpeg','model/tora-mesh','model/gltf-binary'].includes(input.mime),'Use PNG, JPEG, PCM WAV, MP3, Tora 3D mesh or glTF binary');
9
10
  if(input.mime==='audio/wav'){validateWav(bytes);}else if(input.mime==='audio/mpeg'){validateMp3(bytes,'Invalid MP3 audio');}else if(input.mime==='model/tora-mesh'){validateToraMesh(bytes,'Invalid Tora 3D mesh');}else if(input.mime==='model/gltf-binary'){validateGlbHeader(bytes,'Invalid glTF 2.0 binary model');}else{check(input.mime==='image/png'?bytes.slice(0,8).join(',')==='137,80,78,71,13,10,26,10':bytes[0]===255&&bytes[1]===216&&bytes[2]===255,'Asset type does not match its contents');await decodeImage(bytes,input.mime);}
10
11
  return {...input,hash:await hash(bytes),bytes:bytes.length,provenance:'Uploaded in the browser editor; content hash and browser media validation.'};
@@ -62,5 +62,3 @@ export class ProjectIndexCache{
62
62
  return this.#indexes.get(key);
63
63
  }
64
64
  }
65
-
66
- export {resolveHarvestRoles,resolveProjectRoles} from './modules/index.mjs';
@@ -0,0 +1,10 @@
1
+ import {createProjectIndex} from './project-index.mjs';
2
+ import {harvestQaAdapter} from './modules/harvest-restore.mjs';
3
+ import {salvageQaAdapter} from './modules/star-salvage.mjs';
4
+ import {sortPuzzleCompatibility} from './modules/sort-puzzle.mjs';
5
+
6
+ export const qaAdapters=Object.freeze([harvestQaAdapter,salvageQaAdapter,sortPuzzleCompatibility]);
7
+ export function qaAdapterForProject(project){
8
+ const index=createProjectIndex(project);
9
+ return qaAdapters.find(adapter=>adapter.matches(index))??null;
10
+ }