@joplo-app/server 0.2.18 → 0.4.1
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/binary-assets.d.ts +19 -0
- package/dist/binary-assets.js +64 -0
- package/dist/build.d.ts +8 -1
- package/dist/build.js +89 -3
- package/dist/contract.d.ts +57 -0
- package/dist/dev.d.ts +3 -0
- package/dist/dev.js +157 -5
- package/dist/export.d.ts +3 -2
- package/dist/export.js +26 -7
- package/dist/film.d.ts +27 -0
- package/dist/film.js +265 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/local-resources.d.ts +47 -0
- package/dist/local-resources.js +368 -0
- package/dist/local-review.js +2 -1
- package/dist/media-calibration.d.ts +8 -0
- package/dist/media-calibration.js +67 -0
- package/dist/media-check.d.ts +9 -0
- package/dist/media-check.js +56 -0
- package/dist/media-mux.d.ts +9 -0
- package/dist/media-mux.js +68 -0
- package/dist/page-report.js +7 -5
- package/dist/plugin-assets.d.ts +5 -0
- package/dist/plugin-assets.js +35 -0
- package/dist/plugin-keys.d.ts +35 -0
- package/dist/plugin-keys.js +66 -0
- package/dist/preview.d.ts +11 -0
- package/dist/preview.js +83 -0
- package/dist/project.d.ts +10 -0
- package/dist/project.js +33 -6
- package/dist/render.js +4 -4
- package/dist/resources-run.d.ts +31 -0
- package/dist/resources-run.js +43 -0
- package/dist/web-assets.js +3 -3
- package/package.json +5 -5
package/dist/export.js
CHANGED
|
@@ -17,20 +17,22 @@
|
|
|
17
17
|
*
|
|
18
18
|
* 字段流向:job(写入点:这里的 runJob)→ jobs Map(存储)→ SSE / GET(读取点)→ 看板的导出视频弹窗(消费者)。
|
|
19
19
|
*/
|
|
20
|
+
import { recordedCalibration } from "./media-calibration.js";
|
|
21
|
+
import { muxRecordedAudio } from "./media-mux.js";
|
|
20
22
|
import crypto from 'node:crypto';
|
|
21
23
|
import fs from 'node:fs';
|
|
22
24
|
import path from 'node:path';
|
|
23
25
|
import { exportLocale } from "./locale.js";
|
|
24
|
-
import { JoploError,
|
|
26
|
+
import { JoploError, THEME_NAME, displaySceneId, isAppearanceFont, isAppearanceStroke } from '@joplo-app/core';
|
|
25
27
|
import { launch } from "./render.js";
|
|
26
28
|
import { exportRuntimeStatus, installExportRuntime, loadPlaywright } from "./export-runtime.js";
|
|
27
29
|
/**
|
|
28
30
|
* 导出画面的尺寸:电脑 = 舞台 1280×800;手机 = 外框(renderer 的 phoneFrameSize(390, 844) = 446×934)
|
|
29
|
-
* 四周再留 16px(RenderApp 的 frame
|
|
31
|
+
* 四周再留 16px(RenderApp 的 frame 模式)。字幕与步骤标题条浮在舞台上(D97),不另占高度。
|
|
30
32
|
*/
|
|
31
33
|
export const EXPORT_SIZE = {
|
|
32
|
-
desktop: { width: 1280, height: 800
|
|
33
|
-
mobile: { width: 446 + 32, height: 934 + 32
|
|
34
|
+
desktop: { width: 1280, height: 800 },
|
|
35
|
+
mobile: { width: 446 + 32, height: 934 + 32 },
|
|
34
36
|
};
|
|
35
37
|
const send = (res, status, body) => {
|
|
36
38
|
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
|
@@ -70,7 +72,7 @@ async function waitReady(page) {
|
|
|
70
72
|
}
|
|
71
73
|
/** 缺省的录制:Playwright recordVideo + 渲染路由的录制模式(window.__JOPLO_RECORD__)。 */
|
|
72
74
|
export function defaultRecorder(load) {
|
|
73
|
-
return async ({ projectDir, url, size, out, progress, signal }) => {
|
|
75
|
+
return async ({ projectDir, url, size, out, progress, signal, maxMs = 5 * 60_000 }) => {
|
|
74
76
|
const pw = await load(projectDir);
|
|
75
77
|
const browser = await launch(pw);
|
|
76
78
|
const tmp = fs.mkdtempSync(path.join(path.dirname(out), '.rec-'));
|
|
@@ -91,16 +93,33 @@ export function defaultRecorder(load) {
|
|
|
91
93
|
progress(p.step);
|
|
92
94
|
if (p.done)
|
|
93
95
|
break;
|
|
94
|
-
if (Date.now() - t0 >
|
|
95
|
-
throw new JoploError('EXPORT_FAILED',
|
|
96
|
+
if (Date.now() - t0 > maxMs)
|
|
97
|
+
throw new JoploError('EXPORT_FAILED', `Recording exceeded ${Math.round(maxMs / 60000)} minutes and was stopped`);
|
|
96
98
|
await page.waitForTimeout(150);
|
|
97
99
|
}
|
|
98
100
|
await page.waitForTimeout(900); // 停留在结果画面
|
|
101
|
+
const calibrated = await page.evaluate(() => window.__JOPLO_RECORD__.calibrate?.() ?? false);
|
|
102
|
+
const audio = await page.evaluate(() => window.__JOPLO_RECORD__.stopAudio?.() ?? null);
|
|
99
103
|
const video = page.video();
|
|
100
104
|
await ctx.close();
|
|
101
105
|
if (!video)
|
|
102
106
|
throw new JoploError('EXPORT_FAILED', 'The browser did not generate a video');
|
|
103
107
|
await video.saveAs(out);
|
|
108
|
+
if (audio) {
|
|
109
|
+
if (!calibrated)
|
|
110
|
+
throw new Error('Audio/video calibration unavailable');
|
|
111
|
+
const analysis = await browser.newContext();
|
|
112
|
+
const probe = await analysis.newPage();
|
|
113
|
+
await probe.goto(url, { waitUntil: 'domcontentloaded' });
|
|
114
|
+
try {
|
|
115
|
+
const bytes = Buffer.from(audio.data, 'base64');
|
|
116
|
+
const timing = await recordedCalibration(probe, out, bytes);
|
|
117
|
+
await muxRecordedAudio(out, bytes, timing.offsetSeconds, { videoEnd: timing.videoPTS, audioEnd: timing.audioPTS, audioDurations: timing.audioDurations });
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
await analysis.close();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
104
123
|
}
|
|
105
124
|
finally {
|
|
106
125
|
await browser.close().catch(() => undefined);
|
package/dist/film.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { FilmOptions, FilmResult, FilmCut, FilmStill, FilmBoundary, VideoOptions, VideoResult } from './contract.js';
|
|
2
|
+
/** 单帧整屏突变:变化像素占比至少这么多,且是前后帧的 CUT_RATIO 倍以上(排除持续的快速运镜)。 */
|
|
3
|
+
export declare const CUT_CHANGED = 0.3;
|
|
4
|
+
export declare const CUT_RATIO = 2.5;
|
|
5
|
+
/** 静止:与静止起点那一帧相比,变化像素占比低于这个值。 */
|
|
6
|
+
export declare const STILL_CHANGED = 0.004;
|
|
7
|
+
type Sample = {
|
|
8
|
+
t: number;
|
|
9
|
+
diff: number;
|
|
10
|
+
changed: number;
|
|
11
|
+
still: number;
|
|
12
|
+
scenarioId: string | null;
|
|
13
|
+
position: number;
|
|
14
|
+
activeStep: number | null;
|
|
15
|
+
jpg?: string;
|
|
16
|
+
};
|
|
17
|
+
/** 纯函数:从逐帧的相邻差找出硬切。changed[i] 是第 i 帧与第 i-1 帧之间变化像素的占比。 */
|
|
18
|
+
export declare function findCuts(samples: readonly Pick<Sample, 't' | 'changed' | 'diff' | 'scenarioId' | 'position'>[]): FilmCut[];
|
|
19
|
+
/** 纯函数:still[i] = 第 i 帧距离“上一次明显变化”的毫秒数;找出至少 minMs 的静止段。 */
|
|
20
|
+
export declare function findStills(samples: readonly Pick<Sample, 't' | 'still' | 'scenarioId' | 'position'>[], minMs: number): FilmStill[];
|
|
21
|
+
/** 纯函数:每次提交一步(或换场景)前后窗口里的最大相邻帧差,章节衔接是否硬切一眼可见。 */
|
|
22
|
+
export declare function stepBoundaries(samples: readonly Pick<Sample, 't' | 'diff' | 'changed' | 'scenarioId' | 'position'>[], before?: number, after?: number): FilmBoundary[];
|
|
23
|
+
/** 胶片条:按引擎时间逐帧定格取样。 */
|
|
24
|
+
export declare function renderFilm(opts: FilmOptions): Promise<FilmResult>;
|
|
25
|
+
/** 视频:与看板导出相同的录制器(真实时间)。 */
|
|
26
|
+
export declare function renderVideo(opts: VideoOptions): Promise<VideoResult>;
|
|
27
|
+
export {};
|
package/dist/film.js
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 胶片条与视频(`joplo render --film / --video`):让 Agent 看见“运动”,而不只是每一步的终态。
|
|
3
|
+
*
|
|
4
|
+
* - renderFilm:Playwright 假时钟(page.clock)接管页面的 setTimeout / rAF / performance.now,演示控制器与引擎时钟
|
|
5
|
+
* 因此按固定步长(sampleMs,默认 50 ms ≈ 20 fps)逐帧前进;每帧截一张图、在辅助页里用 canvas 算与上一帧的像素差。
|
|
6
|
+
* 每隔 every(默认 250 ms)取一帧放进胶片条,标注时间、场景、步号与相邻帧差;同时客观地标出
|
|
7
|
+
* 硬切(单帧整屏突变,前后帧都平静)与长时间静止(≥ stillMs 画面几乎不变)。结果确定、可复现,与墙钟无关。
|
|
8
|
+
* - renderVideo:复用看板导出的录制器(defaultRecorder,Playwright recordVideo,按真实时间),得到可以直接看的 webm。
|
|
9
|
+
*
|
|
10
|
+
* 两者都走渲染路由的录制模式(record=1&frame=1):与看板导出视频同一套演示控制器、鼠标、字幕;
|
|
11
|
+
* chain=1 按发布站的顺序连续播放到方案的最后一个场景;voice=estimate 让旁白按估算时长“读”(不出声、不调用朗读服务),
|
|
12
|
+
* 停留时间与开着朗读的发布站一致。
|
|
13
|
+
*/
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { JoploError, displaySceneId } from '@joplo-app/core';
|
|
17
|
+
import { createDev } from "./dev.js";
|
|
18
|
+
import { realProjectDir } from "./vite-shared.js";
|
|
19
|
+
import { joploHome } from "./home.js";
|
|
20
|
+
import { loadPlaywright } from "./export-runtime.js";
|
|
21
|
+
import { launch } from "./render.js";
|
|
22
|
+
import { EXPORT_SIZE, defaultRecorder } from "./export.js";
|
|
23
|
+
/** 单帧整屏突变:变化像素占比至少这么多,且是前后帧的 CUT_RATIO 倍以上(排除持续的快速运镜)。 */
|
|
24
|
+
export const CUT_CHANGED = 0.3;
|
|
25
|
+
export const CUT_RATIO = 2.5;
|
|
26
|
+
/** 静止:与静止起点那一帧相比,变化像素占比低于这个值。 */
|
|
27
|
+
export const STILL_CHANGED = 0.004;
|
|
28
|
+
/** 一个像素的 RGB 平均差超过这个值才算“变了”(0–1)。 */
|
|
29
|
+
const PIXEL_THRESHOLD = 0.08;
|
|
30
|
+
const MAX_MS = 10 * 60_000;
|
|
31
|
+
/** 纯函数:从逐帧的相邻差找出硬切。changed[i] 是第 i 帧与第 i-1 帧之间变化像素的占比。 */
|
|
32
|
+
export function findCuts(samples) {
|
|
33
|
+
const cuts = [];
|
|
34
|
+
for (let i = 1; i < samples.length; i++) {
|
|
35
|
+
const c = samples[i].changed;
|
|
36
|
+
if (c < CUT_CHANGED)
|
|
37
|
+
continue;
|
|
38
|
+
const around = Math.max(samples[i - 1]?.changed ?? 0, samples[i + 1]?.changed ?? 0, i > 1 ? 0 : 0);
|
|
39
|
+
if (c >= CUT_RATIO * Math.max(around, 0.02))
|
|
40
|
+
cuts.push({ atMs: samples[i].t, diff: round(samples[i].diff), changed: round(c), scenarioId: samples[i].scenarioId, position: samples[i].position });
|
|
41
|
+
}
|
|
42
|
+
return cuts;
|
|
43
|
+
}
|
|
44
|
+
/** 纯函数:still[i] = 第 i 帧距离“上一次明显变化”的毫秒数;找出至少 minMs 的静止段。 */
|
|
45
|
+
export function findStills(samples, minMs) {
|
|
46
|
+
const out = [];
|
|
47
|
+
let run = null;
|
|
48
|
+
for (const s of samples) {
|
|
49
|
+
if (s.still >= minMs) {
|
|
50
|
+
const from = s.t - s.still;
|
|
51
|
+
if (run && run.fromMs === from) {
|
|
52
|
+
run.toMs = s.t;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
run = { fromMs: from, toMs: s.t, scenarioId: s.scenarioId, position: s.position };
|
|
56
|
+
out.push(run);
|
|
57
|
+
}
|
|
58
|
+
else
|
|
59
|
+
run = null;
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
/** 纯函数:每次提交一步(或换场景)前后窗口里的最大相邻帧差,章节衔接是否硬切一眼可见。 */
|
|
64
|
+
export function stepBoundaries(samples, before = 200, after = 1500) {
|
|
65
|
+
const out = [];
|
|
66
|
+
for (let i = 1; i < samples.length; i++) {
|
|
67
|
+
const a = samples[i - 1], b = samples[i];
|
|
68
|
+
if (a.scenarioId === b.scenarioId && a.position === b.position)
|
|
69
|
+
continue;
|
|
70
|
+
const win = samples.filter((s) => s.t >= b.t - before && s.t <= b.t + after);
|
|
71
|
+
out.push({ atMs: b.t, scenarioId: b.scenarioId, position: b.position, chapter: a.scenarioId !== b.scenarioId, maxDiff: round(Math.max(0, ...win.map((s) => s.diff))), maxChanged: round(Math.max(0, ...win.map((s) => s.changed))) });
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
const round = (n) => Math.round(n * 10000) / 10000;
|
|
76
|
+
const esc = (t) => t.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
|
|
77
|
+
/** 辅助页:解码 JPEG、裁掉字幕区,与上一帧、静止起点比较。状态留在页面里,每帧只传一次图片。 */
|
|
78
|
+
const DIFF_PAGE = `<!doctype html><canvas id=c></canvas><script>
|
|
79
|
+
let prev=null, anchor=null, anchorT=0;
|
|
80
|
+
async function load(b64){ const img=new Image(); img.src='data:image/jpeg;base64,'+b64; await img.decode(); return img; }
|
|
81
|
+
function pixels(img, h){ const c=document.getElementById('c'); c.width=img.width; c.height=h; const g=c.getContext('2d',{willReadFrequently:true}); g.drawImage(img,0,0); return g.getImageData(0,0,img.width,h).data; }
|
|
82
|
+
function compare(a,b,th){ let sum=0, changed=0; const n=a.length/4; for(let i=0;i<a.length;i+=4){ const d=(Math.abs(a[i]-b[i])+Math.abs(a[i+1]-b[i+1])+Math.abs(a[i+2]-b[i+2]))/765; sum+=d; if(d>th) changed++; } return { diff: sum/n, changed: changed/n }; }
|
|
83
|
+
window.step = async (b64, cropRatio, t, th, stillTh) => {
|
|
84
|
+
const img = await load(b64); const d = pixels(img, Math.max(1, Math.round(img.height*cropRatio)));
|
|
85
|
+
const adj = prev ? compare(prev, d, th) : { diff: 0, changed: 0 };
|
|
86
|
+
prev = d;
|
|
87
|
+
if (!anchor || compare(anchor, d, th).changed > stillTh) { anchor = d; anchorT = t; }
|
|
88
|
+
return { ...adj, still: t - anchorT };
|
|
89
|
+
};
|
|
90
|
+
</script>`;
|
|
91
|
+
async function flush(page) {
|
|
92
|
+
// React 用 MessageChannel 调度提交;假时钟不接管它。等两轮,让这一帧的状态都画出来。
|
|
93
|
+
for (let i = 0; i < 2; i++)
|
|
94
|
+
await page.evaluate(() => new Promise((r) => { const c = new MessageChannel(); c.port1.onmessage = () => r(); c.port2.postMessage(0); }));
|
|
95
|
+
}
|
|
96
|
+
function check(opts) {
|
|
97
|
+
const out = path.resolve(opts.out);
|
|
98
|
+
if (fs.existsSync(out) && !opts.overwrite)
|
|
99
|
+
throw new JoploError('USAGE', `Output file already exists: ${out}. To overwrite, pass overwrite: true (CLI: --overwrite)`);
|
|
100
|
+
const dataDir = path.join(realProjectDir(opts.projectDir), '.joplo');
|
|
101
|
+
if (out === dataDir || out.startsWith(dataDir + path.sep))
|
|
102
|
+
throw new JoploError('USAGE', `Cannot write to project data: ${out} (.joplo/ is managed by Joplo)`);
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
async function compiled(projectDir) {
|
|
106
|
+
const server = await createDev({ projectDir, port: 0, watch: false, log: () => undefined });
|
|
107
|
+
const payload = server.payload();
|
|
108
|
+
if (!payload.project) {
|
|
109
|
+
await server.close();
|
|
110
|
+
const errs = payload.diagnostics.filter((d) => d.severity === 'error');
|
|
111
|
+
throw new JoploError('INVALID_SCHEMA', `Project compilation failed: ${errs.map((d) => `${d.at ?? ''} ${d.message}`).join('; ')}`, { diagnostics: payload.diagnostics });
|
|
112
|
+
}
|
|
113
|
+
return { server, project: payload.project };
|
|
114
|
+
}
|
|
115
|
+
function recordUrl(base, projectId, project, o) {
|
|
116
|
+
if (!project.scenarios[o.scenarioId])
|
|
117
|
+
throw new JoploError('NOT_FOUND', `Scenario does not exist: ${o.scenarioId} (available: ${Object.keys(project.scenarios).join(', ') || 'none'})`);
|
|
118
|
+
if (o.content !== undefined && !project.i18n?.locales.includes(o.content))
|
|
119
|
+
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 q = new URLSearchParams({ render: '1', project: projectId, scenario: o.scenarioId, position: '0', theme: o.theme ?? project.theme ?? 'sketch', frame: '1', record: '1', voice: 'estimate', ...(o.chain ? { chain: '1' } : {}), ...(o.audio === false ? { audio: '0' } : {}), ...(o.locale ? { locale: o.locale } : {}), ...(o.content ? { content: o.content } : {}) });
|
|
121
|
+
const device = project.scenes[displaySceneId(project, o.scenarioId, 0)]?.viewport === 'mobile' ? 'mobile' : 'desktop';
|
|
122
|
+
return { url: `${base}?${q}`, size: EXPORT_SIZE[device] };
|
|
123
|
+
}
|
|
124
|
+
/** 胶片条:按引擎时间逐帧定格取样。 */
|
|
125
|
+
export async function renderFilm(opts) {
|
|
126
|
+
const projectDir = realProjectDir(opts.projectDir);
|
|
127
|
+
const out = check({ ...opts, projectDir });
|
|
128
|
+
const sampleMs = Math.max(20, Math.min(250, Math.round(opts.sampleMs ?? 50)));
|
|
129
|
+
const every = Math.max(sampleMs, Math.round((opts.every ?? 250) / sampleMs) * sampleMs);
|
|
130
|
+
const stillMs = opts.stillMs ?? 1500;
|
|
131
|
+
const columns = Math.max(1, Math.min(16, Math.round(opts.columns ?? 8)));
|
|
132
|
+
const cellWidth = Math.max(120, Math.min(640, Math.round(opts.cellWidth ?? 224)));
|
|
133
|
+
const playwright = await loadPlaywright({ home: joploHome(), projectDir });
|
|
134
|
+
const { server, project } = await compiled(projectDir);
|
|
135
|
+
let browser = null;
|
|
136
|
+
try {
|
|
137
|
+
const { url, size } = recordUrl(server.url, server.projectId, project, { ...opts, audio: false });
|
|
138
|
+
browser = await launch(playwright);
|
|
139
|
+
const ctx = await browser.newContext({ viewport: size, deviceScaleFactor: 0.5 });
|
|
140
|
+
const page = await ctx.newPage();
|
|
141
|
+
await page.clock.install({ time: 0 });
|
|
142
|
+
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
143
|
+
// 载入阶段:真实时间里等网络与字体,假时间一点点往前推,直到渲染路由报告就绪
|
|
144
|
+
const t0 = Date.now();
|
|
145
|
+
for (;;) {
|
|
146
|
+
const ready = await page.evaluate(() => window.__JOPLO_READY__ === true);
|
|
147
|
+
if (ready)
|
|
148
|
+
break;
|
|
149
|
+
if (Date.now() - t0 > 60_000)
|
|
150
|
+
throw new JoploError('RENDER_FAILED', 'Render route did not become ready within 60 seconds');
|
|
151
|
+
await page.clock.runFor(16);
|
|
152
|
+
await page.waitForTimeout(10);
|
|
153
|
+
}
|
|
154
|
+
const err = await page.evaluate(() => window.__JOPLO_ERROR__ ?? null);
|
|
155
|
+
if (err)
|
|
156
|
+
throw new JoploError('RENDER_FAILED', `Render route reported an error: ${err}`);
|
|
157
|
+
// 就绪后冻结时钟:之后只由 runFor 推进,截图与像素比较花的真实时间不再混进引擎时间
|
|
158
|
+
const now = await page.evaluate(() => Date.now());
|
|
159
|
+
await page.clock.pauseAt(now + 1);
|
|
160
|
+
const helper = await ctx.newPage();
|
|
161
|
+
await helper.setContent(DIFF_PAGE);
|
|
162
|
+
// 字幕与步骤标题条浮在画面上(D97):胶片条只看画面本身的运动,采样时把它们藏起来,文字换行不算镜头切换
|
|
163
|
+
await page.addStyleTag({ content: '[data-jsubtitle],[data-testid="step-title"]{visibility:hidden!important}' });
|
|
164
|
+
const stageRatio = 1;
|
|
165
|
+
const samples = [];
|
|
166
|
+
let tail = -1;
|
|
167
|
+
// 第一帧在开播之前采(封面 / 第 0 步):开播那一下的切换也要量到
|
|
168
|
+
for (let t = 0; t <= MAX_MS; t += sampleMs) {
|
|
169
|
+
if (t === sampleMs)
|
|
170
|
+
await page.evaluate(() => window.__JOPLO_RECORD__.play());
|
|
171
|
+
if (t > 0)
|
|
172
|
+
await page.clock.runFor(sampleMs);
|
|
173
|
+
await flush(page);
|
|
174
|
+
const p = await page.evaluate(() => window.__JOPLO_RECORD__.progress);
|
|
175
|
+
if (p.error)
|
|
176
|
+
throw new JoploError('RENDER_FAILED', `Playback failed at ${t} ms: ${p.error}`);
|
|
177
|
+
const jpg = (await page.locator('[data-jexport]').screenshot({ type: 'jpeg', quality: 72 })).toString('base64');
|
|
178
|
+
const d = await helper.evaluate(([b64, crop, time, th, st]) => window.step(b64, crop, time, th, st), [jpg, stageRatio, t, PIXEL_THRESHOLD, STILL_CHANGED]);
|
|
179
|
+
samples.push({ t, ...d, scenarioId: p.scenarioId, position: p.position, activeStep: p.activeStep, ...(t % every === 0 ? { jpg } : {}) });
|
|
180
|
+
if (opts.frames && t % every === 0) {
|
|
181
|
+
fs.mkdirSync(opts.frames, { recursive: true });
|
|
182
|
+
fs.writeFileSync(path.join(opts.frames, `${String(t).padStart(7, '0')}.jpg`), Buffer.from(jpg, 'base64'));
|
|
183
|
+
}
|
|
184
|
+
if (p.done && tail < 0)
|
|
185
|
+
tail = t + 1000;
|
|
186
|
+
if (tail >= 0 && t >= tail)
|
|
187
|
+
break;
|
|
188
|
+
}
|
|
189
|
+
if (tail < 0)
|
|
190
|
+
throw new JoploError('RENDER_FAILED', `Playback did not finish within ${MAX_MS / 60000} minutes of engine time`);
|
|
191
|
+
const cuts = findCuts(samples);
|
|
192
|
+
const stills = findStills(samples, stillMs);
|
|
193
|
+
const boundaries = stepBoundaries(samples);
|
|
194
|
+
const durationMs = samples[samples.length - 1].t;
|
|
195
|
+
// 胶片条:每个场景一页,避免一张图太长被缩得看不清
|
|
196
|
+
const pages = new Map();
|
|
197
|
+
for (const s of samples)
|
|
198
|
+
if (s.jpg) {
|
|
199
|
+
const k = s.scenarioId ?? '';
|
|
200
|
+
if (!pages.has(k))
|
|
201
|
+
pages.set(k, []);
|
|
202
|
+
pages.get(k).push(s);
|
|
203
|
+
}
|
|
204
|
+
const name = (sid) => project.scenarios[sid]?.name ?? sid;
|
|
205
|
+
const files = [];
|
|
206
|
+
let index = 0;
|
|
207
|
+
for (const [sid, cells] of pages) {
|
|
208
|
+
index++;
|
|
209
|
+
const file = pages.size === 1 ? out : out.replace(/(\.png)?$/i, `-${index}.png`);
|
|
210
|
+
const cutAt = (s) => cuts.find((c) => c.atMs > s.t - every && c.atMs <= s.t);
|
|
211
|
+
const stillAt = (s) => s.still >= stillMs;
|
|
212
|
+
const body = cells.map((s) => {
|
|
213
|
+
const cut = cutAt(s);
|
|
214
|
+
const step = s.position > 0 ? project.scenarios[sid]?.steps[s.position - 1] : undefined;
|
|
215
|
+
const first = cells.find((c) => c.position === s.position) === s;
|
|
216
|
+
const peak = Math.max(...samples.filter((x) => x.t > s.t - every && x.t <= s.t).map((x) => x.changed), 0);
|
|
217
|
+
return `<div class="cell${cut ? ' cut' : ''}${stillAt(s) ? ' still' : ''}"><img src="data:image/jpeg;base64,${s.jpg}"><div class="meta"><b>${(s.t / 1000).toFixed(2)}s</b> · ${s.position}${s.activeStep !== null ? `→${s.activeStep + 1}` : ''} <span class="bar"><i style="width:${Math.min(100, Math.round(peak * 100))}%"></i></span>${cut ? ` <em>CUT ${(cut.changed * 100).toFixed(0)}%</em>` : ''}${stillAt(s) ? ` <u>STILL ${(s.still / 1000).toFixed(1)}s</u>` : ''}${first && step ? `<div class="cap">${esc(step.caption)}</div>` : ''}</div></div>`;
|
|
218
|
+
}).join('');
|
|
219
|
+
const summary = `${cuts.filter((c) => c.scenarioId === sid).length} cuts · ${stills.filter((x) => x.scenarioId === sid).length} stills ≥ ${(stillMs / 1000).toFixed(1)}s · every ${every} ms, diff sampled every ${sampleMs} ms`;
|
|
220
|
+
const html = `<!doctype html><meta charset="utf-8"><style>
|
|
221
|
+
body{margin:0;padding:18px;background:#16181d;color:#e8e8ea;font:12px/1.35 -apple-system,"PingFang SC","Noto Sans SC",system-ui,sans-serif}
|
|
222
|
+
h1{font-size:16px;margin:0 0 4px} p{margin:0 0 12px;color:#a0a4b0} .grid{display:grid;grid-template-columns:repeat(${columns},${cellWidth}px);gap:8px}
|
|
223
|
+
.cell img{width:100%;display:block;border-radius:3px;border:2px solid #2c2f38} .cut img{border-color:#ff4d4f} .still img{border-color:#8a8f9c;filter:grayscale(.6)}
|
|
224
|
+
.meta{padding:2px 1px 0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} b{color:#ffb020} em{color:#ff6b6b;font-style:normal;font-weight:700} u{color:#c0c4cf;text-decoration:none}
|
|
225
|
+
.bar{display:inline-block;width:40px;height:5px;background:#2c2f38;vertical-align:middle}.bar i{display:block;height:100%;background:#5b8cff}
|
|
226
|
+
.cap{color:#c9ccd4;overflow:hidden;text-overflow:ellipsis}
|
|
227
|
+
</style><h1>${esc(name(sid))} · ${esc(sid)}</h1><p>${esc(summary)}. Red = one-frame full-screen change (hard cut); grey = no visible change for ≥ ${(stillMs / 1000).toFixed(1)}s; blue bar = largest adjacent-frame change in the cell.</p><div class="grid">${body}</div>`;
|
|
228
|
+
const sheet = await ctx.newPage();
|
|
229
|
+
await sheet.setViewportSize({ width: columns * cellWidth + (columns - 1) * 8 + 36, height: 600 });
|
|
230
|
+
await sheet.setContent(html, { waitUntil: 'load' });
|
|
231
|
+
const png = await sheet.screenshot({ type: 'png', fullPage: true });
|
|
232
|
+
await sheet.close();
|
|
233
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
234
|
+
fs.writeFileSync(file, png, opts.overwrite ? undefined : { flag: 'wx' });
|
|
235
|
+
files.push(file);
|
|
236
|
+
}
|
|
237
|
+
await ctx.close();
|
|
238
|
+
const result = { path: files[0], files, durationMs, sampleMs, every, samples: samples.length, cuts, stills, boundaries, maxDiff: round(Math.max(0, ...samples.map((s) => s.diff))), warnings: [] };
|
|
239
|
+
// 完整的判读数据(每一步提交前后的最大帧差、硬切、静止)放在胶片条旁边,评审时可以引用具体数字
|
|
240
|
+
fs.writeFileSync(out.replace(/(\.png)?$/i, '.json'), JSON.stringify({ ...result, frames: samples.map(({ jpg: _jpg, ...rest }) => rest) }, null, 1));
|
|
241
|
+
return result;
|
|
242
|
+
}
|
|
243
|
+
finally {
|
|
244
|
+
await browser?.close().catch(() => undefined);
|
|
245
|
+
await server.close();
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/** 视频:与看板导出相同的录制器(真实时间)。 */
|
|
249
|
+
export async function renderVideo(opts) {
|
|
250
|
+
const projectDir = realProjectDir(opts.projectDir);
|
|
251
|
+
const out = check({ ...opts, projectDir });
|
|
252
|
+
const { server, project } = await compiled(projectDir);
|
|
253
|
+
try {
|
|
254
|
+
const { url, size } = recordUrl(server.url, server.projectId, project, opts);
|
|
255
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
256
|
+
if (opts.overwrite)
|
|
257
|
+
fs.rmSync(out, { force: true });
|
|
258
|
+
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
|
+
return { path: out, durationMs: Date.now() - started };
|
|
261
|
+
}
|
|
262
|
+
finally {
|
|
263
|
+
await server.close();
|
|
264
|
+
}
|
|
265
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -9,8 +9,13 @@
|
|
|
9
9
|
export type { BuildOptions, BuildResult, CloudAccount, CloudBridge, CloudJob, CloudJobError, CloudPublishRequest, CloudPublishResult, DevHandle, DevOptions, RenderOptions, RenderResult, RenderedElement } from './contract.js';
|
|
10
10
|
export { startDev } from './dev.js';
|
|
11
11
|
export { buildSite } from './build.js';
|
|
12
|
+
export { startPreview, SITE_CONTENT_TYPES, type PreviewHandle } from './preview.js';
|
|
12
13
|
export { generateProjectVoice, type VoiceRunOptions, type VoiceRunResult } from './voice-run.js';
|
|
13
14
|
export type { CloudSpeechRequest, CloudSpeechResult, CloudVoice, CloudVoiceBridge, CloudVoiceCatalog, CloudVoiceInfo, CloudVoiceStatus, VoiceQuota } from './cloud.js';
|
|
14
15
|
export { renderSheet, renderStep } from './render.js';
|
|
16
|
+
export { renderFilm, renderVideo } from './film.js';
|
|
15
17
|
export { EXPORT_DOWNLOAD_MB, PLAYWRIGHT_VERSION, SETUP_COMMAND, exportRuntimeStatus, installExportRuntime, uninstallExportRuntime, type ExportRuntimeStatus, type InstallProgress, type InstallResult } from './export-runtime.js';
|
|
16
18
|
export { buildFeatureDiff, publicIRFromHtml, type DiffBuildOptions, type DiffBuildResult } from './feature-diff.js';
|
|
19
|
+
export { generateResources } from './resources-run.js';
|
|
20
|
+
export { LocalResources } from './local-resources.js';
|
|
21
|
+
export { inspectResources, mediaDiagnostics } from './media-check.js';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
export { startDev } from "./dev.js";
|
|
2
2
|
export { buildSite } from "./build.js";
|
|
3
|
+
export { startPreview, SITE_CONTENT_TYPES } from "./preview.js";
|
|
3
4
|
export { generateProjectVoice } from "./voice-run.js";
|
|
4
5
|
export { renderSheet, renderStep } from "./render.js";
|
|
6
|
+
export { renderFilm, renderVideo } from "./film.js";
|
|
5
7
|
export { EXPORT_DOWNLOAD_MB, PLAYWRIGHT_VERSION, SETUP_COMMAND, exportRuntimeStatus, installExportRuntime, uninstallExportRuntime } from "./export-runtime.js";
|
|
6
8
|
export { buildFeatureDiff, publicIRFromHtml } from "./feature-diff.js";
|
|
9
|
+
export { generateResources } from "./resources-run.js";
|
|
10
|
+
export { LocalResources } from "./local-resources.js";
|
|
11
|
+
export { inspectResources, mediaDiagnostics } from "./media-check.js";
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { ResourceRequest, PluginKey, LocalResourceInfo, AudioRegion } from '@joplo-app/kit/plugin';
|
|
2
|
+
import { type Project, type Diagnostic } from '@joplo-app/core';
|
|
3
|
+
type Result = {
|
|
4
|
+
url?: string;
|
|
5
|
+
audio?: AudioRegion;
|
|
6
|
+
credit?: string;
|
|
7
|
+
license?: string;
|
|
8
|
+
bytes?: number;
|
|
9
|
+
diagnostic?: Diagnostic;
|
|
10
|
+
};
|
|
11
|
+
export declare class LocalResources {
|
|
12
|
+
readonly directory: string;
|
|
13
|
+
private entries;
|
|
14
|
+
readonly keys: Record<string, readonly PluginKey[]>;
|
|
15
|
+
private bundles;
|
|
16
|
+
private descriptions;
|
|
17
|
+
constructor(directory: string, entries: Record<string, string>, keys?: Record<string, readonly PluginKey[]>);
|
|
18
|
+
private bundle;
|
|
19
|
+
describe(request: ResourceRequest): Promise<{
|
|
20
|
+
persistent: boolean;
|
|
21
|
+
credits?: number;
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
inspect?: boolean;
|
|
24
|
+
requiresAttribution?: boolean;
|
|
25
|
+
}>;
|
|
26
|
+
/** Lightweight author-only metadata. No rendering, bank download or provider spend. */
|
|
27
|
+
inspect(request: ResourceRequest): Promise<{
|
|
28
|
+
info?: LocalResourceInfo;
|
|
29
|
+
diagnostic?: Diagnostic;
|
|
30
|
+
}>;
|
|
31
|
+
ensure(request: ResourceRequest, limits?: {
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
maxBytes?: number;
|
|
34
|
+
allowSpend?: boolean;
|
|
35
|
+
home?: string;
|
|
36
|
+
}): Promise<Result>;
|
|
37
|
+
}
|
|
38
|
+
export declare function inlineResources(project: Project, requests: ResourceRequest[], host: LocalResources): Promise<{
|
|
39
|
+
assets: Record<string, string>;
|
|
40
|
+
audioInfo: Record<string, AudioRegion>;
|
|
41
|
+
diagnostics: Diagnostic[];
|
|
42
|
+
credits: string[];
|
|
43
|
+
licenses: string[];
|
|
44
|
+
rawBytes: number;
|
|
45
|
+
embeddedBytes: number;
|
|
46
|
+
}>;
|
|
47
|
+
export { nodeResourceIds as referencedResources, resolveResourceProps } from '@joplo-app/core';
|