@joplo-app/server 0.6.2 → 0.7.2

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 (48) hide show
  1. package/dist/asset-usage.d.ts +48 -0
  2. package/dist/asset-usage.js +174 -0
  3. package/dist/audio-timing.d.ts +14 -0
  4. package/dist/audio-timing.js +66 -0
  5. package/dist/build.js +15 -2
  6. package/dist/capture.d.ts +15 -0
  7. package/dist/capture.js +49 -0
  8. package/dist/checkpoint.d.ts +10 -0
  9. package/dist/checkpoint.js +75 -0
  10. package/dist/contract.d.ts +63 -1
  11. package/dist/dev.d.ts +1 -0
  12. package/dist/dev.js +15 -7
  13. package/dist/export.d.ts +6 -0
  14. package/dist/export.js +5 -2
  15. package/dist/film.d.ts +12 -1
  16. package/dist/film.js +231 -25
  17. package/dist/index.d.ts +7 -1
  18. package/dist/index.js +5 -1
  19. package/dist/layout-audit-browser.js +114 -0
  20. package/dist/layout-audit.d.ts +94 -0
  21. package/dist/layout-audit.js +86 -0
  22. package/dist/local-resources.d.ts +5 -0
  23. package/dist/local-resources.js +32 -6
  24. package/dist/media-check.d.ts +7 -1
  25. package/dist/media-check.js +44 -3
  26. package/dist/output-file.d.ts +3 -0
  27. package/dist/output-file.js +23 -0
  28. package/dist/project.d.ts +5 -1
  29. package/dist/project.js +20 -4
  30. package/dist/render.d.ts +2 -0
  31. package/dist/render.js +24 -10
  32. package/dist/resources-run.d.ts +1 -0
  33. package/dist/resources-run.js +23 -2
  34. package/dist/timeline.d.ts +76 -0
  35. package/dist/timeline.js +143 -0
  36. package/dist/video-format.d.ts +2 -0
  37. package/dist/video-format.js +12 -0
  38. package/dist/vite-shared.d.ts +1 -1
  39. package/dist/vite-shared.js +2 -2
  40. package/dist/voice-http.d.ts +1 -0
  41. package/dist/voice-http.js +8 -2
  42. package/dist/voice-run.d.ts +17 -1
  43. package/dist/voice-run.js +71 -9
  44. package/dist/voice.d.ts +1 -0
  45. package/dist/voice.js +10 -2
  46. package/dist/watch-config.d.ts +3 -0
  47. package/dist/watch-config.js +10 -0
  48. package/package.json +4 -4
package/dist/render.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { auditLayout, layoutAuditOptions, layoutReportPath, writeLayoutReport } from "./layout-audit.js";
1
2
  /**
2
3
  * renderStep:用随机端口启动一次性的 dev 服务(只编译一次、不监听),Playwright 打开渲染路由,
3
4
  * 截取舞台并返回元素索引(带 at)与渲染告警:遮挡、溢出、Toast 重叠、字体(PRD 8.8 / AC-22)。
@@ -8,12 +9,13 @@
8
9
  */
9
10
  import fs from 'node:fs';
10
11
  import path from 'node:path';
11
- import { JoploError, VIEWPORT_SIZE, isAppearanceFont, isAppearanceStroke, displaySceneId, findNode, isNodeDisabled, nodeLabel, positionAfterStep, resolveProps, scopeProject, stateAt, walkNodes } from '@joplo-app/core';
12
+ import { JoploError, narrationText, VIEWPORT_SIZE, isAppearanceFont, isAppearanceStroke, displaySceneId, findNode, isNodeDisabled, nodeLabel, positionAfterStep, resolveProps, scopeProject, stateAt, walkNodes } from '@joplo-app/core';
12
13
  import { exportLocale } from "./locale.js";
13
14
  import { createDev } from "./dev.js";
14
15
  import { realProjectDir } from "./vite-shared.js";
15
16
  import { joploHome } from "./home.js";
16
17
  import { EXPORT_DOWNLOAD_MB, NOT_NEEDED, SETUP_COMMAND, loadPlaywright } from "./export-runtime.js";
18
+ import { capture, geometryQuery } from "./capture.js";
17
19
  const STAGE_SIZE = VIEWPORT_SIZE;
18
20
  export { loadPlaywright } from "./export-runtime.js";
19
21
  /** 浏览器启动失败时的一行提示(托管运行时与项目里的 Playwright 都适用:重装 Joplo 自己的导出组件)。 */
@@ -53,7 +55,7 @@ function realish(p) {
53
55
  }
54
56
  }
55
57
  /** 截图不得覆盖项目源文件或 .joplo/(即使传了 overwrite)。 */
