@joplo-app/server 0.2.5 → 0.2.7

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/build.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type Project } from '@joplo-app/core';
2
2
  import type { BuildOptions, BuildResult } from './contract.js';
3
3
  import type { DistWeb } from './web-assets.js';
4
- /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级、镜头与 featureIds 顺序属于演示,保留(D43 / D61)。 */
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>;
7
7
  home: string | null;
package/dist/build.js CHANGED
@@ -23,10 +23,10 @@ import { JoploError, orderedFeatures } from '@joplo-app/core';
23
23
  import { compileProject } from "./project.js";
24
24
  import { joploProjectPlugin, kitAliases, locateWebAssets, realProjectDir } from "./vite-shared.js";
25
25
  import { subsetSiteFonts } from "./site-fonts.js";
26
- /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级、镜头与 featureIds 顺序属于演示,保留(D43 / D61)。 */
26
+ /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级、镜头、角色(说话人、过渡卡、层级的 role)与 featureIds 顺序属于演示,保留(D43 / D56 / D61)。 */
27
27
  export function publishPayload(project, home) {
28
28
  const { rules: _r, cases: _c, issues: _i, ...rest } = project;
29
- const features = Object.fromEntries(orderedFeatures(project).map(f => [f.id, { id: f.id, name: f.name, goal: f.goal, optionIds: f.optionIds, pick: f.pick }]));
29
+ 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 }]));
30
30
  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 ?? {} }]));
