@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,349 @@
1
+ // 课件文档:加载、快照、DTO 与修订索引。
2
+ // 正式文件保持 specVersion 1.1 目录结构;.studio 只保存编辑元数据。
3
+
4
+ import fs from 'node:fs';
5
+ import fsp from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { ERROR_CODES, StudioError } from './errors.js';
8
+ import {
9
+ STUDIO_DIR, ensureStudioDir, existsSync, readJson, resolveInside, resolveRealFile,
10
+ writeJsonAtomic, readChecksumFile, verifyChecksums, answerHash, createSalt, sha256Hex,
11
+ } from './storage.js';
12
+ import { recoverWorkspace } from './transaction.js';
13
+ import { interactionIssues, normalizeInteractionInput, isObjective, defaultPolicy } from './model.js';
14
+ import { lintCourseware, summarize, validateManifest } from './validate.js';
15
+ import { normalizeAnswer, htmlProseChars, proseChars, DEFAULT_ASPECT_RATIO } from './rules.js';
16
+
17
+ const DEFAULT_DOCUMENT = { revision: 0, operationIds: [], createdAt: null, updatedAt: null };
18
+
19
+ export class CoursewareDocument {
20
+ constructor(root) {
21
+ this.root = path.resolve(root);
22
+ this.manifest = null;
23
+ this.sceneTexts = {};
24
+ this.interactions = [];
25
+ this.diagnostics = [];
26
+ this.revision = 0;
27
+ this.operationIds = [];
28
+ this.createdAt = null;
29
+ this.updatedAt = null;
30
+ this.exists = false;
31
+ // 预览 URL 使用会话内稳定的 key;Manifest id 变更时不会让旧 iframe 立即 404。
32
+ this.previewKey = null;
33
+ }
34
+
35
+ static async load(root) {
36
+ // 先恢复未完成事务,再读取课件,避免把半提交状态当成有效文档。
37
+ await recoverWorkspace(root).catch(() => {});
38
+ const document = new CoursewareDocument(root);
39
+ await document.reload();
40
+ return document;
41
+ }
42
+
43
+ get manifestPath() {
44
+ return path.join(this.root, 'manifest.json');
45
+ }
46
+
47
+ hasManifest() {
48
+ return existsSync(this.manifestPath);
49
+ }
50
+
51
+ async reload() {
52
+ this.exists = this.hasManifest();
53
+ this.sceneTexts = {};
54
+ this.interactions = [];
55
+ if (!this.exists) {
56
+ this.manifest = null;
57
+ const meta = await this.readStudioMeta();
58
+ this.revision = meta.revision ?? 0;
59
+ this.diagnostics = [];
60
+ this.previewKey ??= `studio-${sha256Hex(this.root).slice(0, 12)}`;
61
+ return this;
62
+ }
63
+
64
+ let manifest;
65
+ try {
66
+ manifest = JSON.parse(await fsp.readFile(resolveRealFile(this.root, 'manifest.json'), 'utf8'));
67
+ } catch (error) {
68
+ throw new StudioError(ERROR_CODES.COURSEWARE_INVALID, `manifest.json 无法解析:${error.message}`, { path: 'manifest.json' }, 422);
69
+ }
70
+ this.manifest = manifest;
71
+ this.previewKey ??= typeof manifest.id === 'string' ? manifest.id : `studio-${sha256Hex(this.root).slice(0, 12)}`;
72
+
73
+ for (const scene of manifest.scenes ?? []) {
74
+ if (typeof scene.file !== 'string' || !scene.file.startsWith('scenes/')) continue;
75
+ try {
76
+ this.sceneTexts[scene.file] = await fsp.readFile(resolveRealFile(this.root, scene.file), 'utf8');
77
+ } catch {
78
+ this.sceneTexts[scene.file] = null;
79
+ }
80
+ }
81
+
82
+ this.interactions = [];
83
+ for (const entry of manifest.interactions ?? []) {
84
+ const record = { entry, file: entry.file, body: null, error: null };
85
+ try {
86
+ const { value } = await readJson(resolveRealFile(this.root, entry.file));
87
+ record.body = value;
88
+ if (value?.id !== entry.id) {
89
+ record.idMismatch = { declared: entry.id, actual: value?.id };
90
+ }
91
+ } catch (error) {
92
+ record.error = error.message;
93
+ }
94
+ this.interactions.push(record);
95
+ }
96
+
97
+ const meta = await this.readStudioMeta();
98
+ this.revision = meta.revision ?? 0;
99
+ this.operationIds = Array.isArray(meta.operationIds) ? meta.operationIds : [];
100
+ this.createdAt = meta.createdAt ?? null;
101
+ this.updatedAt = meta.updatedAt ?? null;
102
+ this.diagnostics = this.validate();
103
+ return this;
104
+ }
105
+
106
+ validate() {
107
+ const items = [...validateManifest(this.manifest)];
108
+ const checksums = readChecksumFile(this.root, 'checksums.json');
109
+ items.push(...verifyChecksums(this.root, this.manifest, checksums));
110
+
111
+ for (const record of this.interactions) {
112
+ if (record.error) {
113
+ items.push({ code: 'P009', level: 'error', path: record.file, message: `交互文件解析失败:${record.error}` });
114
+ continue;
115
+ }
116
+ if (record.idMismatch) {
117
+ items.push({
118
+ code: 'P007',
119
+ level: 'warning',
120
+ path: record.file,
121
+ message: `文件内 id \`${record.idMismatch.actual}\` 与 manifest id \`${record.idMismatch.declared}\` 不一致`,
122
+ });
123
+ }
124
+ for (const issue of interactionIssues(record.body)) {
125
+ items.push({ code: 'P009', level: 'error', path: record.file, message: issue });
126
+ }
127
+ }
128
+
129
+ for (const [file, text] of Object.entries(this.sceneTexts)) {
130
+ if (text === null) {
131
+ items.push({ code: 'P003', level: 'error', path: file, message: '场景文件缺失或不可读' });
132
+ }
133
+ }
134
+
135
+ const script = this.readScript();
136
+ if (script.error) {
137
+ items.push({ code: 'P010', level: 'error', path: 'script.json', message: script.error });
138
+ }
139
+ items.push(...lintCourseware(this.manifest, Object.fromEntries(Object.entries(this.sceneTexts).filter(([, text]) => text !== null)), script.value));
140
+
141
+ return items;
142
+ }
143
+
144
+ readScript() {
145
+ const name = this.manifest?.script;
146
+ if (!name) return { value: null, error: null };
147
+ try {
148
+ const { value } = readJsonSync(resolveRealFile(this.root, name));
149
+ return { value, error: null };
150
+ } catch (error) {
151
+ return { value: null, error: error.message };
152
+ }
153
+ }
154
+
155
+ async readStudioMeta() {
156
+ try {
157
+ const { value } = await readJson(resolveRealFile(this.root, `${STUDIO_DIR}/document.json`));
158
+ return { ...DEFAULT_DOCUMENT, ...value };
159
+ } catch (error) {
160
+ // 缺失是正常空状态;符号链接/越界等安全错误必须向上抛出。
161
+ if (error instanceof StudioError && error.status !== 404) throw error;
162
+ return { ...DEFAULT_DOCUMENT };
163
+ }
164
+ }
165
+
166
+ async writeStudioMeta() {
167
+ await ensureStudioDir(this.root);
168
+ await writeJsonAtomic(path.join(resolveInside(this.root, STUDIO_DIR), 'document.json'), {
169
+ revision: this.revision,
170
+ operationIds: this.operationIds.slice(-200),
171
+ createdAt: this.createdAt,
172
+ updatedAt: this.updatedAt,
173
+ });
174
+ }
175
+
176
+ get report() {
177
+ return summarize(this.diagnostics);
178
+ }
179
+
180
+ sceneById(sceneId) {
181
+ return (this.manifest?.scenes ?? []).find((scene) => scene.id === sceneId) ?? null;
182
+ }
183
+
184
+ interactionEntry(interactionId) {
185
+ return (this.manifest?.interactions ?? []).find((entry) => entry.id === interactionId) ?? null;
186
+ }
187
+
188
+ // 作者视图:可含答案材料摘要,但绝不下发 answerHash/answerSalt 给学生视图。
189
+ toAuthorView() {
190
+ if (!this.manifest) {
191
+ return { exists: false, revision: this.revision, root: this.root, previewKey: this.previewKey, report: summarize([]), document: null };
192
+ }
193
+ const manifest = this.manifest;
194
+ const previewKey = this.previewKey ?? manifest.id;
195
+ return {
196
+ exists: true,
197
+ revision: this.revision,
198
+ root: this.root,
199
+ previewKey,
200
+ coursewareId: manifest.id,
201
+ title: manifest.title,
202
+ version: manifest.version ?? '1.0.0',
203
+ report: this.report,
204
+ source: manifest.source ?? null,
205
+ meta: {
206
+ id: manifest.id,
207
+ title: manifest.title,
208
+ subject: manifest.subject,
209
+ grade: manifest.grade,
210
+ durationMin: manifest.durationMin,
211
+ aspectRatio: manifest.aspectRatio ?? DEFAULT_ASPECT_RATIO,
212
+ locale: manifest.locale ?? 'zh-CN',
213
+ runtime: manifest.runtime ?? '>=1.1 <2.0',
214
+ authors: manifest.authors ?? [],
215
+ tags: manifest.tags ?? [],
216
+ objectives: manifest.objectives ?? [],
217
+ prerequisites: manifest.prerequisites ?? [],
218
+ theme: manifest.theme ?? null,
219
+ compliance: manifest.compliance ?? {},
220
+ },
221
+ scenes: (manifest.scenes ?? []).map((scene, index) => ({
222
+ index,
223
+ id: scene.id,
224
+ file: scene.file,
225
+ title: scene.title ?? scene.id,
226
+ phase: scene.phase,
227
+ minutes: scene.minutes,
228
+ layout: scene.layout ?? 'full',
229
+ modes: scene.modes ?? ['broadcast', 'explore', 'converge'],
230
+ components: scene.components ?? [],
231
+ notes: scene.notes ?? '',
232
+ hidden: scene.hidden ?? false,
233
+ runtime: scene.file.endsWith('.html') ? 'html' : 'markdown',
234
+ contentUrl: `/lessons/${encodeURIComponent(previewKey)}/content/${scene.file}`,
235
+ contentHash: typeof this.sceneTexts[scene.file] === 'string' ? sha256Hex(this.sceneTexts[scene.file]).slice(0, 16) : null,
236
+ proseChars: this.proseFor(scene.file),
237
+ failure: this.sceneTexts[scene.file] === null ? '场景文件缺失' : null,
238
+ })),
239
+ interactions: this.interactions.map((record) => ({
240
+ id: record.entry.id,
241
+ file: record.file,
242
+ scene: record.entry.scene,
243
+ points: record.entry.points ?? 1,
244
+ graded: record.entry.graded ?? true,
245
+ body: record.body ? toAuthorInteraction(record.body) : null,
246
+ error: record.error,
247
+ })),
248
+ assets: (manifest.assets ?? []).map((asset) => ({ ...asset })),
249
+ checksums: manifest.checksums ?? null,
250
+ };
251
+ }
252
+
253
+ proseFor(file) {
254
+ const text = this.sceneTexts[file];
255
+ if (typeof text !== 'string') return 0;
256
+ return file.endsWith('.html') ? htmlProseChars(text) : proseChars(text);
257
+ }
258
+ }
259
+
260
+ function readJsonSync(absolutePath) {
261
+ const text = fs.readFileSync(absolutePath, 'utf8');
262
+ return { text, value: JSON.parse(text) };
263
+ }
264
+
265
+ // 作者视图的题目:用于界面回填与 Diff。
266
+ // 哈希与盐仍不下发;正确答案由「候选值逐个比对哈希」还原,
267
+ // 这样界面能显示当前答案,又不必额外保存一份明文答案。
268
+ function toAuthorInteraction(body) {
269
+ const copy = structuredClone(body);
270
+ if (copy.answerHash) {
271
+ copy.answerConfigured = true;
272
+ const derived = deriveAnswer(copy);
273
+ if (derived) copy.answer = derived;
274
+ }
275
+ delete copy.answerHash;
276
+ delete copy.answerSalt;
277
+ return copy;
278
+ }
279
+
280
+ // 从 answerHash 反推正确答案。只覆盖可枚举候选的类型。
281
+ export function deriveAnswer(body) {
282
+ const hash = body?.answerHash;
283
+ const salt = body?.answerSalt;
284
+ if (typeof hash !== 'string' || typeof salt !== 'string') return null;
285
+ if (body.type === 'single-choice') {
286
+ for (const option of body.options ?? []) {
287
+ if (answerHash(salt, `choice:${String(option.key).trim()}`) === hash) {
288
+ return { choice: option.key };
289
+ }
290
+ }
291
+ return null;
292
+ }
293
+ if (body.type === 'multi-choice') {
294
+ if (Array.isArray(body.answerKeys) && body.answerKeys.length > 0) {
295
+ return { choices: [...body.answerKeys] };
296
+ }
297
+ const keys = (body.options ?? []).map((option) => option.key);
298
+ // 只在规模可控时穷举组合,避免指数爆炸。
299
+ if (keys.length > 8) return null;
300
+ for (let mask = 1; mask < 1 << keys.length; mask += 1) {
301
+ const picked = keys.filter((_, index) => mask & (1 << index));
302
+ const normalized = `choices:${[...picked].map((key) => key.trim()).sort().join(',')}`;
303
+ if (answerHash(salt, normalized) === hash) return { choices: picked };
304
+ }
305
+ return null;
306
+ }
307
+ // 填空题没有候选集合,无法从哈希反推;如实返回 null。
308
+ return null;
309
+ }
310
+
311
+ // 学生视图:彻底剥离答案材料、解析与讲稿。
312
+ export function toStudentInteraction(record, points, graded) {
313
+ const body = record.body ?? {};
314
+ return {
315
+ id: record.entry.id,
316
+ type: body.type,
317
+ stem: body.stem,
318
+ options: (body.options ?? []).map((option) => ({ key: option.key, text: option.text })),
319
+ scene: record.entry.scene,
320
+ points: points ?? 1,
321
+ graded: graded ?? true,
322
+ aiReviewEnabled: body.grading?.enabled ?? true,
323
+ policy: defaultPolicy(body.policy ?? {}),
324
+ };
325
+ }
326
+
327
+ // 由明文答案生成服务端材料,并写入规范字段。
328
+ export function applyAnswerMaterial(interaction, { regenerateSalt = true } = {}) {
329
+ if (!isObjective(interaction.type)) return interaction;
330
+ if (interaction.answer === undefined) return interaction;
331
+ const normalized = normalizeAnswer(interaction.type, interaction.answer);
332
+ if (!normalized) {
333
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '答案结构无法规范化', { interactionId: interaction.id }, 400);
334
+ }
335
+ const salt = regenerateSalt || !interaction.answerSalt ? createSalt() : interaction.answerSalt;
336
+ interaction.answerSalt = salt;
337
+ interaction.answerHash = answerHash(salt, normalized);
338
+ if (interaction.type === 'multi-choice' && Array.isArray(interaction.answer.choices)) {
339
+ interaction.answerKeys = [...new Set(interaction.answer.choices.map((key) => String(key).trim()))];
340
+ }
341
+ return interaction;
342
+ }
343
+
344
+ export function answerMaterialDigest(body) {
345
+ if (!body?.answerHash || !body?.answerSalt) return null;
346
+ return sha256Hex(`${body.answerSalt}:${body.answerHash}`).slice(0, 16);
347
+ }
348
+
349
+ export { normalizeInteractionInput };
@@ -0,0 +1,44 @@
1
+ export const ERROR_CODES = {
2
+ ENV_INVALID: 'STUDIO_ENV_INVALID',
3
+ ROOT_FORBIDDEN: 'STUDIO_ROOT_FORBIDDEN',
4
+ COURSEWARE_INVALID: 'STUDIO_COURSEWARE_INVALID',
5
+ SESSION_EXPIRED: 'STUDIO_SESSION_EXPIRED',
6
+ TOOL_UNKNOWN: 'STUDIO_TOOL_UNKNOWN',
7
+ OPERATION_INVALID: 'STUDIO_OPERATION_INVALID',
8
+ REVISION_CONFLICT: 'REVISION_CONFLICT',
9
+ OPERATION_CONFLICT: 'OPERATION_CONFLICT',
10
+ VALIDATION_FAILED: 'VALIDATION_FAILED',
11
+ ASSET_FORBIDDEN: 'ASSET_FORBIDDEN',
12
+ PAYLOAD_TOO_LARGE: 'PAYLOAD_TOO_LARGE',
13
+ STORAGE_WRITE_FAILED: 'STORAGE_WRITE_FAILED',
14
+ PREVIEW_UNAVAILABLE: 'PREVIEW_UNAVAILABLE',
15
+ AI_NOT_CONFIGURED: 'AI_NOT_CONFIGURED',
16
+ AI_UNAVAILABLE: 'AI_UNAVAILABLE',
17
+ AI_OUTPUT_INVALID: 'AI_OUTPUT_INVALID',
18
+ BAD_REQUEST: 'BAD_REQUEST',
19
+ INTERNAL: 'INTERNAL_ERROR',
20
+ };
21
+
22
+ export class StudioError extends Error {
23
+ constructor(code, message, details = undefined, status = 400) {
24
+ super(message);
25
+ this.name = 'StudioError';
26
+ this.code = code;
27
+ this.details = details;
28
+ this.status = status;
29
+ }
30
+
31
+ toJSON() {
32
+ return {
33
+ error: {
34
+ code: this.code,
35
+ message: this.message,
36
+ ...(this.details === undefined ? {} : { details: this.details }),
37
+ },
38
+ };
39
+ }
40
+ }
41
+
42
+ export function fail(code, message, details, status) {
43
+ return new StudioError(code, message, details, status);
44
+ }
@@ -0,0 +1,272 @@
1
+ // 目录导出:从固定 revision 快照复制,禁止导出到课件 root 内。
2
+ // CLI 与 HTTP 共用同一实现,导出后重新执行 Node 侧完整校验。
3
+
4
+ import fsp from 'node:fs/promises';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { ERROR_CODES, StudioError } from './errors.js';
8
+ import { createSnapshot, readSnapshot } from './storage.js';
9
+ import { CoursewareDocument } from './document.js';
10
+ import { createZip, readZip, stripSingleRoot } from './zip.js';
11
+
12
+ export function assertExportTarget(root, out) {
13
+ const rootAbsolute = path.resolve(root);
14
+ const target = path.resolve(out);
15
+ if (target === rootAbsolute) {
16
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '导出目录不能等于课件根目录', { out: target }, 400);
17
+ }
18
+ const relative = path.relative(rootAbsolute, target);
19
+ if (relative && !relative.startsWith('..') && !path.isAbsolute(relative)) {
20
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '导出目录不能位于课件根目录内', { out: target }, 400);
21
+ }
22
+ return target;
23
+ }
24
+
25
+ export async function exportCourseware({ root, out, revision, force = false }) {
26
+ const target = assertExportTarget(root, out);
27
+ let entries = [];
28
+ try {
29
+ entries = await fsp.readdir(target);
30
+ } catch {
31
+ entries = [];
32
+ }
33
+ if (entries.length > 0 && !force) {
34
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, `导出目录非空:${target}`, { out: target }, 409);
35
+ }
36
+ if (entries.length > 0 && force) {
37
+ for (const entry of entries) {
38
+ await fsp.rm(path.join(target, entry), { recursive: true, force: true });
39
+ }
40
+ }
41
+ await fsp.mkdir(target, { recursive: true });
42
+
43
+ if (revision !== undefined && revision !== null) {
44
+ const current = await CoursewareDocument.load(root);
45
+ if (revision !== current.revision) {
46
+ throw new StudioError(
47
+ ERROR_CODES.REVISION_CONFLICT,
48
+ `只能导出当前已提交 revision,当前为 ${current.revision}`,
49
+ { revision, currentRevision: current.revision },
50
+ 409,
51
+ );
52
+ }
53
+ }
54
+ const document = await CoursewareDocument.load(root);
55
+ if (!document.exists) {
56
+ throw new StudioError(ERROR_CODES.COURSEWARE_INVALID, '没有可导出的课件', undefined, 422);
57
+ }
58
+ if (!document.report.valid) {
59
+ throw new StudioError(ERROR_CODES.VALIDATION_FAILED, '课件校验未通过,拒绝导出', { report: document.report }, 422);
60
+ }
61
+ await createSnapshot(root, document.revision);
62
+ const snapshot = await readSnapshot(root, document.revision);
63
+ let copied = 0;
64
+ for (const [relative, content] of snapshot.files) {
65
+ const destination = path.join(target, relative);
66
+ const relativeCheck = path.relative(target, destination);
67
+ if (!relativeCheck || relativeCheck.startsWith('..') || path.isAbsolute(relativeCheck)) {
68
+ throw new StudioError(ERROR_CODES.STORAGE_WRITE_FAILED, `导出路径越界:${relative}`, { path: relative }, 500);
69
+ }
70
+ await fsp.mkdir(path.dirname(destination), { recursive: true });
71
+ await fsp.writeFile(destination, content);
72
+ copied += 1;
73
+ }
74
+
75
+ // 导出物必须能被同一套加载与校验逻辑接受。
76
+ const exported = await CoursewareDocument.load(target);
77
+ if (!exported.report.valid) {
78
+ throw new StudioError(
79
+ ERROR_CODES.VALIDATION_FAILED,
80
+ '导出目录未通过重新校验',
81
+ { out: target, report: exported.report },
82
+ 422,
83
+ );
84
+ }
85
+ return {
86
+ out: target,
87
+ files: copied,
88
+ revision: document.revision,
89
+ validation: { errors: exported.report.errors, warnings: exported.report.warnings },
90
+ };
91
+ }
92
+
93
+ // .lume 打包:从已提交 revision 快照写入单个 ZIP,便于直接传阅。
94
+ export async function packageCourseware({ root, out, revision, force = false }) {
95
+ const target = path.resolve(out);
96
+ if (!target.toLowerCase().endsWith('.lume')) {
97
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '打包文件必须以 .lume 结尾', { out: target }, 400);
98
+ }
99
+ let stats = null;
100
+ try {
101
+ stats = await fsp.stat(target);
102
+ } catch {
103
+ stats = null;
104
+ }
105
+ if (stats) {
106
+ if (!stats.isFile()) throw new StudioError(ERROR_CODES.OPERATION_INVALID, '打包目标不是文件', { out: target }, 409);
107
+ if (!force) throw new StudioError(ERROR_CODES.OPERATION_INVALID, `打包文件已存在:${target}`, { out: target }, 409);
108
+ }
109
+
110
+ const document = await CoursewareDocument.load(root);
111
+ if (!document.exists) {
112
+ throw new StudioError(ERROR_CODES.COURSEWARE_INVALID, '没有可打包的课件', undefined, 422);
113
+ }
114
+ if (!document.report.valid) {
115
+ throw new StudioError(ERROR_CODES.VALIDATION_FAILED, '课件校验未通过,拒绝打包', { report: document.report }, 422);
116
+ }
117
+ if (revision !== undefined && revision !== null && revision !== document.revision) {
118
+ throw new StudioError(
119
+ ERROR_CODES.REVISION_CONFLICT,
120
+ `只能打包当前已提交 revision,当前为 ${document.revision}`,
121
+ { revision, currentRevision: document.revision },
122
+ 409,
123
+ );
124
+ }
125
+
126
+ await createSnapshot(root, document.revision);
127
+ const snapshot = await readSnapshot(root, document.revision);
128
+ const entries = [];
129
+ for (const [relative, content] of snapshot.files) {
130
+ if (relative.split('/').some((part) => part.startsWith('.'))) continue;
131
+ entries.push({ path: relative, data: content });
132
+ }
133
+ const buffer = createZip(entries);
134
+ // 打包结果必须能被同一读取器重新解开并保留完整清单。
135
+ const reopened = stripSingleRoot(readZip(buffer));
136
+ if (!reopened.some((entry) => entry.path === 'manifest.json')) {
137
+ throw new StudioError(ERROR_CODES.STORAGE_WRITE_FAILED, '打包结果缺少 manifest.json', { out: target }, 500);
138
+ }
139
+
140
+ await fsp.mkdir(path.dirname(target), { recursive: true });
141
+ const temporary = `${target}.${process.pid}.tmp`;
142
+ try {
143
+ await fsp.writeFile(temporary, buffer);
144
+ await fsp.rename(temporary, target);
145
+ } catch (error) {
146
+ await fsp.rm(temporary, { force: true }).catch(() => {});
147
+ throw error;
148
+ }
149
+ return {
150
+ out: target,
151
+ files: entries.length,
152
+ bytes: buffer.length,
153
+ revision: document.revision,
154
+ coursewareId: document.manifest.id,
155
+ title: document.manifest.title,
156
+ };
157
+ }
158
+
159
+ // 读取 .lume 字节流:先解到临时目录跑完整校验,返回文件集合供工作区事务提交。
160
+ // 与 importCourseware 的区别是不替换目标目录,因此可以保留 .studio 历史与运行会话。
161
+ export async function inspectCoursewareArchive(buffer) {
162
+ if (!Buffer.isBuffer(buffer) || buffer.length === 0) {
163
+ throw new StudioError(ERROR_CODES.BAD_REQUEST, '导入文件为空', undefined, 400);
164
+ }
165
+ const entries = stripSingleRoot(readZip(buffer));
166
+ if (!entries.some((entry) => entry.path === 'manifest.json')) {
167
+ throw new StudioError(ERROR_CODES.COURSEWARE_INVALID, '打包文件缺少 manifest.json', undefined, 422);
168
+ }
169
+ const temporary = await fsp.mkdtemp(path.join(os.tmpdir(), 'lume-archive-'));
170
+ try {
171
+ for (const entry of entries) {
172
+ const destination = path.join(temporary, entry.path);
173
+ const relative = path.relative(temporary, destination);
174
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
175
+ throw new StudioError(ERROR_CODES.STORAGE_WRITE_FAILED, `导入路径越界:${entry.path}`, { path: entry.path }, 500);
176
+ }
177
+ await fsp.mkdir(path.dirname(destination), { recursive: true });
178
+ await fsp.writeFile(destination, entry.data, { mode: 0o600 });
179
+ }
180
+ const document = await CoursewareDocument.load(temporary);
181
+ if (!document.exists || !document.report.valid) {
182
+ throw new StudioError(
183
+ ERROR_CODES.VALIDATION_FAILED,
184
+ '导入包未通过课件校验',
185
+ { report: document.report },
186
+ 422,
187
+ );
188
+ }
189
+ return {
190
+ files: new Map(entries.map((entry) => [entry.path, entry.data])),
191
+ manifest: document.manifest,
192
+ coursewareId: document.manifest.id,
193
+ title: document.manifest.title,
194
+ scenes: (document.manifest.scenes ?? []).length,
195
+ validation: { errors: document.report.errors, warnings: document.report.warnings },
196
+ };
197
+ } finally {
198
+ await fsp.rm(temporary, { recursive: true, force: true }).catch(() => {});
199
+ }
200
+ }
201
+
202
+ // .lume 导入:安全解包到新目录,并在落盘后重新执行完整课件校验。
203
+ export async function importCourseware({ file, out, force = false }) {
204
+ const source = path.resolve(file);
205
+ let buffer;
206
+ try {
207
+ buffer = await fsp.readFile(source);
208
+ } catch {
209
+ throw new StudioError(ERROR_CODES.BAD_REQUEST, `无法读取打包文件:${source}`, { file: source }, 400);
210
+ }
211
+ const entries = stripSingleRoot(readZip(buffer));
212
+ if (!entries.some((entry) => entry.path === 'manifest.json')) {
213
+ throw new StudioError(ERROR_CODES.COURSEWARE_INVALID, '打包文件缺少 manifest.json', { file: source }, 422);
214
+ }
215
+
216
+ const target = path.resolve(out);
217
+ if (target === path.parse(target).root) {
218
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '不能把课件导入到文件系统根目录', { out: target }, 400);
219
+ }
220
+ let existing = null;
221
+ try {
222
+ existing = await fsp.stat(target);
223
+ } catch {
224
+ existing = null;
225
+ }
226
+ if (existing) {
227
+ if (!existing.isDirectory()) {
228
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '导入目标不是目录', { out: target }, 409);
229
+ }
230
+ const children = await fsp.readdir(target);
231
+ if (children.length > 0 && !force) {
232
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, `导入目标非空:${target}`, { out: target }, 409);
233
+ }
234
+ }
235
+
236
+ await fsp.mkdir(path.dirname(target), { recursive: true });
237
+ const staging = await fsp.mkdtemp(path.join(path.dirname(target), '.lume-import-'));
238
+ try {
239
+ for (const entry of entries) {
240
+ const destination = path.join(staging, entry.path);
241
+ const relative = path.relative(staging, destination);
242
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
243
+ throw new StudioError(ERROR_CODES.STORAGE_WRITE_FAILED, `导入路径越界:${entry.path}`, { path: entry.path }, 500);
244
+ }
245
+ await fsp.mkdir(path.dirname(destination), { recursive: true });
246
+ await fsp.writeFile(destination, entry.data, { mode: 0o600 });
247
+ }
248
+
249
+ const document = await CoursewareDocument.load(staging);
250
+ if (!document.exists || !document.report.valid) {
251
+ throw new StudioError(
252
+ ERROR_CODES.VALIDATION_FAILED,
253
+ '导入包未通过课件校验',
254
+ { file: source, report: document.report },
255
+ 422,
256
+ );
257
+ }
258
+
259
+ if (existing) await fsp.rm(target, { recursive: true, force: true });
260
+ await fsp.rename(staging, target);
261
+ return {
262
+ out: target,
263
+ files: entries.length,
264
+ coursewareId: document.manifest.id,
265
+ title: document.manifest.title,
266
+ scenes: document.manifest.scenes.length,
267
+ };
268
+ } catch (error) {
269
+ await fsp.rm(staging, { recursive: true, force: true }).catch(() => {});
270
+ throw error;
271
+ }
272
+ }