56
- function assertNotProjectData(projectDir, out) {
58
+ export function assertNotProjectData(projectDir, out) {
57
59
  const fold = (p) => (process.platform === 'darwin' || process.platform === 'win32' ? p.toLowerCase() : p);
58
60
  const o = fold(realish(out));
59
61
  const dir = fold(realish(projectDir));
@@ -87,6 +89,11 @@ export async function renderStep(opts) {
87
89
  assertNotProjectData(projectDir, out);
88
90
  if (fs.existsSync(out) && !opts.overwrite)
89
91
  throw new JoploError('USAGE', `Output file already exists: ${out}. To overwrite, pass overwrite: true (CLI: --overwrite)`);
92
+ if (opts.auditLayout) {
93
+ layoutAuditOptions(opts.auditLayout);
94
+ if (fs.existsSync(layoutReportPath(out)) && !opts.overwrite)
95
+ throw new JoploError('USAGE', `Layout report already exists: ${layoutReportPath(out)}`);
96
+ }
90
97
  // 先确认 Playwright 可用,再启动编译服务(缺失时尽快失败)
91
98
  const playwright = await loadPlaywright({ home: joploHome(), projectDir });
92
99
  const server = await createDev({ projectDir, port: 0, watch: false, log: () => undefined });
@@ -114,20 +121,23 @@ export async function renderStep(opts) {
114
121
  const theme = opts.theme ?? project.theme ?? 'sketch';
115
122
  const next = state.completed ? undefined : sc.steps[position];
116
123
  const nextTargetId = next && 'target' in next.action ? next.action.target : null;
117
- const stage = STAGE_SIZE[scene.viewport === 'mobile' ? 'mobile' : 'desktop'];
124
+ const stage = opts.logicalViewport ?? STAGE_SIZE[scene.viewport === 'mobile' ? 'mobile' : 'desktop'];
118
125
  // 字幕与步骤标题条浮在舞台上(D97):页面就是舞台大小
119
126
  const viewport = opts.viewport ?? { width: stage.width, height: stage.height };
120
127
  browser = await launch(playwright);
121
128
  const page = await browser.newPage({ viewport, deviceScaleFactor: opts.scale ?? 1, reducedMotion: 'reduce' });
122
129
  // D44:舞台宽度固定为页面自己的 viewport;指定 viewport 时它只是截图尺寸(舞台按比例放进去)
123
- const q = renderQuery({ projectId: server.projectId, scenarioId: sc.id, position, theme, locale: opts.locale, content: opts.content, font: opts.font, stroke: opts.stroke, ...(opts.viewport ? { viewport: opts.viewport } : {}) });
130
+ const q0 = renderQuery({ projectId: server.projectId, scenarioId: sc.id, position, theme, locale: opts.locale, content: opts.content, font: opts.font, stroke: opts.stroke, ...(opts.viewport ? { viewport: opts.viewport } : {}) });
131
+ const q = new URLSearchParams(q0);
132
+ for (const [key, value] of Object.entries(geometryQuery(opts)))
133
+ q.set(key, value);
124
134
  await page.goto(`${server.url}?${q}`, { waitUntil: 'domcontentloaded' });
125
135
  await page.waitForFunction(() => window.__JOPLO_READY__ === true, null, { timeout: 60000 });
126
136
  const err = await page.evaluate(() => window.__JOPLO_ERROR__ ?? null);
127
137
  if (err)
128
138
  throw new JoploError('RENDER_FAILED', `Render route reported an error: ${err}`);
129
139
  const report = (await page.evaluate(`(${COLLECT_REPORT})(${JSON.stringify({ nextTargetId, theme })})`));
130
- const png = await page.locator(opts.viewport ? '[data-jshot]' : '[data-jrender]').screenshot({ type: 'png', animations: 'disabled' });
140
+ const png = await capture(page, opts.viewport ? '[data-jshot]' : '[data-jrender]', opts.crop);
131
141
  fs.mkdirSync(path.dirname(out), { recursive: true });
132
142
  if (opts.overwrite)
133
143
  fs.writeFileSync(out, png);
@@ -149,11 +159,12 @@ export async function renderStep(opts) {
149
159
  box: { x: 0, y: 0, width: 0, height: 0 },
150
160
  });
151
161
  });
162
+ const audit = opts.auditLayout ? writeLayoutReport(layoutReportPath(out), [{ ...await auditLayout(page, layoutAuditOptions(opts.auditLayout), opts.crop), phases: ['static-final'], atMs: null, timeBasis: 'static-final-state', scenarioId: sc.id, position, stepId: sc.steps[position - 1]?.id ?? null, workId: sc.workId, evidence: out }], opts.overwrite) : undefined;
152
163
  const elements = [...report.elements, ...hidden];
153
164
  const warnings = [...report.warnings];
154
165
  if (nextTargetId && findNode(scene, nextTargetId) && !elements.find((e) => e.id === nextTargetId && e.visible))
155
166
  warnings.push(`Next action target ${nextTargetId} is not visible in the stage`);
156
- return { path: out, sceneId: scene.id, position, elements, warnings, scale: opts.scale ?? 1 };
167
+ return { ...(audit ? { audit } : {}), path: out, sceneId: scene.id, position, elements, warnings, scale: opts.scale ?? 1 };
157
168
  }
