@joplo-app/server 0.6.1 → 0.6.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.
- package/dist/contract.d.ts +26 -0
- package/dist/export.d.ts +32 -3
- package/dist/export.js +68 -10
- package/dist/film.js +59 -16
- package/dist/local-resources.js +3 -3
- package/dist/project.js +31 -4
- package/dist/vite-shared.d.ts +6 -0
- package/dist/vite-shared.js +37 -1
- package/package.json +4 -4
package/dist/contract.d.ts
CHANGED
|
@@ -199,9 +199,35 @@ export declare function renderFilm(opts: FilmOptions): Promise<FilmResult>;
|
|
|
199
199
|
/** 视频(`joplo render --video`):与看板导出同一个录制器(真实时间,webm)。 */
|
|
200
200
|
export type VideoOptions = Omit<RenderOptions, 'stepId' | 'viewport' | 'scope' | 'scale'> & {
|
|
201
201
|
chain?: boolean;
|
|
202
|
+
/**
|
|
203
|
+
* 输出分辨率(#55,两个都给或都不给):舞台原样居中放进这个画幅,四周是主题背景色,按比例放大或缩小保持清晰
|
|
204
|
+
* (例如 1920×1080、1080×1920)。缺省 = 舞台尺寸(电脑 1280×800,手机带外框)。
|
|
205
|
+
*/
|
|
206
|
+
width?: number;
|
|
207
|
+
height?: number;
|
|
208
|
+
/** 旁白(#56):real(缺省)= 已生成的音频混进音轨并按真实时长停留,没有音频的段按估算;estimate = 不出声、按估算时长;off = 不读旁白。 */
|
|
209
|
+
voice?: 'real' | 'estimate' | 'off';
|
|
210
|
+
/** 干净画面(#59):不画这些播放器元素。title 包括结束时的完成徽标。 */
|
|
211
|
+
hide?: ('cover' | 'cursor' | 'title' | 'subtitles')[];
|
|
212
|
+
/** 另存字幕(#59):SubRip 文件路径,时间对到视频时间轴。 */
|
|
213
|
+
srt?: string;
|
|
202
214
|
};
|
|
203
215
|
export type VideoResult = {
|
|
204
216
|
path: string;
|
|
205
217
|
durationMs: number;
|
|
218
|
+
/** 视频分辨率。 */
|
|
219
|
+
size: {
|
|
220
|
+
width: number;
|
|
221
|
+
height: number;
|
|
222
|
+
};
|
|
223
|
+
/** 写了字幕文件时的路径。 */
|
|
224
|
+
srt: string | null;
|
|
225
|
+
voice: {
|
|
226
|
+
mode: 'real' | 'estimate' | 'off'; /** 没有音频、按估算时长停留的段(只有 real 时有)。 */
|
|
227
|
+
missing: {
|
|
228
|
+
text: string;
|
|
229
|
+
role: string | null;
|
|
230
|
+
}[];
|
|
231
|
+
};
|
|
206
232
|
};
|
|
207
233
|
export declare function renderVideo(opts: VideoOptions): Promise<VideoResult>;
|
package/dist/export.d.ts
CHANGED
|
@@ -25,7 +25,24 @@ export type VideoJob = {
|
|
|
25
25
|
file: string | null;
|
|
26
26
|
error: string | null;
|
|
27
27
|
};
|
|
28
|
-
/**
|
|
28
|
+
/** 字幕的一条(秒,相对视频开头)。 */
|
|
29
|
+
export type VideoCue = {
|
|
30
|
+
start: number;
|
|
31
|
+
end: number;
|
|
32
|
+
text: string;
|
|
33
|
+
};
|
|
34
|
+
/** 录制结果(#56 #59):字幕时间轴(对到视频时间)与没有音频、按估算时长停留的旁白。 */
|
|
35
|
+
export type RecordOutcome = {
|
|
36
|
+
cues: VideoCue[];
|
|
37
|
+
voice: {
|
|
38
|
+
mode: 'estimate' | 'real' | 'off';
|
|
39
|
+
missing: {
|
|
40
|
+
text: string;
|
|
41
|
+
role: string | null;
|
|
42
|
+
}[];
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
/** 录制实现:报告进度,写好 out。测试可注入。size 是视口,也是视频分辨率(录屏按 CSS 像素取帧)。 */
|
|
29
46
|
export type VideoRecorder = (input: {
|
|
30
47
|
projectDir: string;
|
|
31
48
|
url: string;
|
|
@@ -38,7 +55,14 @@ export type VideoRecorder = (input: {
|
|
|
38
55
|
progress: (step: number) => void;
|
|
39
56
|
signal: AbortSignal; /** 最长录制时长(毫秒,默认 5 分钟)。 */
|
|
40
57
|
maxMs?: number;
|
|
41
|
-
}) => Promise<void>;
|
|
58
|
+
}) => Promise<RecordOutcome | void>;
|
|
59
|
+
/** 页面里记下的字幕变化 → 视频时间轴上的字幕条(originMs = 视频第 0 秒对应的页面时间)。纯函数。 */
|
|
60
|
+
export declare function videoCues(raw: readonly {
|
|
61
|
+
at: number;
|
|
62
|
+
text: string | null;
|
|
63
|
+
}[], originMs: number, endSeconds: number): VideoCue[];
|
|
64
|
+
/** SubRip 字幕文件。纯函数。 */
|
|
65
|
+
export declare function srt(cues: readonly VideoCue[]): string;
|
|
42
66
|
export type ExportDeps = {
|
|
43
67
|
/** 按项目解析 Playwright(托管运行时优先,其次项目里已有的)。 */
|
|
44
68
|
loadPlaywright: (projectDir: string) => Promise<PlaywrightModule>;
|
|
@@ -80,7 +104,12 @@ export declare function exportAppearance(body: unknown): {
|
|
|
80
104
|
font: AppearanceFont | null;
|
|
81
105
|
stroke: AppearanceStroke | null;
|
|
82
106
|
};
|
|
83
|
-
/**
|
|
107
|
+
/**
|
|
108
|
+
* 缺省的录制:渲染路由的录制模式(window.__JOPLO_RECORD__)。
|
|
109
|
+
*
|
|
110
|
+
* 开播前的准备(载入、字体、解码配乐与旁白)不进视频(#57):Playwright 有 page.screencast 时,prepare() 之后才开始录屏,
|
|
111
|
+
* 视频从封面淡出 / 第一步开始;项目自带的旧版 Playwright 没有它时退回 recordVideo(从建页开始录)。
|
|
112
|
+
*/
|
|
84
113
|
export declare function defaultRecorder(load: (projectDir: string) => Promise<PlaywrightModule>): VideoRecorder;
|
|
85
114
|
export declare class ExportHub {
|
|
86
115
|
private readonly opts;
|
package/dist/export.js
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
*
|
|
4
4
|
* - 图片:`POST /__joplo/p/<id>/export/image` `{ scenarioId, position, theme, font?, stroke? }` → PNG(当前步骤;尺寸跟随页面自己的 viewport,
|
|
5
5
|
* 手机页面带外框;D44 起不再选择设备;镜头用这一步的导演镜头)。Playwright 打开本看板的渲染路由(与 renderStep 同一条渲染路径),截取 `[data-jexport]`。
|
|
6
|
-
* - 视频(只在本机):`POST …/export/video` `{ scenarioId, theme, font?, stroke? }` → 202 `{ jobId }`(尺寸跟随场景起始页面的 viewport
|
|
6
|
+
* - 视频(只在本机):`POST …/export/video` `{ scenarioId, theme, font?, stroke?, voice? }` → 202 `{ jobId }`(尺寸跟随场景起始页面的 viewport;
|
|
7
|
+
* voice: true = 看板开着朗读,已生成的旁白混进音轨并按真实时长停留,#56);
|
|
7
8
|
* Playwright `recordVideo` 录下渲染路由的自动播放(含鼠标与字幕),保存为 `<项目>/exports/<场景>-<时间>.webm`。
|
|
8
9
|
* 进度:`GET …/export/video/events`(SSE,先发当前状态,之后每次变化一条,结束后关闭);`GET …/export/video` 取当前状态。
|
|
9
10
|
* 同一项目同时只能有一个视频任务(再提交返回 409);`DELETE …/export/video` 取消正在进行的任务(D55)。没有导出组件时图片返回 503 EXPORT_COMPONENT_MISSING、
|
|
@@ -34,6 +35,29 @@ export const EXPORT_SIZE = {
|
|
|
34
35
|
desktop: { width: 1280, height: 800 },
|
|
35
36
|
mobile: { width: 446 + 32, height: 934 + 32 },
|
|
36
37
|
};
|
|
38
|
+
/** 页面里记下的字幕变化 → 视频时间轴上的字幕条(originMs = 视频第 0 秒对应的页面时间)。纯函数。 */
|
|
39
|
+
export function videoCues(raw, originMs, endSeconds) {
|
|
40
|
+
const out = [];
|
|
41
|
+
for (let i = 0; i < raw.length; i++) {
|
|
42
|
+
const c = raw[i];
|
|
43
|
+
if (!c.text)
|
|
44
|
+
continue;
|
|
45
|
+
const start = Math.max(0, (c.at - originMs) / 1000);
|
|
46
|
+
const end = Math.min(endSeconds, i + 1 < raw.length ? (raw[i + 1].at - originMs) / 1000 : endSeconds);
|
|
47
|
+
if (end - start >= 0.05)
|
|
48
|
+
out.push({ start: Math.round(start * 1000) / 1000, end: Math.round(end * 1000) / 1000, text: c.text });
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
/** SubRip 字幕文件。纯函数。 */
|
|
53
|
+
export function srt(cues) {
|
|
54
|
+
const ts = (sec) => {
|
|
55
|
+
const ms = Math.max(0, Math.round(sec * 1000));
|
|
56
|
+
const p = (n, w = 2) => String(n).padStart(w, '0');
|
|
57
|
+
return `${p(Math.floor(ms / 3600000))}:${p(Math.floor(ms / 60000) % 60)}:${p(Math.floor(ms / 1000) % 60)},${p(ms % 1000, 3)}`;
|
|
58
|
+
};
|
|
59
|
+
return cues.map((c, i) => `${i + 1}\n${ts(c.start)} --> ${ts(c.end)}\n${c.text.replace(/\r?\n+/g, '\n')}\n`).join('\n');
|
|
60
|
+
}
|
|
37
61
|
const send = (res, status, body) => {
|
|
38
62
|
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
|
39
63
|
res.end(JSON.stringify(body));
|
|
@@ -60,7 +84,7 @@ function parseRequest(project, body, needPosition) {
|
|
|
60
84
|
const device = project.scenes[sceneId]?.viewport === 'mobile' ? 'mobile' : 'desktop';
|
|
61
85
|
// 主题(D51):请求里的主题名,没有或不合法时用项目配置的主题
|
|
62
86
|
const theme = typeof b.theme === 'string' && THEME_NAME.test(b.theme) ? b.theme : project.theme;
|
|
63
|
-
return { sc, position, device, look: { theme, ...exportAppearance(body), locale: exportLocale(b.locale), ...(exportLocale(b.contentLocale) ? { content: exportLocale(b.contentLocale) } : {}) } };
|
|
87
|
+
return { sc, position, device, look: { theme, ...exportAppearance(body), locale: exportLocale(b.locale), ...(exportLocale(b.contentLocale) ? { content: exportLocale(b.contentLocale) } : {}), ...(b.voice === true ? { voice: true } : {}) } };
|
|
64
88
|
}
|
|
65
89
|
const fileSafe = (s) => s.replace(/[^\w.-]+/g, '_').slice(0, 80) || 'scenario';
|
|
66
90
|
const stamp = (d = new Date()) => `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}-${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}${String(d.getSeconds()).padStart(2, '0')}`;
|
|
@@ -70,18 +94,35 @@ async function waitReady(page) {
|
|
|
70
94
|
if (err)
|
|
71
95
|
throw new JoploError('RENDER_FAILED', `Render route reported an error: ${err}`);
|
|
72
96
|
}
|
|
73
|
-
/**
|
|
97
|
+
/**
|
|
98
|
+
* 缺省的录制:渲染路由的录制模式(window.__JOPLO_RECORD__)。
|
|
99
|
+
*
|
|
100
|
+
* 开播前的准备(载入、字体、解码配乐与旁白)不进视频(#57):Playwright 有 page.screencast 时,prepare() 之后才开始录屏,
|
|
101
|
+
* 视频从封面淡出 / 第一步开始;项目自带的旧版 Playwright 没有它时退回 recordVideo(从建页开始录)。
|
|
102
|
+
*/
|
|
74
103
|
export function defaultRecorder(load) {
|
|
75
104
|
return async ({ projectDir, url, size, out, progress, signal, maxMs = 5 * 60_000 }) => {
|
|
76
105
|
const pw = await load(projectDir);
|
|
77
106
|
const browser = await launch(pw);
|
|
78
107
|
const tmp = fs.mkdtempSync(path.join(path.dirname(out), '.rec-'));
|
|
79
108
|
try {
|
|
80
|
-
|
|
81
|
-
|
|
109
|
+
let ctx = await browser.newContext({ viewport: size, deviceScaleFactor: 1 });
|
|
110
|
+
let page = await ctx.newPage();
|
|
111
|
+
const screencast = typeof page.screencast?.start === 'function';
|
|
112
|
+
if (!screencast) {
|
|
113
|
+
await ctx.close();
|
|
114
|
+
ctx = await browser.newContext({ viewport: size, deviceScaleFactor: 1, recordVideo: { dir: tmp, size } });
|
|
115
|
+
page = await ctx.newPage();
|
|
116
|
+
}
|
|
82
117
|
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
83
118
|
await waitReady(page);
|
|
84
119
|
await page.waitForTimeout(400);
|
|
120
|
+
await page.evaluate(() => window.__JOPLO_RECORD__.prepare?.());
|
|
121
|
+
const file = path.join(tmp, 'screen.webm');
|
|
122
|
+
if (screencast)
|
|
123
|
+
await page.screencast.start({ path: file, size });
|
|
124
|
+
// 视频第 0 秒对应的页面时间:录屏刚开始时(recordVideo 从建页开始录,近似为导航开始 = 0)
|
|
125
|
+
let origin = screencast ? await page.evaluate(() => performance.now()) : 0;
|
|
85
126
|
await page.evaluate(() => window.__JOPLO_RECORD__.play());
|
|
86
127
|
const t0 = Date.now();
|
|
87
128
|
for (;;) {
|
|
@@ -98,13 +139,25 @@ export function defaultRecorder(load) {
|
|
|
98
139
|
await page.waitForTimeout(150);
|
|
99
140
|
}
|
|
100
141
|
await page.waitForTimeout(900); // 停留在结果画面
|
|
142
|
+
const endAt = await page.evaluate(() => performance.now());
|
|
101
143
|
const calibrated = await page.evaluate(() => window.__JOPLO_RECORD__.calibrate?.() ?? false);
|
|
144
|
+
const page_ = await page.evaluate(() => { const r = window.__JOPLO_RECORD__; return { cues: r.cues?.() ?? [], voice: r.voice?.() ?? { mode: 'off', missing: [] }, flash: r.calibratedAt?.() ?? null }; });
|
|
102
145
|
const audio = await page.evaluate(() => window.__JOPLO_RECORD__.stopAudio?.() ?? null);
|
|
103
|
-
|
|
146
|
+
if (screencast)
|
|
147
|
+
await page.screencast.stop();
|
|
148
|
+
const video = screencast ? null : page.video();
|
|
104
149
|
await ctx.close();
|
|
105
|
-
if (
|
|
106
|
-
|
|
107
|
-
|
|
150
|
+
if (screencast) {
|
|
151
|
+
if (!fs.existsSync(file))
|
|
152
|
+
throw new JoploError('EXPORT_FAILED', 'The browser did not generate a video');
|
|
153
|
+
fs.renameSync(file, out);
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
if (!video)
|
|
157
|
+
throw new JoploError('EXPORT_FAILED', 'The browser did not generate a video');
|
|
158
|
+
await video.saveAs(out);
|
|
159
|
+
}
|
|
160
|
+
let endSeconds = (endAt - origin) / 1000;
|
|
108
161
|
if (audio) {
|
|
109
162
|
if (!calibrated)
|
|
110
163
|
throw new Error('Audio/video calibration unavailable');
|
|
@@ -115,11 +168,16 @@ export function defaultRecorder(load) {
|
|
|
115
168
|
const bytes = Buffer.from(audio.data, 'base64');
|
|
116
169
|
const timing = await recordedCalibration(probe, out, bytes);
|
|
117
170
|
await muxRecordedAudio(out, bytes, timing.offsetSeconds, { videoEnd: timing.videoPTS, audioEnd: timing.audioPTS, audioDurations: timing.audioDurations });
|
|
171
|
+
// 校准闪屏:页面时间 flash ↔ 视频时间 videoPTS,比录屏开始时的估计更准;视频在闪屏处截断
|
|
172
|
+
if (page_.flash !== null)
|
|
173
|
+
origin = page_.flash - timing.videoPTS * 1000;
|
|
174
|
+
endSeconds = timing.videoPTS;
|
|
118
175
|
}
|
|
119
176
|
finally {
|
|
120
177
|
await analysis.close();
|
|
121
178
|
}
|
|
122
179
|
}
|
|
180
|
+
return { cues: videoCues(page_.cues, origin, endSeconds), voice: page_.voice };
|
|
123
181
|
}
|
|
124
182
|
finally {
|
|
125
183
|
await browser.close().catch(() => undefined);
|
|
@@ -244,7 +302,7 @@ export class ExportHub {
|
|
|
244
302
|
this.update(job, { phase: 'starting', percent: 2 });
|
|
245
303
|
await this.deps.recordVideo({
|
|
246
304
|
projectDir: dir,
|
|
247
|
-
url: this.renderUrl(projectId, { scenario: scenarioId, position: '0', theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), ...(look.content ? { content: look.content } : {}), frame: '1', record: '1' }),
|
|
305
|
+
url: this.renderUrl(projectId, { scenario: scenarioId, position: '0', theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), ...(look.content ? { content: look.content } : {}), ...(look.voice ? { voice: 'real' } : {}), frame: '1', record: '1' }),
|
|
248
306
|
size: EXPORT_SIZE[device],
|
|
249
307
|
out,
|
|
250
308
|
total,
|
package/dist/film.js
CHANGED
|
@@ -4,11 +4,13 @@
|
|
|
4
4
|
* - renderFilm:Playwright 假时钟(page.clock)接管页面的 setTimeout / rAF / performance.now,演示控制器与引擎时钟
|
|
5
5
|
* 因此按固定步长(sampleMs,默认 50 ms ≈ 20 fps)逐帧前进;每帧截一张图、在辅助页里用 canvas 算与上一帧的像素差。
|
|
6
6
|
* 每隔 every(默认 250 ms)取一帧放进胶片条,标注时间、场景、步号与相邻帧差;同时客观地标出
|
|
7
|
-
* 硬切(单帧整屏突变,前后帧都平静)与长时间静止(≥ stillMs
|
|
8
|
-
* - renderVideo:复用看板导出的录制器(defaultRecorder
|
|
7
|
+
* 硬切(单帧整屏突变,前后帧都平静)与长时间静止(≥ stillMs 画面几乎不变)。加载耗时不进入采样时间;浏览器调度与栅格差异仍须实测复核。
|
|
8
|
+
* - renderVideo:复用看板导出的录制器(defaultRecorder,按真实时间),得到可以直接发布的 webm:
|
|
9
|
+
* 开播前的准备不进视频(#57);可指定输出分辨率(#55);已生成的旁白混进音轨(voice=real,#56);
|
|
10
|
+
* 可隐藏封面、鼠标、步骤标题条、字幕条,字幕另存为 .srt(#59)。
|
|
9
11
|
*
|
|
10
12
|
* 两者都走渲染路由的录制模式(record=1&frame=1):与看板导出视频同一套演示控制器、鼠标、字幕;
|
|
11
|
-
* chain=1
|
|
13
|
+
* chain=1 按发布站的顺序连续播放到方案的最后一个场景。胶片条用 voice=estimate:旁白按估算时长“读”(不出声、不调用朗读服务),
|
|
12
14
|
* 停留时间与开着朗读的发布站一致。
|
|
13
15
|
*/
|
|
14
16
|
import fs from 'node:fs';
|
|
@@ -19,7 +21,7 @@ import { realProjectDir } from "./vite-shared.js";
|
|
|
19
21
|
import { joploHome } from "./home.js";
|
|
20
22
|
import { loadPlaywright } from "./export-runtime.js";
|
|
21
23
|
import { launch } from "./render.js";
|
|
22
|
-
import { EXPORT_SIZE, defaultRecorder } from "./export.js";
|
|
24
|
+
import { EXPORT_SIZE, defaultRecorder, srt } from "./export.js";
|
|
23
25
|
/** 单帧整屏突变:变化像素占比至少这么多,且是前后帧的 CUT_RATIO 倍以上(排除持续的快速运镜)。 */
|
|
24
26
|
export const CUT_CHANGED = 0.3;
|
|
25
27
|
export const CUT_RATIO = 2.5;
|
|
@@ -89,9 +91,22 @@ window.step = async (b64, cropRatio, t, th, stillTh) => {
|
|
|
89
91
|
};
|
|
90
92
|
</script>`;
|
|
91
93
|
async function flush(page) {
|
|
92
|
-
// React
|
|
93
|
-
|
|
94
|
-
|
|
94
|
+
// React 的提交可能跨多轮 MessageChannel;连续三轮无 DOM 变化后才采样。
|
|
95
|
+
await page.evaluate(`() => new Promise((resolve, reject) => {
|
|
96
|
+
let changed = false, quiet = 0, turns = 0;
|
|
97
|
+
const observer = new MutationObserver(() => { changed = true; });
|
|
98
|
+
observer.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true });
|
|
99
|
+
const channel = new MessageChannel();
|
|
100
|
+
const finish = () => { observer.disconnect(); channel.port1.close(); channel.port2.close(); };
|
|
101
|
+
channel.port1.onmessage = () => {
|
|
102
|
+
quiet = changed ? 0 : quiet + 1;
|
|
103
|
+
changed = false;
|
|
104
|
+
if (quiet >= 3) { finish(); resolve(); }
|
|
105
|
+
else if (++turns >= 100) { finish(); reject(new Error('Render did not settle within 100 message turns')); }
|
|
106
|
+
else channel.port2.postMessage(0);
|
|
107
|
+
};
|
|
108
|
+
channel.port2.postMessage(0);
|
|
109
|
+
})`);
|
|
95
110
|
}
|
|
96
111
|
function check(opts) {
|
|
97
112
|
const out = path.resolve(opts.out);
|
|
@@ -112,14 +127,21 @@ async function compiled(projectDir) {
|
|
|
112
127
|
}
|
|
113
128
|
return { server, project: payload.project };
|
|
114
129
|
}
|
|
130
|
+
/** 视频分辨率:2–4096 的偶数(VP8 / VP9 编码要求偶数边长)。 */
|
|
131
|
+
function videoDimension(name, v) {
|
|
132
|
+
if (!Number.isInteger(v) || v < 2 || v > 4096 || v % 2)
|
|
133
|
+
throw new JoploError('USAGE', `--${name} for --video must be an even number of pixels from 2 to 4096 (got ${v})`);
|
|
134
|
+
return v;
|
|
135
|
+
}
|
|
115
136
|
function recordUrl(base, projectId, project, o) {
|
|
116
137
|
if (!project.scenarios[o.scenarioId])
|
|
117
138
|
throw new JoploError('NOT_FOUND', `Scenario does not exist: ${o.scenarioId} (available: ${Object.keys(project.scenarios).join(', ') || 'none'})`);
|
|
118
139
|
if (o.content !== undefined && !project.i18n?.locales.includes(o.content))
|
|
119
140
|
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`);
|
|
120
|
-
const
|
|
141
|
+
const voice = o.voice ?? 'estimate';
|
|
142
|
+
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(',') } : {}), ...(o.canvas ? { w: String(o.canvas.width), h: String(o.canvas.height) } : {}) });
|
|
121
143
|
const device = project.scenes[displaySceneId(project, o.scenarioId, 0)]?.viewport === 'mobile' ? 'mobile' : 'desktop';
|
|
122
|
-
return { url: `${base}?${q}`, size: EXPORT_SIZE[device] };
|
|
144
|
+
return { url: `${base}?${q}`, size: EXPORT_SIZE[device], device };
|
|
123
145
|
}
|
|
124
146
|
/** 胶片条:按引擎时间逐帧定格取样。 */
|
|
125
147
|
export async function renderFilm(opts) {
|
|
@@ -139,6 +161,8 @@ export async function renderFilm(opts) {
|
|
|
139
161
|
const ctx = await browser.newContext({ viewport: size, deviceScaleFactor: 0.5 });
|
|
140
162
|
const page = await ctx.newPage();
|
|
141
163
|
await page.clock.install({ time: 0 });
|
|
164
|
+
// 先冻结空白页,避免读 now 与 pauseAt 两次调用之间的墙钟竞态。
|
|
165
|
+
await page.clock.pauseAt(86_400_000);
|
|
142
166
|
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
143
167
|
// 载入阶段:真实时间里等网络与字体,假时间一点点往前推,直到渲染路由报告就绪
|
|
144
168
|
const t0 = Date.now();
|
|
@@ -154,9 +178,8 @@ export async function renderFilm(opts) {
|
|
|
154
178
|
const err = await page.evaluate(() => window.__JOPLO_ERROR__ ?? null);
|
|
155
179
|
if (err)
|
|
156
180
|
throw new JoploError('RENDER_FAILED', `Render route reported an error: ${err}`);
|
|
157
|
-
//
|
|
158
|
-
|
|
159
|
-
await page.clock.pauseAt(now + 1);
|
|
181
|
+
// 加载期间也只按 16ms 网格推进;开播相位不随网络和字体加载耗时改变。
|
|
182
|
+
await flush(page);
|
|
160
183
|
const helper = await ctx.newPage();
|
|
161
184
|
await helper.setContent(DIFF_PAGE);
|
|
162
185
|
// 字幕与步骤标题条浮在画面上(D97):胶片条只看画面本身的运动,采样时把它们藏起来,文字换行不算镜头切换
|
|
@@ -166,8 +189,10 @@ export async function renderFilm(opts) {
|
|
|
166
189
|
let tail = -1;
|
|
167
190
|
// 第一帧在开播之前采(封面 / 第 0 步):开播那一下的切换也要量到
|
|
168
191
|
for (let t = 0; t <= MAX_MS; t += sampleMs) {
|
|
169
|
-
if (t === sampleMs)
|
|
192
|
+
if (t === sampleMs) {
|
|
170
193
|
await page.evaluate(() => window.__JOPLO_RECORD__.play());
|
|
194
|
+
await flush(page);
|
|
195
|
+
}
|
|
171
196
|
if (t > 0)
|
|
172
197
|
await page.clock.runFor(sampleMs);
|
|
173
198
|
await flush(page);
|
|
@@ -245,19 +270,37 @@ export async function renderFilm(opts) {
|
|
|
245
270
|
await server.close();
|
|
246
271
|
}
|
|
247
272
|
}
|
|
273
|
+
const HIDE = ['cover', 'cursor', 'title', 'subtitles'];
|
|
248
274
|
/** 视频:与看板导出相同的录制器(真实时间)。 */
|
|
249
275
|
export async function renderVideo(opts) {
|
|
250
276
|
const projectDir = realProjectDir(opts.projectDir);
|
|
251
277
|
const out = check({ ...opts, projectDir });
|
|
278
|
+
if ((opts.width === undefined) !== (opts.height === undefined))
|
|
279
|
+
throw new JoploError('USAGE', 'Video width and height must be provided together');
|
|
280
|
+
const video = opts.width !== undefined ? { width: videoDimension('width', opts.width), height: videoDimension('height', opts.height) } : null;
|
|
281
|
+
const bad = (opts.hide ?? []).find((h) => !HIDE.includes(h));
|
|
282
|
+
if (bad)
|
|
283
|
+
throw new JoploError('USAGE', `Unknown --hide item ${JSON.stringify(bad)} (use ${HIDE.join(', ')})`);
|
|
284
|
+
const voice = opts.voice ?? 'real';
|
|
285
|
+
if (!['real', 'estimate', 'off'].includes(voice))
|
|
286
|
+
throw new JoploError('USAGE', `--voice must be real, estimate or off (got ${String(voice)})`);
|
|
287
|
+
const srtOut = opts.srt ? check({ out: opts.srt, overwrite: opts.overwrite, projectDir }) : null;
|
|
288
|
+
if (srtOut && srtOut === out)
|
|
289
|
+
throw new JoploError('USAGE', 'The subtitle file must differ from the video file');
|
|
252
290
|
const { server, project } = await compiled(projectDir);
|
|
253
291
|
try {
|
|
254
|
-
|
|
292
|
+
// 输出分辨率(#55):视口就是视频分辨率,渲染路由把舞台等比缩放进这块画布(录屏按 CSS 像素取帧,deviceScaleFactor 不会让它更清晰)
|
|
293
|
+
const { url, size } = recordUrl(server.url, server.projectId, project, { ...opts, voice, hide: opts.hide ?? [], ...(video ? { canvas: video } : {}) });
|
|
255
294
|
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
256
295
|
if (opts.overwrite)
|
|
257
296
|
fs.rmSync(out, { force: true });
|
|
258
297
|
const started = Date.now();
|
|
259
|
-
await defaultRecorder((dir) => loadPlaywright({ home: joploHome(), projectDir: dir }))({ projectDir, url, size, out, total: 0, progress: () => undefined, signal: new AbortController().signal, maxMs: MAX_MS });
|
|
260
|
-
|
|
298
|
+
const outcome = await defaultRecorder((dir) => loadPlaywright({ home: joploHome(), projectDir: dir }))({ projectDir, url, size: video ?? size, out, total: 0, progress: () => undefined, signal: new AbortController().signal, maxMs: MAX_MS });
|
|
299
|
+
if (srtOut) {
|
|
300
|
+
fs.mkdirSync(path.dirname(srtOut), { recursive: true });
|
|
301
|
+
fs.writeFileSync(srtOut, srt(outcome?.cues ?? []), opts.overwrite ? undefined : { flag: 'wx' });
|
|
302
|
+
}
|
|
303
|
+
return { path: out, durationMs: Date.now() - started, size: video ?? size, srt: srtOut, voice: outcome?.voice ?? { mode: voice, missing: [] } };
|
|
261
304
|
}
|
|
262
305
|
finally {
|
|
263
306
|
await server.close();
|
package/dist/local-resources.js
CHANGED
|
@@ -360,9 +360,9 @@ export async function inlineResources(project, requests, host) {
|
|
|
360
360
|
? Number(bytes.readBigUInt64BE(18) & 0xfffffffffn) * 1000 / (bytes.readUInt32BE(18) >>> 12)
|
|
361
361
|
: inspected.info?.durationMs;
|
|
362
362
|
diagnostics.push({ severity: 'info', source: 'structure', code: 'MEDIA_ASSET', at: request.source, message: `${request.plugin}/${request.id}: ${bytes.length} bytes${durationMs ? `, ${(durationMs / 1000).toFixed(3)} s` : ''}` });
|
|
363
|
-
//
|
|
364
|
-
if (bytes.length > 2 * 1024 * 1024 || durationMs && bytes.length / durationMs * 60000 > 750000)
|
|
365
|
-
diagnostics.push({ severity: 'warning', source: 'structure', code: 'MEDIA_ASSET_LARGE', at: request.source, message: `${request.plugin}/${request.id}: audio exceeds 2 MiB per track or 0.75 MB/min
|
|
363
|
+
// Short clips pay fixed codec context overhead; only assess bitrate after 15 seconds.
|
|
364
|
+
if (bytes.length > 2 * 1024 * 1024 || durationMs && durationMs >= 15000 && bytes.length / durationMs * 60000 > 750000)
|
|
365
|
+
diagnostics.push({ severity: 'warning', source: 'structure', code: 'MEDIA_ASSET_LARGE', at: request.source, message: `${request.plugin}/${request.id}: audio exceeds 2 MiB per track or 0.75 MB/min for clips at least 15 s long; shorten large tracks or review encoding bitrate (splitting does not reduce bitrate)` });
|
|
366
366
|
}
|
|
367
367
|
}
|
|
368
368
|
if (r.diagnostic)
|
package/dist/project.js
CHANGED
|
@@ -9,7 +9,7 @@ import { LocalResources, referencedResources } from "./local-resources.js";
|
|
|
9
9
|
import { isPluginDef } from '@joplo-app/kit/plugin';
|
|
10
10
|
import { compile } from '@joplo-app/core';
|
|
11
11
|
import { discoverFiles, loadAuthoring, enabledPlugins } from '@joplo-app/core/node';
|
|
12
|
-
import { isProjectSource } from "./vite-shared.js";
|
|
12
|
+
import { isProjectSource, isSharedJoploSource } from "./vite-shared.js";
|
|
13
13
|
/** config({ plugins }) 里每个插件的运行时入口(编译器另外校验清单;这里只取存在的文件)。 */
|
|
14
14
|
export function pluginRuntimesOf(plugins) {
|
|
15
15
|
const out = {};
|
|
@@ -19,19 +19,38 @@ export function pluginRuntimesOf(plugins) {
|
|
|
19
19
|
return out;
|
|
20
20
|
}
|
|
21
21
|
const LOC_IN_MESSAGE = /((?:[\w@.-]+\/)*[\w@.-]+\.(?:tsx|ts|jsx|js|mts)):(\d+):(\d+)/;
|
|
22
|
-
/**
|
|
22
|
+
/** 运行时错误(模块求值时抛出):从调用栈里找第一处项目文件位置(项目外按 Joplo JSX 转译的共享文件也算,路径相对项目目录)。 */
|
|
23
23
|
function stackLoc(projectDir, e) {
|
|
24
24
|
const stack = e instanceof Error ? (e.stack ?? '') : '';
|
|
25
|
+
const jsxMissing = jsxRuntimeMissing(e);
|
|
25
26
|
for (const line of stack.split('\n')) {
|
|
26
27
|
const m = /\(?((?:file:\/\/)?\/[^():\s]+):(\d+):(\d+)\)?\s*$/.exec(line);
|
|
27
28
|
if (!m)
|
|
28
29
|
continue;
|
|
29
30
|
const file = decodeURIComponent(m[1].replace(/^file:\/\//, ''));
|
|
30
|
-
|
|
31
|
+
// JSX 运行时没生效(#61):抛错的就是那个没有按 Joplo JSX 转译的 TSX,不管它在不在项目里
|
|
32
|
+
const culprit = jsxMissing && /\.(tsx|jsx)$/.test(file) && !file.split(path.sep).includes('node_modules');
|
|
33
|
+
if (culprit || isProjectSource(projectDir, file) || isSharedJoploSource(projectDir, file))
|
|
31
34
|
return `${path.relative(projectDir, file).split(path.sep).join('/')}:${m[2]}:${m[3]}`;
|
|
32
35
|
}
|
|
33
36
|
return null;
|
|
34
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* JSX 没有走 Joplo 的运行时(项目外、最近的 tsconfig 不是 Joplo 的 JSX 设置):经典转译后找不到 React,
|
|
40
|
+
* 或自动转译去找 react/jsx-dev-runtime。返回能确定的那个文件(绝对路径),只知道是这类错误时返回 true。
|
|
41
|
+
*/
|
|
42
|
+
function jsxRuntimeMissing(e) {
|
|
43
|
+
const msg = e instanceof Error ? e.message : '';
|
|
44
|
+
if (e instanceof ReferenceError && /\bReact is not defined\b/.test(msg))
|
|
45
|
+
return true;
|
|
46
|
+
const m = /Cannot find (?:module|package) '(?:react\/jsx-(?:dev-)?runtime|react)' imported from '([^']+)'/.exec(msg);
|
|
47
|
+
if (!m)
|
|
48
|
+
return false;
|
|
49
|
+
// 只有导入方是作者写的 TSX / JSX 时才是“JSX 运行时没生效”;依赖包真的缺 react 时保留原错误
|
|
50
|
+
const file = decodeURIComponent(m[1].replace(/^file:\/\//, ''));
|
|
51
|
+
return /\.(tsx|jsx)$/.test(file) && !file.split(path.sep).includes('node_modules') ? file : false;
|
|
52
|
+
}
|
|
53
|
+
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 */";
|
|
35
54
|
export async function compileProject(server, projectDir, mode) {
|
|
36
55
|
const errorAt = new Map(); // 载入失败的文件(绝对路径)→ 精确位置
|
|
37
56
|
const importer = async (abs) => {
|
|
@@ -44,6 +63,14 @@ export async function compileProject(server, projectDir, mode) {
|
|
|
44
63
|
const at = m ? `${m[1]}:${m[2]}:${m[3]}` : stackLoc(projectDir, e);
|
|
45
64
|
if (at)
|
|
46
65
|
errorAt.set(abs, at);
|
|
66
|
+
const jsx = jsxRuntimeMissing(e);
|
|
67
|
+
if (jsx) {
|
|
68
|
+
// 能从报错里确定文件时以它为准(位置只知道文件,记为第 1 行)
|
|
69
|
+
const culprit = typeof jsx === 'string' ? `${path.relative(projectDir, jsx).split(path.sep).join('/')}:1:1` : at;
|
|
70
|
+
if (culprit)
|
|
71
|
+
errorAt.set(abs, culprit);
|
|
72
|
+
throw new Error(`${culprit ? culprit.replace(/:\d+:\d+$/, '') : 'A TSX file'} ${JSX_HINT}`);
|
|
73
|
+
}
|
|
47
74
|
throw e instanceof Error ? e : new Error(msg);
|
|
48
75
|
}
|
|
49
76
|
};
|
|
@@ -174,7 +201,7 @@ export function invalidateProjectModules(server, projectDir) {
|
|
|
174
201
|
for (const env of Object.values(server.environments)) {
|
|
175
202
|
const graph = env.moduleGraph;
|
|
176
203
|
for (const mod of graph.idToModuleMap.values())
|
|
177
|
-
if (mod.file && isProjectSource(projectDir, mod.file))
|
|
204
|
+
if (mod.file && (isProjectSource(projectDir, mod.file) || isSharedJoploSource(projectDir, mod.file)))
|
|
178
205
|
graph.invalidateModule(mod);
|
|
179
206
|
}
|
|
180
207
|
}
|
package/dist/vite-shared.d.ts
CHANGED
|
@@ -6,6 +6,12 @@ export declare function realProjectDir(dir: string): string;
|
|
|
6
6
|
/** 不参与编译的项目子目录。 */
|
|
7
7
|
export declare const IGNORED_DIRS: string[];
|
|
8
8
|
export declare function isProjectSource(projectDir: string, file: string): boolean;
|
|
9
|
+
/**
|
|
10
|
+
* 项目目录之外、不在 node_modules 里的源文件(例如一个仓库里多个 Joplo 项目共用的上层组件):
|
|
11
|
+
* 最近的 tsconfig.json 声明了 jsxImportSource "@joplo-app/kit" 时,同样按 Joplo 的 JSX 运行时转译(#61)。
|
|
12
|
+
* 其余文件(Joplo 自己的界面源码等)保持原样。每次都重新查找(只在转译时调用),新建或修改 tsconfig 立即生效。
|
|
13
|
+
*/
|
|
14
|
+
export declare function isSharedJoploSource(projectDir: string, file: string): boolean;
|
|
9
15
|
/** 语法错误的位置:从转译器报错里取 `文件:行:列`。 */
|
|
10
16
|
export type SourceLoc = {
|
|
11
17
|
file: string;
|
package/dist/vite-shared.js
CHANGED
|
@@ -30,6 +30,42 @@ export function isProjectSource(projectDir, file) {
|
|
|
30
30
|
const first = rel.split(path.sep)[0] ?? '';
|
|
31
31
|
return !IGNORED_DIRS.includes(first);
|
|
32
32
|
}
|
|
33
|
+
/** 读 tsconfig(允许注释与尾逗号),沿相对路径的 extends 找 compilerOptions.jsxImportSource。 */
|
|
34
|
+
function tsconfigJsxSource(file, depth = 0) {
|
|
35
|
+
let raw;
|
|
36
|
+
try {
|
|
37
|
+
const text = fs.readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\/|("(?:\\.|[^"\\])*")|\/\/[^\n]*/g, (m, str) => str ?? '').replace(/,(\s*[}\]])/g, '$1');
|
|
38
|
+
raw = JSON.parse(text);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
const own = raw?.compilerOptions?.jsxImportSource;
|
|
44
|
+
if (typeof own === 'string')
|
|
45
|
+
return own;
|
|
46
|
+
const ext = raw?.extends;
|
|
47
|
+
if (depth < 5 && typeof ext === 'string' && ext.startsWith('.')) {
|
|
48
|
+
const next = path.resolve(path.dirname(file), ext.endsWith('.json') ? ext : `${ext}.json`);
|
|
49
|
+
return tsconfigJsxSource(next, depth + 1);
|
|
50
|
+
}
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* 项目目录之外、不在 node_modules 里的源文件(例如一个仓库里多个 Joplo 项目共用的上层组件):
|
|
55
|
+
* 最近的 tsconfig.json 声明了 jsxImportSource "@joplo-app/kit" 时,同样按 Joplo 的 JSX 运行时转译(#61)。
|
|
56
|
+
* 其余文件(Joplo 自己的界面源码等)保持原样。每次都重新查找(只在转译时调用),新建或修改 tsconfig 立即生效。
|
|
57
|
+
*/
|
|
58
|
+
export function isSharedJoploSource(projectDir, file) {
|
|
59
|
+
if (!path.isAbsolute(file) || file.startsWith(projectDir + path.sep) || file.split(path.sep).includes('node_modules'))
|
|
60
|
+
return false;
|
|
61
|
+
for (let dir = path.dirname(file);; dir = path.dirname(dir)) {
|
|
62
|
+
const cfg = path.join(dir, 'tsconfig.json');
|
|
63
|
+
if (fs.existsSync(cfg))
|
|
64
|
+
return tsconfigJsxSource(cfg) === '@joplo-app/kit';
|
|
65
|
+
if (path.dirname(dir) === dir)
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
33
69
|
const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, '');
|
|
34
70
|
export class ProjectSyntaxError extends Error {
|
|
35
71
|
loc;
|
|
@@ -83,7 +119,7 @@ export function joploProjectPlugin(projectDir, web = locateWebAssets(), publicCs
|
|
|
83
119
|
css = css.replace(/@import\s+["']tailwindcss["']/, `@import ${JSON.stringify(tailwindIndexCss())}`);
|
|
84
120
|
return { code: `${css}\n@source ${JSON.stringify(publicCssSource ?? projectDir)};\n`, map: null };
|
|
85
121
|
}
|
|
86
|
-
if (
|
|
122
|
+
if (!/\.(tsx|ts|jsx|js|mts)$/.test(file) || !(isProjectSource(projectDir, file) || isSharedJoploSource(projectDir, file)))
|
|
87
123
|
return;
|
|
88
124
|
const lang = file.endsWith('.tsx') ? 'tsx' : file.endsWith('.jsx') ? 'jsx' : file.endsWith('.js') ? 'js' : 'ts';
|
|
89
125
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@joplo-app/server",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.2",
|
|
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.6.
|
|
19
|
-
"@joplo-app/kit": "0.6.
|
|
20
|
-
"@joplo-app/web": "0.6.
|
|
18
|
+
"@joplo-app/core": "0.6.2",
|
|
19
|
+
"@joplo-app/kit": "0.6.2",
|
|
20
|
+
"@joplo-app/web": "0.6.2",
|
|
21
21
|
"@tailwindcss/vite": "4.3.4",
|
|
22
22
|
"mediabunny": "1.65.2",
|
|
23
23
|
"tailwindcss": "4.3.4",
|