@lumesync/studio 0.0.0-stage → 1.0.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.
@@ -0,0 +1,671 @@
1
+ // 操作解释器:把结构化编辑计划映射到临时课件副本。
2
+ // 事务失败时整份副本丢弃,正式目录不受影响。
3
+
4
+ import { ERROR_CODES, StudioError } from '../core/errors.js';
5
+ import { applyAnswerMaterial, deriveAnswer, normalizeInteractionInput } from '../core/document.js';
6
+ import { sha256Hex } from '../core/storage.js';
7
+ import {
8
+ answerMaterialIssues, answerShapeIssues, interactionInputIssues, interactionIssues, isObjective, normalizePolicy,
9
+ PHASE_VALUES, LAYOUT_VALUES, RUN_MODE_VALUES, BLOOM_VALUES, SUBJECT_VALUES,
10
+ COMPONENT_VALUES, COLLECT_VALUES, INTERACTION_KIND_VALUES, defaultPolicy,
11
+ } from '../core/model.js';
12
+ import {
13
+ isSceneId, isComponentCid, isInteractionId, isSafeRelative, isPackageId, isGrade, isSemver, charLen,
14
+ ASPECT_RATIOS, htmlSafetyIssues,
15
+ } from '../core/rules.js';
16
+
17
+ export const OPERATION_TYPES = [
18
+ 'courseware.patch',
19
+ 'scene.create',
20
+ 'scene.patch',
21
+ 'scene.move',
22
+ 'scene.remove',
23
+ 'component.upsert',
24
+ 'component.remove',
25
+ 'interaction.upsert',
26
+ 'interaction.remove',
27
+ 'asset.put',
28
+ 'asset.remove',
29
+ ];
30
+
31
+ function invalid(message, details) {
32
+ return new StudioError(ERROR_CODES.OPERATION_INVALID, message, details, 400);
33
+ }
34
+
35
+ // 临时工作区:内存中的 manifest + 场景文本 + 题目正文 + 资源。
36
+ export class DraftWorkspace {
37
+ constructor(document) {
38
+ this.manifest = document.manifest ? structuredClone(document.manifest) : null;
39
+ // 旧课件的 steps 字段仅做兼容读取,任何一次提交都会把它从清单中移除。
40
+ for (const scene of this.manifest?.scenes ?? []) delete scene.steps;
41
+ this.sceneTexts = { ...document.sceneTexts };
42
+ this.interactions = new Map();
43
+ for (const record of document.interactions) {
44
+ if (record.body) this.interactions.set(record.entry.id, structuredClone(record.body));
45
+ }
46
+ this.assets = new Map();
47
+ this.filesToDelete = [];
48
+ }
49
+
50
+ scene(sceneId) {
51
+ return (this.manifest.scenes ?? []).find((scene) => scene.id === sceneId) ?? null;
52
+ }
53
+
54
+ nextSceneId() {
55
+ const ids = (this.manifest.scenes ?? []).map((scene) => Number(scene.id.slice(1))).filter(Number.isFinite);
56
+ const next = ids.length === 0 ? 1 : Math.max(...ids) + 1;
57
+ if (next > 999) throw invalid('场景数量已达上限');
58
+ return `s${next}`;
59
+ }
60
+
61
+ nextObjectiveId() {
62
+ const ids = (this.manifest.objectives ?? []).map((objective) => Number(objective.id.slice(1))).filter(Number.isFinite);
63
+ const next = ids.length === 0 ? 1 : Math.max(...ids) + 1;
64
+ if (next > 99) throw invalid('教学目标数量已达上限');
65
+ return `o${next}`;
66
+ }
67
+
68
+ ensureSceneFileUnique(file) {
69
+ if ((this.manifest.scenes ?? []).some((scene) => scene.file === file)) {
70
+ throw invalid(`场景文件已被占用:${file}`, { file });
71
+ }
72
+ }
73
+ }
74
+
75
+ export function applyOperation(workspace, operation, context = {}) {
76
+ if (!operation || typeof operation !== 'object' || typeof operation.op !== 'string') {
77
+ throw invalid('操作必须包含 op 字段');
78
+ }
79
+ if (!OPERATION_TYPES.includes(operation.op)) {
80
+ throw new StudioError(ERROR_CODES.TOOL_UNKNOWN, `不支持的操作:${operation.op}`, { op: operation.op }, 400);
81
+ }
82
+ switch (operation.op) {
83
+ case 'courseware.patch':
84
+ return applyCoursewarePatch(workspace, operation);
85
+ case 'scene.create':
86
+ return applySceneCreate(workspace, operation, context);
87
+ case 'scene.patch':
88
+ return applyScenePatch(workspace, operation);
89
+ case 'scene.move':
90
+ return applySceneMove(workspace, operation);
91
+ case 'scene.remove':
92
+ return applySceneRemove(workspace, operation);
93
+ case 'component.upsert':
94
+ return applyComponentUpsert(workspace, operation);
95
+ case 'component.remove':
96
+ return applyComponentRemove(workspace, operation);
97
+ case 'interaction.upsert':
98
+ return applyInteractionUpsert(workspace, operation);
99
+ case 'interaction.remove':
100
+ return applyInteractionRemove(workspace, operation);
101
+ case 'asset.put':
102
+ return applyAssetPut(workspace, operation);
103
+ case 'asset.remove':
104
+ return applyAssetRemove(workspace, operation);
105
+ default:
106
+ throw invalid(`不支持的操作:${operation.op}`);
107
+ }
108
+ }
109
+
110
+ function applyCoursewarePatch(workspace, operation) {
111
+ const manifest = workspace.manifest;
112
+ const set = operation.set ?? {};
113
+ const appendObjectives = operation.appendObjectives;
114
+ const allowedKeys = ['id', 'title', 'subject', 'grade', 'durationMin', 'version', 'authors', 'tags', 'prerequisites', 'theme', 'compliance', 'ai', 'locale', 'source', 'aspectRatio'];
115
+ for (const key of Object.keys(set)) {
116
+ if (!allowedKeys.includes(key)) throw invalid(`courseware.patch 不允许修改 ${key}`, { key });
117
+ }
118
+ if (set.id !== undefined) {
119
+ if (!isPackageId(set.id)) throw invalid('课件 id 必须是 6-96 位小写字母/数字的点分层级');
120
+ manifest.id = set.id;
121
+ }
122
+ if (set.title !== undefined) {
123
+ if (charLen(set.title) < 2 || charLen(set.title) > 60) throw invalid('标题长度必须是 2-60 个字符');
124
+ manifest.title = set.title;
125
+ }
126
+ if (set.subject !== undefined) {
127
+ if (!SUBJECT_VALUES.includes(set.subject)) throw invalid(`学科必须是 ${SUBJECT_VALUES.join(' / ')}`);
128
+ manifest.subject = set.subject;
129
+ }
130
+ if (set.grade !== undefined) {
131
+ if (!isGrade(set.grade)) throw invalid('年级格式不合法,示例:七年级 / 小学四年级 / 高二');
132
+ manifest.grade = set.grade;
133
+ }
134
+ if (set.durationMin !== undefined) {
135
+ if (!Number.isInteger(set.durationMin) || set.durationMin < 10 || set.durationMin > 90) throw invalid('课时长度必须是 10-90 分钟');
136
+ manifest.durationMin = set.durationMin;
137
+ }
138
+ if (set.version !== undefined) {
139
+ if (!isSemver(set.version)) throw invalid('version 必须是 x.y.z 形式');
140
+ manifest.version = set.version;
141
+ }
142
+ if (set.locale !== undefined) {
143
+ if (typeof set.locale !== 'string' || set.locale.trim() === '') throw invalid('locale 必须是非空字符串');
144
+ manifest.locale = set.locale;
145
+ }
146
+ if (set.aspectRatio !== undefined) {
147
+ if (!ASPECT_RATIOS.includes(set.aspectRatio)) {
148
+ throw invalid(`不支持的比例 ${set.aspectRatio},可用:${ASPECT_RATIOS.join(' / ')}`, { available: ASPECT_RATIOS });
149
+ }
150
+ manifest.aspectRatio = set.aspectRatio;
151
+ }
152
+ for (const [key, max] of [['authors', 10], ['tags', 12], ['prerequisites', 5]]) {
153
+ if (set[key] === undefined) continue;
154
+ if (!Array.isArray(set[key]) || set[key].some((item) => typeof item !== 'string')) {
155
+ throw invalid(`${key} 必须是字符串数组`);
156
+ }
157
+ manifest[key] = set[key].slice(0, max);
158
+ }
159
+ for (const key of ['theme', 'compliance', 'ai', 'source']) {
160
+ if (set[key] !== undefined && (!set[key] || typeof set[key] !== 'object' || Array.isArray(set[key]))) {
161
+ throw invalid(`${key} 必须是对象`);
162
+ }
163
+ if (set[key] !== undefined) manifest[key] = set[key];
164
+ }
165
+ if (appendObjectives !== undefined) {
166
+ if (!Array.isArray(appendObjectives)) throw invalid('appendObjectives 必须是数组');
167
+ manifest.objectives = [...(manifest.objectives ?? []), ...appendObjectives.map((objective) => normalizeObjective(objective, workspace))];
168
+ if (manifest.objectives.length > 8) throw invalid('教学目标数量必须是 1-8 条');
169
+ }
170
+ if (operation.setObjectives !== undefined) {
171
+ if (!Array.isArray(operation.setObjectives) || operation.setObjectives.length < 1 || operation.setObjectives.length > 8) {
172
+ throw invalid('教学目标数量必须是 1-8 条');
173
+ }
174
+ manifest.objectives = operation.setObjectives.map((objective) => normalizeObjective(objective, workspace));
175
+ }
176
+ if (operation.removeObjectives !== undefined) {
177
+ const remove = new Set(operation.removeObjectives);
178
+ manifest.objectives = (manifest.objectives ?? []).filter((objective) => !remove.has(objective.id));
179
+ if ((manifest.objectives ?? []).length === 0) throw invalid('至少需要保留 1 条教学目标');
180
+ }
181
+ return { kind: 'courseware', parts: Object.keys(set).concat(appendObjectives ? ['objectives'] : []) };
182
+ }
183
+
184
+ function normalizeObjective(objective, workspace) {
185
+ if (!objective || typeof objective !== 'object') throw invalid('目标必须是对象');
186
+ const id = objective.id ?? workspace.nextObjectiveId();
187
+ const text = String(objective.text ?? '').trim();
188
+ if (charLen(text) < 4 || charLen(text) > 80) throw invalid('目标描述长度必须是 4-80 个字符');
189
+ if (!BLOOM_VALUES.includes(objective.bloom)) throw invalid(`bloom 必须是 ${BLOOM_VALUES.join(' / ')}`);
190
+ return { id, text, bloom: objective.bloom };
191
+ }
192
+
193
+ function sceneMetadataFrom(input, defaults) {
194
+ const scene = {
195
+ id: input.id,
196
+ file: input.file,
197
+ title: input.title ?? defaults.title,
198
+ phase: input.phase ?? defaults.phase,
199
+ minutes: input.minutes ?? defaults.minutes,
200
+ layout: input.layout ?? defaults.layout,
201
+ components: input.components ?? defaults.components ?? [],
202
+ notes: input.notes ?? defaults.notes ?? '',
203
+ hidden: input.hidden ?? defaults.hidden ?? false,
204
+ };
205
+ if (input.modes !== undefined) scene.modes = input.modes;
206
+ return scene;
207
+ }
208
+
209
+ function validateSceneMetadata(scene) {
210
+ if (!isSceneId(scene.id)) throw invalid('场景 id 必须形如 s1 / s12 / s123', { sceneId: scene.id });
211
+ if (!PHASE_VALUES.includes(scene.phase)) throw invalid(`教学阶段必须是 ${PHASE_VALUES.join(' / ')}`, { sceneId: scene.id });
212
+ if (typeof scene.minutes !== 'number' || !Number.isFinite(scene.minutes) || scene.minutes < 0.5 || scene.minutes > 30) {
213
+ throw invalid('场景时长必须是 0.5-30 分钟', { sceneId: scene.id });
214
+ }
215
+ if (scene.layout !== undefined && !LAYOUT_VALUES.includes(scene.layout)) throw invalid(`layout 必须是 ${LAYOUT_VALUES.join(' / ')}`, { sceneId: scene.id });
216
+ if (scene.title !== undefined && typeof scene.title !== 'string') throw invalid('场景标题必须是字符串', { sceneId: scene.id });
217
+ if (scene.title !== undefined && charLen(scene.title) > 40) throw invalid('场景标题不能超过 40 个字符', { sceneId: scene.id });
218
+ if (scene.notes !== undefined && typeof scene.notes !== 'string') throw invalid('教师讲稿必须是字符串', { sceneId: scene.id });
219
+ if (scene.hidden !== undefined && typeof scene.hidden !== 'boolean') throw invalid('hidden 必须是布尔值', { sceneId: scene.id });
220
+ if (scene.modes !== undefined) {
221
+ if (!Array.isArray(scene.modes) || scene.modes.length === 0) throw invalid('modes 至少声明一个运行态', { sceneId: scene.id });
222
+ for (const mode of scene.modes) {
223
+ if (!RUN_MODE_VALUES.includes(mode)) throw invalid(`未知运行态 ${mode}`, { sceneId: scene.id });
224
+ }
225
+ }
226
+ }
227
+
228
+ function applySceneCreate(workspace, operation, context = {}) {
229
+ const manifest = workspace.manifest;
230
+ const sceneId = operation.sceneId ?? workspace.nextSceneId();
231
+ if ((manifest.scenes ?? []).some((scene) => scene.id === sceneId)) throw invalid(`场景 id 已存在:${sceneId}`, { sceneId });
232
+ const file = operation.file ?? `scenes/${String((manifest.scenes ?? []).length + 1).padStart(2, '0')}-${sceneId}.html`;
233
+ if (!file.startsWith('scenes/') || !/^scenes\/[a-z0-9\-_]+\.(html|md)$/.test(file)) {
234
+ throw invalid('场景文件必须位于 scenes/ 且以 .html 或 .md 结尾', { file });
235
+ }
236
+ workspace.ensureSceneFileUnique(file);
237
+ const scene = sceneMetadataFrom({
238
+ id: sceneId,
239
+ file,
240
+ title: operation.title ?? sceneId,
241
+ phase: operation.phase ?? 'explain',
242
+ minutes: operation.minutes ?? 5,
243
+ layout: operation.layout ?? 'full',
244
+ components: normalizeComponents(operation.components ?? []),
245
+ notes: operation.notes ?? '',
246
+ hidden: operation.hidden ?? false,
247
+ modes: operation.modes,
248
+ });
249
+ validateSceneMetadata(scene);
250
+ const html = operation.html ?? renderSceneTemplate(scene, operation.content ?? null);
251
+ if (operation.html !== undefined) {
252
+ const safety = htmlSafetyIssues(String(html));
253
+ if (safety.length > 0) throw invalid(safety.join(';'), { sceneId, issues: safety });
254
+ }
255
+ workspace.sceneTexts[file] = html;
256
+ const index = operation.position === undefined ? manifest.scenes.length : clampIndex(operation.position, manifest.scenes.length);
257
+ manifest.scenes.splice(index, 0, scene);
258
+ return { kind: 'scene', sceneId, parts: ['created'], created: true };
259
+ }
260
+
261
+ function clampIndex(position, length) {
262
+ const value = Number(position);
263
+ if (!Number.isInteger(value)) throw invalid('position 必须是整数');
264
+ return Math.max(0, Math.min(value, length));
265
+ }
266
+
267
+ function applyScenePatch(workspace, operation) {
268
+ const scene = workspace.scene(operation.sceneId);
269
+ if (!scene) throw invalid(`找不到场景 ${operation.sceneId}`, { sceneId: operation.sceneId });
270
+ const set = operation.set ?? {};
271
+ const allowed = ['title', 'phase', 'minutes', 'layout', 'modes', 'notes', 'hidden', 'components'];
272
+ for (const key of Object.keys(set)) {
273
+ if (!allowed.includes(key)) throw invalid(`scene.patch 不允许修改 ${key}`, { key });
274
+ }
275
+ const before = structuredClone(scene);
276
+ if (set.components !== undefined) scene.components = normalizeComponents(set.components);
277
+ if (set.title !== undefined) scene.title = set.title;
278
+ if (set.phase !== undefined) scene.phase = set.phase;
279
+ if (set.minutes !== undefined) scene.minutes = set.minutes;
280
+ if (set.layout !== undefined) scene.layout = set.layout;
281
+ if (set.modes !== undefined) scene.modes = set.modes;
282
+ if (set.notes !== undefined) scene.notes = set.notes;
283
+ if (set.hidden !== undefined) scene.hidden = Boolean(set.hidden);
284
+ validateSceneMetadata(scene);
285
+ if (operation.html !== undefined) {
286
+ if (!scene.file.endsWith('.html')) {
287
+ throw invalid('只有 HTML 场景可以写入 HTML 源码', { sceneId: scene.id });
288
+ }
289
+ const html = String(operation.html);
290
+ const safety = htmlSafetyIssues(html);
291
+ if (safety.length > 0) throw invalid(safety.join(';'), { sceneId: scene.id, issues: safety });
292
+ workspace.sceneTexts[scene.file] = html;
293
+ } else if (operation.content !== undefined) {
294
+ workspace.sceneTexts[scene.file] = renderSceneTemplate(scene, operation.content);
295
+ }
296
+ const changed = Object.keys(set);
297
+ if (operation.html !== undefined || operation.content !== undefined) changed.push('html');
298
+ return { kind: 'scene', sceneId: scene.id, parts: changed, before };
299
+ }
300
+
301
+ function applySceneMove(workspace, operation) {
302
+ const manifest = workspace.manifest;
303
+ const index = manifest.scenes.findIndex((scene) => scene.id === operation.sceneId);
304
+ if (index === -1) throw invalid(`找不到场景 ${operation.sceneId}`, { sceneId: operation.sceneId });
305
+ const [scene] = manifest.scenes.splice(index, 1);
306
+ const target = clampIndex(operation.toIndex, manifest.scenes.length);
307
+ manifest.scenes.splice(target, 0, scene);
308
+ return { kind: 'scene-order', sceneId: scene.id, parts: ['order'], fromIndex: index, toIndex: target };
309
+ }
310
+
311
+ function applySceneRemove(workspace, operation) {
312
+ const manifest = workspace.manifest;
313
+ const index = manifest.scenes.findIndex((scene) => scene.id === operation.sceneId);
314
+ if (index === -1) throw invalid(`找不到场景 ${operation.sceneId}`, { sceneId: operation.sceneId });
315
+ if (manifest.scenes.length <= 1) throw invalid('至少需要保留 1 个场景');
316
+ const related = (manifest.interactions ?? []).filter((entry) => entry.scene === operation.sceneId);
317
+ if (related.length > 0 && !operation.cascadeInteractions) {
318
+ throw new StudioError(
319
+ ERROR_CODES.OPERATION_CONFLICT,
320
+ `场景 ${operation.sceneId} 仍有关联题目:${related.map((entry) => entry.id).join(', ')};请显式设置 cascadeInteractions 或先删除题目`,
321
+ { sceneId: operation.sceneId, interactions: related.map((entry) => entry.id) },
322
+ 409,
323
+ );
324
+ }
325
+ const scene = manifest.scenes.splice(index, 1)[0];
326
+ delete workspace.sceneTexts[scene.file];
327
+ if (operation.cascadeInteractions) {
328
+ for (const entry of related) {
329
+ manifest.interactions = manifest.interactions.filter((item) => item.id !== entry.id);
330
+ workspace.interactions.delete(entry.id);
331
+ workspace.filesToDelete.push(entry.file);
332
+ }
333
+ }
334
+ if (operation.deleteFile !== false) workspace.filesToDelete.push(scene.file);
335
+ return {
336
+ kind: 'scene',
337
+ sceneId: operation.sceneId,
338
+ parts: ['removed'],
339
+ removed: true,
340
+ cascadeInteractions: related.map((entry) => entry.id),
341
+ file: scene.file,
342
+ };
343
+ }
344
+
345
+ function normalizeComponents(components) {
346
+ if (!Array.isArray(components)) throw invalid('components 必须是数组');
347
+ if (components.length > 6) throw invalid('单个场景最多 6 个组件');
348
+ const normalized = components.map((component) => {
349
+ if (!component || typeof component !== 'object') throw invalid('组件必须是对象');
350
+ const cid = component.cid;
351
+ if (!isComponentCid(cid)) throw invalid('组件 cid 必须是小写字母开头、最多 16 位的字母数字', { cid });
352
+ if (!COMPONENT_VALUES.includes(component.type)) throw invalid(`组件类型不在白名单:${component.type}`, { cid });
353
+ if (component.collect === undefined || !COLLECT_VALUES.includes(component.collect)) {
354
+ throw invalid(`组件 ${cid} 必须显式声明合法的 collect`, { cid });
355
+ }
356
+ const result = { cid, type: component.type, collect: component.collect };
357
+ if (component.props !== undefined) {
358
+ if (typeof component.props !== 'object' || component.props === null || Array.isArray(component.props)) {
359
+ throw invalid(`组件 ${cid} 的 props 必须是对象`, { cid });
360
+ }
361
+ result.props = component.props;
362
+ }
363
+ if (component.state !== undefined) {
364
+ if (typeof component.state !== 'object' || component.state === null || Array.isArray(component.state)) {
365
+ throw invalid(`组件 ${cid} 的 state 必须是对象`, { cid });
366
+ }
367
+ result.state = component.state;
368
+ }
369
+ if (component.sandbox !== undefined) {
370
+ if (!['iframe', 'inline'].includes(component.sandbox)) throw invalid(`组件 ${cid} 的 sandbox 必须是 iframe 或 inline`, { cid });
371
+ result.sandbox = component.sandbox;
372
+ }
373
+ if (component.role !== undefined) {
374
+ if (!['primary', 'support', 'reference'].includes(component.role)) throw invalid(`组件 ${cid} 的 role 不合法`, { cid });
375
+ result.role = component.role;
376
+ }
377
+ return result;
378
+ });
379
+ const cids = new Set();
380
+ for (const component of normalized) {
381
+ if (cids.has(component.cid)) throw invalid(`同一场景内组件 cid 重复:${component.cid}`, { cid: component.cid });
382
+ cids.add(component.cid);
383
+ }
384
+ return normalized;
385
+ }
386
+
387
+ function applyComponentUpsert(workspace, operation) {
388
+ const scene = workspace.scene(operation.sceneId);
389
+ if (!scene) throw invalid(`找不到场景 ${operation.sceneId}`, { sceneId: operation.sceneId });
390
+ const components = scene.components ?? [];
391
+ const previous = components.find((component) => component.cid === operation.component?.cid) ?? null;
392
+ // 组件 upsert 同样按字段合并,未提交的 props/state 不因局部编辑丢失。
393
+ const merged = previous
394
+ ? { ...structuredClone(previous), ...(operation.component ?? {}) }
395
+ : operation.component;
396
+ const incoming = normalizeComponents([merged])[0];
397
+ const index = components.findIndex((component) => component.cid === incoming.cid);
398
+ if (index === -1) {
399
+ if (components.length >= 6) throw invalid('单个场景最多 6 个组件');
400
+ components.push(incoming);
401
+ } else {
402
+ components[index] = incoming;
403
+ }
404
+ scene.components = components;
405
+ return { kind: 'component', sceneId: scene.id, cid: incoming.cid, parts: [index === -1 ? 'created' : 'updated'] };
406
+ }
407
+
408
+ function applyComponentRemove(workspace, operation) {
409
+ const scene = workspace.scene(operation.sceneId);
410
+ if (!scene) throw invalid(`找不到场景 ${operation.sceneId}`, { sceneId: operation.sceneId });
411
+ const index = (scene.components ?? []).findIndex((component) => component.cid === operation.cid);
412
+ if (index === -1) throw invalid(`找不到组件 ${operation.cid}`, { cid: operation.cid });
413
+ scene.components.splice(index, 1);
414
+ return { kind: 'component', sceneId: scene.id, cid: operation.cid, parts: ['removed'] };
415
+ }
416
+
417
+ // interaction.upsert 是受控 patch:缺省字段继承已有正文,显式字段才覆盖。
418
+ function mergeInteractionBody(previous, value) {
419
+ const merged = {
420
+ id: value.id,
421
+ type: value.type ?? value.kind ?? previous?.type,
422
+ stem: value.stem ?? previous?.stem,
423
+ options: value.options !== undefined ? value.options : previous?.options,
424
+ policy: value.policy !== undefined
425
+ ? { ...(previous?.policy ?? {}), ...value.policy }
426
+ : previous?.policy,
427
+ };
428
+ for (const key of ['explain', 'answerKeys', 'partialCredit', 'grading', 'language', 'starter', 'tests', 'timeLimitMs', 'memoryLimitMb', 'deadline', 'shuffleOptions', 'allowResubmit', 'timeLimitSec']) {
429
+ if (value[key] !== undefined) merged[key] = value[key];
430
+ else if (previous?.[key] !== undefined) merged[key] = previous[key];
431
+ }
432
+ if (value.answer !== undefined) merged.answer = value.answer;
433
+ // 答案材料只能来自已有正文;调用方直接写 hash/salt 一律拒绝。
434
+ if (previous?.answerHash !== undefined) merged.answerHash = previous.answerHash;
435
+ if (previous?.answerSalt !== undefined) merged.answerSalt = previous.answerSalt;
436
+ return merged;
437
+ }
438
+
439
+ function assertAnswerStillValid(previousBody, merged, interactionId) {
440
+ if (!previousBody?.answerHash || !previousBody?.answerSalt) return;
441
+ if (merged.answer !== undefined) return;
442
+ const derived = deriveAnswer(previousBody);
443
+ if (Array.isArray(merged.answerKeys) && Array.isArray(derived?.choices)) {
444
+ const before = [...derived.choices].sort().join(',');
445
+ const after = [...merged.answerKeys].sort().join(',');
446
+ if (before !== after) {
447
+ throw new StudioError(
448
+ ERROR_CODES.OPERATION_CONFLICT,
449
+ `题目 ${interactionId} 的 answerKeys 与已落盘答案不一致;请显式提交新的 answer`,
450
+ { interactionId },
451
+ 409,
452
+ );
453
+ }
454
+ }
455
+ const previousOptions = Array.isArray(previousBody.options) ? previousBody.options : [];
456
+ const mergedOptions = Array.isArray(merged.options) ? merged.options : [];
457
+ const optionsChanged = JSON.stringify(previousOptions) !== JSON.stringify(mergedOptions);
458
+ if (!optionsChanged && previousBody.type === merged.type) return;
459
+
460
+ if (!derived) {
461
+ throw new StudioError(
462
+ ERROR_CODES.OPERATION_CONFLICT,
463
+ `题目 ${interactionId} 的选项或类型已变化,旧答案无法自动校验;请显式提交新的 answer`,
464
+ { interactionId },
465
+ 409,
466
+ );
467
+ }
468
+ const keys = derived.choice !== undefined
469
+ ? [derived.choice]
470
+ : Array.isArray(derived.choices) ? derived.choices : [];
471
+ for (const key of keys) {
472
+ if (!mergedOptions.some((option) => option.key === key)) {
473
+ throw new StudioError(
474
+ ERROR_CODES.OPERATION_CONFLICT,
475
+ `题目 ${interactionId} 的旧答案 \`${key}\` 已不在选项中;请显式提交新的 answer`,
476
+ { interactionId, answerKey: key },
477
+ 409,
478
+ );
479
+ }
480
+ }
481
+ }
482
+
483
+ function applyInteractionUpsert(workspace, operation) {
484
+ const manifest = workspace.manifest;
485
+ const value = operation.value;
486
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw invalid('interaction.upsert 需要 value 对象');
487
+ const inputIssues = interactionInputIssues(value);
488
+ if (inputIssues.length > 0) throw invalid(inputIssues.join(';'), { issues: inputIssues });
489
+ if (value.answerHash !== undefined || value.answerSalt !== undefined) {
490
+ throw invalid('不要直接编辑 answerHash / answerSalt,请提交明文 answer');
491
+ }
492
+ const interactionId = operation.interactionId ?? value.id;
493
+ if (!isInteractionId(interactionId)) throw invalid('交互 id 必须是 3-40 位小写字母/数字/-/_', { interactionId });
494
+ const sceneId = operation.sceneId ?? value.scene;
495
+ if (!isSceneId(sceneId) || !workspace.scene(sceneId)) throw invalid(`题目所属场景不存在:${sceneId}`, { sceneId });
496
+
497
+ const previousBody = workspace.interactions.get(interactionId) ?? null;
498
+ const previousType = previousBody?.type ?? null;
499
+ const merged = mergeInteractionBody(previousBody, { ...value, id: interactionId });
500
+ if (!merged.type || !INTERACTION_KIND_VALUES.includes(merged.type)) throw invalid(`未知题目类型 ${merged.type}`, { interactionId });
501
+ if (value.answer !== undefined) {
502
+ const shapeIssues = answerShapeIssues(merged.type, value.answer);
503
+ if (shapeIssues.length > 0) throw invalid(shapeIssues.join(';'), { interactionId, issues: shapeIssues });
504
+ }
505
+ if (previousType && previousType !== merged.type && merged.answer === undefined && isObjective(merged.type)) {
506
+ throw new StudioError(
507
+ ERROR_CODES.OPERATION_CONFLICT,
508
+ `题目 ${interactionId} 的类型已变化,请显式提交新的 answer`,
509
+ { interactionId, previousType, nextType: merged.type },
510
+ 409,
511
+ );
512
+ }
513
+ assertAnswerStillValid(previousBody, merged, interactionId);
514
+
515
+ const normalized = normalizeInteractionInput(merged);
516
+ normalized.policy = normalizePolicy(merged.policy ?? {});
517
+ if (isObjective(normalized.type) && normalized.answer !== undefined) {
518
+ const issues = answerMaterialIssues(normalized);
519
+ if (issues.length > 0) throw invalid(issues.join(';'), { interactionId, issues });
520
+ applyAnswerMaterial(normalized, { regenerateSalt: true });
521
+ }
522
+ const structural = interactionIssues(normalized);
523
+ if (structural.length > 0) throw invalid(structural.join(';'), { interactionId, issues: structural });
524
+
525
+ const points = operation.points ?? (manifest.interactions ?? []).find((entry) => entry.id === interactionId)?.points ?? 1;
526
+ if (typeof points !== 'number' || !Number.isFinite(points) || points < 0 || points > 100) throw invalid('分值必须是 0-100 的有限数', { interactionId });
527
+ const graded = operation.graded ?? (manifest.interactions ?? []).find((entry) => entry.id === interactionId)?.graded ?? true;
528
+ if (typeof graded !== 'boolean') throw invalid('graded 必须是布尔值', { interactionId });
529
+ const file = operation.file ?? `interactions/${interactionId}.json`;
530
+ if (!/^interactions\/[a-z0-9\-_]+\.json$/.test(file)) throw invalid('交互文件必须位于 interactions/ 且以 .json 结尾', { file });
531
+
532
+ workspace.interactions.set(interactionId, toPersistedBody(normalized));
533
+ const entries = manifest.interactions ?? (manifest.interactions = []);
534
+ const entryIndex = entries.findIndex((entry) => entry.id === interactionId);
535
+ const entry = { id: interactionId, file, scene: sceneId, points, graded };
536
+ if (entryIndex === -1) entries.push(entry);
537
+ else entries[entryIndex] = { ...entries[entryIndex], ...entry, file: entries[entryIndex].file };
538
+ return {
539
+ kind: 'interaction',
540
+ interactionId,
541
+ sceneId,
542
+ parts: [entryIndex === -1 ? 'created' : 'updated', ...(normalized.answer !== undefined ? ['answer-material'] : [])],
543
+ answerChanged: normalized.answer !== undefined,
544
+ };
545
+ }
546
+
547
+ // 落盘正文:删除编辑态专用字段,保留运行时 schema 字段。
548
+ function toPersistedBody(normalized) {
549
+ const body = {
550
+ id: normalized.id,
551
+ type: normalized.type,
552
+ stem: normalized.stem,
553
+ options: normalized.options,
554
+ policy: normalized.policy ?? defaultPolicy(),
555
+ };
556
+ if (normalized.explain !== undefined) body.explain = normalized.explain;
557
+ if (normalized.answerHash !== undefined) body.answerHash = normalized.answerHash;
558
+ if (normalized.answerSalt !== undefined) body.answerSalt = normalized.answerSalt;
559
+ if (normalized.answerKeys !== undefined) body.answerKeys = normalized.answerKeys;
560
+ if (normalized.partialCredit !== undefined) body.partialCredit = normalized.partialCredit;
561
+ if (normalized.grading !== undefined) body.grading = normalized.grading;
562
+ if (normalized.language !== undefined) body.language = normalized.language;
563
+ if (normalized.starter !== undefined) body.starter = normalized.starter;
564
+ if (normalized.tests !== undefined) body.tests = normalized.tests;
565
+ if (normalized.timeLimitMs !== undefined) body.timeLimitMs = normalized.timeLimitMs;
566
+ if (normalized.memoryLimitMb !== undefined) body.memoryLimitMb = normalized.memoryLimitMb;
567
+ if (normalized.deadline !== undefined) body.deadline = normalized.deadline;
568
+ return body;
569
+ }
570
+
571
+ function applyInteractionRemove(workspace, operation) {
572
+ const manifest = workspace.manifest;
573
+ const entry = (manifest.interactions ?? []).find((item) => item.id === operation.interactionId);
574
+ if (!entry) throw invalid(`找不到题目 ${operation.interactionId}`, { interactionId: operation.interactionId });
575
+ manifest.interactions = manifest.interactions.filter((item) => item.id !== operation.interactionId);
576
+ workspace.interactions.delete(operation.interactionId);
577
+ if (operation.deleteFile !== false) workspace.filesToDelete.push(entry.file);
578
+ return { kind: 'interaction', interactionId: operation.interactionId, parts: ['removed'], removed: true, file: entry.file };
579
+ }
580
+
581
+ function applyAssetPut(workspace, operation) {
582
+ const file = operation.path;
583
+ if (typeof file !== 'string' || !file.startsWith('assets/') || !isSafeRelative(file)) {
584
+ throw new StudioError(ERROR_CODES.ASSET_FORBIDDEN, '资源路径必须以 assets/ 开头且位于课件包内', { path: file }, 400);
585
+ }
586
+ if (!/^assets\/[a-z0-9\-_/]+\.(js|css|json|svg|png|jpg|jpeg|gif|webp|mp3|mp4|woff|woff2|txt|md)$/.test(file)) {
587
+ throw new StudioError(ERROR_CODES.ASSET_FORBIDDEN, '不支持的资源类型', { path: file }, 400);
588
+ }
589
+ const content = operation.content;
590
+ if (typeof content !== 'string') throw invalid('asset.put 需要 content 字符串');
591
+ const bytes = operation.encoding === 'base64'
592
+ ? Buffer.from(content, 'base64').length
593
+ : Buffer.byteLength(content, 'utf8');
594
+ if (bytes > 8 * 1024 * 1024) {
595
+ throw new StudioError(ERROR_CODES.PAYLOAD_TOO_LARGE, '单个资源不能超过 8 MB', { path: file, bytes }, 413);
596
+ }
597
+ if (!operation.encoding || operation.encoding === 'utf8') {
598
+ workspace.assets.set(file, { content, encoding: 'utf8' });
599
+ } else if (operation.encoding === 'base64') {
600
+ workspace.assets.set(file, { content, encoding: 'base64' });
601
+ } else {
602
+ throw invalid(`不支持的 encoding:${operation.encoding}`);
603
+ }
604
+ const assets = workspace.manifest.assets ?? (workspace.manifest.assets = []);
605
+ const index = assets.findIndex((asset) => asset.path === file);
606
+ if (index === -1 && assets.length >= 100) {
607
+ throw new StudioError(ERROR_CODES.PAYLOAD_TOO_LARGE, '单个课件最多 100 个声明资源', { count: assets.length }, 413);
608
+ }
609
+ const digest = sha256Hex(operation.encoding === 'base64' ? Buffer.from(content, 'base64') : Buffer.from(content, 'utf8'));
610
+ const record = { path: file, bytes, sha256: digest };
611
+ if (index === -1) assets.push(record);
612
+ else assets[index] = record;
613
+ return { kind: 'asset', path: file, parts: [index === -1 ? 'created' : 'updated'] };
614
+ }
615
+
616
+ function applyAssetRemove(workspace, operation) {
617
+ const assets = workspace.manifest.assets ?? (workspace.manifest.assets = []);
618
+ const index = assets.findIndex((asset) => asset.path === operation.path);
619
+ if (index === -1) throw invalid(`找不到资源 ${operation.path}`, { path: operation.path });
620
+ assets.splice(index, 1);
621
+ workspace.assets.delete(operation.path);
622
+ workspace.filesToDelete.push(operation.path);
623
+ return { kind: 'asset', path: operation.path, parts: ['removed'], removed: true };
624
+ }
625
+
626
+ // 生成 HTML 场景骨架。保持最小依赖:不引入外部脚本,只使用课件 SDK。
627
+ export function renderSceneTemplate(scene, content = null) {
628
+ const title = escapeHtml(scene.title ?? scene.id);
629
+ const heading = escapeHtml(content?.heading ?? scene.title ?? '');
630
+ const body = escapeHtml(content?.body ?? '');
631
+ const bullets = Array.isArray(content?.bullets) ? content.bullets : [];
632
+ const list = bullets.length > 0
633
+ ? `<ul class="points">${bullets.map((item) => `<li>${escapeHtml(item)}</li>`).join('')}</ul>`
634
+ : '';
635
+ return `<!doctype html>
636
+ <html lang="zh-CN">
637
+ <head>
638
+ <meta charset="utf-8">
639
+ <meta name="viewport" content="width=device-width,initial-scale=1">
640
+ <title>${title}</title>
641
+ <style>
642
+ *{box-sizing:border-box}
643
+ body{margin:0;padding:6%;min-height:100vh;font-family:system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;background:#0f172a;color:#e2e8f0}
644
+ main{max-width:920px;margin:auto}
645
+ h1{font-size:clamp(26px,3.6vw,46px);margin:0 0 16px;line-height:1.2}
646
+ p{color:#94a3b8;font-size:clamp(16px,1.6vw,21px);line-height:1.7;margin:0 0 14px}
647
+ ul.points{margin:24px 0 0;padding-left:1.2em;color:#cbd5e1;font-size:clamp(15px,1.5vw,19px);line-height:2}
648
+ .tag{display:inline-block;margin-bottom:18px;padding:6px 12px;border-radius:999px;background:#1e293b;color:#818cf8;font-size:13px;letter-spacing:.04em}
649
+ </style>
650
+ </head>
651
+ <body>
652
+ <main>
653
+ <span class="tag">${escapeHtml(scene.phase)}</span>
654
+ <h1>${heading}</h1>
655
+ ${body ? `<p>${body}</p>` : ''}
656
+ ${list}
657
+ </main>
658
+ <script src="../assets/lume-courseware.js"></script>
659
+ </body>
660
+ </html>
661
+ `;
662
+ }
663
+
664
+ export function escapeHtml(value) {
665
+ return String(value ?? '')
666
+ .replace(/&/g, '&amp;')
667
+ .replace(/</g, '&lt;')
668
+ .replace(/>/g, '&gt;')
669
+ .replace(/"/g, '&quot;')
670
+ .replace(/'/g, '&#39;');
671
+ }