@joplo-app/server 0.7.1 → 0.7.3

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,14 @@
1
+ import { type Project, type Diagnostic, type VoiceConfig } from '@joplo-app/core';
2
+ export declare function audioDuration(bytes: Uint8Array): Promise<number | undefined>;
3
+ export declare function readAudioTiming(projectDir: string, project: Project, options?: {
4
+ voiceConfig?: VoiceConfig;
5
+ defaultProfile?: string | null;
6
+ home?: string;
7
+ }): Promise<{
8
+ diagnostics: Diagnostic[];
9
+ audioDurationFor: (url: string) => number | undefined;
10
+ voiceDurationFor: (stepId: string) => {
11
+ durationMs: number;
12
+ key: string;
13
+ } | undefined;
14
+ }>;
@@ -0,0 +1,66 @@
1
+ /** Read-only audio facts. Never generate resources, call a voice provider, or serialize local paths. */
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { Input, ALL_FORMATS, BufferSource } from 'mediabunny';
5
+ import { spokenLine, speakerRoleAt } from '@joplo-app/core';
6
+ import { joploHome } from "./home.js";
7
+ import { ProfileStore, VoiceCache, resolveVoices, voiceLocaleOf } from "./voice.js";
8
+ export async function audioDuration(bytes) {
9
+ const input = new Input({ formats: ALL_FORMATS, source: new BufferSource(bytes) });
10
+ try {
11
+ const track = await input.getPrimaryAudioTrack();
12
+ const ms = track ? await track.computeDuration() * 1000 : 0;
13
+ return Number.isFinite(ms) && ms > 0 ? ms : undefined;
14
+ }
15
+ finally {
16
+ input.dispose();
17
+ }
18
+ }
19
+ export async function readAudioTiming(projectDir, project, options = {}) {
20
+ const audio = new Map(), voice = new Map();
21
+ const diagnostics = [];
22
+ const ids = new Set(Object.values(project.scenarios).flatMap(sc => sc.steps.flatMap(st => [st.audio, st.holdFor?.audio].filter((x) => !!x))));
23
+ for (const token of ids) {
24
+ const url = project.mediaAssets?.[token.slice(15)];
25
+ // localResource metadata follows the existing inspect/prepared mechanism; do not ensure or fetch here.
26
+ if (!url?.startsWith('data:audio/'))
27
+ continue;
28
+ try {
29
+ const region = project.mediaInfo?.[token.slice(15)];
30
+ const ms = region ? region.contentFrames / region.sourceSampleRate * 1000 : await audioDuration(Buffer.from(url.slice(url.indexOf(',') + 1), 'base64'));
31
+ if (ms) {
32
+ audio.set(url, ms);
33
+ audio.set(token, ms);
34
+ }
35
+ else
36
+ throw new Error('no finite audio duration');
37
+ }
38
+ catch {
39
+ const at = Object.values(project.scenarios).flatMap(sc => sc.steps).find(st => st.audio === token || st.holdFor?.audio === token)?.source;
40
+ diagnostics.push({ code: 'AUDIO_INVALID', severity: 'error', source: 'structure', at, message: 'An explicitly supplied audio asset is undecodable or has no finite positive duration; no voice provider was called' });
41
+ }
42
+ }
43
+ const cache = new VoiceCache(projectDir), store = new ProfileStore(options.home ?? joploHome());
44
+ const resolved = resolveVoices(options.voiceConfig ?? project.voiceConfig, cache.selection(), store, voiceLocaleOf(project, null), options.defaultProfile, cache.pins(), cache.officialCloud());
45
+ for (const sc of Object.values(project.scenarios))
46
+ for (const [i, st] of sc.steps.entries()) {
47
+ if (st.holdFor?.kind !== 'voice' || st.audio || st.mute)
48
+ continue;
49
+ const line = spokenLine(st, st.caption, speakerRoleAt(project, sc.id, i + 1));
50
+ const plan = cache.plan({ stepId: st.id, ...line }, resolved);
51
+ const file = plan && cache.clipOf(plan.key);
52
+ if (!plan || !file)
53
+ continue;
54
+ const locale = project.i18n?.default ?? 'und';
55
+ const record = cache.read().clips[plan.key];
56
+ if (!record || record.fp !== plan.fp || record.text !== plan.text || record.locale !== locale)
57
+ continue;
58
+ try {
59
+ const ms = await audioDuration(await fs.readFile(path.join(cache.clipsDir, file)));
60
+ if (ms)
61
+ voice.set(st.id, { durationMs: ms, key: `${plan.key}:${locale}` });
62
+ }
63
+ catch { /* A missing/invalid cached clip is an estimate, never an implicit synthesis request. */ }
64
+ }
65
+ return { diagnostics, audioDurationFor: (url) => audio.get(url), voiceDurationFor: (stepId) => voice.get(stepId) };
66
+ }
package/dist/build.js CHANGED
@@ -132,7 +132,7 @@ export async function buildSite(opts) {
132
132
  });
133
133
  let compiled;
