@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
|
@@ -0,0 +1,19 @@
|
|
|
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;
|
|
7
|
+
/** 发布素材的扩展名(D98):IR 里这些类型的 data URL 在构建时写成 assets/<sha256>.<ext>。 */
|
|
8
|
+
export declare const SITE_ASSET_TYPES: Record<string, string>;
|
|
9
|
+
/**
|
|
10
|
+
* 发布素材改成独立文件(D98,不再 base64 内联):把 value 里整串是 data URL 的素材写进 directory/<sha256>.<ext>,
|
|
11
|
+
* 换成 prefix + 文件名(页面按相对路径引用)。同一内容只写一次;返回新值与写出的文件名。未知类型原样保留。
|
|
12
|
+
*/
|
|
13
|
+
export declare function extractSiteAssets<T>(value: T, opts: {
|
|
14
|
+
directory: string;
|
|
15
|
+
prefix: string;
|
|
16
|
+
}): {
|
|
17
|
+
value: T;
|
|
18
|
+
files: string[];
|
|
19
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** Dev serves binary bytes by content hash; builds write every embedded asset as its own file (D98). */
|
|
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.+-]+|video\/(?:mp4|webm)|application\/json);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' : mime === 'video/mp4' ? '.mp4' : mime === 'video/webm' ? '.webm' : mime === 'application/json' ? '.json' : '.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
|
+
}
|
|
26
|
+
/** 发布素材的扩展名(D98):IR 里这些类型的 data URL 在构建时写成 assets/<sha256>.<ext>。 */
|
|
27
|
+
export const SITE_ASSET_TYPES = {
|
|
28
|
+
'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif', 'image/webp': '.webp', 'image/svg+xml': '.svg', 'image/avif': '.avif',
|
|
29
|
+
'model/gltf-binary': '.glb',
|
|
30
|
+
'audio/mpeg': '.mp3', 'audio/wav': '.wav', 'audio/x-wav': '.wav', 'audio/ogg': '.ogg', 'audio/flac': '.flac', 'audio/mp4': '.m4a', 'audio/aac': '.aac',
|
|
31
|
+
'video/mp4': '.mp4', 'video/webm': '.webm',
|
|
32
|
+
'application/json': '.json',
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* 发布素材改成独立文件(D98,不再 base64 内联):把 value 里整串是 data URL 的素材写进 directory/<sha256>.<ext>,
|
|
36
|
+
* 换成 prefix + 文件名(页面按相对路径引用)。同一内容只写一次;返回新值与写出的文件名。未知类型原样保留。
|
|
37
|
+
*/
|
|
38
|
+
export function extractSiteAssets(value, opts) {
|
|
39
|
+
const files = new Set();
|
|
40
|
+
const walk = (v) => {
|
|
41
|
+
if (typeof v === 'string' && v.startsWith('data:')) {
|
|
42
|
+
const m = /^data:([a-z0-9.+/-]+)(;[^,]*)?;base64,/i.exec(v);
|
|
43
|
+
const ext = m ? SITE_ASSET_TYPES[m[1].toLowerCase()] : undefined;
|
|
44
|
+
if (!m || !ext)
|
|
45
|
+
return v;
|
|
46
|
+
const bytes = Buffer.from(v.slice(m[0].length), 'base64');
|
|
47
|
+
const name = `${crypto.createHash('sha256').update(bytes).digest('hex')}${ext}`;
|
|
48
|
+
if (!files.has(name)) {
|
|
49
|
+
fs.mkdirSync(opts.directory, { recursive: true });
|
|
50
|
+
const file = path.join(opts.directory, name);
|
|
51
|
+
if (!fs.existsSync(file))
|
|
52
|
+
fs.writeFileSync(file, bytes);
|
|
53
|
+
files.add(name);
|
|
54
|
+
}
|
|
55
|
+
return `${opts.prefix}${name}`;
|
|
56
|
+
}
|
|
57
|
+
if (Array.isArray(v))
|
|
58
|
+
return v.map(walk);
|
|
59
|
+
if (v && typeof v === 'object')
|
|
60
|
+
return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)]));
|
|
61
|
+
return v;
|
|
62
|
+
};
|
|
63
|
+
return { value: walk(value), files: [...files] };
|
|
64
|
+
}
|
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, extractSiteAssets } 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;
|
|
@@ -158,15 +174,32 @@ export async function buildSite(opts) {
|
|
|
158
174
|
if (voice.index)
|
|
159
175
|
inline.project.voiceIndex = scope ? scopeProject({ ...project, voiceIndex: voice.index }, scope.scenarios).project.voiceIndex : voice.index;
|
|
160
176
|
voiceReport = voice.report;
|
|
177
|
+
// 素材写成独立文件(D98):IR 里的图片、模型、音频、视频 data URL → assets/<sha256>.<ext>,页面按相对路径引用;
|
|
178
|
+
// 构建产物只保证通过 HTTP 打开(Cloud 分享、joplo preview、任意静态服务器),不再支持 file:// 双击。
|
|
179
|
+
inline.project = extractSiteAssets(inline.project, { directory: path.join(staging, 'assets'), prefix: './assets/' }).value;
|
|
161
180
|
// 3. 后处理
|
|
162
181
|
const siteHtml = path.join(staging, 'site.html');
|
|
163
182
|
const { html, inlined } = finalizeHtml(fs.readFileSync(siteHtml, 'utf8'), (rel) => fs.readFileSync(path.join(staging, rel), 'utf8'), inline, stepIdentity(project));
|
|
164
183
|
fs.rmSync(siteHtml);
|
|
165
184
|
for (const rel of inlined)
|
|
166
185
|
fs.rmSync(path.join(staging, rel));
|
|
167
|
-
|
|
186
|
+
// 插件运行时(D86):每个打成一个文件,内联在入口脚本之前(file:// 也能打开);只打包 IR 里用到的插件
|
|
187
|
+
const used = Object.fromEntries(Object.entries(compiled.pluginRuntimes).filter(([id]) => project.plugins?.[id]));
|
|
188
|
+
const pluginCode = await bundlePluginRuntimes(used, projectDir, web);
|
|
189
|
+
let withPlugins = injectPluginScripts(html, pluginCode);
|
|
190
|
+
if (mediaCredits.length) {
|
|
191
|
+
if (mediaLicenses.length)
|
|
192
|
+
fs.writeFileSync(path.join(staging, 'music-LICENSE.txt'), mediaLicenses.join('\n\n'));
|
|
193
|
+
fs.writeFileSync(path.join(staging, 'credits.txt'), `Music sound libraries\n\n${mediaCredits.join('\n\n')}\n`);
|
|
194
|
+
withPlugins = withPlugins.replace('</head>', '<link rel="license" href="./credits.txt" title="Music credits"></head>');
|
|
195
|
+
}
|
|
196
|
+
fs.writeFileSync(path.join(staging, 'index.html'), withPlugins.replace(/<title>[^<]*<\/title>/i, () => `<title>${escapeHtml(project.name)} · Joplo</title>`));
|
|
168
197
|
// D59: scan every staged text artifact, then retain only font subsets its content needs.
|
|
169
198
|
subsetSiteFonts(staging, web);
|
|
199
|
+
const siteBytes = listFiles(staging).reduce((n, f) => n + fs.statSync(path.join(staging, f)).size, 0);
|
|
200
|
+
compiled.diagnostics.push({ severity: 'info', source: 'structure', code: 'SITE_BUDGET', message: `Complete site: ${siteBytes} bytes (including asset files, fonts and narration)` });
|
|
201
|
+
if (siteBytes >= 18 * 1024 * 1024)
|
|
202
|
+
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
203
|
// 4. 写入目标目录
|
|
171
204
|
if (fs.existsSync(outDir))
|
|
172
205
|
fs.rmSync(outDir, { recursive: true, force: true });
|
|
@@ -200,7 +233,7 @@ async function buildSourceSite(web, projectDir, staging) {
|
|
|
200
233
|
base: './',
|
|
201
234
|
mode: 'production',
|
|
202
235
|
logLevel: 'error',
|
|
203
|
-
resolve: { alias: [{ find: /^@joplo-app\/core
|
|
236
|
+
resolve: { alias: [{ find: /^@joplo-app\/core(?:\/runtime)?$/, replacement: path.join(web.webDir, 'src/site/core-lite.ts') }, ...kitAliases(web, projectDir)] },
|
|
204
237
|
define: { 'process.env.NODE_ENV': '"production"' },
|
|
205
238
|
plugins: [joploProjectPlugin(projectDir, web), react(), tailwindcss()],
|
|
206
239
|
build: {
|
|
@@ -251,4 +284,57 @@ export async function stageDistSite(web, projectDir, staging) {
|
|
|
251
284
|
fs.rmSync(cssOut, { recursive: true, force: true });
|
|
252
285
|
}
|
|
253
286
|
}
|
|
287
|
+
/**
|
|
288
|
+
* 把每个插件运行时打成一个自包含的 ES 模块(依赖一起打进去),执行时注册到 globalThis.__JOPLO_PLUGINS__
|
|
289
|
+
* (web 的 renderer/plugins.ts 取走)。按插件 id 排序,产物稳定。
|
|
290
|
+
*/
|
|
291
|
+
export async function bundlePluginRuntimes(runtimes, projectDir, web, mode = 'factory') {
|
|
292
|
+
const out = [];
|
|
293
|
+
const modules = sharedModules;
|
|
294
|
+
const shared = Object.keys(modules);
|
|
295
|
+
const bridge = (name) => {
|
|
296
|
+
const keys = modules[name];
|
|
297
|
+
return `const shared = globalThis.__JOPLO_SHARED__[${JSON.stringify(name)}]; export default shared; ${keys.map(k => `export const ${k} = shared.${k};`).join(' ')}`;
|
|
298
|
+
};
|
|
299
|
+
for (const [id, file] of Object.entries(runtimes).sort(([a], [b]) => a.localeCompare(b))) {
|
|
300
|
+
const entry = '\0joplo-plugin-entry';
|
|
301
|
+
const r = (await viteBuild({
|
|
302
|
+
configFile: false,
|
|
303
|
+
envDir: false,
|
|
304
|
+
root: path.dirname(file),
|
|
305
|
+
base: PLUGIN_ASSET_BASE,
|
|
306
|
+
mode: 'production',
|
|
307
|
+
logLevel: 'error',
|
|
308
|
+
resolve: { alias: kitAliases(web, projectDir) },
|
|
309
|
+
define: { 'process.env.NODE_ENV': '"production"' },
|
|
310
|
+
oxc: { jsx: { runtime: 'automatic', importSource: 'react', development: false } },
|
|
311
|
+
plugins: [{
|
|
312
|
+
name: 'joplo:plugin-entry',
|
|
313
|
+
// Resolve shared modules before Vite finds a plugin's installed React copy.
|
|
314
|
+
enforce: 'pre',
|
|
315
|
+
resolveId: (src) => src === 'joplo-plugin-entry' ? entry : shared.includes(src) ? `\0joplo-shared:${src}` : null,
|
|
316
|
+
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),
|
|
317
|
+
}],
|
|
318
|
+
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 } } },
|
|
319
|
+
}));
|
|
320
|
+
const output = (Array.isArray(r) ? r : [r]).flatMap(o => o.output);
|
|
321
|
+
const chunks = output.filter((x) => x.type === 'chunk');
|
|
322
|
+
if (chunks.length !== 1)
|
|
323
|
+
throw new JoploError('EXPORT_FAILED', `Plugin ${id}: expected one bundled runtime file, got ${chunks.length}`);
|
|
324
|
+
const code = inlinePluginAssets(id, chunks[0].code, output.filter((x) => x.type === 'asset'));
|
|
325
|
+
// Defer evaluation until the host has initialized its shared React instance.
|
|
326
|
+
out.push(mode === 'module' ? code : `(globalThis.__JOPLO_PLUGIN_FACTORIES__ ??= []).push({id:${JSON.stringify(id)},load:()=>{\n${code}\n}});`);
|
|
327
|
+
}
|
|
328
|
+
return out;
|
|
329
|
+
}
|
|
330
|
+
/** 插件脚本放在第一个模块脚本(入口)之前:模块脚本按文档顺序执行,注册表载入时插件已经就位。 */
|
|
331
|
+
export function injectPluginScripts(html, codes) {
|
|
332
|
+
if (!codes.length)
|
|
333
|
+
return html;
|
|
334
|
+
const tags = codes.map((c) => `<script type="module" data-joplo-plugin>${c.replace(/<\/script/gi, '<\\/script')}</script>`).join('\n');
|
|
335
|
+
const i = html.indexOf('<script type="module">');
|
|
336
|
+
if (i < 0)
|
|
337
|
+
throw new JoploError('EXPORT_FAILED', 'Published site has no entry script to put plugin runtimes before');
|
|
338
|
+
return `${html.slice(0, i)}${tags}\n${html.slice(i)}`;
|
|
339
|
+
}
|
|
254
340
|
const escapeHtml = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
package/dist/contract.d.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
379
|
-
|
|
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,59 @@ 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|mp4|webm|json)$/.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
|
+
const type = { glb: 'model/gltf-binary', mp4: 'video/mp4', webm: 'video/webm', json: 'application/json' }[match[2]] ?? 'application/octet-stream';
|
|
568
|
+
res.setHeader('Content-Type', type);
|
|
569
|
+
res.setHeader('Accept-Ranges', 'bytes');
|
|
570
|
+
const bytes = fs.readFileSync(file);
|
|
571
|
+
// 视频拖动(D96 媒体插件):单段 Range
|
|
572
|
+
const range = /^bytes=(\d*)-(\d*)$/.exec(String(req.headers.range ?? ''));
|
|
573
|
+
if (range && (range[1] || range[2])) {
|
|
574
|
+
const start = range[1] ? Number(range[1]) : Math.max(0, bytes.length - Number(range[2]));
|
|
575
|
+
const end = range[1] && range[2] ? Math.min(bytes.length - 1, Number(range[2])) : bytes.length - 1;
|
|
576
|
+
if (start > end || start >= bytes.length) {
|
|
577
|
+
res.statusCode = 416;
|
|
578
|
+
res.setHeader('Content-Range', `bytes */${bytes.length}`);
|
|
579
|
+
res.end();
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
res.statusCode = 206;
|
|
583
|
+
res.setHeader('Content-Range', `bytes ${start}-${end}/${bytes.length}`);
|
|
584
|
+
res.end(bytes.subarray(start, end + 1));
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
res.end(bytes);
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
if (rest.startsWith('resources/') && method === 'POST') {
|
|
591
|
+
if (!guardWrite(req, res))
|
|
592
|
+
return;
|
|
593
|
+
const slot = await ensure(id), local = localResources.get(id);
|
|
594
|
+
const request = local?.requests.find(r => r.id === rest.slice('resources/'.length));
|
|
595
|
+
if (!request || !local)
|
|
596
|
+
return sendJson(res, 404, { error: 'Unknown resource' });
|
|
597
|
+
const version = slot.payload.version;
|
|
598
|
+
const result = await local.host.ensure(request);
|
|
599
|
+
if (slot.payload.version === version) {
|
|
600
|
+
const warnings = resourceWarnings.get(id);
|
|
601
|
+
if (result.diagnostic)
|
|
602
|
+
warnings.set(request.id, result.diagnostic);
|
|
603
|
+
else
|
|
604
|
+
warnings.delete(request.id);
|
|
605
|
+
const diagnostics = [...slot.payload.diagnostics.filter(d => !d.code.startsWith('LOCAL_RESOURCE_')), ...warnings.values()];
|
|
606
|
+
if (JSON.stringify(diagnostics) !== JSON.stringify(slot.payload.diagnostics)) {
|
|
607
|
+
slot.payload = { ...slot.payload, diagnostics };
|
|
608
|
+
server?.ws.send({ type: 'custom', event: 'joplo:diagnostics', data: { projectId: id, version, diagnostics } });
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
return sendJson(res, 200, result);
|
|
612
|
+
}
|
|
461
613
|
if (rest === 'voice' || rest.startsWith('voice/')) {
|
|
462
614
|
const slot = await ensure(id);
|
|
463
615
|
const ctx = { guardWrite: (needJson = true) => guardWrite(req, res, 403, needJson), jsonBody: () => jsonBody(req, res), send: (status, body) => sendJson(res, status, body) };
|
|
@@ -589,7 +741,7 @@ export async function createHub(opts = {}) {
|
|
|
589
741
|
appType: 'spa',
|
|
590
742
|
clearScreen: false,
|
|
591
743
|
customLogger: makeLogger(log),
|
|
592
|
-
resolve: { alias: web.mode === 'source' ? kitAliases(web, web.webDir) : [] },
|
|
744
|
+
resolve: { dedupe: ['react', 'react-dom'], alias: web.mode === 'source' ? kitAliases(web, web.webDir) : [] },
|
|
593
745
|
plugins: [cssSourcePlugin(activeDirs, web), boardPlugin, ...(await webPlugins(web))],
|
|
594
746
|
// dist 形态不往 node_modules 里写缓存(可能只读,或被多个项目共享)
|
|
595
747
|
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
|
@@ -4,7 +4,7 @@ import { type InstallDeps, type InstallProgress, type PlaywrightModule } from '.
|
|
|
4
4
|
export type Device = 'desktop' | 'mobile';
|
|
5
5
|
/**
|
|
6
6
|
* 导出画面的尺寸:电脑 = 舞台 1280×800;手机 = 外框(renderer 的 phoneFrameSize(390, 844) = 446×934)
|
|
7
|
-
* 四周再留 16px(RenderApp 的 frame
|
|
7
|
+
* 四周再留 16px(RenderApp 的 frame 模式)。字幕与步骤标题条浮在舞台上(D97),不另占高度。
|
|
8
8
|
*/
|
|
9
9
|
export declare const EXPORT_SIZE: Record<Device, {
|
|
10
10
|
width: number;
|
|
@@ -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(托管运行时优先,其次项目里已有的)。 */
|