@joplo-app/server 0.2.18 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ import type { Diagnostic } from '@joplo-app/core';
2
+ export declare function binaryAssets<T>(value: T, opts: {
3
+ directory?: string;
4
+ prefix?: string;
5
+ diagnostics?: Diagnostic[];
6
+ }, seen?: Set<string>): T;
@@ -0,0 +1,25 @@
1
+ /** Dev serves binary bytes by content hash; static builds keep data URIs for file://. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+ export function binaryAssets(value, opts, seen = new Set()) {
6
+ if (typeof value === 'string' && /^data:(model\/gltf-binary|audio\/[a-z0-9.+-]+);base64,/.test(value)) {
7
+ const comma = value.indexOf(','), mime = value.slice(5, comma - 7), bytes = Buffer.from(value.slice(comma + 1), 'base64'), hash = crypto.createHash('sha256').update(bytes).digest('hex');
8
+ if (!seen.has(hash) && mime === 'model/gltf-binary' && bytes.length > 5 * 1024 * 1024)
9
+ opts.diagnostics?.push({ severity: 'warning', source: 'structure', code: 'MODEL_SIZE', message: `GLB model is ${(bytes.length / 1024 / 1024).toFixed(1)} MB; reduce face_limit/textures before publishing (recommended below 5 MB).` });
10
+ seen.add(hash);
11
+ if (opts.directory && opts.prefix) {
12
+ const file = path.join(opts.directory, hash);
13
+ fs.mkdirSync(opts.directory, { recursive: true });
14
+ if (!fs.existsSync(file))
15
+ fs.writeFileSync(file, bytes);
16
+ return `${opts.prefix}${hash}${mime === 'model/gltf-binary' ? '.glb' : '.audio'}`;
17
+ }
18
+ return value;
19
+ }
20
+ if (Array.isArray(value))
21
+ return value.map(v => binaryAssets(v, opts, seen));
22
+ if (value && typeof value === 'object')
23
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, binaryAssets(v, opts, seen)]));
24
+ return value;
25
+ }
package/dist/build.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type StepIdentity, type Project } from '@joplo-app/core';
2
2
  import type { BuildOptions, BuildResult } from './contract.js';
3
- import type { DistWeb } from './web-assets.js';
3
+ import type { DistWeb, WebAssets } from './web-assets.js';
4
4
  /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级、镜头、角色(说话人、过渡卡、层级的 role)与 featureIds 顺序属于演示,保留(D43 / D56 / D61)。 */