134
134
  try {
135
- compiled = await compileProject(loader, projectDir, opts.review === true ? 'review' : 'publish');
135
+ compiled = await compileProject(loader, projectDir, opts.review === true ? 'review' : 'publish', { voiceDefault: opts.voiceDefault });
136
136
  // 发布编译已跳过草稿与未选功能;范围的公开校验需要原始条目,避免误报不存在。
137
137
  if (opts.scope?.entryIds?.length || opts.scope?.scenarios?.length && compiled.diagnostics.some(d => d.code === 'WORK_DRAFT_SKIPPED')) {
138
138
  const dev = await compileProject(loader, projectDir, 'dev');
@@ -179,13 +179,26 @@ export async function buildSite(opts) {
179
179
  if (compiled.resources) {
180
180
  const resources = await inlineResources(project, compiled.resources.requests, compiled.resources.host);
181
181
  if (Object.keys(resources.assets).length)
182
- project = { ...project, mediaAssets: resources.assets, mediaInfo: resources.audioInfo };
182
+ project = { ...project, mediaAssets: { ...project.mediaAssets, ...resources.assets }, mediaInfo: { ...project.mediaInfo, ...resources.audioInfo } };
183
183
  compiled.diagnostics.push(...resources.diagnostics);
184
184
  mediaCredits = resources.credits;
185
185
  mediaLicenses = resources.licenses;
186
186
  if (resources.diagnostics.some(d => d.severity === 'error'))
187
187
  throw new JoploError('EXPORT_FAILED', 'Audio attribution is incomplete; no site was published', { diagnostics: resources.diagnostics });
188
188
  }
189
+ // Explicit speech must be deliverable in this selected publication. Timing-only
190
+ // holdFor.audio references may remain estimated and are not playback requirements.
191
+ const missingSpeech = Object.values(project.scenarios).flatMap(sc => sc.steps.flatMap(step => {
192
+ if (!step.audio)
193
+ return [];
194
+ const asset = project.mediaAssets?.[step.audio.slice('joplo-resource:'.length)];
195
+ if (typeof asset === 'string' && /^data:audio\/[^;,]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(asset))
196
+ return [];
197
+ return [{ severity: 'error', source: 'structure', code: asset === undefined ? 'AUDIO_ASSET_MISSING' : 'AUDIO_ASSET_INVALID',
198
+ at: step.source, message: `${step.id}: explicit narration audio is missing or is not a prepared audio asset. Prepare or repair it before building; no voice provider was called.` }];
199
+ }));
200
+ if (missingSpeech.length)
201
+ throw new JoploError('EXPORT_FAILED', 'Explicit narration audio is unavailable; no site was published', { diagnostics: missingSpeech });
189
202
  binaryAssets(project, { diagnostics: compiled.diagnostics });
190
203
  const inline = publishPayload(project, compiled.home);
191
204
  if (scope)
@@ -18,7 +18,7 @@ export type DevOptions = {
18
18
  };
19
19
  /** 单进程:同一个 JOPLO_HOME 下只有一个看板进程,同时服务多个项目(编译、热更新、选中、导出)。 */
20
20
  /**
21
- * url:项目在看板中的链接。attached = true 表示本机已有存活的看板,项目只是注册进去(没有启动第二个进程,close 不做事)。
21
+ * url:项目在看板中的链接。attached = true 表示本机已有存活的看板,项目加入该看板并等待初次编译完成(没有启动第二个进程,close 不做事)。
22
22
  */
23
23
  export type DevHandle = {
24
24
  url: string;
package/dist/dev.js CHANGED
@@ -250,7 +250,7 @@ export async function createHub(opts = {}) {
250
250
  localResources.delete(slot.id);
251
251
  resourceWarnings.set(slot.id, new Map());
252
252
  if (out.project && out.resources?.requests.length)
253
- out.project.mediaAssets = Object.fromEntries(out.resources.requests.map(r => [r.id, `/__joplo/p/${encodeURIComponent(slot.id)}/resources/${encodeURIComponent(r.id)}`]));
253
+ out.project.mediaAssets = { ...out.project.mediaAssets, ...Object.fromEntries(out.resources.requests.map(r => [r.id, `/__joplo/p/${encodeURIComponent(slot.id)}/resources/${encodeURIComponent(r.id)}`])) };
254
254
  if (out.project) {
255
255
  if (out.resources) {
256
256
  const resources = await inlineResources(out.project, out.resources.requests.filter(r => referencedResources(out.project).has(r.id)), out.resources.host);
@@ -677,6 +677,7 @@ export async function createHub(opts = {}) {
677
677
  if (typeof dir !== 'string' || !path.isAbsolute(dir))
678
678
  return sendJson(res, 400, { error: { code: 'USAGE', message: 'dir must be an absolute path to the project directory' } });
679
679
  const r = addProject(dir);
680
+ await r.slot?.ready;
680
681
  return sendJson(res, 200, { id: r.id, url: r.url });
681
682
  }
682
683
  const del = /^\/__joplo\/projects\/([^/]+)$/.exec(url.pathname);
@@ -854,7 +855,8 @@ export async function attachToRunning(home, projectDir, log, ownVersion = server
854
855
  method: 'POST',
855
856
  headers: { 'content-type': 'application/json', 'x-joplo-token': info.token },
856
857
  body: JSON.stringify({ dir: realProjectDir(projectDir) }),
857
- signal: AbortSignal.timeout(10000),
858
+ // Registration acknowledges the initial compilation, which can take longer than a ping.
859
+ signal: AbortSignal.timeout(120000),
858
860
  });
859
861
  const body = (await res.json().catch(() => null));
860
862
  if (!res.ok || !body?.url)
@@ -910,7 +912,8 @@ export async function startDev(opts) {
910
912
  }
911
913
  throw e;
912
914
  }
913
- const { url } = hub.addProject(projectDir);
915
+ const { url, slot } = hub.addProject(projectDir);
916
+ await slot?.ready;
914
917
  const cleanup = () => clearServerInfo(home, process.pid);
915
918
  process.once('exit', cleanup);
916
919
  if (opts.open)
package/dist/film.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { Page } from 'playwright-core';
1
2
  import type { FilmOptions, FilmResult, FilmCut, FilmStill, FilmBoundary, VideoOptions, VideoResult } from './contract.js';
2
3
  /** 单帧整屏突变:变化像素占比至少这么多,且是前后帧的 CUT_RATIO 倍以上(排除持续的快速运镜)。 */
3
4
  export declare const CUT_CHANGED = 0.3;
@@ -21,6 +22,7 @@ export declare function findCuts(samples: readonly Pick<Sample, 't' | 'changed'
21
22
  export declare function findStills(samples: readonly Pick<Sample, 't' | 'still' | 'scenarioId' | 'position'>[], minMs: number): FilmStill[];
22
23
  /** 纯函数:每次提交一步(或换场景)前后窗口里的最大相邻帧差,章节衔接是否硬切一眼可见。 */
23
24
  export declare function stepBoundaries(samples: readonly Pick<Sample, 't' | 'diff' | 'changed' | 'scenarioId' | 'position'>[], before?: number, after?: number): FilmBoundary[];
25
+ export declare function waitForSample(page: Page, atMs: number, timeoutMs?: number, signal?: AbortSignal): Promise<void>;
24
26
  export declare function renderFilm(opts: FilmOptions): Promise<FilmResult>;
25
27
  /** 视频:与看板导出相同的录制器(真实时间)。 */
26
28
  export declare function renderVideo(opts: VideoOptions): Promise<VideoResult>;
package/dist/film.js CHANGED
@@ -123,6 +123,35 @@ async function flush(page) {
123
123
  channel.port2.postMessage(0);
124
124
  })`);
125
125
  }
126
+ export async function waitForSample(page, atMs, timeoutMs = 10000, signal) {
127
+ const started = Date.now();
128
+ let stable;
129
+ try {
130
+ for (;;) {
131
+ if (signal?.aborted)
132
+ throw new JoploError('RENDER_FAILED', `Sample cancelled at ${atMs} ms`);
133
+ await flush(page);
134
+ const status = await page.evaluate(() => window.__JOPLO_RECORD__?.frameStatus?.() ?? { pending: 0, error: null });
135
+ if (status.error)
136
+ throw new JoploError('RENDER_FAILED', `Presentation failed at ${atMs} ms: ${status.error}`);
137
+ if (!status.pending) {
138
+ const revision = status.revision ?? 0;
139
+ if (stable === revision)
140
+ return;
141
+ stable = revision;
142
+ }
143
+ else
144
+ stable = undefined;
145
+ if (Date.now() - started >= timeoutMs)
146
+ throw new JoploError('RENDER_FAILED', `Presentation timed out at ${atMs} ms after ${timeoutMs} wall-clock ms (${status.pending} pending); complete or cancel frameReady tasks before capture`);
147
+ await page.waitForTimeout(5);
148
+ }
149
+ }
150
+ catch (error) {
151
+ await page.evaluate(() => window.__JOPLO_RECORD__?.cancelFrame?.()).catch(() => { });
152
+ throw error;
153
+ }
154
+ }
126
155
  function check(opts) {
127
156
  const out = path.resolve(opts.out);
128
157
  assertNotProjectData(opts.projectDir, out);
@@ -155,7 +184,7 @@ function recordUrl(base, projectId, project, o) {
155
184
  if (o.content !== undefined && !project.i18n?.locales.includes(o.content))
156
185
  throw new JoploError('USAGE', project.i18n ? `--content ${o.content} is not in config locales (${project.i18n.locales.join(', ')})` : `--content needs config({ locales }); this project has a single language`);
157
186
  const voice = o.voice ?? 'estimate';
158
- const q = new URLSearchParams({ render: '1', project: projectId, scenario: o.scenarioId, position: '0', theme: o.theme ?? project.theme ?? 'sketch', frame: '1', record: '1', ...(voice !== 'off' ? { voice } : {}), ...(o.chain ? { chain: '1' } : {}), ...(o.audio === false ? { audio: '0' } : {}), ...(o.locale ? { locale: o.locale } : {}), ...(o.content ? { content: o.content } : {}), ...(o.hide?.length ? { hide: o.hide.join(',') } : {}), ...geometryQuery(o), ...(o.canvas ? { w: String(o.canvas.width), h: String(o.canvas.height) } : {}) });
187
+ const q = new URLSearchParams({ render: '1', project: projectId, scenario: o.scenarioId, position: '0', theme: o.theme ?? project.theme ?? 'sketch', frame: '1', record: '1', ...(voice !== 'off' ? { voice } : {}), ...(o.chain ? { chain: '1' } : {}), ...(o.sampling ? { sampling: '1' } : {}), ...(o.audio === false ? { audio: '0' } : {}), ...(o.locale ? { locale: o.locale } : {}), ...(o.content ? { content: o.content } : {}), ...(o.hide?.length ? { hide: o.hide.join(',') } : {}), ...geometryQuery(o), ...(o.canvas ? { w: String(o.canvas.width), h: String(o.canvas.height) } : {}) });
159
188
  const device = project.scenes[displaySceneId(project, o.scenarioId, 0)]?.viewport === 'mobile' ? 'mobile' : 'desktop';
160
189
  return { url: `${base}?${q}`, size: o.logicalViewport ?? (o.noFrame ? VIEWPORT_SIZE[device] : EXPORT_SIZE[device]), device };
161
190
  }
@@ -219,7 +248,7 @@ async function samplePlayback(opts) {
219
248
  try {
220
249
  const audit = opts.auditLayout ? createLayoutAuditSession({ out, project, crop: opts.crop, options: opts.auditLayout, overwrite: opts.overwrite, sampleMs }) : null;
221
250
  const canvas = opts.width && opts.height ? { width: opts.width, height: opts.height } : opts.logicalViewport;
222
- const { url, size: defaultSize } = recordUrl(server.url, server.projectId, project, { ...opts, audio: false, voice: opts.voice ?? (opts.framesOnly ? 'real' : 'estimate'), ...(canvas ? { canvas } : {}) });
251
+ const { url, size: defaultSize } = recordUrl(server.url, server.projectId, project, { ...opts, sampling: true, audio: false, voice: opts.voice ?? (opts.framesOnly ? 'real' : 'estimate'), ...(canvas ? { canvas } : {}) });
223
252
  const size = canvas ?? defaultSize;
224
253
  browser = await launch(playwright);
225
254
  const ctx = await browser.newContext({ viewport: size, deviceScaleFactor: opts.framesOnly ? opts.frameScale ?? 1 : 0.5 });
@@ -284,6 +313,7 @@ async function samplePlayback(opts) {
284
313
  await page.clock.runFor(t - previousTime);
285
314
  previousTime = t;
286
315
  await flush(page);
316
+ await waitForSample(page, t);
287
317
  const p = await page.evaluate(() => window.__JOPLO_RECORD__.progress);
288
318
  if (p.error)
289
319
  throw new JoploError('RENDER_FAILED', `Playback failed at ${t} ms: ${p.error}`);
package/dist/index.d.ts CHANGED
@@ -24,3 +24,4 @@ export { assetUsage, type AssetUsageReport, type AssetUsageEntry, type AssetUsag
24
24
  export type { ExportCrop, FramesOptions, FilmOptions, FilmResult, VideoOptions, VideoResult } from './contract.js';
25
25
  export type { PlaybackTimeline, PlaybackEvent } from './timeline.js';
26
26
  export { auditLayout, createLayoutAuditSession, type LayoutAuditOptions, type LayoutFinding, type LayoutAuditSample } from './layout-audit.js';
27
+ export { readAudioTiming, audioDuration } from './audio-timing.js';
package/dist/index.js CHANGED
@@ -12,3 +12,4 @@ export { inspectResources, mediaDiagnostics } from "./media-check.js";
12
12
  export { watchConfigDiagnostics } from "./watch-config.js";
13
13
  export { assetUsage } from "./asset-usage.js";
14
14
  export { auditLayout, createLayoutAuditSession } from "./layout-audit.js";
15
+ export { readAudioTiming, audioDuration } from "./audio-timing.js";
@@ -28,6 +28,11 @@ export declare class LocalResources {
28
28
  info?: LocalResourceInfo;
29
29
  diagnostic?: Diagnostic;
30
30
  }>;
31
+ /** Read existing prepared metadata only; never generate resources or incur provider spend. */
32
+ prepared(request: ResourceRequest): Promise<{
33
+ bytes: number;
34
+ audio?: import('@joplo-app/kit/plugin').AudioRegion;
35
+ } | null>;
31
36
  ensure(request: ResourceRequest, limits?: {
32
37
  timeoutMs?: number;
33
38
  maxBytes?: number;
@@ -8,6 +8,11 @@ import crypto from 'node:crypto';
8
8
  import { spawn } from 'node:child_process';
9
9
  import { build } from 'vite';
10
10
  import { AudioRegionSchema, nodeResourceIds as referencedResources, mediaResourceIds } from '@joplo-app/core';
11
+ function encodedBudget(result, request) {
12
+ if (result.url?.startsWith('data:audio/') && (result.bytes ?? 0) > 4 * 1048576)
13
+ return { ...result, diagnostic: { severity: 'warning', source: 'structure', code: 'MEDIA_ENCODE_BUDGET', at: request.source, message: `${request.plugin}/${request.id}: encoded audio is ${result.bytes} bytes (${(result.bytes / 1048576).toFixed(2)} MiB), exceeding the independent 4 MiB encoded cache. Transcode large WAV/PCM to FLAC or another smaller supported format; the 50 MiB local artifact limit is not a playback budget.` } };
14
+ return result;
15
+ }
11
16
  const inflight = new Map();
12
17
  const digest = (s) => crypto.createHash('sha256').update(s).digest('hex');
13
18
  const LIMIT = 50 * 1024 * 1024;
@@ -144,9 +149,9 @@ export class LocalResources {
144
149
  const script = `import {pathToFileURL} from 'node:url';
145
150
  let s=''; for await(const c of process.stdin)s+=c; const r=JSON.parse(s);
146
151
  try { const c=(await import(pathToFileURL(r.entry).href)).default.compilers[r.compiler];
147
- process.stdout.write(JSON.stringify({info:await c.inspect(r.input,{directory:r.directory})}));
152
+ process.stdout.write(JSON.stringify({info:await c.inspect(r.input,{directory:r.directory,projectDir:r.projectDir})}));
148
153
  }catch(e){process.stdout.write(JSON.stringify({error:String(e.message)}));process.exitCode=1;}`;
149
- const child = spawn(process.execPath, ['--input-type=module', '-e', script], { cwd: job, stdio: ['pipe', 'pipe', 'ignore'], detached: process.platform !== 'win32' });
154
+ const child = spawn(process.execPath, ['--input-type=module', '-e', script], { cwd: job, env: compilerEnvironment(), stdio: ['pipe', 'pipe', 'ignore'], detached: process.platform !== 'win32' });
150
155
  let output = '', settled = false;
151
156
  const finish = (error, value) => {
152
157
  if (settled)
@@ -179,7 +184,7 @@ export class LocalResources {
179
184
  finish(e);
180
185
  } });
181
186
  child.stdin.on('error', () => { });
182
- child.stdin.end(JSON.stringify({ entry, compiler: request.compiler, input: request.input, directory: job }));
187
+ child.stdin.end(JSON.stringify({ entry, compiler: request.compiler, input: request.input, directory: job, projectDir: this.directory }));
183
188
  });
184
189
  const tmp = `${cache}.${crypto.randomUUID()}.tmp`;
185
190
  fs.writeFileSync(tmp, JSON.stringify(info));
@@ -194,6 +199,25 @@ export class LocalResources {
194
199
  return { diagnostic: { severity: 'warning', source: 'structure', code: 'LOCAL_RESOURCE_INSPECTION_FAILED', message: `${request.plugin}/${request.compiler}: ${e.message}`, at: request.source?.replace(this.directory + path.sep, '') ?? 'joplo.config.ts:1:1' } };
195
200
  }
196
201
  }
202
+ /** Read existing prepared metadata only; never generate resources or incur provider spend. */
203
+ async prepared(request) {
204
+ try {
205
+ const code = await this.bundle(request.plugin), description = await this.describe(request);
206
+ if (description.persistent)
207
+ return null;
208
+ const key = digest(JSON.stringify([request.plugin, request.compiler, code, request.input]));
209
+ const saved = JSON.parse(fs.readFileSync(path.join(this.directory, '.joplo', 'resources', `${key}.json`), 'utf8'));
210
+ if (!Number.isInteger(saved.bytes) || saved.bytes < 0 || typeof saved.url !== 'string')
211
+ return null;
212
+ const data = /^data:audio\/[^;,]+;base64,/.exec(saved.url);
213
+ if (!data)
214
+ return null;
215
+ return { bytes: Buffer.byteLength(saved.url.slice(data[0].length), 'base64'), ...(saved.audio ? { audio: AudioRegionSchema.parse(saved.audio) } : {}) };
216
+ }
217
+ catch {
218
+ return null;
219
+ }
220
+ }
197
221
  async ensure(request, limits = {}) {
198
222
  const warning = (code, message) => ({ diagnostic: { severity: code === 'LOCAL_RESOURCE_ATTRIBUTION_MISSING' ? 'error' : 'warning', source: 'structure', code, message: `${request.plugin}/${request.compiler}: ${message}`, at: request.source ? request.source.replace(this.directory + path.sep, '') : 'joplo.config.ts:1:1' } });
199
223
  try {
@@ -225,7 +249,7 @@ export class LocalResources {
225
249
  };
226
250
  const hit = cached();
227
251
  if (hit)
228
- return hit;
252
+ return encodedBudget(hit, request);
229
253
  const lock = `${cache}:${maxBytes}:${!!limits.allowSpend}:${limits.timeoutMs ?? 30000}`;
230
254
  const existing = inflight.get(lock);
231
255
  if (existing) {
@@ -238,7 +262,7 @@ export class LocalResources {
238
262
  try {
239
263
  const hit = cached();
240
264
  if (hit)
241
- return hit;
265
+ return encodedBudget(hit, request);
242
266
  const entry = path.join(dir, `${digest(code)}.mjs`);
243
267
  if (!fs.existsSync(entry)) {
244
268
  const tmp = `${entry}.${crypto.randomUUID()}.tmp`;
@@ -304,7 +328,7 @@ export class LocalResources {
304
328
  fs.writeFileSync(tmp, JSON.stringify({ url, bytes: result.bytes, audio: result.audio, credit: result.credit, license: result.license }));
305
329
  fs.renameSync(tmp, cache);
306
330
  }
307
- return { url, bytes: result.bytes, audio: result.audio, credit: result.credit, license: result.license };
331
+ return encodedBudget({ url, bytes: result.bytes, audio: result.audio, credit: result.credit, license: result.license }, request);
308
332
  }
309
333
  catch (e) {
310
334
  const err = e;
@@ -2,10 +2,14 @@ import { type Diagnostic, type Project } from '@joplo-app/core';
2
2
  import type { LocalResourceInfo, ResourceRequest } from '@joplo-app/kit/plugin';
3
3
  import type { LocalResources } from './local-resources.js';
4
4
  export declare function inspectResources(project: Project | null, requests: ResourceRequest[], host: LocalResources): Promise<{
5
- resourceInfo: Record<string, LocalResourceInfo>;
5
+ resourceInfo: Record<string, LocalResourceInfo & {
6
+ encodedBytes?: number;
7
+ }>;
6
8
  diagnostics: Diagnostic[];
7
9
  }>;
8
10
  /** Measure uninterrupted runs, not each individual step. Stop/replacement ends a run. */
9
11
  export declare function mediaDiagnostics(project: Project, info: Record<string, LocalResourceInfo>): Diagnostic[];
10
12
  /** PCM memory is charged per resource, including both sides of an active crossfade. */
11
- export declare function mediaBudgetDiagnostics(project: Project, info: Record<string, LocalResourceInfo | import('@joplo-app/kit/plugin').AudioRegion>): Diagnostic[];
13
+ export declare function mediaBudgetDiagnostics(project: Project, info: Record<string, (LocalResourceInfo | import('@joplo-app/kit/plugin').AudioRegion) & {
14
+ encodedBytes?: number;
15
+ }>): Diagnostic[];
@@ -7,8 +7,9 @@ export async function inspectResources(project, requests, host) {
7
7
  for (const request of requests)
8
8
  if (used.has(request.id)) {
9
9
  const result = await host.inspect(request);
10
- if (result.info)
11
- resourceInfo[request.id] = result.info;
10
+ const prepared = await host.prepared(request);
11
+ if (result.info || prepared)
12
+ resourceInfo[request.id] = { ...result.info, ...(prepared?.audio ? { ...prepared.audio, durationMs: prepared.audio.contentFrames / prepared.audio.sourceSampleRate * 1000 } : {}), ...(prepared ? { encodedBytes: prepared.bytes } : {}) };
12
13
  if (result.diagnostic)
13
14
  diagnostics.push(result.diagnostic);
14
15
  }
@@ -59,10 +60,20 @@ export function mediaDiagnostics(project, info) {
59
60
  /** PCM memory is charged per resource, including both sides of an active crossfade. */
60
61
  export function mediaBudgetDiagnostics(project, info) {
61
62
  const out = [], budget = 32 * 1024 * 1024;
63
+ const encodedSeen = new Set();
64
+ for (const sc of Object.values(project.scenarios))
65
+ for (const [position, snapshot, at] of [[0, sc.media, undefined], ...sc.steps.map((s, i) => [i + 1, s.media, s.source])]) {
66
+ const ids = [...new Set(Object.values(snapshot ?? {}).filter(t => (t.stopAfterMs ?? 1) > 0 && (t.endAfterMs ?? 1) > 0).map(t => t.resource))].sort();
67
+ const known = ids.filter(id => info[id]?.encodedBytes !== undefined), bytes = known.reduce((n, id) => n + info[id].encodedBytes, 0), key = ids.join(',');
68
+ if (bytes > 4 * 1048576 && !encodedSeen.has(key)) {
69
+ encodedSeen.add(key);
70
+ out.push({ code: 'MEDIA_ENCODE_BUDGET', severity: 'warning', source: 'structure', at, message: `${sc.id} position ${position}: planned simultaneous encoded audio [${ids.join(', ')}] needs ${bytes} bytes (${(bytes / 1048576).toFixed(2)} MiB), exceeding the 4 MiB encoded cache${known.length < ids.length ? '; additional resources unknown' : ''}. Transcode large WAV/PCM to lossless FLAC or another smaller supported format; the decoded 32 MiB budget is independent.` });
71
+ }
72
+ }
62
73
  for (const sc of Object.values(project.scenarios)) {
63
74
  const seen = new Set();
64
75
  for (const [position, snapshot, at] of [[0, sc.media, undefined], ...sc.steps.map((s, i) => [i + 1, s.media, s.source])]) {
65
- const ids = [...new Set(Object.values(snapshot ?? {}).filter(t => t.stopAfterMs === undefined || t.stopAfterMs > 0).map(t => t.resource))].sort();
76
+ const ids = [...new Set(Object.values(snapshot ?? {}).filter(t => (t.stopAfterMs === undefined || t.stopAfterMs > 0) && (t.endAfterMs === undefined || t.endAfterMs > 0)).map(t => t.resource))].sort();
66
77
  const key = ids.join(',');
67
78
  if (!key || seen.has(key))
68
79
  continue;
@@ -81,7 +92,7 @@ export function mediaBudgetDiagnostics(project, info) {
81
92
  const code = at48 > budget ? 'MEDIA_DECODE_BUDGET' : at96 > budget ? 'MEDIA_DECODE_HEADROOM' : null;
82
93
  if (code)
83
94
  out.push({ code, severity: 'warning', source: 'structure', at,
84
- message: `${sc.id} position ${position}: simultaneous audio [${ids.join(', ')}] needs ${(at48 / 1048576).toFixed(2)} MiB at 48 kHz and ${(at96 / 1048576).toFixed(2)} MiB at 96 kHz (32 MiB decoded budget${known < ids.length ? '; some resources unknown' : ''}). Shorten overlapping tracks or avoid crossfading them; actual device sample rate and decoder padding affect usage.` });
95
+ message: `${sc.id} position ${position}: planned simultaneous audio [${ids.join(', ')}] needs ${(at48 / 1048576).toFixed(2)} MiB at 48 kHz and ${(at96 / 1048576).toFixed(2)} MiB at 96 kHz (32 MiB decoded budget${known < ids.length ? '; some resources unknown' : ''}). Shorten overlapping tracks or avoid crossfading them; snapshot overlap is planned (actual narration can change retirement timing); device sample rate and decoder padding affect usage.` });
85
96
  }
86
97
  }
87
98
  return out;
package/dist/project.d.ts CHANGED
@@ -19,7 +19,10 @@ export type CompileOutcome = {
19
19
  };
20
20
  /** config({ plugins }) 里每个插件的运行时入口(编译器另外校验清单;这里只取存在的文件)。 */
21
21
  export declare function pluginRuntimesOf(plugins: unknown): Record<string, string>;
22
- export declare function compileProject(server: ViteDevServer, projectDir: string, mode: CompileMode): Promise<CompileOutcome>;
22
+ export declare function compileProject(server: ViteDevServer, projectDir: string, mode: CompileMode, options?: {
23
+ work?: string;
24
+ voiceDefault?: string | null;
25
+ }): Promise<CompileOutcome>;
23
26
  /** 让项目源文件在下次载入时重新转译、重新求值。 */
24
27
  export declare function invalidateProjectModules(server: ViteDevServer, projectDir: string): void;
25
28
  export { discoverFiles };
package/dist/project.js CHANGED
@@ -3,6 +3,7 @@
3
3
  * dev(看板、截图)与 build(发布站)共用这一条路径。
4
4
  */
5
5
  import fs from 'node:fs';
6
+ import { readAudioTiming } from "./audio-timing.js";
6
7
  import { watchConfigDiagnostics } from "./watch-config.js";
7
8
  import path from 'node:path';
8
9
  import { inspectResources, mediaDiagnostics } from "./media-check.js";
@@ -52,7 +53,7 @@ function jsxRuntimeMissing(e) {
52
53
  return /\.(tsx|jsx)$/.test(file) && !file.split(path.sep).includes('node_modules') ? file : false;
53
54
  }
54
55
  const JSX_HINT = "was compiled without Joplo's JSX runtime. TSX outside the project uses the JSX settings of its nearest tsconfig.json: give that folder a tsconfig.json with jsx: \"react-jsxdev\" and jsxImportSource: \"@joplo-app/kit\", or start the file with /** @jsxRuntime automatic */ /** @jsxImportSource @joplo-app/kit */";
55
- export async function compileProject(server, projectDir, mode) {
56
+ export async function compileProject(server, projectDir, mode, options = {}) {
56
57
  const errorAt = new Map(); // 载入失败的文件(绝对路径)→ 精确位置
57
58
  const importer = async (abs) => {
58
59
  try {
@@ -75,7 +76,7 @@ export async function compileProject(server, projectDir, mode) {
75
76
  throw e instanceof Error ? e : new Error(msg);
76
77
  }
77
78
  };
78
- const loaded = await loadAuthoring(projectDir, importer);
79
+ const loaded = await loadAuthoring(projectDir, importer, options);
79
80
  const rel = (abs) => path.relative(projectDir, abs).split(path.sep).join('/');
80
81
  const byRel = new Map([...errorAt].map(([abs, at]) => [rel(abs), at]));
81
82
  const seen = new Set();
@@ -139,16 +140,29 @@ export async function compileProject(server, projectDir, mode) {
139
140
  const checked = inspected;
140
141
  knownInfo.set(projectDir, new Map(requests.flatMap(request => checked.resourceInfo[request.id] ? [[requestKey(request), checked.resourceInfo[request.id]]] : [])));
141
142
  const resources = { requests, host };
142
- diagnostics.push(...inspected.diagnostics, ...(r.project ? mediaDiagnostics(r.project, inspected.resourceInfo) : []));
143
+ diagnostics.push(...inspected.diagnostics);
143
144
  const missing = Object.keys(r.project?.plugins ?? {}).filter((id) => !pluginRuntimes[id]);
144
145
  const extra = missing.map((id) => ({ severity: 'error', code: 'PLUGIN_RUNTIME_MISSING', message: `Plugin ${id}: runtime file not found; reinstall the plugin package`, source: 'reference', at: `${loaded.authoring.config.file}:1:1` }));
146
+ const timingAssets = { ...r.project?.mediaAssets };
147
+ const timingInfo = { ...r.project?.mediaInfo };
145
148
  for (const request of requests)
146
149
  if (referencedResources(r.project).has(request.id)) {
147
150
  const result = await resources.host.ensure(request);
148
151
  if (result.diagnostic)
149
152
  diagnostics.push(result.diagnostic);
153
+ if (result.url)
154
+ timingAssets[request.id] = result.url;
155
+ if (result.audio)
156
+ timingInfo[request.id] = result.audio;
150
157
  }
151
- return { watchIgnore: loaded.authoring.config.watch?.ignore, project: extra.length ? null : r.project, diagnostics: [...diagnostics, ...r.diagnostics, ...extra], home, pluginRuntimes, resources };
158
+ if (r.project && Object.values(r.project.scenarios).some(sc => sc.steps.some(st => st.audio || st.holdFor))) {
159
+ const timing = await readAudioTiming(projectDir, { ...r.project, mediaAssets: timingAssets, mediaInfo: timingInfo }, { voiceConfig: loaded.authoring.config.voice, defaultProfile: options.voiceDefault });
160
+ diagnostics.push(...timing.diagnostics);
161
+ r = compile(loaded.authoring, mode, { resourceInfo: inspected.resourceInfo, audioDurationFor: timing.audioDurationFor, voiceDurationFor: timing.voiceDurationFor });
162
+ }
163
+ if (r.project)
164
+ diagnostics.push(...mediaDiagnostics(r.project, inspected.resourceInfo));
165
+ return { watchIgnore: loaded.authoring.config.watch?.ignore, project: extra.length || diagnostics.some(d => d.severity === 'error') ? null : r.project, diagnostics: [...diagnostics, ...r.diagnostics, ...extra], home, pluginRuntimes, resources };
152
166
  }
153
167
  const requestKey = (request) => JSON.stringify([request.plugin, request.compiler, request.input]);
154
168
  /** 项目目录 → 上一次编译检查到的资源元数据(按请求内容)。只是让第一遍编译用得上的提示;每次编译仍会重新检查并核对。 */
@@ -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;
package/dist/timeline.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { AudioRegionSchema } from '@joplo-app/core';
1
2
  import { writeOutput } from "./output-file.js";
2
3
  export function playbackTimeline(raw, outputOriginMs = raw.startedAt ?? 0, sampleToleranceMs = 50) {
3
4
  const steps = [], chapters = [];
@@ -42,7 +43,7 @@ export function playbackTimeline(raw, outputOriginMs = raw.startedAt ?? 0, sampl
42
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 });
43
44
  for (const [track, value] of Object.entries(current)) {
44
45
  const before = previous[track];
45
- if (!before || before.resource !== value.resource)
46
+ if (!before || before.resource !== value.resource || before.startEventId !== value.startEventId)
46
47
  emit(track, 'play', value, Number(value.fadeInMs ?? 0));
47
48
  else if (value.startOffsetMs !== undefined && value.startOffsetMs !== before.startOffsetMs)
48
49
  emit(track, 'seek', value, Number(value.fadeInMs ?? 0));
@@ -119,9 +120,12 @@ export async function persistTimeline(file, timeline, mediaAssets, baseUrl, over
119
120
  const voiceFiles = new Map();
120
121
  for (const event of timeline.events)
121
122
  if (event.type === 'narration' && event.source === 'clip' && typeof event.file === 'string') {
122
- const source = event.file;
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');
123
127
  if (!voiceFiles.has(source))
124
- voiceFiles.set(source, await copy(String(event.clipId ?? source), 'narration', source));
128
+ voiceFiles.set(source, await copy(String(event.clipId ?? source), 'narration', source, event.audioInfo ? AudioRegionSchema.parse(event.audioInfo) : undefined));
125
129
  event.file = voiceFiles.get(source);
126
130
  }
127
131
  const resources = new Set();
@@ -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 ?? project?.i18n?.default ?? (typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'und'), 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);
@@ -39,6 +39,7 @@ export type VoiceStepDetail = {
39
39
  chars: number;
40
40
  missing: boolean;
41
41
  estimatedBillableChars: number;
42
+ audio?: 'provided';
42
43
  };
43
44
  export type VoiceRunLocale = {
44
45
  details?: VoiceStepDetail[];
package/dist/voice-run.js CHANGED
@@ -29,13 +29,32 @@ export function projectSegments(project, scope = {}) {
29
29
  sc.steps.forEach((st, i) => {
30
30
  const line = spokenLine(st, st.caption, speakerRoleAt(project, sc.id, i + 1));
31
31
  if (line.text)
32
- out.push({ stepId: st.id, text: line.text, role: line.role });
32
+ out.push({ stepId: st.id, ...line });
33
33
  });
34
34
  }
35
35
  return out;
36
36
  }
37
37
  export async function generateProjectVoice(opts) {
38
38
  voiceScenarioIds(opts.project, opts);
39
+ const supplied = projectSegments(opts.project, opts);
40
+ if (supplied.length && supplied.every(s => s.audio)) {
41
+ const declared = opts.project.i18n?.locales ?? [];
42
+ if ((opts.locales ?? []).some(l => !declared.includes(l)))
43
+ throw new VoiceError('INVALID', 'Unknown content language');
44
+ const locales = opts.project.i18n ? opts.locales?.length ? opts.locales : declared : [null];
45
+ const rows = locales.map(locale => {
46
+ const p = locale ? localizeProject(opts.project, locale) : opts.project;
47
+ const segments = projectSegments(p, opts);
48
+ const selected = voiceScenarioIds(p, opts), byId = new Map(segments.map(seg => [seg.stepId, seg]));
49
+ const details = Object.values(p.scenarios).filter(sc => selected.has(sc.id)).flatMap(sc => sc.steps.map(st => {
50
+ const seg = byId.get(st.id);
51
+ return { workId: sc.workId, scenarioId: sc.id, stepId: st.id, text: seg?.text ?? '', chars: 0, missing: !!seg?.audio && !p.mediaAssets?.[seg.audio.slice(15)], estimatedBillableChars: 0, ...(seg?.audio ? { audio: 'provided' } : {}) };
52
+ }));
53
+ const failed = details.filter(d => d.missing).map(d => ({ stepId: d.stepId, message: 'Explicit audio resource is not prepared; no voice provider was called' }));
54
+ return { locale, details, segments: segments.length, missing: 0, chars: 0, generated: 0, skipped: segments.length - failed.length, failed };
55
+ });
56
+ return { profile: { id: 'provided', name: 'Existing audio', kind: 'provided' }, source: null, dryRun: !!opts.dryRun, locales: rows, total: { segments: rows.reduce((n, r) => n + r.segments, 0), missing: 0, chars: 0, generated: 0, failed: rows.reduce((n, r) => n + r.failed.length, 0) }, quota: null, usageUrl: null, exhausted: null };
57
+ }
39
58
  const status = opts.cloud ? await opts.cloud.status().catch(() => null) : null;
40
59
  const live = status?.signedIn && status.voice ? status.voice : null;
41
60
  const store = new ProfileStore(opts.home ?? joploHome(), process.env, { catalog: () => live });
@@ -71,6 +90,7 @@ export async function generateProjectVoice(opts) {
71
90
  const locales = project.i18n ? (opts.locales?.length ? opts.locales : declared) : [null];
72
91
  let quota = live?.quota ? { ...live.quota } : null;
73
92
  const result = { profile: { id: base.profile.id, name: base.profile.name, kind: base.profile.kind }, source: base.source, dryRun: !!opts.dryRun, locales: [], total: { segments: 0, missing: 0, chars: 0, generated: 0, failed: 0 }, quota, usageUrl, exhausted: null };
93
+ let billableFailed = 0;
74
94
  for (const locale of locales) {
75
95
  const p = locale ? localizeProject(project, locale) : project;
76
96
  const resolved = resolveVoices(project.voiceConfig, selected, store, voiceLocaleOf(project, locale), fallback, cache.pins(), cache.officialCloud());
@@ -90,13 +110,15 @@ export async function generateProjectVoice(opts) {
90
110
  continue;
91
111
  }
92
112
  const planned = cache.plan(seg, resolved);
93
- const missing = !!planned && !cache.clipOf(planned.key);
113
+ const missing = seg.audio ? !p.mediaAssets?.[seg.audio.slice(15)] : !!planned && !cache.clipOf(planned.key);
94
114
  const estimatedBillableChars = missing && planned && !seen.has(planned.key) ? spokenChars(planned.text) : 0;
95
115
  if (planned)
96
116
  seen.add(planned.key);
97
- details.push({ workId: sc.workId, scenarioId: sc.id, stepId: st.id, text: seg.text, chars: spokenChars(seg.text), missing, estimatedBillableChars });
117
+ details.push({ workId: sc.workId, scenarioId: sc.id, stepId: st.id, text: seg.text, chars: seg.audio ? 0 : spokenChars(seg.text), missing, estimatedBillableChars, ...(seg.audio ? { audio: 'provided' } : {}) });
98
118
  }
99
- const row = { details, locale, segments: segments.length, missing: est.steps, chars: est.chars, generated: 0, skipped: 0, failed: [] };
119
+ const providedFailed = details.filter(d => d.audio === 'provided' && d.missing).map(d => ({ stepId: d.stepId, message: 'Explicit audio resource is not prepared; no voice provider was called' }));
120
+ const row = { details, locale, segments: segments.length, missing: est.steps, chars: est.chars, generated: 0, skipped: 0, failed: providedFailed };
121
+ result.total.failed += providedFailed.length;
100
122
  result.locales.push(row);
101
123
  result.total.segments += segments.length;
102
124
  result.total.missing += est.steps;
@@ -116,7 +138,8 @@ export async function generateProjectVoice(opts) {
116
138
  });
117
139
  row.generated = summary.generated;
118
140
  row.skipped = summary.skipped;
119
- row.failed = summary.failed;
141
+ row.failed.push(...summary.failed);
142
+ billableFailed += summary.failed.length;
120
143
  result.total.generated += summary.generated;
121
144
  result.total.failed += summary.failed.length;
122
145
  if (summary.quota) {
@@ -128,7 +151,7 @@ export async function generateProjectVoice(opts) {
128
151
  throw new VoiceError(summary.error.code, summary.error.message);
129
152
  }
130
153
  if (result.exhausted)
131
- result.exhausted.remainingSteps = result.total.missing - result.total.generated - result.total.failed;
154
+ result.exhausted.remainingSteps = Math.max(0, result.total.missing - result.total.generated - billableFailed);
132
155
  result.quota = quota;
133
156
  return result;
134
157
  }
package/dist/voice.d.ts CHANGED
@@ -257,6 +257,7 @@ export type Segment = {
257
257
  stepId: string;
258
258
  text: string;
259
259
  role: string | null;
260
+ audio?: string;
260
261
  };
261
262
  export type GenerateSummary = {
262
263
  total: number;
package/dist/voice.js CHANGED
@@ -639,6 +639,8 @@ export class VoiceCache {
639
639
  }
640
640
  /** 这一段的键与要用的音色;文字为空或没有供应商时为 null。 */
641
641
  plan(seg, resolved) {
642
+ if (seg.audio)
643
+ return null;
642
644
  const p = resolved.profile;
643
645
  const text = seg.text.replace(/\s+/g, ' ').trim();
644
646
  if (!p || !text)
@@ -672,6 +674,8 @@ export class VoiceCache {
672
674
  * inflight:同一个项目共用的“正在生成”表(片段键 → 结果)。批量生成与边放边生成传同一张表,同一段同时只请求一次,后来的等先来的结果(generated 为 false)。
673
675
  */
674
676
  async generateOne(seg, locale, resolved, store, opts = {}) {
677
+ if (seg.audio)
678
+ throw new VoiceError('INVALID', 'This line supplies existing audio; it must never call a voice provider');
675
679
  const p = resolved.profile;
676
680
  const j = this.plan(seg, resolved);
677
681
  if (!p || !j)
@@ -810,6 +814,8 @@ export async function reuseSharedVoice(projectDir, project, shared, store, devCo
810
814
  if (st.captionAuto && !st.say && !st.narrate)
811
815
  continue;
812
816
  const line = spokenLine(st, st.caption, speakerRoleAt(p, sc.id, i + 1));
817
+ if (line.audio)
818
+ continue;
813
819
  const fp = voiceFingerprint(voices, line.role, line.text);
814
820
  if (!fp || !line.text)
815
821
  continue;
@@ -868,6 +874,8 @@ export function bundleVoice(projectDir, project, outDir, store, devConfig, fallb
868
874
  for (const sc of Object.values(p.scenarios))
869
875
  sc.steps.forEach((st, i) => {
870
876
  const line = spokenLine(st, st.caption, speakerRoleAt(p, sc.id, i + 1));
877
+ if (line.audio)
878
+ return;
871
879
  const primary = voiceFingerprint(voices, line.role);
872
880
  if (!primary || !line.text)
873
881
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joplo-app/server",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
4
4
  "description": "Joplo 作品本地服务:dev 看板、build 静态发布站、render 截图,服务链接与嵌入交付",
5
5
  "license": "PolyForm-Shield-1.0.0",
6
6
  "type": "module",
@@ -15,9 +15,9 @@
15
15
  "dist"
16
16
  ],
17
17
  "dependencies": {
18
- "@joplo-app/core": "0.7.1",
19
- "@joplo-app/kit": "0.7.1",
20
- "@joplo-app/web": "0.7.1",
18
+ "@joplo-app/core": "0.7.3",
19
+ "@joplo-app/kit": "0.7.3",
20
+ "@joplo-app/web": "0.7.3",
21
21
  "@tailwindcss/vite": "4.3.4",
22
22
  "mediabunny": "1.65.2",
23
23
  "tailwindcss": "4.3.4",