158
169
  finally {
159
170
  await browser?.close().catch(() => undefined);
@@ -196,11 +207,14 @@ export async function renderSheet(opts) {
196
207
  for (let position = 0; position <= sc.steps.length; position++) {
197
208
  const state = stateAt(project, sc.id, position);
198
209
  const scene = project.scenes[displaySceneId(project, sc.id, position)];
199
- const stage = STAGE_SIZE[scene.viewport === 'mobile' ? 'mobile' : 'desktop'];
210
+ const stage = opts.logicalViewport ?? STAGE_SIZE[scene.viewport === 'mobile' ? 'mobile' : 'desktop'];
200
211
  const next = state.completed ? undefined : sc.steps[position];
201
212
  const nextTargetId = next && 'target' in next.action ? next.action.target : null;
202
213
  const page = await browser.newPage({ viewport: { width: stage.width, height: stage.height }, deviceScaleFactor: 1, reducedMotion: 'reduce' });
203
- const q = renderQuery({ projectId: server.projectId, scenarioId: sc.id, position, theme, locale: opts.locale, content: opts.content, font: opts.font, stroke: opts.stroke });
214
+ const q0 = renderQuery({ projectId: server.projectId, scenarioId: sc.id, position, theme, locale: opts.locale, content: opts.content, font: opts.font, stroke: opts.stroke });
215
+ const q = new URLSearchParams(q0);
216
+ for (const [key, value] of Object.entries(geometryQuery(opts)))
217
+ q.set(key, value);
204
218
  await page.goto(`${server.url}?${q}`, { waitUntil: 'domcontentloaded' });
205
219
  await page.waitForFunction(() => window.__JOPLO_READY__ === true, null, { timeout: 60000 });
206
220
  const err = await page.evaluate(() => window.__JOPLO_ERROR__ ?? null);
@@ -209,14 +223,14 @@ export async function renderSheet(opts) {
209
223
  const report = (await page.evaluate(`(${COLLECT_REPORT})(${JSON.stringify({ nextTargetId, theme })})`));
210
224
  for (const w of report.warnings)
211
225
  warnings.push(`Step ${position}: ${w}`);
212
- const png = await page.locator('[data-jrender]').screenshot({ type: 'png', animations: 'disabled' });
226
+ const png = await capture(page, '[data-jrender]', opts.crop);
213
227
  await page.close();
214
228
  const step = position > 0 ? sc.steps[position - 1] : undefined;
215
229
  cells.push({
216
230
  png: png.toString('base64'),
217
231
  label: position === 0 ? '0 · start' : `${position} · ${step.kind}`,
218
232
  caption: step?.caption ?? sc.description ?? sc.name,
219
- voice: step?.narrate ?? step?.say ?? '',
233
+ voice: step ? narrationText(step, step.caption) : '',
220
234
  });
221
235
  }
222
236
  const html = `<!doctype html><meta charset="utf-8"><style>
@@ -1,5 +1,6 @@
1
1
  /** Explicit local-resource generation. No network before per-item confirmation. */
2
2
  export declare function generateResources(directory: string, opts?: {
3
+ work?: string;
3
4
  dryRun?: boolean;
4
5
  allowSpend?: boolean;
5
6
  confirm?: (message: string) => Promise<boolean>;
@@ -1,3 +1,4 @@
1
+ import { JoploError, mediaResourceIds, nodeResourceIds } from '@joplo-app/core';
1
2
  import { createServer } from 'vite';
2
3
  import { compileProject } from "./project.js";
3
4
  import { realProjectDir, joploProjectPlugin, locateWebAssets, kitAliases } from "./vite-shared.js";
@@ -6,11 +7,31 @@ export async function generateResources(directory, opts = {}) {
6
7
  const projectDir = realProjectDir(directory), web = locateWebAssets();
7
8
  const loader = await createServer({ configFile: false, envDir: false, root: projectDir, logLevel: 'silent', appType: 'custom', resolve: { alias: kitAliases(web, projectDir) }, plugins: [joploProjectPlugin(projectDir, web)], server: { middlewareMode: true, hmr: false, watch: null }, optimizeDeps: { noDiscovery: true, include: [] } });
8
9
  try {
9
- const compiled = await compileProject(loader, projectDir, 'dev');
10
+ const compiled = await compileProject(loader, projectDir, 'dev', { work: opts.work });
10
11
  if (!compiled.project || !compiled.resources || compiled.diagnostics.some(d => d.severity === 'error'))
11
- throw new Error('Project compilation failed; run joplo check for diagnostics.');
12
+ throw new JoploError(compiled.diagnostics.some(d => d.code === 'WORK_NOT_FOUND') ? 'NOT_FOUND' : 'INVALID_SCHEMA', `Project compilation failed: ${compiled.diagnostics.filter(d => d.severity === 'error').map(d => `${d.code}: ${d.message}`).join('; ')}. Shared sources and referenced dependencies must be valid in the selected scope.`, { diagnostics: compiled.diagnostics });
12
13
  const { host, requests } = compiled.resources, results = [];
14
+ // Shared routes still compile, but an unused route must not enlarge a work's spending plan.
15
+ const used = mediaResourceIds(compiled.project);
16
+ const scenes = new Set();
17
+ for (const scenario of Object.values(compiled.project.scenarios)) {
18
+ scenes.add(scenario.initial.sceneId);
19
+ for (const step of scenario.steps)
20
+ for (const effect of step.effects)
21
+ if (effect.type === 'navigate')
22
+ scenes.add(effect.sceneId);
23
+ }
24
+ for (const work of Object.values(compiled.project.works))
25
+ for (const layer of Object.values(work.layers))
26
+ scenes.add(layer.sceneId);
27
+ for (const [id, scene] of Object.entries(compiled.project.scenes))
28
+ if (scene.workId && compiled.project.works[scene.workId])
29
+ scenes.add(id);
30
+ for (const id of scenes)
31
+ nodeResourceIds(compiled.project.scenes[id], used);
13
32
  for (const request of requests) {
33
+ if (opts.work && !used.has(request.id))
34
+ continue;
14
35
  const description = await host.describe(request);
15
36
  if (!description.persistent)
16
37
  continue;
@@ -0,0 +1,76 @@
1
+ import type { AudioRegion } from '@joplo-app/kit/plugin';
2
+ /** Versioned actual-playback observation schema. Times are milliseconds, never outline estimates. */
3
+ export type TimelineStep = {
4
+ scenarioId: string;
5
+ stepId: string;
6
+ position: number;
7
+ commitMs: number;
8
+ outputCommitMs: number;
9
+ endMs: number;
10
+ outputEndMs: number;
11
+ camera: unknown;
12
+ media: unknown;
13
+ text: unknown;
14
+ };
15
+ export type TimelineMediaEvent = {
16
+ track: string;
17
+ action: 'play' | 'stop' | 'seek' | 'volume';
18
+ engineMs: number;
19
+ outputMs: number;
20
+ resource: string;
21
+ offsetMs: number;
22
+ volume: number;
23
+ fadeMs: number;
24
+ snapshot: Record<string, unknown>;
25
+ };
26
+ export type PlaybackTimeline = {
27
+ completion?: {
28
+ completed: boolean;
29
+ scenarioId: string | null;
30
+ engineMs: number;
31
+ outputMs: number;
32
+ };
33
+ mediaEvents: TimelineMediaEvent[];
34
+ assets?: {
35
+ id: string;
36
+ kind: 'narration' | 'media';
37
+ file: string;
38
+ audioInfo?: AudioRegion;
39
+ }[];
40
+ steps: TimelineStep[];
41
+ chapters: {
42
+ scenarioId: string;
43
+ startMs: number;
44
+ endMs: number;
45
+ }[];
46
+ schemaVersion: 1;
47
+ origin: 'playback';
48
+ timing: {
49
+ sampleToleranceMs: number;
50
+ outputOriginMs: number;
51
+ };
52
+ events: PlaybackEvent[];
53
+ };
54
+ export type PlaybackEvent = {
55
+ at: number;
56
+ engineMs: number;
57
+ outputMs: number;
58
+ scenarioId?: string | null;
59
+ position?: number;
60
+ stepId?: string | null;
61
+ [key: string]: unknown;
62
+ };
63
+ export type RawTimeline = {
64
+ completed?: boolean;
65
+ schemaVersion: 1;
66
+ startedAt: number | null;
67
+ events: (Record<string, unknown> & {
68
+ at: number;
69
+ engineMs: number;
70
+ })[];
71
+ };
72
+ export declare function playbackTimeline(raw: RawTimeline, outputOriginMs?: number, sampleToleranceMs?: number): PlaybackTimeline;
73
+ /** Accumulated integer targets avoid ceil(1000 / fps) drift in Playwright runFor. */
74
+ export declare function frameTime(index: number, fps: number): number;
75
+ /** Make the timeline useful after its temporary recording server has closed. Only referenced audio is copied. */
76
+ export declare function persistTimeline(file: string, timeline: PlaybackTimeline, mediaAssets: Readonly<Record<string, string>>, baseUrl: string, overwrite?: boolean, localToken?: string, mediaInfo?: Readonly<Record<string, AudioRegion>>): Promise<void>;
@@ -0,0 +1,143 @@
1
+ import { AudioRegionSchema } from '@joplo-app/core';
2
+ import { writeOutput } from "./output-file.js";
3
+ export function playbackTimeline(raw, outputOriginMs = raw.startedAt ?? 0, sampleToleranceMs = 50) {
4
+ const steps = [], chapters = [];
5
+ const ended = new Set(), dwelled = new Set();
6
+ for (const e of raw.events) {
7
+ const sid = typeof e.scenarioId === 'string' ? e.scenarioId : null;
8
+ if (!sid)
9
+ continue;
10
+ if (chapters.at(-1)?.scenarioId !== sid) {
11
+ if (chapters.length)
12
+ chapters.at(-1).endMs = e.engineMs;
13
+ chapters.push({ scenarioId: sid, startMs: e.engineMs, endMs: e.engineMs });
14
+ }
15
+ chapters.at(-1).endMs = e.engineMs;
16
+ if (typeof e.stepId === 'string' && !steps.some(s => s.stepId === e.stepId)) {
17
+ if (steps.length && !ended.has(steps.at(-1).stepId)) {
18
+ steps.at(-1).endMs = e.engineMs;
19
+ steps.at(-1).outputEndMs = e.at - outputOriginMs;
20
+ }
21
+ steps.push({ scenarioId: sid, stepId: e.stepId, position: Number(e.position), commitMs: e.engineMs, outputCommitMs: e.at - outputOriginMs, endMs: e.engineMs, outputEndMs: e.at - outputOriginMs, camera: e.camera, media: e.media, text: e.text });
22
+ }
23
+ const current = steps.at(-1);
24
+ if (current && !ended.has(current.stepId)) {
25
+ current.endMs = e.engineMs;
26
+ current.outputEndMs = e.at - outputOriginMs;
27
+ if (e.dwell && e.stepId === current.stepId)
28
+ dwelled.add(current.stepId);
29
+ if ((dwelled.has(current.stepId) && e.dwell === null && e.activeStep === null) || (e.position === current.position && e.activeStep === e.position) || e.playing === false)
30
+ ended.add(current.stepId);
31
+ }
32
+ }
33
+ const mediaEvents = [];
34
+ let previous = {}, previousCommit = '';
35
+ for (const e of raw.events) {
36
+ if (!e.media || typeof e.media !== 'object')
37
+ continue;
38
+ const key = `${e.scenarioId}:${e.position}`;
39
+ if (key === previousCommit)
40
+ continue;
41
+ previousCommit = key;
42
+ const current = e.media;
43
+ const emit = (track, action, value, fadeMs = 0) => mediaEvents.push({ track, action, engineMs: e.engineMs, outputMs: e.at - outputOriginMs, resource: String(value.resource), offsetMs: Number(value.offsetMs ?? 0), volume: Number(value.volume ?? 1), fadeMs, snapshot: value });
44
+ for (const [track, value] of Object.entries(current)) {
45
+ const before = previous[track];
46
+ if (!before || before.resource !== value.resource || before.startEventId !== value.startEventId)
47
+ emit(track, 'play', value, Number(value.fadeInMs ?? 0));
48
+ else if (value.startOffsetMs !== undefined && value.startOffsetMs !== before.startOffsetMs)
49
+ emit(track, 'seek', value, Number(value.fadeInMs ?? 0));
50
+ if (value.stopAfterMs !== undefined && before?.stopAfterMs === undefined)
51
+ emit(track, 'stop', value, Number(value.stopAfterMs));
52
+ else if (before && value.volume !== before.volume && value.stopAfterMs === undefined)
53
+ emit(track, 'volume', value);
54
+ }
55
+ for (const [track, value] of Object.entries(previous))
56
+ if (!current[track] && value.stopAfterMs === undefined && value.endAfterMs === undefined)
57
+ emit(track, 'stop', value);
58
+ previous = current;
59
+ }
60
+ const final = raw.events.at(-1);
61
+ return { completion: { completed: raw.completed ?? false, scenarioId: typeof final?.scenarioId === 'string' ? final.scenarioId : null, engineMs: final?.engineMs ?? 0, outputMs: final ? final.at - outputOriginMs : 0 }, mediaEvents, steps, chapters, schemaVersion: 1, origin: 'playback', timing: { sampleToleranceMs, outputOriginMs }, events: raw.events.map(e => ({ ...e, at: e.at - (raw.startedAt ?? 0), outputMs: e.at - outputOriginMs, ...(typeof e.endAt === 'number' ? { endAt: e.endAt - (raw.startedAt ?? 0), outputEndMs: e.endAt - outputOriginMs } : {}) })) };
62
+ }
63
+ /** Accumulated integer targets avoid ceil(1000 / fps) drift in Playwright runFor. */
64
+ export function frameTime(index, fps) { return Math.round(index * 1000 / fps); }
65
+ /** Make the timeline useful after its temporary recording server has closed. Only referenced audio is copied. */
66
+ export async function persistTimeline(file, timeline, mediaAssets, baseUrl, overwrite = false, localToken, mediaInfo = {}) {
67
+ const fs = await import('node:fs/promises'), path = await import('node:path'), crypto = await import('node:crypto');
68
+ const directory = `${file.replace(/\.json$/i, '')}.assets`, assets = [];
69
+ const copy = async (id, kind, source, audioInfo) => {
70
+ const url = new URL(source, baseUrl);
71
+ let response;
72
+ if (localToken && url.origin === new URL(baseUrl).origin && /^\/__joplo\/p\/[^/]+\/resources\//.test(url.pathname)) {
73
+ const resolved = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', 'x-joplo-token': localToken }, body: '{}' });
74
+ if (!resolved.ok)
75
+ throw new Error(`Timeline media resource ${id} could not be resolved (${resolved.status})`);
76
+ const result = await resolved.json();
77
+ audioInfo = result.audio ?? audioInfo;
78
+ if (!result.url?.startsWith('data:'))
79
+ throw new Error(`Timeline media resource ${id} is unavailable; prepare local resources first`);
80
+ response = await fetch(result.url);
81
+ }
82
+ else
83
+ response = await fetch(url);
84
+ if (!response.ok)
85
+ throw new Error(`Timeline audio asset ${id} could not be read (${response.status})`);
86
+ const bytes = Buffer.from(await response.arrayBuffer());
87
+ const mime = response.headers.get('content-type') ?? '';
88
+ const suffix = mime.includes('wav') ? '.wav' : mime.includes('ogg') ? '.ogg' : mime.includes('flac') ? '.flac' : mime.includes('webm') ? '.webm' : '.mp3';
89
+ const name = crypto.createHash('sha256').update(bytes).digest('hex') + suffix;
90
+ await fs.mkdir(directory, { recursive: true });
91
+ const destination = path.join(directory, name);
92
+ let existing = null;
93
+ try {
94
+ existing = await fs.readFile(destination);
95
+ }
96
+ catch (e) {
97
+ if (e.code !== 'ENOENT')
98
+ throw e;
99
+ }
100
+ const valid = existing?.length === bytes.length && crypto.createHash('sha256').update(existing).digest('hex') === name.split('.')[0];
101
+ if (existing && !valid && !overwrite)
102
+ throw new Error(`Timeline asset ${name} is incomplete or corrupt; use --overwrite to replace it`);
103
+ if (!valid) {
104
+ try {
105
+ await writeOutput(destination, bytes, !!existing && overwrite);
106
+ }
107
+ catch (e) {
108
+ if (e.code !== 'EEXIST')
109
+ throw e;
110
+ const raced = await fs.readFile(destination);
111
+ if (raced.length !== bytes.length || crypto.createHash('sha256').update(raced).digest('hex') !== name.split('.')[0])
112
+ throw new Error(`Concurrent timeline asset ${name} failed content validation`);
113
+ }
114
+ }
115
+ const relative = `${path.basename(directory)}/${name}`;
116
+ if (!assets.some(a => a.id === id && a.kind === kind))
117
+ assets.push({ id, kind, file: relative, ...(audioInfo ? { audioInfo } : {}) });
118
+ return relative;
119
+ };
120
+ const voiceFiles = new Map();
121
+ for (const event of timeline.events)
122
+ if (event.type === 'narration' && event.source === 'clip' && typeof event.file === 'string') {
123
+ const reference = event.file;
124
+ const source = reference.startsWith('joplo-resource:') ? mediaAssets[reference.slice(15)] : reference;
125
+ if (!source)
126
+ throw new Error('Explicit narration audio is unavailable; prepare the resource before exporting');
127
+ if (!voiceFiles.has(source))
128
+ voiceFiles.set(source, await copy(String(event.clipId ?? source), 'narration', source, event.audioInfo ? AudioRegionSchema.parse(event.audioInfo) : undefined));
129
+ event.file = voiceFiles.get(source);
130
+ }
131
+ const resources = new Set();
132
+ for (const event of timeline.events)
133
+ if (event.media && typeof event.media === 'object')
134
+ for (const track of Object.values(event.media))
135
+ if (track.resource)
136
+ resources.add(track.resource);
137
+ for (const id of resources)
138
+ if (mediaAssets[id])
139
+ await copy(id, 'media', mediaAssets[id], mediaInfo[id]);
140
+ timeline.assets = assets;
141
+ await fs.mkdir(path.dirname(file), { recursive: true });
142
+ await writeOutput(file, JSON.stringify(timeline, null, 2), overwrite);
143
+ }
@@ -0,0 +1,2 @@
1
+ /** Optional local encoder. Capture and sample-clock calibration always happen before conversion. */
2
+ export declare function encodeMp4(input: string, output: string, overwrite?: boolean): Promise<void>;
@@ -0,0 +1,12 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { JoploError } from '@joplo-app/core';
3
+ /** Optional local encoder. Capture and sample-clock calibration always happen before conversion. */
4
+ export async function encodeMp4(input, output, overwrite = false) {
5
+ await new Promise((resolve, reject) => {
6
+ const child = spawn('ffmpeg', ['-nostdin', '-v', 'error', overwrite ? '-y' : '-n', '-i', input, '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-movflags', '+faststart', output], { stdio: ['ignore', 'ignore', 'pipe'] });
7
+ let stderr = '';
8
+ child.stderr.on('data', b => { stderr = (stderr + String(b)).slice(-16000); });
9
+ child.once('error', e => reject(new JoploError('EXPORT_FAILED', `MP4 needs local ffmpeg with H.264/AAC support: ${e.message}. Use .webm to export without it.`)));
10
+ child.once('close', code => code === 0 ? resolve() : reject(new JoploError('EXPORT_FAILED', `MP4 encoding failed (exit ${code}): ${stderr}`)));
11
+ });
12
+ }
@@ -5,7 +5,7 @@ export { kitAliases, locateWebAssets } from './web-assets.js';
5
5
  export declare function realProjectDir(dir: string): string;
6
6
  /** 不参与编译的项目子目录。 */
7
7
  export declare const IGNORED_DIRS: string[];
8
- export declare function isProjectSource(projectDir: string, file: string): boolean;
8
+ export declare function isProjectSource(projectDir: string, file: string, ignored?: readonly string[]): boolean;
9
9
  /**
10
10
  * 项目目录之外、不在 node_modules 里的源文件(例如一个仓库里多个 Joplo 项目共用的上层组件):
11
11
  * 最近的 tsconfig.json 声明了 jsxImportSource "@joplo-app/kit" 时,同样按 Joplo 的 JSX 运行时转译(#61)。
@@ -23,12 +23,12 @@ export function realProjectDir(dir) {
23
23
  }
24
24
  /** 不参与编译的项目子目录。 */
25
25
  export const IGNORED_DIRS = ['.joplo', 'dist', 'node_modules', '.git'];
26
- export function isProjectSource(projectDir, file) {
26
+ export function isProjectSource(projectDir, file, ignored = []) {
27
27
  if (!file.startsWith(projectDir + path.sep))
28
28
  return false;
29
29
  const rel = file.slice(projectDir.length + 1);
30
30
  const first = rel.split(path.sep)[0] ?? '';
31
- return !IGNORED_DIRS.includes(first);
31
+ return !IGNORED_DIRS.includes(first) && !ignored.some(p => rel.split(path.sep).join('/') === p || rel.split(path.sep).join('/').startsWith(p + '/'));
32
32
  }
33
33
  /** 读 tsconfig(允许注释与尾逗号),沿相对路径的 extends 找 compilerOptions.jsxImportSource。 */
34
34
  function tsconfigJsxSource(file, depth = 0) {
@@ -122,6 +122,7 @@ export declare class VoiceHub {
122
122
  /** cloud 请求的内容语言(D84):项目写了 locales 时是当前内容语言(没传时是默认语言);没写时不带,由云端按文字判断。 */
123
123
  private speechLocaleOf;
124
124
  /** dev IR 的草稿仍能本地播放,但不能把它的朗读文字发送给任何供应商。 */
125
+ private suppliedSegments;
125
126
  private draftSegments;
126
127
  /** /__joplo/p/:id/voice[/…];不认识的路径返回 false。 */
127
128
  handleProject(projectId: string, dir: string, project: Project | null, rest: string, req: http.IncomingMessage, res: http.ServerResponse, ctx: Ctx): Promise<boolean>;
@@ -252,6 +252,10 @@ export class VoiceHub {
252
252
  return project?.i18n ? (content ?? project.i18n.default) : null;
253
253
  }
254
254
  /** dev IR 的草稿仍能本地播放,但不能把它的朗读文字发送给任何供应商。 */
255
+ suppliedSegments(project, segments) {
256
+ const explicit = new Map(Object.values(project?.scenarios ?? {}).flatMap(sc => sc.steps.filter(st => st.audio).map(st => [st.id, st.audio])));
257
+ return segments.map(s => explicit.has(s.stepId) ? { ...s, audio: explicit.get(s.stepId) } : s);
258
+ }
255
259
  draftSegments(project, segments) {
256
260
  const privateIds = new Set(Object.values(project?.scenarios ?? {}).filter(s => project?.works[s.workId]?.draft).flatMap(s => s.steps.map(st => st.id)));
257
261
  return segments.some(s => privateIds.has(s.stepId));
@@ -302,7 +306,7 @@ export class VoiceHub {
302
306
  this.jobs.set(projectId, job);
303
307
  let summary;
304
308
  try {
305
- summary = await cache.generate(segs, content ?? (typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en'), resolved, this.store, {
309
+ summary = await cache.generate(this.suppliedSegments(project, segs), content ?? project?.i18n?.default ?? (typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'und'), resolved, this.store, {
306
310
  fetch: this.opts.fetch,
307
311
  signal: job.abort.signal,
308
312
  inflight: this.inflightOf(projectId),
@@ -338,6 +342,8 @@ export class VoiceHub {
338
342
  return ctx.send(400, { error: { code: 'USAGE', message: 'segment must be { stepId, text, role }' } }), true;
339
343
  if (this.draftSegments(project, [seg]))
340
344
  return ctx.send(403, { error: { code: 'USAGE', message: 'Draft narration stays on this computer. Remove draft: true before sending it to a voice service' } }), true;
345
+ if (this.suppliedSegments(project, [seg])[0]?.audio)
346
+ return ctx.send(409, { error: { code: 'AUDIO_PROVIDED', message: 'This step uses existing audio; no voice provider will be called' } }), true;
341
347
  const cache = new VoiceCache(dir);
342
348
  const content = contentLocaleOf(project, body.contentLocale);
343
349
  const resolved = await this.resolveFor(dir, project, content);
@@ -347,7 +353,7 @@ export class VoiceHub {
347
353
  // Joplo Cloud 朗读不在播放时现场生成(会花用户的字数):只有「生成缺少的音频」或 joplo voice 才请求云端;缺音频的步骤用浏览器朗读
348
354
  if (resolved.profile?.kind === 'cloud')
349
355
  return ctx.send(409, { error: { code: 'CLOUD_GENERATE_ONLY', message: 'Joplo Cloud narration is generated only with Generate missing audio (or npx joplo voice); this step uses the browser voice' } }), true;
350
- const p = cache.generateOne(seg, content ?? (typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en'), resolved, this.store, {
356
+ const p = cache.generateOne(seg, content ?? project?.i18n?.default ?? (typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'und'), resolved, this.store, {
351
357
  fetch: this.opts.fetch,
352
358
  inflight: this.inflightOf(projectId),
353
359
  cloud: this.opts.cloud,
@@ -21,13 +21,28 @@ export type VoiceRunOptions = {
21
21
  /** 托管朗读(CLI 的 cloud bridge 的 voice)。 */
22
22
  cloud?: CloudVoiceBridge;
23
23
  dryRun?: boolean;
24
+ /** Exact compiled work id; CLI resolves standalone entry keys without splitting ids. */
25
+ workId?: string;
26
+ scenarioId?: string;
24
27
  /** 只做这几种内容语言(必须是项目声明的);缺省全部。 */
25
28
  locales?: string[];
26
29
  onProgress?: (line: string) => void;
27
30
  /** 测试:OpenAI / ElevenLabs 的 fetch。 */
28
31
  fetch?: (url: string, init?: RequestInit) => Promise<Response>;
29
32
  };
33
+ /** Estimates use local cache only; remote Cloud cache hits can reduce the actual charge to zero. */
34
+ export type VoiceStepDetail = {
35
+ workId: string;
36
+ scenarioId: string;
37
+ stepId: string;
38
+ text: string;
39
+ chars: number;
40
+ missing: boolean;
41
+ estimatedBillableChars: number;
42
+ audio?: 'provided';
43
+ };
30
44
  export type VoiceRunLocale = {
45
+ details?: VoiceStepDetail[];
31
46
  locale: string | null;
32
47
  segments: number;
33
48
  missing: number;
@@ -67,5 +82,6 @@ export type VoiceRunResult = {
67
82
  } | null;
68
83
  };
69
84
  /** 选定方案的全部场景里,每一步要读的段(文字为空的跳过)。 */
70
- export declare function projectSegments(project: Project): Segment[];
85
+ export declare function voiceScenarioIds(project: Project, scope?: Pick<VoiceRunOptions, 'workId' | 'scenarioId'>): Set<string>;
86
+ export declare function projectSegments(project: Project, scope?: Pick<VoiceRunOptions, 'workId' | 'scenarioId'>): Segment[];
71
87
  export declare function generateProjectVoice(opts: VoiceRunOptions): Promise<VoiceRunResult>;