5
5
  export declare function publishPayload(project: Project, home: string | null): {
6
6
  project: Record<string, unknown>;
@@ -20,3 +20,10 @@ export declare function finalizeHtml(html: string, readAsset: (rel: string) => s
20
20
  export declare function buildSite(opts: BuildOptions): Promise<BuildResult>;
21
21
  /** 从 npm 安装时:复制预构建的发布站,单独编译作者 className 的 CSS 并在 site.html 里引用。 */
22
22
  export declare function stageDistSite(web: DistWeb, projectDir: string, staging: string): Promise<void>;
23
+ /**
24
+ * 把每个插件运行时打成一个自包含的 ES 模块(依赖一起打进去),执行时注册到 globalThis.__JOPLO_PLUGINS__
25
+ * (web 的 renderer/plugins.ts 取走)。按插件 id 排序,产物稳定。
26
+ */
27
+ export declare function bundlePluginRuntimes(runtimes: Record<string, string>, projectDir: string, web: WebAssets, mode?: 'factory' | 'module'): Promise<string[]>;
28
+ /** 插件脚本放在第一个模块脚本(入口)之前:模块脚本按文档顺序执行,注册表载入时插件已经就位。 */
29
+ export declare function injectPluginScripts(html: string, codes: string[]): string;
package/dist/build.js CHANGED
@@ -1,3 +1,7 @@
1
+ import { binaryAssets } from "./binary-assets.js";
2
+ import { inlineResources } from "./local-resources.js";
3
+ import { inlinePluginAssets, PLUGIN_ASSET_BASE } from "./plugin-assets.js";
4
+ import sharedModules from '@joplo-app/web/shared-modules.json' with { type: 'json' };
1
5
  /**
2
6
  * `joplo build`:静态发布站。
3
7
  *
@@ -30,7 +34,7 @@ export function publishPayload(project, home) {
30
34
  // voiceConfig(D74):profile 名与音色属于作者本机的设置,发布站只需要 build 写进的 voiceIndex
31
35
  const { rules: _r, cases: _c, issues: _i, voiceConfig: _v, ...rest } = project;
32
36
  const features = Object.fromEntries(orderedFeatures(project).map(f => [f.id, { id: f.id, name: f.name, goal: f.goal, roles: f.roles, optionIds: f.optionIds, pick: f.pick }]));
33
- const options = Object.fromEntries(Object.entries(project.options).map(([id, o]) => [id, { id: o.id, featureId: o.featureId, key: o.key, name: o.name, idea: o.idea, routes: o.routes, coverage: {}, layers: o.layers ?? {} }]));
37
+ const options = Object.fromEntries(Object.entries(project.options).map(([id, o]) => [id, { id: o.id, featureId: o.featureId, key: o.key, name: o.name, idea: o.idea, routes: o.routes, coverage: {}, layers: o.layers ?? {}, ...(o.free ? { free: o.free } : {}) }]));
34
38
  const scenarios = Object.fromEntries(Object.entries(project.scenarios).map(([id, s]) => {
35
39
  const { caseIds: _ci, ...sr } = s;
36
40
  return [id, { ...sr, caseIds: [], steps: s.steps.map(({ ruleIds: _ri, key: _key, ...st }) => ({ ...st, ruleIds: [] })) }];
@@ -133,6 +137,18 @@ export async function buildSite(opts) {
133
137
  project = r.project;
134
138
  scope = r.info;
135
139
  }
140
+ let mediaCredits = [], mediaLicenses = [];
141
+ if (compiled.resources) {
142
+ const resources = await inlineResources(project, compiled.resources.requests, compiled.resources.host);
143
+ if (Object.keys(resources.assets).length)
144
+ project = { ...project, mediaAssets: resources.assets, mediaInfo: resources.audioInfo };
145
+ compiled.diagnostics.push(...resources.diagnostics);
146
+ mediaCredits = resources.credits;
147
+ mediaLicenses = resources.licenses;
148
+ if (resources.diagnostics.some(d => d.severity === 'error'))
149
+ throw new JoploError('EXPORT_FAILED', 'Audio attribution is incomplete; no site was published', { diagnostics: resources.diagnostics });
150
+ }
151
+ binaryAssets(project, { diagnostics: compiled.diagnostics });
136
152
  const inline = publishPayload(project, compiled.home);
137
153
  if (scope)
138
154
  inline.scoped = true;
@@ -164,9 +180,23 @@ export async function buildSite(opts) {
164
180
  fs.rmSync(siteHtml);
165
181
  for (const rel of inlined)
166
182
  fs.rmSync(path.join(staging, rel));
167
- fs.writeFileSync(path.join(staging, 'index.html'), html.replace(/<title>[^<]*<\/title>/i, () => `<title>${escapeHtml(project.name)} · Joplo</title>`));
183
+ // 插件运行时(D86):每个打成一个文件,内联在入口脚本之前(file:// 也能打开);只打包 IR 里用到的插件
184
+ const used = Object.fromEntries(Object.entries(compiled.pluginRuntimes).filter(([id]) => project.plugins?.[id]));
185
+ const pluginCode = await bundlePluginRuntimes(used, projectDir, web);
186
+ let withPlugins = injectPluginScripts(html, pluginCode);
187
+ if (mediaCredits.length) {
188
+ if (mediaLicenses.length)
189
+ fs.writeFileSync(path.join(staging, 'music-LICENSE.txt'), mediaLicenses.join('\n\n'));
190
+ fs.writeFileSync(path.join(staging, 'credits.txt'), `Music sound libraries\n\n${mediaCredits.join('\n\n')}\n`);
191
+ withPlugins = withPlugins.replace('</head>', '<link rel="license" href="./credits.txt" title="Music credits"></head>');
192
+ }
193
+ fs.writeFileSync(path.join(staging, 'index.html'), withPlugins.replace(/<title>[^<]*<\/title>/i, () => `<title>${escapeHtml(project.name)} · Joplo</title>`));
168
194
  // D59: scan every staged text artifact, then retain only font subsets its content needs.
169
195
  subsetSiteFonts(staging, web);
196
+ const siteBytes = listFiles(staging).reduce((n, f) => n + fs.statSync(path.join(staging, f)).size, 0);
197
+ compiled.diagnostics.push({ severity: 'info', source: 'structure', code: 'SITE_BUDGET', message: `Complete site: ${siteBytes} bytes (including embedded audio, fonts, models and narration)` });
198
+ if (siteBytes >= 18 * 1024 * 1024)
199
+ compiled.diagnostics.push({ severity: 'warning', source: 'structure', code: 'SITE_BUDGET_LARGE', message: 'Site approaches the documented Free 20 MiB single-upload budget (18 MiB warning); actual account limits come from the service' });
170
200
  // 4. 写入目标目录
171
201
  if (fs.existsSync(outDir))
172
202
  fs.rmSync(outDir, { recursive: true, force: true });
@@ -200,7 +230,7 @@ async function buildSourceSite(web, projectDir, staging) {
200
230
  base: './',
201
231
  mode: 'production',
202
232
  logLevel: 'error',
203
- resolve: { alias: [{ find: /^@joplo-app\/core$/, replacement: path.join(web.webDir, 'src/site/core-lite.ts') }, ...kitAliases(web, projectDir)] },
233
+ resolve: { alias: [{ find: /^@joplo-app\/core(?:\/runtime)?$/, replacement: path.join(web.webDir, 'src/site/core-lite.ts') }, ...kitAliases(web, projectDir)] },
204
234
  define: { 'process.env.NODE_ENV': '"production"' },
205
235
  plugins: [joploProjectPlugin(projectDir, web), react(), tailwindcss()],
206
236
  build: {
@@ -251,4 +281,57 @@ export async function stageDistSite(web, projectDir, staging) {
251
281
  fs.rmSync(cssOut, { recursive: true, force: true });
252
282
  }
253
283
  }
284
+ /**
285
+ * 把每个插件运行时打成一个自包含的 ES 模块(依赖一起打进去),执行时注册到 globalThis.__JOPLO_PLUGINS__
286
+ * (web 的 renderer/plugins.ts 取走)。按插件 id 排序,产物稳定。
287
+ */
288
+ export async function bundlePluginRuntimes(runtimes, projectDir, web, mode = 'factory') {
289
+ const out = [];
290
+ const modules = sharedModules;
291
+ const shared = Object.keys(modules);
292
+ const bridge = (name) => {
293
+ const keys = modules[name];
294
+ return `const shared = globalThis.__JOPLO_SHARED__[${JSON.stringify(name)}]; export default shared; ${keys.map(k => `export const ${k} = shared.${k};`).join(' ')}`;
295
+ };
296
+ for (const [id, file] of Object.entries(runtimes).sort(([a], [b]) => a.localeCompare(b))) {
297
+ const entry = '\0joplo-plugin-entry';
298
+ const r = (await viteBuild({
299
+ configFile: false,
300
+ envDir: false,
301
+ root: path.dirname(file),
302
+ base: PLUGIN_ASSET_BASE,
303
+ mode: 'production',
304
+ logLevel: 'error',
305
+ resolve: { alias: kitAliases(web, projectDir) },
306
+ define: { 'process.env.NODE_ENV': '"production"' },
307
+ oxc: { jsx: { runtime: 'automatic', importSource: 'react', development: false } },
308
+ plugins: [{
309
+ name: 'joplo:plugin-entry',
310
+ // Resolve shared modules before Vite finds a plugin's installed React copy.
311
+ enforce: 'pre',
312
+ resolveId: (src) => src === 'joplo-plugin-entry' ? entry : shared.includes(src) ? `\0joplo-shared:${src}` : null,
313
+ load: (resolved) => (resolved.startsWith('\0joplo-shared:') ? bridge(resolved.slice('\0joplo-shared:'.length)) : resolved === entry ? `import runtime from ${JSON.stringify(file)};\n${mode === 'module' ? 'export default runtime;' : '(globalThis.__JOPLO_PLUGINS__ ??= []).push(runtime);'}\n` : null),
314
+ }],
315
+ build: { write: false, assetsInlineLimit: 0, cssCodeSplit: false, minify: true, sourcemap: false, modulePreload: false, reportCompressedSize: false, emptyOutDir: false, rolldownOptions: { input: 'joplo-plugin-entry', ...(mode === 'module' ? { preserveEntrySignatures: 'strict' } : {}), output: { format: 'es', codeSplitting: false } } },
316
+ }));
317
+ const output = (Array.isArray(r) ? r : [r]).flatMap(o => o.output);
318
+ const chunks = output.filter((x) => x.type === 'chunk');
319
+ if (chunks.length !== 1)
320
+ throw new JoploError('EXPORT_FAILED', `Plugin ${id}: expected one bundled runtime file, got ${chunks.length}`);
321
+ const code = inlinePluginAssets(id, chunks[0].code, output.filter((x) => x.type === 'asset'));
322
+ // Defer evaluation until the host has initialized its shared React instance.
323
+ out.push(mode === 'module' ? code : `(globalThis.__JOPLO_PLUGIN_FACTORIES__ ??= []).push({id:${JSON.stringify(id)},load:()=>{\n${code}\n}});`);
324
+ }
325
+ return out;
326
+ }
327
+ /** 插件脚本放在第一个模块脚本(入口)之前:模块脚本按文档顺序执行,注册表载入时插件已经就位。 */
328
+ export function injectPluginScripts(html, codes) {
329
+ if (!codes.length)
330
+ return html;
331
+ const tags = codes.map((c) => `<script type="module" data-joplo-plugin>${c.replace(/<\/script/gi, '<\\/script')}</script>`).join('\n');
332
+ const i = html.indexOf('<script type="module">');
333
+ if (i < 0)
334
+ throw new JoploError('EXPORT_FAILED', 'Published site has no entry script to put plugin runtimes before');
335
+ return `${html.slice(0, i)}${tags}\n${html.slice(i)}`;
336
+ }
254
337
  const escapeHtml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
@@ -142,3 +142,60 @@ export type SheetResult = {
142
142
  warnings: string[];
143
143
  };
144
144
  export declare function renderSheet(opts: SheetOptions): Promise<SheetResult>;
145
+ /**
146
+ * 胶片条(`joplo render --film`):按引擎时间逐帧定格(Playwright 假时钟),每 sampleMs 算一次相邻帧差,每 every 取一格。
147
+ * 每个场景一页(多页时 out 之后加 -1、-2…);cuts = 单帧整屏突变,stills = 至少 stillMs 没有可见变化,boundaries = 每次提交一步前后的最大相邻帧差。
148
+ */
149
+ export type FilmOptions = Omit<RenderOptions, 'stepId' | 'viewport' | 'scope' | 'scale'> & {
150
+ chain?: boolean;
151
+ every?: number;
152
+ sampleMs?: number;
153
+ stillMs?: number;
154
+ columns?: number;
155
+ cellWidth?: number; /** 把胶片格另存为 JPEG 的目录(可选)。 */
156
+ frames?: string;
157
+ };
158
+ export type FilmCut = {
159
+ atMs: number;
160
+ diff: number;
161
+ changed: number;
162
+ scenarioId: string | null;
163
+ position: number;
164
+ };
165
+ export type FilmStill = {
166
+ fromMs: number;
167
+ toMs: number;
168
+ scenarioId: string | null;
169
+ position: number;
170
+ };
171
+ export type FilmBoundary = {
172
+ atMs: number;
173
+ scenarioId: string | null;
174
+ position: number;
175
+ chapter: boolean;
176
+ maxDiff: number;
177
+ maxChanged: number;
178
+ };
179
+ export type FilmResult = {
180
+ path: string;
181
+ files: string[];
182
+ durationMs: number;
183
+ sampleMs: number;
184
+ every: number;
185
+ samples: number;
186
+ cuts: FilmCut[];
187
+ stills: FilmStill[];
188
+ boundaries: FilmBoundary[];
189
+ maxDiff: number;
190
+ warnings: string[];
191
+ };
192
+ export declare function renderFilm(opts: FilmOptions): Promise<FilmResult>;
193
+ /** 视频(`joplo render --video`):与看板导出同一个录制器(真实时间,webm)。 */
194
+ export type VideoOptions = Omit<RenderOptions, 'stepId' | 'viewport' | 'scope' | 'scale'> & {
195
+ chain?: boolean;
196
+ };
197
+ export type VideoResult = {
198
+ path: string;
199
+ durationMs: number;
200
+ };
201
+ export declare function renderVideo(opts: VideoOptions): Promise<VideoResult>;
package/dist/dev.d.ts CHANGED
@@ -12,6 +12,8 @@ export type DevPayload = {
12
12
  project: Project | null;
13
13
  diagnostics: Diagnostic[];
14
14
  home: string | null;
15
+ /** 插件(D86):插件 id → 运行时地址(本服务以 /@fs/<绝对路径> 提供,Vite 负责转译与依赖解析)。 */
16
+ plugins?: Record<string, string>;
15
17
  };
16
18
  /** 首页项目列表的一行。status:idle 未编译、compiling 首次编译中、ok、error(编译出错)、missing(目录不存在)。 */
17
19
  export type ProjectSummary = {
@@ -40,6 +42,7 @@ export type ProjectSlot = {
40
42
  loader: ViteDevServer | null;
41
43
  ready: Promise<void>;
42
44
  payload: DevPayload;
45
+ runtimeModules: Map<string, string>;
43
46
  compiling: boolean;
44
47
  closed: boolean;
45
48
  running: Promise<void> | null;
package/dist/dev.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { PluginKeyStore } from "./plugin-keys.js";
2
+ import { binaryAssets } from "./binary-assets.js";
3
+ import { inlineResources, referencedResources } from "./local-resources.js";
1
4
  /**
2
5
  * `joplo dev`:本机只运行一个看板进程(D39),同时服务多个项目。
3
6
  *
@@ -13,6 +16,7 @@
13
16
  * 端口被占用时直接报错(strictPort),不静默换端口。
14
17
  */
15
18
  import { spawn } from 'node:child_process';
19
+ import { bundlePluginRuntimes } from "./build.js";
16
20
  import crypto from 'node:crypto';
17
21
  import fs from 'node:fs';
18
22
  import path from 'node:path';
@@ -27,6 +31,17 @@ import { Registry, clearServerInfo, joploHome, normalizeSettings, pidAlive, proj
27
31
  import { compileProject, invalidateProjectModules } from "./project.js";
28
32
  import { SelectionBody, readSelection, resolveSelection, writeSelection } from "./selection.js";
29
33
  import { IGNORED_DIRS, cssSourcePlugin, isProjectSource, joploProjectPlugin, kitAliases, locateWebAssets, realProjectDir } from "./vite-shared.js";
34
+ /** 文件绝对路径 → Vite 的 /@fs/ 地址。 */
35
+ const fsUrl = (abs) => `/@fs${abs.split(path.sep).join('/').replace(/^(?!\/)/, '/')}`;
36
+ /** 离文件最近的 package.json 所在目录(插件包根目录);没有时用文件所在目录。 */
37
+ function packageRootOf(file) {
38
+ for (let d = path.dirname(file);; d = path.dirname(d)) {
39
+ if (fs.existsSync(path.join(d, 'package.json')))
40
+ return d;
41
+ if (path.dirname(d) === d)
42
+ return path.dirname(file);
43
+ }
44
+ }
30
45
  export const IR_EVENT = 'joplo:ir';
31
46
  export const PROJECTS_EVENT = 'joplo:projects';
32
47
  /** 朗读状态变化(D74):{ projectId, state }。 */
@@ -201,7 +216,7 @@ export async function createHub(opts = {}) {
201
216
  root: slot.dir,
202
217
  appType: 'custom',
203
218
  customLogger: makeLogger(log),
204
- resolve: { alias: kitAliases(web, slot.dir) },
219
+ resolve: { dedupe: ['react', 'react-dom'], alias: kitAliases(web, slot.dir) },
205
220
  plugins: [joploProjectPlugin(slot.dir, web)],
206
221
  // 只在服务端载入模块:不开 HMR、不开 WebSocket(多个项目同时运行时不能争用端口)、不监听
207
222
  server: { middlewareMode: true, hmr: false, ws: false, watch: null },
@@ -209,12 +224,60 @@ export async function createHub(opts = {}) {
209
224
  cacheDir: path.join(slot.dir, '.joplo/vite'),
210
225
  });
211
226
  }
227
+ /**
228
+ * 插件运行时由看板的 Vite 服务以 /@fs/ 提供(D86)。dist 形态的 fs.allow 只有 @joplo-app/web:
229
+ * 把项目目录(npm 安装的插件与它的依赖在 node_modules 里)和插件包目录加进去。source 形态也可能打开工作区外的项目,同样补齐其显式启用的插件目录。
230
+ */
231
+ function allowPluginFiles(projectDir, runtimes) {
232
+ if (!server)
233
+ return;
234
+ const allow = server.config.server.fs.allow;
235
+ for (const dir of [projectDir, ...runtimes.map(packageRootOf)])
236
+ if (!allow.some((a) => dir === a || dir.startsWith(a + path.sep)))
237
+ allow.push(dir);
238
+ }
239
+ const localResources = new Map();
240
+ const resourceWarnings = new Map();
212
241
  async function recompile(slot) {
213
242
  const loader = slot.loader;
214
243
  invalidateProjectModules(loader, slot.dir);
215
244
  const out = await compileProject(loader, slot.dir, 'dev');
245
+ if (out.resources)
246
+ localResources.set(slot.id, out.resources);
247
+ else
248
+ localResources.delete(slot.id);
249
+ resourceWarnings.set(slot.id, new Map());
250
+ if (out.project && out.resources?.requests.length)
251
+ out.project.mediaAssets = Object.fromEntries(out.resources.requests.map(r => [r.id, `/__joplo/p/${encodeURIComponent(slot.id)}/resources/${encodeURIComponent(r.id)}`]));
252
+ if (out.project) {
253
+ if (out.resources) {
254
+ const resources = await inlineResources(out.project, out.resources.requests.filter(r => referencedResources(out.project).has(r.id)), out.resources.host);
255
+ out.project.mediaAssets = { ...out.project.mediaAssets, ...resources.assets };
256
+ }
257
+ out.project = binaryAssets(out.project, { directory: path.join(slot.dir, '.joplo', 'binary'), prefix: `/__joplo/p/${encodeURIComponent(slot.id)}/binary/`, diagnostics: out.diagnostics });
258
+ }
216
259
  const prev = slot.payload;
217
- slot.payload = { version: prev.version + 1, ok: out.project !== null, project: out.project ?? prev.project, diagnostics: out.diagnostics, home: out.home ?? prev.home };
260
+ const plugins = out.pluginRuntimes;
261
+ let runtimeUrls = {};
262
+ if (web.mode === 'dist' && out.project) {
263
+ // A prebuilt board owns React. Bundle npm/CommonJS dependencies and bridge
264
+ // React to that exact host instance, just as the file:// publish path does.
265
+ const ids = Object.keys(plugins).sort();
266
+ const modules = await bundlePluginRuntimes(plugins, slot.dir, web, 'module');
267
+ const next = new Map();
268
+ ids.forEach((id, i) => {
269
+ const code = modules[i];
270
+ const key = `${id}-${crypto.createHash('sha256').update(code).digest('hex').slice(0, 20)}.js`;
271
+ next.set(key, code);
272
+ runtimeUrls[id] = `/__joplo/p/${encodeURIComponent(slot.id)}/runtime/${key}`;
273
+ });
274
+ slot.runtimeModules = next;
275
+ }
276
+ else if (web.mode === 'source') {
277
+ allowPluginFiles(slot.dir, Object.values(plugins));
278
+ runtimeUrls = Object.fromEntries(Object.entries(plugins).map(([id, f]) => [id, fsUrl(f)]));
279
+ }
280
+ slot.payload = { version: prev.version + 1, ok: out.project !== null, project: out.project ?? prev.project, diagnostics: out.diagnostics, home: out.home ?? prev.home, plugins: out.project ? runtimeUrls : prev.plugins ?? runtimeUrls };
218
281
  const errors = out.diagnostics.filter((d) => d.severity === 'error');
219
282
  if (errors.length)
220
283
  log(`[joplo] ${path.basename(slot.dir)} compilation failed (${errors.length}): ${errors.map((d) => `${d.at ?? ''} ${d.message}`).join('; ').slice(0, 400)}`);
@@ -265,6 +328,7 @@ export async function createHub(opts = {}) {
265
328
  loader: null,
266
329
  ready: Promise.resolve(),
267
330
  payload: { version: 0, ok: false, project: null, diagnostics: [], home: null },
331
+ runtimeModules: new Map(),
268
332
  compiling: true,
269
333
  closed: false,
270
334
  running: null,
@@ -336,6 +400,7 @@ export async function createHub(opts = {}) {
336
400
  onEvent: () => undefined,
337
401
  });
338
402
  // 朗读(D74):声音供应商 profile(本机)与项目音频缓存;状态变化推 joplo:voice
403
+ const pluginKeys = new PluginKeyStore(opts.home ?? joploHome());
339
404
  const voiceHub = new VoiceHub(opts.home ?? joploHome(), {
340
405
  // 托管朗读(D85):CLI 注入的登录与合成;旧 CLI 没有时只用浏览器朗读与自带 Key 的供应商
341
406
  cloud: opts.cloud?.voice,
@@ -375,8 +440,10 @@ export async function createHub(opts = {}) {
375
440
  try {
376
441
  return { ok: true, body: JSON.parse(raw.text) };
377
442
  }
378
- catch (e) {
379
- return sendJson(res, 400, { error: { code: 'USAGE', message: `Request body is not valid JSON: ${e instanceof Error ? e.message : String(e)}` } }), { ok: false };
443
+ catch {
444
+ // SyntaxError messages can include request fragments, including unsaved credentials.
445
+ // Keep the shared parser safe for every caller; never return or log the original error.
446
+ return sendJson(res, 400, { error: { code: 'USAGE', message: 'Request body is not valid JSON' } }), { ok: false };
380
447
  }
381
448
  };
382
449
  const fail = (res, e) => {
@@ -386,6 +453,30 @@ export async function createHub(opts = {}) {
386
453
  };
387
454
  async function handleProject(id, rest, req, res) {
388
455
  const method = req.method ?? 'GET';
456
+ if (rest === 'plugin-keys' || rest.startsWith('plugin-keys/')) {
457
+ if (!guardWrite(req, res, 403, method === 'PUT'))
458
+ return;
459
+ await ensure(id);
460
+ const declarations = localResources.get(id)?.host.keys ?? {};
461
+ if (rest === 'plugin-keys' && method === 'GET')
462
+ return sendJson(res, 200, Object.entries(declarations).flatMap(([plugin, keys]) => keys.map(key => pluginKeys.status(plugin, key))));
463
+ const match = /^plugin-keys\/([a-z][a-z0-9-]*)\/([a-z][a-z0-9-]*)$/.exec(rest);
464
+ const declaration = match && Object.hasOwn(declarations, match[1]) ? declarations[match[1]].find(key => key.id === match[2]) : undefined;
465
+ if (!match || !declaration)
466
+ return sendJson(res, 404, { error: { code: 'NOT_FOUND', message: 'Plugin key is not declared by this project' } });
467
+ if (method === 'PUT') {
468
+ const parsed = await jsonBody(req, res);
469
+ if (!parsed.ok)
470
+ return;
471
+ try {
472
+ return sendJson(res, 200, pluginKeys.save(match[1], declaration, parsed.body?.key));
473
+ }
474
+ catch {
475
+ return sendJson(res, 400, { error: { code: 'INVALID_KEY', message: 'Invalid plugin API key' } });
476
+ }
477
+ }
478
+ return sendJson(res, 405, { error: { code: 'METHOD_NOT_ALLOWED', message: 'Method not allowed' } });
479
+ }
389
480
  if (rest === 'review' && (method === 'GET' || method === 'POST')) {
390
481
  if (!guardWrite(req, res, 403, method === 'POST'))
391
482
  return;
@@ -406,6 +497,14 @@ export async function createHub(opts = {}) {
406
497
  throw new JoploError('USAGE', 'Invalid review request: include a sessionId, requestId, type, and page context for feedback (1–10000 characters)');
407
498
  return sendJson(res, 200, reviewHub.write(slot.dir, slot.payload.project, input.data));
408
499
  }
500
+ if (rest.startsWith('runtime/') && method === 'GET') {
501
+ const slot = await ensure(id), code = slot.runtimeModules.get(rest.slice('runtime/'.length));
502
+ if (code === undefined)
503
+ throw new JoploError('NOT_FOUND', 'Plugin runtime is not available for this project revision');
504
+ res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-cache', 'x-content-type-options': 'nosniff' });
505
+ res.end(code);
506
+ return;
507
+ }
409
508
  if (rest === 'ir' && method === 'GET') {
410
509
  const slot = await ensure(id);
411
510
  return sendJson(res, 200, { projectId: id, ...slot.payload });
@@ -458,6 +557,40 @@ export async function createHub(opts = {}) {
458
557
  req.method = 'GET';
459
558
  return 'next';
460
559
  }
560
+ if (rest.startsWith('binary/') && method === 'GET') {
561
+ const slot = await ensure(id), match = /^binary\/([a-f0-9]{64})\.(glb|audio)$/.exec(rest);
562
+ if (!match)
563
+ return sendJson(res, 404, { error: 'Unknown binary asset' });
564
+ const file = path.join(slot.dir, '.joplo', 'binary', match[1]);
565
+ if (!fs.existsSync(file))
566
+ return sendJson(res, 404, { error: 'Missing binary asset' });
567
+ res.setHeader('Content-Type', match[2] === 'glb' ? 'model/gltf-binary' : 'application/octet-stream');
568
+ res.end(fs.readFileSync(file));
569
+ return;
570
+ }
571
+ if (rest.startsWith('resources/') && method === 'POST') {
572
+ if (!guardWrite(req, res))
573
+ return;
574
+ const slot = await ensure(id), local = localResources.get(id);
575
+ const request = local?.requests.find(r => r.id === rest.slice('resources/'.length));
576
+ if (!request || !local)
577
+ return sendJson(res, 404, { error: 'Unknown resource' });
578
+ const version = slot.payload.version;
579
+ const result = await local.host.ensure(request);
580
+ if (slot.payload.version === version) {
581
+ const warnings = resourceWarnings.get(id);
582
+ if (result.diagnostic)
583
+ warnings.set(request.id, result.diagnostic);
584
+ else
585
+ warnings.delete(request.id);
586
+ const diagnostics = [...slot.payload.diagnostics.filter(d => !d.code.startsWith('LOCAL_RESOURCE_')), ...warnings.values()];
587
+ if (JSON.stringify(diagnostics) !== JSON.stringify(slot.payload.diagnostics)) {
588
+ slot.payload = { ...slot.payload, diagnostics };
589
+ server?.ws.send({ type: 'custom', event: 'joplo:diagnostics', data: { projectId: id, version, diagnostics } });
590
+ }
591
+ }
592
+ return sendJson(res, 200, result);
593
+ }
461
594
  if (rest === 'voice' || rest.startsWith('voice/')) {
462
595
  const slot = await ensure(id);
463
596
  const ctx = { guardWrite: (needJson = true) => guardWrite(req, res, 403, needJson), jsonBody: () => jsonBody(req, res), send: (status, body) => sendJson(res, status, body) };
@@ -589,7 +722,7 @@ export async function createHub(opts = {}) {
589
722
  appType: 'spa',
590
723
  clearScreen: false,
591
724
  customLogger: makeLogger(log),
592
- resolve: { alias: web.mode === 'source' ? kitAliases(web, web.webDir) : [] },
725
+ resolve: { dedupe: ['react', 'react-dom'], alias: web.mode === 'source' ? kitAliases(web, web.webDir) : [] },
593
726
  plugins: [cssSourcePlugin(activeDirs, web), boardPlugin, ...(await webPlugins(web))],
594
727
  // dist 形态不往 node_modules 里写缓存(可能只读,或被多个项目共享)
595
728
  cacheDir: web.mode === 'dist' ? path.join(opts.home ?? path.join(process.cwd(), '.joplo'), 'vite') : path.join(web.webDir, 'node_modules/.vite-joplo'),
package/dist/export.d.ts CHANGED
@@ -36,7 +36,8 @@ export type VideoRecorder = (input: {
36
36
  out: string;
37
37
  total: number;
38
38
  progress: (step: number) => void;
39
- signal: AbortSignal;
39
+ signal: AbortSignal; /** 最长录制时长(毫秒,默认 5 分钟)。 */
40
+ maxMs?: number;
40
41
  }) => Promise<void>;
41
42
  export type ExportDeps = {
42
43
  /** 按项目解析 Playwright(托管运行时优先,其次项目里已有的)。 */
package/dist/export.js CHANGED
@@ -17,6 +17,8 @@
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';
@@ -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 > 5 * 60_000)
95
- throw new JoploError('EXPORT_FAILED', 'Recording exceeded 5 minutes and was stopped');
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 {};