31
31
  const scenarios = Object.fromEntries(Object.entries(project.scenarios).map(([id, s]) => {
32
32
  const { caseIds: _ci, ...sr } = s;
package/dist/dev.d.ts CHANGED
@@ -52,7 +52,10 @@ export type HubOptions = {
52
52
  home?: string | null;
53
53
  /** 测试注入:导出用的 Playwright 载入、视频录制。 */
54
54
  exportDeps?: Partial<ExportDeps>;
55
+ /** 启动这个看板的项目目录(写进 server.json,后来加入的 joplo dev 会说明)。 */
56
+ startedIn?: string;
55
57
  };
58
+ export declare function serverVersion(): string;
56
59
  export type Hub = {
57
60
  url: string;
58
61
  port: number;
@@ -85,10 +88,16 @@ export type InternalDevHandle = DevHandle & {
85
88
  };
86
89
  /** 启动一个看板进程并打开一个项目(等首次编译完成)。缺省不持久化。 */
87
90
  export declare function createDev(opts: InternalDevOptions): Promise<InternalDevHandle>;
88
- /** 已有存活的看板:用令牌注册项目,返回项目链接;没有或不可用时返回 null。 */
89
- export declare function attachToRunning(home: string, projectDir: string, log: (s: string) => void): Promise<{
91
+ /**
92
+ * 已有存活的看板:用令牌注册项目,返回项目链接;没有或不可用时返回 null。
93
+ * 提示里写出那个看板的 Joplo 版本与启动目录;和 ownVersion(当前项目用的 Joplo)不一致时再给一行警告和处理办法(D65)。
94
+ */
95
+ export declare function attachToRunning(home: string, projectDir: string, log: (s: string) => void, ownVersion?: string): Promise<{
90
96
  url: string;
91
97
  port: number;
98
+ pid: number;
99
+ version: string | null;
100
+ dir: string | null;
92
101
  } | null>;
93
102
  /**
94
103
  * CLI 的 `joplo dev`:同一个 JOPLO_HOME 下只运行一个看板进程。
@@ -96,5 +105,6 @@ export declare function attachToRunning(home: string, projectDir: string, log: (
96
105
  */
97
106
  export declare function startDev(opts: DevOptions & {
98
107
  home?: string;
99
- exportDeps?: Partial<ExportDeps>;
108
+ exportDeps?: Partial<ExportDeps>; /** 测试注入:当前项目的 Joplo 版本。 */
109
+ version?: string;
100
110
  }): Promise<DevHandle>;
package/dist/dev.js CHANGED
@@ -141,6 +141,20 @@ class MemoryRegistry {
141
141
  return this.items.length !== n;
142
142
  }
143
143
  }
144
+ /** 本包(与 CLI 同一版本)的版本号:看板 ping 与 server.json 都带上,加入时比较。 */
145
+ let cachedVersion = null;
146
+ export function serverVersion() {
147
+ if (cachedVersion !== null)
148
+ return cachedVersion;
149
+ try {
150
+ const v = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
151
+ cachedVersion = typeof v === 'string' ? v : '0.0.0';
152
+ }
153
+ catch {
154
+ cachedVersion = '0.0.0';
155
+ }
156
+ return cachedVersion;
157
+ }
144
158
  const projectUrl = (base, id) => `${base}#/${encodeURIComponent(id)}`;
145
159
  export async function createHub(opts = {}) {
146
160
  const log = opts.log ?? ((m) => process.stderr.write(m + '\n'));
@@ -304,6 +318,7 @@ export async function createHub(opts = {}) {
304
318
  const exportsHub = new ExportHub({
305
319
  baseUrl,
306
320
  log,
321
+ home: opts.home ?? joploHome(),
307
322
  deps: opts.exportDeps,
308
323
  onEvent: () => undefined,
309
324
  });
@@ -334,7 +349,7 @@ export async function createHub(opts = {}) {
334
349
  };
335
350
  const fail = (res, e) => {
336
351
  const code = e instanceof JoploError ? e.code : 'INTERNAL';
337
- const status = code === 'NOT_FOUND' ? 404 : code === 'USAGE' ? 400 : code === 'RENDER_FAILED' ? 503 : 500;
352
+ const status = code === 'NOT_FOUND' ? 404 : code === 'USAGE' ? 400 : code === 'RENDER_FAILED' || code === 'EXPORT_COMPONENT_MISSING' ? 503 : 500;
338
353
  sendJson(res, status, { error: { code, message: e instanceof Error ? e.message : String(e) } });
339
354
  };
340
355
  async function handleProject(id, rest, req, res) {
@@ -415,7 +430,7 @@ export async function createHub(opts = {}) {
415
430
  return next();
416
431
  const method = req.method ?? 'GET';
417
432
  if (url.pathname === '/__joplo/ping' && method === 'GET')
418
- return sendJson(res, 200, { joplo: true, pid: process.pid });
433
+ return sendJson(res, 200, { joplo: true, pid: process.pid, version: serverVersion() });
419
434
  if (url.pathname === '/__joplo/projects' && method === 'GET')
420
435
  return sendJson(res, 200, { projects: summaries() });
421
436
  // 看板设置(D51):主题选择,存于 <JOPLO_HOME>/settings.json(没有 home 时只在内存里)
@@ -458,6 +473,9 @@ export async function createHub(opts = {}) {
458
473
  broadcastProjects();
459
474
  return sendJson(res, 200, { ok: true });
460
475
  }
476
+ // 导出组件的安装(D66):只接受本机看板带令牌的请求(handleRuntime 内校验)
477
+ if (url.pathname.startsWith('/__joplo/export-runtime/'))
478
+ return exportsHub.handleRuntime(url.pathname.slice('/__joplo/export-runtime/'.length), req, res, { guardWrite: (needJson = true) => guardWrite(req, res, 403, needJson), jsonBody: () => jsonBody(req, res), fail: (e) => fail(res, e) });
461
479
  const pm = /^\/__joplo\/p\/([^/]+)\/(.+)$/.exec(url.pathname);
462
480
  if (pm) {
463
481
  const r = await handleProject(decodeURIComponent(pm[1]), pm[2], req, res);
@@ -528,7 +546,7 @@ export async function createHub(opts = {}) {
528
546
  const addr = server.httpServer?.address();
529
547
  actualPort = typeof addr === 'object' && addr ? addr.port : port;
530
548
  if (opts.home)
531
- writeServerInfo(opts.home, { port: actualPort, pid: process.pid, token });
549
+ writeServerInfo(opts.home, { port: actualPort, pid: process.pid, token, version: serverVersion(), dir: opts.startedIn ?? process.cwd() });
532
550
  if (watch) {
533
551
  server.watcher.on('all', (_ev, file) => {
534
552
  const slot = slotOfFile(path.resolve(file));
@@ -575,8 +593,11 @@ export async function createDev(opts) {
575
593
  throw e;
576
594
  }
577
595
  }
578
- /** 已有存活的看板:用令牌注册项目,返回项目链接;没有或不可用时返回 null。 */
579
- export async function attachToRunning(home, projectDir, log) {
596
+ /**
597
+ * 已有存活的看板:用令牌注册项目,返回项目链接;没有或不可用时返回 null。
598
+ * 提示里写出那个看板的 Joplo 版本与启动目录;和 ownVersion(当前项目用的 Joplo)不一致时再给一行警告和处理办法(D65)。
599
+ */
600
+ export async function attachToRunning(home, projectDir, log, ownVersion = serverVersion()) {
580
601
  const info = readServerInfo(home);
581
602
  if (!info)
582
603
  return null;
@@ -585,11 +606,13 @@ export async function attachToRunning(home, projectDir, log) {
585
606
  return null;
586
607
  }
587
608
  const base = `http://127.0.0.1:${info.port}`;
609
+ let boardVersion = null;
588
610
  try {
589
611
  const ping = await fetch(`${base}/__joplo/ping`, { signal: AbortSignal.timeout(1500) });
590
612
  const body = (await ping.json());
591
613
  if (!ping.ok || body.joplo !== true || body.pid !== info.pid)
592
614
  return null;
615
+ boardVersion = typeof body.version === 'string' ? body.version : typeof info.version === 'string' ? info.version : null;
593
616
  }
594
617
  catch {
595
618
  return null;
@@ -603,8 +626,11 @@ export async function attachToRunning(home, projectDir, log) {
603
626
  const body = (await res.json().catch(() => null));
604
627
  if (!res.ok || !body?.url)
605
628
  throw new JoploError('UNSUPPORTED_ACTION', `Cannot add the project to the running board (${base}, pid ${info.pid}): ${body?.error?.message ?? `HTTP ${res.status}`}`);
606
- log(`[joplo] Joined the running board (pid ${info.pid})`);
607
- return { url: body.url, port: info.port };
629
+ const dir = typeof info.dir === 'string' ? info.dir : null;
630
+ log(`[joplo] Joined the running board: Joplo ${boardVersion ?? 'version unknown (0.2.6 or earlier)'}, started in ${dir ?? 'an unknown directory'} (pid ${info.pid})`);
631
+ if (boardVersion !== ownVersion)
632
+ log(`[joplo] ! That board runs Joplo ${boardVersion ?? '0.2.6 or earlier'}, this project uses ${ownVersion}; the board may behave differently. To use ${ownVersion}, stop it (Ctrl+C in its terminal, or kill ${info.pid}), then run joplo dev here again.`);
633
+ return { url: body.url, port: info.port, pid: info.pid, version: boardVersion, dir };
608
634
  }
609
635
  function openBrowser(url, log) {
610
636
  const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
@@ -627,7 +653,7 @@ export async function startDev(opts) {
627
653
  if (!fs.existsSync(projectDir))
628
654
  throw new JoploError('NOT_FOUND', `Project directory does not exist: ${projectDir}`);
629
655
  const attach = async () => {
630
- const a = await attachToRunning(home, projectDir, log);
656
+ const a = await attachToRunning(home, projectDir, log, opts.version);
631
657
  if (!a)
632
658
  return null;
633
659
  if (opts.open)
@@ -639,7 +665,7 @@ export async function startDev(opts) {
639
665
  return existing;
640
666
  let hub;
641
667
  try {
642
- hub = await createHub({ port: opts.port, log, home, exportDeps: opts.exportDeps });
668
+ hub = await createHub({ port: opts.port, log, home, exportDeps: opts.exportDeps, startedIn: projectDir });
643
669
  }
644
670
  catch (e) {
645
671
  // 另一个 joplo dev 恰好同时启动:端口被它占了,改为加入它
@@ -0,0 +1,100 @@
1
+ import { JoploError } from '@joplo-app/core';
2
+ export type PlaywrightModule = typeof import('playwright-core');
3
+ /** 固定版本:与 server 的 devDependencies.playwright-core 一致(测试校验)。 */
4
+ export declare const PLAYWRIGHT_VERSION: string;
5
+ /** 下载量估计(MB,十进制):playwright-core 包 + Chromium headless shell + ffmpeg(macOS arm64 实测,见 D66)。 */
6
+ export declare const EXPORT_DOWNLOAD_MB: number;
7
+ export declare const SETUP_COMMAND: string;
8
+ export declare const NOT_NEEDED = "Writing demos, dev, check, build, and share do not need it.";
9
+ export type RuntimePaths = {
10
+ root: string;
11
+ dir: string;
12
+ browsers: string;
13
+ marker: string;
14
+ lock: string;
15
+ entry: string;
16
+ cli: string;
17
+ };
18
+ export declare function runtimePaths(home?: string): RuntimePaths;
19
+ /** 托管运行时是否已就绪(ready.json 版本一致、入口存在)。 */
20
+ export declare function managedReady(home?: string): boolean;
21
+ /** 项目里已有的 Playwright(从项目目录按 Node 的解析顺序找;只读取,不安装)。 */
22
+ export declare function projectPlaywright(projectDir: string | undefined): {
23
+ name: string;
24
+ file: string;
25
+ } | null;
26
+ /** 正在安装的进程(锁里的 pid 仍存活);没有时为 null。 */
27
+ export declare function installingPid(home?: string): number | null;
28
+ export type ExportRuntimeStatus = {
29
+ /** 能导出:托管运行时已就绪,或项目里已有 Playwright。 */
30
+ ready: boolean;
31
+ source: 'managed' | 'project' | null;
32
+ version: string;
33
+ dir: string;
34
+ downloadMB: number;
35
+ installingPid: number | null;
36
+ command: string;
37
+ };
38
+ export declare function exportRuntimeStatus(o?: {
39
+ home?: string;
40
+ projectDir?: string;
41
+ }): ExportRuntimeStatus;
42
+ export declare function missingError(): JoploError;
43
+ export type LoadOptions = {
44
+ home?: string;
45
+ projectDir?: string;
46
+ /** 测试注入:载入一个模块文件(缺省 import(file URL))。 */
47
+ importFile?: (file: string) => Promise<unknown>;
48
+ };
49
+ /**
50
+ * 解析 Playwright:托管运行时优先,其次项目里已有的;都没有时抛 EXPORT_COMPONENT_MISSING。
51
+ * 托管运行时载入前把 PLAYWRIGHT_BROWSERS_PATH 指向它自己的 browsers/(playwright-core 在初始化时读取)。
52
+ */
53
+ export declare function resolvePlaywright(o?: LoadOptions): Promise<{
54
+ source: 'managed' | 'project';
55
+ module: PlaywrightModule;
56
+ }>;
57
+ export declare function loadPlaywright(o?: LoadOptions): Promise<PlaywrightModule>;
58
+ export type InstallPhase = 'package' | 'browser' | 'verify' | 'done';
59
+ export type InstallProgress = {
60
+ phase: InstallPhase; /** 0–100(整体)。 */
61
+ percent: number; /** 正在下载的文件大小(MiB),playwright 报告后才有。 */
62
+ totalMB: number | null;
63
+ message: string;
64
+ };
65
+ export type CommandRunner = (cmd: string, args: string[], o: {
66
+ cwd: string;
67
+ env: NodeJS.ProcessEnv;
68
+ onLine: (line: string) => void;
69
+ signal?: AbortSignal;
70
+ }) => Promise<void>;
71
+ export type InstallDeps = {
72
+ run: CommandRunner;
73
+ /** 装好后的自检:能载入、能启动 Chromium。 */
74
+ verify: (p: RuntimePaths) => Promise<void>;
75
+ };
76
+ /** 缺省的命令执行:stdout / stderr 按行回调;非 0 退出时抛错(带最后几行输出)。 */
77
+ export declare const runCommand: CommandRunner;
78
+ export type InstallResult = {
79
+ alreadyInstalled: boolean;
80
+ dir: string;
81
+ version: string;
82
+ removedOld: string[];
83
+ };
84
+ /**
85
+ * 安装托管运行时:npm 装 playwright-core(cwd 与 --prefix 都是运行时目录)→ playwright-core 的 CLI 下载 Chromium headless shell
86
+ * 到运行时的 browsers/ → 自检 → 写 ready.json → 删掉旧版本的运行时目录。已就绪且没有 force 时直接返回。
87
+ */
88
+ export declare function installExportRuntime(o?: {
89
+ home?: string;
90
+ force?: boolean;
91
+ onProgress?: (p: InstallProgress) => void;
92
+ signal?: AbortSignal;
93
+ deps?: Partial<InstallDeps>;
94
+ }): Promise<InstallResult>;
95
+ /** 删除托管运行时(所有版本);有进程正在安装时报错。只动 `<JOPLO_HOME>/runtime/playwright-*`。 */
96
+ export declare function uninstallExportRuntime(o?: {
97
+ home?: string;
98
+ }): {
99
+ removed: string[];
100
+ };
@@ -0,0 +1,318 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ /**
10
+ * 导出组件(D66):图片 / 视频导出、`joplo render` 截图、`joplo share` 预览图用到的 Playwright + Chromium,
11
+ * 由 Joplo 自己装在 `<JOPLO_HOME>/runtime/playwright-<版本>/`,绝不写用户项目的 package.json、lockfile 或 node_modules。
12
+ *
13
+ * 目录(runtimePaths):
14
+ * - `node_modules/playwright-core/`:`npm install` 的 cwd 与 --prefix 都是这个目录(不是项目);
15
+ * - `browsers/`:`PLAYWRIGHT_BROWSERS_PATH`,只装 Chromium headless shell(+ 录视频用的 ffmpeg);
16
+ * - `ready.json`:最后一步写入;只有它在、版本一致、入口存在才算“已就绪”(中途失败的目录不算)。
17
+ * - `<runtime>/playwright-<版本>.lock`:安装锁(内容是 pid),CLI 与看板进程不会同时安装;持锁进程已退出时视为过期。
18
+ *
19
+ * 解析顺序(resolvePlaywright):托管运行时 → 项目里已有的 playwright / playwright-core / @playwright/test(兼容老项目,
20
+ * 只读取、不安装)→ 都没有时抛 EXPORT_COMPONENT_MISSING(带安装命令)。任何解析都不会触发下载;只有 installExportRuntime 下载,
21
+ * 而它只由 `joplo setup export`、交互终端里用户确认后的 render、本机看板的已授权安装请求调用。
22
+ */
23
+ import { spawn } from 'node:child_process';
24
+ import fs from 'node:fs';
25
+ import { createRequire } from 'node:module';
26
+ import path from 'node:path';
27
+ import { pathToFileURL } from 'node:url';
28
+ import { JoploError } from '@joplo-app/core';
29
+ import { joploHome, pidAlive } from "./home.js";
30
+ /** 固定版本:与 server 的 devDependencies.playwright-core 一致(测试校验)。 */
31
+ export const PLAYWRIGHT_VERSION = '1.64.1';
32
+ /** 下载量估计(MB,十进制):playwright-core 包 + Chromium headless shell + ffmpeg(macOS arm64 实测,见 D66)。 */
33
+ export const EXPORT_DOWNLOAD_MB = 100;
34
+ export const SETUP_COMMAND = 'npx joplo setup export';
35
+ export const NOT_NEEDED = 'Writing demos, dev, check, build, and share do not need it.';
36
+ export function runtimePaths(home = joploHome()) {
37
+ const root = path.join(home, 'runtime');
38
+ const dir = path.join(root, `playwright-${PLAYWRIGHT_VERSION}`);
39
+ return {
40
+ root,
41
+ dir,
42
+ browsers: path.join(dir, 'browsers'),
43
+ marker: path.join(dir, 'ready.json'),
44
+ lock: path.join(root, `playwright-${PLAYWRIGHT_VERSION}.lock`),
45
+ entry: path.join(dir, 'node_modules/playwright-core/index.mjs'),
46
+ cli: path.join(dir, 'node_modules/playwright-core/cli.js'),
47
+ };
48
+ }
49
+ function readMarker(p) {
50
+ try {
51
+ const v = JSON.parse(fs.readFileSync(p.marker, 'utf8'));
52
+ return v && v.version === PLAYWRIGHT_VERSION && typeof v.installedAt === 'string' ? v : null;
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ /** 托管运行时是否已就绪(ready.json 版本一致、入口存在)。 */
59
+ export function managedReady(home) {
60
+ const p = runtimePaths(home);
61
+ return !!readMarker(p) && fs.existsSync(p.entry);
62
+ }
63
+ const PROJECT_PACKAGES = ['playwright', 'playwright-core', '@playwright/test'];
64
+ /** 项目里已有的 Playwright(从项目目录按 Node 的解析顺序找;只读取,不安装)。 */
65
+ export function projectPlaywright(projectDir) {
66
+ if (!projectDir)
67
+ return null;
68
+ // 只沿项目目录向上找 node_modules/<包>(不走 NODE_PATH 等全局路径:pnpm 的 bin 包装会设置 NODE_PATH)
69
+ let cur = path.resolve(projectDir);
70
+ for (;;) {
71
+ for (const name of PROJECT_PACKAGES) {
72
+ if (!fs.existsSync(path.join(cur, 'node_modules', name, 'package.json')))
73
+ continue;
74
+ try {
75
+ return { name, file: createRequire(path.join(cur, '__joplo_resolve__.js')).resolve(name) };
76
+ }
77
+ catch {
78
+ // 包不完整:继续找
79
+ }
80
+ }
81
+ const parent = path.dirname(cur);
82
+ if (parent === cur)
83
+ return null;
84
+ cur = parent;
85
+ }
86
+ }
87
+ /** 正在安装的进程(锁里的 pid 仍存活);没有时为 null。 */
88
+ export function installingPid(home) {
89
+ try {
90
+ const pid = Number(fs.readFileSync(runtimePaths(home).lock, 'utf8').trim());
91
+ return Number.isInteger(pid) && pid > 0 && pidAlive(pid) ? pid : null;
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ }
97
+ export function exportRuntimeStatus(o = {}) {
98
+ const p = runtimePaths(o.home);
99
+ const source = managedReady(o.home) ? 'managed' : projectPlaywright(o.projectDir) ? 'project' : null;
100
+ return { ready: source !== null, source, version: PLAYWRIGHT_VERSION, dir: p.dir, downloadMB: EXPORT_DOWNLOAD_MB, installingPid: installingPid(o.home), command: SETUP_COMMAND };
101
+ }
102
+ export function missingError() {
103
+ return new JoploError('EXPORT_COMPONENT_MISSING', `Exporting images and video needs the Joplo export component (Playwright ${PLAYWRIGHT_VERSION} + Chromium, about ${EXPORT_DOWNLOAD_MB} MB download, kept in the Joplo home directory, not in your project), which is not installed. Run: ${SETUP_COMMAND}. ${NOT_NEEDED}`, { details: { command: SETUP_COMMAND, downloadMB: EXPORT_DOWNLOAD_MB } });
104
+ }
105
+ const normalize = (m) => {
106
+ const x = m;
107
+ if (x && x.chromium)
108
+ return x;
109
+ if (x?.default?.chromium)
110
+ return x.default;
111
+ return null;
112
+ };
113
+ /**
114
+ * 解析 Playwright:托管运行时优先,其次项目里已有的;都没有时抛 EXPORT_COMPONENT_MISSING。
115
+ * 托管运行时载入前把 PLAYWRIGHT_BROWSERS_PATH 指向它自己的 browsers/(playwright-core 在初始化时读取)。
116
+ */
117
+ export async function resolvePlaywright(o = {}) {
118
+ const load = o.importFile ?? ((file) => import(__rewriteRelativeImportExtension(pathToFileURL(file).href)));
119
+ const p = runtimePaths(o.home);
120
+ if (managedReady(o.home)) {
121
+ process.env.PLAYWRIGHT_BROWSERS_PATH = p.browsers;
122
+ const m = normalize(await load(p.entry));
123
+ if (!m)
124
+ throw new JoploError('RENDER_FAILED', `The Joplo export component at ${p.dir} is damaged. Run: ${SETUP_COMMAND} --force`);
125
+ return { source: 'managed', module: m };
126
+ }
127
+ const found = projectPlaywright(o.projectDir);
128
+ if (found) {
129
+ const m = normalize(await load(found.file));
130
+ if (m)
131
+ return { source: 'project', module: m };
132
+ }
133
+ throw missingError();
134
+ }
135
+ export async function loadPlaywright(o = {}) {
136
+ return (await resolvePlaywright(o)).module;
137
+ }
138
+ const lastLines = (lines) => lines.slice(-6).join(' | ').slice(0, 600);
139
+ /** 缺省的命令执行:stdout / stderr 按行回调;非 0 退出时抛错(带最后几行输出)。 */
140
+ export const runCommand = (cmd, args, o) => new Promise((resolve, reject) => {
141
+ // Windows 上 npm 是 npm.cmd,只能经 shell 启动:带空格的参数(例如用户目录)要加引号
142
+ const viaShell = process.platform === 'win32' && cmd === 'npm';
143
+ const argv = viaShell ? args.map((a) => (/[\s"&|<>^]/.test(a) ? `"${a.replace(/"/g, '""')}"` : a)) : args;
144
+ const child = spawn(viaShell ? 'npm.cmd' : cmd, argv, { cwd: o.cwd, env: o.env, stdio: ['ignore', 'pipe', 'pipe'], shell: viaShell, windowsHide: true });
145
+ const tail = [];
146
+ let buf = '';
147
+ const feed = (chunk) => {
148
+ buf += chunk.toString('utf8');
149
+ let i;
150
+ while ((i = buf.search(/[\r\n]/)) >= 0) {
151
+ const line = buf.slice(0, i).trim();
152
+ buf = buf.slice(i + 1);
153
+ if (!line)
154
+ continue;
155
+ tail.push(line);
156
+ if (tail.length > 20)
157
+ tail.shift();
158
+ o.onLine(line);
159
+ }
160
+ };
161
+ child.stdout.on('data', feed);
162
+ child.stderr.on('data', feed);
163
+ const onAbort = () => child.kill();
164
+ o.signal?.addEventListener('abort', onAbort, { once: true });
165
+ child.on('error', (e) => {
166
+ o.signal?.removeEventListener('abort', onAbort);
167
+ reject(e.code === 'ENOENT' ? new JoploError('EXPORT_FAILED', `${cmd} was not found; installing the export component needs ${cmd === 'npm' ? 'npm (it ships with Node.js)' : cmd}`) : e);
168
+ });
169
+ child.on('close', (code, sig) => {
170
+ o.signal?.removeEventListener('abort', onAbort);
171
+ if (o.signal?.aborted)
172
+ return reject(new JoploError('EXPORT_FAILED', 'Installation was cancelled'));
173
+ if (code === 0)
174
+ return resolve();
175
+ reject(new JoploError('EXPORT_FAILED', `${path.basename(cmd)} ${args[0] ?? ''} failed (${sig ?? `exit ${code}`}): ${lastLines(tail) || 'no output'}`));
176
+ });
177
+ });
178
+ /** 缺省的自检:以托管方式载入并启动一次 Chromium。 */
179
+ async function defaultVerify(p) {
180
+ process.env.PLAYWRIGHT_BROWSERS_PATH = p.browsers;
181
+ const m = normalize(await import(__rewriteRelativeImportExtension(pathToFileURL(p.entry).href)));
182
+ if (!m)
183
+ throw new JoploError('EXPORT_FAILED', 'The installed playwright-core does not provide chromium');
184
+ const browser = await m.chromium.launch({ headless: true }).catch((e) => {
185
+ throw new JoploError('EXPORT_FAILED', `Chromium was downloaded but failed to start: ${(e instanceof Error ? e.message : String(e)).split('\n')[0]}`);
186
+ });
187
+ await browser.close();
188
+ }
189
+ /** 取得安装锁;已有存活进程在安装时报错。返回释放函数。 */
190
+ function acquireLock(p) {
191
+ fs.mkdirSync(p.root, { recursive: true, mode: 0o700 });
192
+ for (let attempt = 0; attempt < 2; attempt++) {
193
+ try {
194
+ fs.writeFileSync(p.lock, String(process.pid), { flag: 'wx' });
195
+ return () => {
196
+ try {
197
+ if (fs.readFileSync(p.lock, 'utf8').trim() === String(process.pid))
198
+ fs.rmSync(p.lock, { force: true });
199
+ }
200
+ catch {
201
+ // 忽略
202
+ }
203
+ };
204
+ }
205
+ catch (e) {
206
+ if (e.code !== 'EEXIST')
207
+ throw e;
208
+ const pid = Number(fs.readFileSync(p.lock, 'utf8').trim());
209
+ if (Number.isInteger(pid) && pid > 0 && pid !== process.pid && pidAlive(pid))
210
+ throw new JoploError('UNSUPPORTED_ACTION', `Another Joplo process (pid ${pid}) is installing the export component; wait for it to finish`);
211
+ fs.rmSync(p.lock, { force: true }); // 过期的锁
212
+ }
213
+ }
214
+ throw new JoploError('UNSUPPORTED_ACTION', 'Could not acquire the export component install lock');
215
+ }
216
+ /** 安装命令只能在运行时目录里运行(不变量:绝不在项目目录里执行 npm)。 */
217
+ function childEnv(extra) {
218
+ const env = { ...process.env, ...extra };
219
+ // npx 父进程可能带着全局 / 工作区配置,避免 npm 把包装到别处
220
+ for (const k of Object.keys(env))
221
+ if (/^npm_config_(global|location|prefix|workspaces?|include_workspace_root|save.*)$/i.test(k))
222
+ delete env[k];
223
+ return env;
224
+ }
225
+ /**
226
+ * 安装托管运行时:npm 装 playwright-core(cwd 与 --prefix 都是运行时目录)→ playwright-core 的 CLI 下载 Chromium headless shell
227
+ * 到运行时的 browsers/ → 自检 → 写 ready.json → 删掉旧版本的运行时目录。已就绪且没有 force 时直接返回。
228
+ */
229
+ export async function installExportRuntime(o = {}) {
230
+ const p = runtimePaths(o.home);
231
+ if (!o.force && managedReady(o.home))
232
+ return { alreadyInstalled: true, dir: p.dir, version: PLAYWRIGHT_VERSION, removedOld: [] };
233
+ const run = o.deps?.run ?? runCommand;
234
+ const verify = o.deps?.verify ?? defaultVerify;
235
+ const progress = (x) => o.onProgress?.(x);
236
+ const release = acquireLock(p);
237
+ try {
238
+ if (o.force)
239
+ fs.rmSync(p.dir, { recursive: true, force: true });
240
+ fs.rmSync(p.marker, { force: true });
241
+ fs.mkdirSync(p.dir, { recursive: true, mode: 0o700 });
242
+ fs.writeFileSync(path.join(p.dir, 'package.json'), JSON.stringify({ name: 'joplo-export-runtime', private: true, description: `Managed by Joplo. Remove with: ${SETUP_COMMAND} --uninstall` }, null, 2) + '\n');
243
+ progress({ phase: 'package', percent: 1, totalMB: null, message: `Installing playwright-core ${PLAYWRIGHT_VERSION}` });
244
+ await run('npm', ['install', `playwright-core@${PLAYWRIGHT_VERSION}`, '--prefix', p.dir, '--no-global', '--no-save', '--no-package-lock', '--no-audit', '--no-fund', '--ignore-scripts', '--loglevel=error'], { cwd: p.dir, env: childEnv({}), onLine: () => undefined, signal: o.signal });
245
+ if (!fs.existsSync(p.cli))
246
+ throw new JoploError('EXPORT_FAILED', `npm finished, but ${p.cli} is missing`);
247
+ // 浏览器:只装 headless shell(截图与录视频都用无头模式);ffmpeg 由 playwright 一起装
248
+ let segment = 0;
249
+ let title = 'Chromium';
250
+ let totalMB = null;
251
+ progress({ phase: 'browser', percent: 5, totalMB, message: 'Downloading Chromium' });
252
+ await run(process.execPath, [p.cli, 'install', '--only-shell', 'chromium'], {
253
+ cwd: p.dir,
254
+ env: childEnv({ PLAYWRIGHT_BROWSERS_PATH: p.browsers }),
255
+ signal: o.signal,
256
+ onLine: (line) => {
257
+ const d = /^Downloading (.+?)(?:\s+from\s|\s*$)/.exec(line);
258
+ if (d) {
259
+ segment++;
260
+ // 之后的小文件(ffmpeg)算作 Chromium 的一部分:标题和大小保持第一个下载的
261
+ if (segment === 1)
262
+ title = d[1].replace(/\s*\(playwright.*$/i, '').trim();
263
+ return;
264
+ }
265
+ const m = /(\d+)% of ([\d.]+) MiB/.exec(line);
266
+ if (!m)
267
+ return;
268
+ const pct = Math.min(100, Number(m[1]));
269
+ if (segment <= 1)
270
+ totalMB = Number(m[2]);
271
+ // 第一个下载(Chromium,绝大部分体积)占 5–90,之后的小文件(ffmpeg)占 90–95
272
+ const overall = segment <= 1 ? 5 + pct * 0.85 : 90 + pct * 0.05;
273
+ progress({ phase: 'browser', percent: Math.round(overall), totalMB, message: `Downloading ${title}` });
274
+ },
275
+ });
276
+ progress({ phase: 'verify', percent: 96, totalMB: null, message: 'Checking that Chromium starts' });
277
+ await verify(p);
278
+ fs.writeFileSync(p.marker, JSON.stringify({ version: PLAYWRIGHT_VERSION, installedAt: new Date().toISOString() }, null, 2) + '\n');
279
+ // 旧版本的运行时(升级 Joplo 后 Playwright 版本变了)不再使用
280
+ const removedOld = [];
281
+ for (const name of fs.readdirSync(p.root)) {
282
+ const full = path.join(p.root, name);
283
+ if (full === p.dir || !/^playwright-[\w.-]+$/.test(name) || !fs.statSync(full).isDirectory())
284
+ continue;
285
+ fs.rmSync(full, { recursive: true, force: true });
286
+ removedOld.push(name);
287
+ }
288
+ progress({ phase: 'done', percent: 100, totalMB: null, message: 'Export component is ready' });
289
+ return { alreadyInstalled: false, dir: p.dir, version: PLAYWRIGHT_VERSION, removedOld };
290
+ }
291
+ finally {
292
+ release();
293
+ }
294
+ }
295
+ /** 删除托管运行时(所有版本);有进程正在安装时报错。只动 `<JOPLO_HOME>/runtime/playwright-*`。 */
296
+ export function uninstallExportRuntime(o = {}) {
297
+ const p = runtimePaths(o.home);
298
+ const pid = installingPid(o.home);
299
+ if (pid !== null && pid !== process.pid)
300
+ throw new JoploError('UNSUPPORTED_ACTION', `Another Joplo process (pid ${pid}) is installing the export component; wait for it to finish`);
301
+ const removed = [];
302
+ let names = [];
303
+ try {
304
+ names = fs.readdirSync(p.root);
305
+ }
306
+ catch {
307
+ return { removed };
308
+ }
309
+ for (const name of names) {
310
+ if (!/^playwright-[\w.-]+$/.test(name) || name.endsWith('.lock'))
311
+ continue;
312
+ fs.rmSync(path.join(p.root, name), { recursive: true, force: true });
313
+ removed.push(name);
314
+ }
315
+ if (process.env.PLAYWRIGHT_BROWSERS_PATH === p.browsers)
316
+ delete process.env.PLAYWRIGHT_BROWSERS_PATH;
317
+ return { removed };
318
+ }
package/dist/export.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type http from 'node:http';
2
2
  import { type AppearanceFont, type AppearanceStroke, type Project } from '@joplo-app/core';
3
- import { type PlaywrightModule } from './render.js';
3
+ import { type InstallDeps, type InstallProgress, type PlaywrightModule } from './export-runtime.js';
4
4
  export type Device = 'desktop' | 'mobile';
5
5
  /**
6
6
  * 导出画面的尺寸:电脑 = 舞台 1280×800;手机 = 外框(renderer 的 phoneFrameSize(390, 844) = 446×934)
@@ -27,6 +27,7 @@ export type VideoJob = {
27
27
  };
28
28
  /** 录制实现:报告进度,返回写好的文件绝对路径。测试可注入。 */
29
29
  export type VideoRecorder = (input: {
30
+ projectDir: string;
30
31
  url: string;
31
32
  size: {
32
33
  width: number;
@@ -38,8 +39,26 @@ export type VideoRecorder = (input: {
38
39
  signal: AbortSignal;
39
40
  }) => Promise<void>;
40
41
  export type ExportDeps = {
41
- loadPlaywright: () => Promise<PlaywrightModule>;
42
+ /** 按项目解析 Playwright(托管运行时优先,其次项目里已有的)。 */
43
+ loadPlaywright: (projectDir: string) => Promise<PlaywrightModule>;
42
44
  recordVideo: VideoRecorder;
45
+ /** 导出组件的安装(测试注入假的 npm / 下载 / 自检)。 */
46
+ install: Partial<InstallDeps>;
47
+ };
48
+ /**
49
+ * 导出组件的安装任务(D66)。字段流向:startInstall(写入点,installExportRuntime 的进度回调)→ this.install(存储)
50
+ * → `GET …/export/runtime`、`GET /__joplo/export-runtime/install`、SSE(读取点)→ 看板导出菜单的安装卡与「导出」按钮进度环(消费者)。
51
+ */
52
+ export type InstallJob = {
53
+ id: string;
54
+ status: 'running' | 'done' | 'error';
55
+ phase: InstallProgress['phase'] | 'error';
56
+ percent: number;
57
+ /** 正在下载的文件大小(MiB)。 */
58
+ totalMB: number | null;
59
+ /** 英文进度说明(看板按 phase 显示本地化文字,这里只作日志)。 */
60
+ message: string;
61
+ error: string | null;
43
62
  };
44
63
  type Ctx = {
45
64
  projectId: string;
@@ -61,7 +80,7 @@ export declare function exportAppearance(body: unknown): {
61
80
  stroke: AppearanceStroke | null;
62
81
  };
63
82
  /** 缺省的录制:Playwright recordVideo + 渲染路由的录制模式(window.__JOPLO_RECORD__)。 */
64
- export declare function defaultRecorder(load: () => Promise<PlaywrightModule>): VideoRecorder;
83
+ export declare function defaultRecorder(load: (projectDir: string) => Promise<PlaywrightModule>): VideoRecorder;
65
84
  export declare class ExportHub {
66
85
  private readonly opts;
67
86
  private jobs;
@@ -69,9 +88,14 @@ export declare class ExportHub {
69
88
  private aborts;
70
89
  private running;
71
90
  private deps;
91
+ private install;
92
+ private installListeners;
93
+ private installAbort;
94
+ /** home:导出组件所在的 JOPLO_HOME(看板进程的 home;没有时用环境变量 / ~/.joplo)。 */
72
95
  constructor(opts: {
73
96
  baseUrl: () => string;
74
97
  log: (s: string) => void;
98
+ home: string;
75
99
  deps?: Partial<ExportDeps>;
76
100
  onEvent?: (j: VideoJob) => void;
77
101
  });
@@ -84,6 +108,14 @@ export declare class ExportHub {
84
108
  private image;
85
109
  private startVideo;
86
110
  private sse;
111
+ /**
112
+ * 全局接口 `/__joplo/export-runtime/<sub>`。调用方(dev.ts)已校验 Host;这里对写接口与进度流再校验本机令牌与 Origin。
113
+ * 不变量:只有带本机令牌、来自看板自己源的请求能触发下载。
114
+ */
115
+ handleRuntime(sub: string, req: http.IncomingMessage, res: http.ServerResponse, ctx: Pick<Ctx, 'guardWrite' | 'jsonBody' | 'fail'>): Promise<void>;
116
+ /** 开始安装;已有任务在运行时返回那个任务(不重复下载)。 */
117
+ startInstall(force?: boolean): InstallJob;
118
+ private installSse;
87
119
  close(): Promise<void>;
88
120
  }
89
121
  export {};
package/dist/export.js CHANGED
@@ -6,7 +6,11 @@
6
6
  * - 视频(只在本机):`POST …/export/video` `{ scenarioId, theme, font?, stroke? }` → 202 `{ jobId }`(尺寸跟随场景起始页面的 viewport);
7
7
  * Playwright `recordVideo` 录下渲染路由的自动播放(含鼠标与字幕),保存为 `<项目>/exports/<场景>-<时间>.webm`。
8
8
  * 进度:`GET …/export/video/events`(SSE,先发当前状态,之后每次变化一条,结束后关闭);`GET …/export/video` 取当前状态。
9
- * 同一项目同时只能有一个视频任务(再提交返回 409);`DELETE …/export/video` 取消正在进行的任务(D55)。没有 Playwright / Chromium 时任务失败,错误里带安装命令。
9
+ * 同一项目同时只能有一个视频任务(再提交返回 409);`DELETE …/export/video` 取消正在进行的任务(D55)。没有导出组件时图片返回 503 EXPORT_COMPONENT_MISSING、
10
+ * 视频任务失败,错误里带安装命令。
11
+ * - 导出组件(D66):`GET …/export/runtime` → `{ runtime: 状态(含项目里已有的 Playwright), install: 安装任务 | null }`;
12
+ * `POST /__joplo/export-runtime/install`(本机令牌 + Origin + JSON)开始安装(已有任务时返回那个任务)、
13
+ * `GET /__joplo/export-runtime/install/events`(令牌,SSE)推送进度。只有这条路径会下载,导出本身从不下载。
10
14
  *
11
15
  * 外观(D55):font / stroke 由 exportAppearance 校验(未知值 = null = 跟随主题),非 null 时作为渲染路由的 URL 参数,
12
16
  * RenderApp 读出后交给舞台、字幕与手机外框(与看板里看到的一致)。
@@ -18,7 +22,8 @@ import fs from 'node:fs';
18
22
  import path from 'node:path';
19
23
  import { exportLocale } from "./locale.js";
20
24
  import { JoploError, SUBTITLE_HEIGHT, THEME_NAME, displaySceneId, isAppearanceFont, isAppearanceStroke } from '@joplo-app/core';
21
- import { launch, loadPlaywright } from "./render.js";
25
+ import { launch } from "./render.js";
26
+ import { exportRuntimeStatus, installExportRuntime, loadPlaywright } from "./export-runtime.js";
22
27
  /**
23
28
  * 导出画面的尺寸:电脑 = 舞台 1280×800;手机 = 外框(renderer 的 phoneFrameSize(390, 844) = 446×934)
24
29
  * 四周再留 16px(RenderApp 的 frame 模式)。舞台正下方是字幕区(SUBTITLE_HEIGHT),一起导出。
@@ -65,8 +70,8 @@ async function waitReady(page) {
65
70
  }
66
71
  /** 缺省的录制:Playwright recordVideo + 渲染路由的录制模式(window.__JOPLO_RECORD__)。 */
67
72
  export function defaultRecorder(load) {
68
- return async ({ url, size, out, progress, signal }) => {
69
- const pw = await load();
73
+ return async ({ projectDir, url, size, out, progress, signal }) => {
74
+ const pw = await load(projectDir);
70
75
  const browser = await launch(pw);
71
76
  const tmp = fs.mkdtempSync(path.join(path.dirname(out), '.rec-'));
72
77
  try {
@@ -110,10 +115,14 @@ export class ExportHub {
110
115
  aborts = new Map();
111
116
  running = new Set();
112
117
  deps;
118
+ install = null;
119
+ installListeners = new Set();
120
+ installAbort = null;
121
+ /** home:导出组件所在的 JOPLO_HOME(看板进程的 home;没有时用环境变量 / ~/.joplo)。 */
113
122
  constructor(opts) {
114
123
  this.opts = opts;
115
- const load = opts.deps?.loadPlaywright ?? (() => loadPlaywright());
116
- this.deps = { loadPlaywright: load, recordVideo: opts.deps?.recordVideo ?? defaultRecorder(load) };
124
+ const load = opts.deps?.loadPlaywright ?? ((projectDir) => loadPlaywright({ home: opts.home, projectDir }));
125
+ this.deps = { loadPlaywright: load, recordVideo: opts.deps?.recordVideo ?? defaultRecorder(load), install: opts.deps?.install ?? {} };
117
126
  }
118
127
  renderUrl(projectId, q) {
119
128
  return `${this.opts.baseUrl()}?${new URLSearchParams({ render: '1', project: projectId, ...q })}`;
@@ -148,7 +157,7 @@ export class ExportHub {
148
157
  if (!b.ok)
149
158
  return;
150
159
  const { sc, position, device, look } = parseRequest(ctx.project, b.body, true);
151
- const png = await this.image(ctx.projectId, sc.id, position, device, look);
160
+ const png = await this.image(ctx.projectId, ctx.dir, sc.id, position, device, look);
152
161
  res.writeHead(200, { 'content-type': 'image/png', 'cache-control': 'no-store', 'content-disposition': `attachment; filename="${fileSafe(sc.id)}-${position}.png"` });
153
162
  res.end(png);
154
163
  return;
@@ -168,6 +177,8 @@ export class ExportHub {
168
177
  }
169
178
  if (sub === 'video' && method === 'GET')
170
179
  return send(res, 200, { job: this.job(ctx.projectId) });
180
+ if (sub === 'runtime' && method === 'GET')
181
+ return send(res, 200, { runtime: exportRuntimeStatus({ home: this.opts.home, projectDir: ctx.dir }), install: this.install });
171
182
  if (sub === 'video' && method === 'DELETE') {
172
183
  if (!ctx.guardWrite(false))
173
184
  return;
@@ -188,8 +199,8 @@ export class ExportHub {
188
199
  res.end();
189
200
  }
190
201
  }
191
- async image(projectId, scenarioId, position, device, look) {
192
- const pw = await this.deps.loadPlaywright();
202
+ async image(projectId, dir, scenarioId, position, device, look) {
203
+ const pw = await this.deps.loadPlaywright(dir);
193
204
  const browser = await launch(pw);
194
205
  try {
195
206
  const page = await browser.newPage({ viewport: EXPORT_SIZE[device], deviceScaleFactor: 2, reducedMotion: 'reduce' });
@@ -213,6 +224,7 @@ export class ExportHub {
213
224
  fs.mkdirSync(path.dirname(out), { recursive: true });
214
225
  this.update(job, { phase: 'starting', percent: 2 });
215
226
  await this.deps.recordVideo({
227
+ projectDir: dir,
216
228
  url: this.renderUrl(projectId, { scenario: scenarioId, position: '0', theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), frame: '1', record: '1' }),
217
229
  size: EXPORT_SIZE[device],
218
230
  out,
@@ -270,10 +282,96 @@ export class ExportHub {
270
282
  set.add(l);
271
283
  res.on('close', () => set.delete(l));
272
284
  }
285
+ // ---------- 导出组件的安装(D66):全局一个任务,进度推给所有看板页面 ----------
286
+ /**
287
+ * 全局接口 `/__joplo/export-runtime/<sub>`。调用方(dev.ts)已校验 Host;这里对写接口与进度流再校验本机令牌与 Origin。
288
+ * 不变量:只有带本机令牌、来自看板自己源的请求能触发下载。
289
+ */
290
+ async handleRuntime(sub, req, res, ctx) {
291
+ const method = req.method ?? 'GET';
292
+ try {
293
+ if (sub === 'install' && method === 'POST') {
294
+ if (!ctx.guardWrite())
295
+ return;
296
+ const b = await ctx.jsonBody();
297
+ if (!b.ok)
298
+ return;
299
+ const force = b.body?.force === true;
300
+ return send(res, 202, { job: this.startInstall(force) });
301
+ }
302
+ if (sub === 'install' && method === 'GET')
303
+ return send(res, 200, { job: this.install, runtime: exportRuntimeStatus({ home: this.opts.home }) });
304
+ if (sub === 'install/events' && method === 'GET') {
305
+ if (!ctx.guardWrite(false))
306
+ return;
307
+ return this.installSse(res);
308
+ }
309
+ return send(res, 404, { error: { code: 'NOT_FOUND', message: `Unknown endpoint: ${method} export-runtime/${sub}` } });
310
+ }
311
+ catch (e) {
312
+ if (!res.headersSent)
313
+ ctx.fail(e);
314
+ else
315
+ res.end();
316
+ }
317
+ }
318
+ /** 开始安装;已有任务在运行时返回那个任务(不重复下载)。 */
319
+ startInstall(force = false) {
320
+ if (this.install?.status === 'running')
321
+ return { ...this.install };
322
+ const job = { id: crypto.randomBytes(6).toString('hex'), status: 'running', phase: 'package', percent: 0, totalMB: null, message: 'Starting', error: null };
323
+ this.install = job;
324
+ const ac = new AbortController();
325
+ this.installAbort = ac;
326
+ const set = (patch) => {
327
+ Object.assign(job, patch);
328
+ const snap = { ...job };
329
+ for (const l of this.installListeners)
330
+ l(snap);
331
+ };
332
+ const p = (async () => {
333
+ try {
334
+ const r = await installExportRuntime({ home: this.opts.home, force, signal: ac.signal, deps: this.deps.install, onProgress: (x) => set({ phase: x.phase, percent: x.percent, totalMB: x.totalMB, message: x.message }) });
335
+ set({ status: 'done', phase: 'done', percent: 100, message: r.alreadyInstalled ? 'Already installed' : 'Export component is ready' });
336
+ this.opts.log(`[joplo] Export component ready: ${r.dir}`);
337
+ }
338
+ catch (e) {
339
+ set({ status: 'error', phase: 'error', error: e instanceof Error ? e.message : String(e) });
340
+ }
341
+ finally {
342
+ if (this.installAbort === ac)
343
+ this.installAbort = null;
344
+ }
345
+ })();
346
+ this.running.add(p);
347
+ void p.finally(() => this.running.delete(p));
348
+ return { ...job };
349
+ }
350
+ installSse(res) {
351
+ res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-store', connection: 'keep-alive', 'x-content-type-options': 'nosniff' });
352
+ const write = (j) => res.write(`data: ${JSON.stringify(j)}\n\n`);
353
+ const cur = this.install;
354
+ write(cur ? { ...cur } : null);
355
+ if (!cur || cur.status !== 'running') {
356
+ res.end();
357
+ return;
358
+ }
359
+ const l = (j) => {
360
+ write(j);
361
+ if (j.status !== 'running') {
362
+ this.installListeners.delete(l);
363
+ res.end();
364
+ }
365
+ };
366
+ this.installListeners.add(l);
367
+ res.on('close', () => this.installListeners.delete(l));
368
+ }
273
369
  async close() {
370
+ this.installAbort?.abort();
274
371
  for (const ac of this.aborts.values())
275
372
  ac.abort();
276
373
  await Promise.allSettled([...this.running]);
277
374
  this.listeners.clear();
375
+ this.installListeners.clear();
278
376
  }
279
377
  }
package/dist/home.d.ts CHANGED
@@ -4,10 +4,13 @@ export type ProjectRecord = {
4
4
  name: string;
5
5
  lastOpened: string;
6
6
  };
7
+ /** version / dir(D65,0.2.7 起):看板进程的 Joplo 版本与启动它的项目目录,供后来的 joplo dev 在加入时说明;旧看板没有。 */
7
8
  export type ServerInfo = {
8
9
  port: number;
9
10
  pid: number;
10
11
  token: string;
12
+ version?: string;
13
+ dir?: string;
11
14
  };
12
15
  export declare function joploHome(env?: Record<string, string | undefined>): string;
13
16
  /** 项目在 URL 里的标识:目录名(小写、只留安全字符)+ 目录绝对路径的短哈希,稳定且不暴露完整路径。 */
package/dist/index.d.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  /**
2
- * @joplo-app/server:CLI 只依赖这里导出的三个函数(接口见 contract.ts)。
2
+ * @joplo-app/server:CLI 只依赖这里导出的函数(接口见 contract.ts)。
3
3
  *
4
4
  * - startDev:单进程 Vite 开发服务,提供看板、编译与热更新;选中写入 .joplo/selection.json。
5
5
  * - buildSite:静态发布站(只含选定方案,hash 路由,file:// 可直接打开)。
6
6
  * - renderStep:某个场景某一步之后的截图、元素索引(带 at)与渲染告警。
7
+ * - exportRuntimeStatus / installExportRuntime / uninstallExportRuntime:Joplo 托管的导出组件(D66,`joplo setup export`)。
7
8
  */
8
9
  export type { BuildOptions, BuildResult, DevHandle, DevOptions, RenderOptions, RenderResult, RenderedElement } from './contract.js';
9
10
  export { startDev } from './dev.js';
10
11
  export { buildSite } from './build.js';
11
12
  export { renderStep } from './render.js';
13
+ export { EXPORT_DOWNLOAD_MB, PLAYWRIGHT_VERSION, SETUP_COMMAND, exportRuntimeStatus, installExportRuntime, uninstallExportRuntime, type ExportRuntimeStatus, type InstallProgress, type InstallResult } from './export-runtime.js';
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { startDev } from "./dev.js";
2
2
  export { buildSite } from "./build.js";
3
3
  export { renderStep } from "./render.js";
4
+ export { EXPORT_DOWNLOAD_MB, PLAYWRIGHT_VERSION, SETUP_COMMAND, exportRuntimeStatus, installExportRuntime, uninstallExportRuntime } from "./export-runtime.js";
package/dist/render.d.ts CHANGED
@@ -1,10 +1,9 @@
1
- import type { Browser } from 'playwright';
1
+ import type { Browser } from 'playwright-core';
2
2
  import { type AppearanceFont, type AppearanceStroke } from '@joplo-app/core';
3
3
  import type { RenderOptions, RenderResult } from './contract.js';
4
- export type PlaywrightModule = typeof import('playwright');
5
- /** 按需载入 Playwright;没有安装时抛出带安装命令的 RENDER_FAILED。 */
6
- export declare function loadPlaywright(importer?: () => Promise<PlaywrightModule>): Promise<PlaywrightModule>;
7
- /** 浏览器启动失败时的一行提示。 */
4
+ import { type PlaywrightModule } from './export-runtime.js';
5
+ export { loadPlaywright, type PlaywrightModule } from './export-runtime.js';
6
+ /** 浏览器启动失败时的一行提示(托管运行时与项目里的 Playwright 都适用:重装 Joplo 自己的导出组件)。 */
8
7
  export declare function launchHint(e: unknown): string;
9
8
  export declare function launch({ chromium }: PlaywrightModule): Promise<Browser>;
10
9
  /**
package/dist/render.js CHANGED
@@ -3,7 +3,8 @@
3
3
  * 截取舞台并返回元素索引(带 at)与渲染告警:遮挡、溢出、Toast 重叠、字体(PRD 8.8 / AC-22)。
4
4
  * 页面读取的 IR 与这里用来计算位置、隐藏元素的 IR 是同一份(无 TOCTOU)。
5
5
  *
6
- * Playwright 是可选依赖(D36):只在这里按需载入;没装或没有浏览器时给出安装命令,dev/check/build 不受影响。
6
+ * Playwright 不装进项目(D66):由 export-runtime 解析 Joplo 托管的运行时(兼容项目里已有的 playwright);
7
+ * 都没有时抛 EXPORT_COMPONENT_MISSING(带安装命令),这里从不下载。dev/check/build 不受影响。
7
8
  */
8
9
  import fs from 'node:fs';
9
10
  import path from 'node:path';
@@ -11,27 +12,14 @@ import { JoploError, SUBTITLE_HEIGHT, VIEWPORT_SIZE, isAppearanceFont, isAppeara
11
12
  import { exportLocale } from "./locale.js";
12
13
  import { createDev } from "./dev.js";
13
14
  import { realProjectDir } from "./vite-shared.js";
15
+ import { joploHome } from "./home.js";
16
+ import { EXPORT_DOWNLOAD_MB, NOT_NEEDED, SETUP_COMMAND, loadPlaywright } from "./export-runtime.js";
14
17
  const STAGE_SIZE = VIEWPORT_SIZE;
15
- const NOT_NEEDED = 'dev, check, and build do not require it.';
16
- const isMissingModule = (e) => {
17
- const code = e?.code;
18
- return (code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND') && /playwright/.test(e instanceof Error ? e.message : String(e));
19
- };
20
- /** 按需载入 Playwright;没有安装时抛出带安装命令的 RENDER_FAILED。 */
21
- export async function loadPlaywright(importer = () => import('playwright')) {
22
- try {
23
- return await importer();
24
- }
25
- catch (e) {
26
- if (!isMissingModule(e))
27
- throw e;
28
- throw new JoploError('RENDER_FAILED', `Screenshots require Playwright and Chromium, which are not installed. Run: npm i -D playwright && npx playwright install chromium (about 150 MB). ${NOT_NEEDED}`);
29
- }
30
- }
31
- /** 浏览器启动失败时的一行提示。 */
18
+ export { loadPlaywright } from "./export-runtime.js";
19
+ /** 浏览器启动失败时的一行提示(托管运行时与项目里的 Playwright 都适用:重装 Joplo 自己的导出组件)。 */
32
20
  export function launchHint(e) {
33
21
  const first = (e instanceof Error ? e.message : String(e)).split('\n')[0].trim();
34
- return `Screenshots require Chromium; browser launch failed (${first}). Run: npx playwright install chromium (about 150 MB). ${NOT_NEEDED}`;
22
+ return `Screenshots need Chromium, but it failed to start (${first}). Run: ${SETUP_COMMAND} --force to reinstall the Joplo export component (about ${EXPORT_DOWNLOAD_MB} MB). ${NOT_NEEDED}`;
35
23
  }
36
24
  export async function launch({ chromium }) {
37
25
  try {
@@ -99,7 +87,7 @@ export async function renderStep(opts) {
99
87
  if (fs.existsSync(out) && !opts.overwrite)
100
88
  throw new JoploError('USAGE', `Output file already exists: ${out}. To overwrite, pass overwrite: true (CLI: --overwrite)`);
101
89
  // 先确认 Playwright 可用,再启动编译服务(缺失时尽快失败)
102
- const playwright = await loadPlaywright();
90
+ const playwright = await loadPlaywright({ home: joploHome(), projectDir });
103
91
  const server = await createDev({ projectDir, port: 0, watch: false, log: () => undefined });
104
92
  let browser = null;
105
93
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joplo-app/server",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "Joplo 本地服务:dev 看板、build 发布站、render 截图",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -15,25 +15,18 @@
15
15
  "dist"
16
16
  ],
17
17
  "dependencies": {
18
- "@joplo-app/core": "0.2.5",
19
- "@joplo-app/kit": "0.2.5",
20
- "@joplo-app/web": "0.2.5",
18
+ "@joplo-app/core": "0.2.7",
19
+ "@joplo-app/kit": "0.2.7",
20
+ "@joplo-app/web": "0.2.7",
21
21
  "@tailwindcss/vite": "4.3.4",
22
22
  "tailwindcss": "4.3.4",
23
23
  "vite": "8.3.5",
24
24
  "zod": "4.6.7"
25
25
  },
26
- "peerDependencies": {
27
- "playwright": "^1.64.1"
28
- },
29
- "peerDependenciesMeta": {
30
- "playwright": {
31
- "optional": true
32
- }
33
- },
34
26
  "devDependencies": {
35
27
  "@vitejs/plugin-react": "6.2.1",
36
- "playwright": "1.64.1"
28
+ "playwright": "1.64.1",
29
+ "playwright-core": "1.64.1"
37
30
  },
38
31
  "engines": {
39
32
  "node": ">=22"