@joplo-app/server 0.5.0 → 0.6.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.
package/dist/build.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type StepIdentity, type Project } from '@joplo-app/core';
2
2
  import type { BuildOptions, BuildResult } from './contract.js';
3
3
  import type { DistWeb, WebAssets } from './web-assets.js';
4
- /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级、镜头、角色(说话人、过渡卡、层级的 role)与 featureIds 顺序属于演示,保留(D43 / D56 / D61)。 */
4
+ /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级、镜头、角色(说话人、过渡卡、层级的 role)与 entryIds 顺序属于演示,保留(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;
@@ -19,7 +19,7 @@ export declare function finalizeHtml(html: string, readAsset: (rel: string) => s
19
19
  };
20
20
  export declare function buildSite(opts: BuildOptions): Promise<BuildResult>;
21
21
  /** 从 npm 安装时:复制预构建的发布站,单独编译作者 className 的 CSS 并在 site.html 里引用。 */
22
- export declare function stageDistSite(web: DistWeb, projectDir: string, staging: string): Promise<void>;
22
+ export declare function stageDistSite(web: DistWeb, projectDir: string, staging: string, publicCssSource: string): Promise<void>;
23
23
  /**
24
24
  * 把每个插件运行时打成一个自包含的 ES 模块(依赖一起打进去),执行时注册到 globalThis.__JOPLO_PLUGINS__
25
25
  * (web 的 renderer/plugins.ts 取走)。按插件 id 排序,产物稳定。
package/dist/build.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { publishCssContent } from "./publish-css.js";
1
2
  import { binaryAssets, extractSiteAssets } from "./binary-assets.js";
2
3
  import { inlineResources } from "./local-resources.js";
3
4
  import { inlinePluginAssets, PLUGIN_ASSET_BASE } from "./plugin-assets.js";
@@ -7,7 +8,7 @@ import sharedModules from '@joplo-app/web/shared-modules.json' with { type: 'jso
7
8
  *
8
9
  * 1. 用 Vite(中间件模式,不监听端口)ssrLoadModule 载入项目,compile(…, 'publish'):只含选定方案,
9
10
  * 已去掉规则、情况、问题、备注、源路径(D33)。这里再去掉 IR 中创作侧的空字段与约束、角色。
10
- * 2. vite build 发布站入口(packages/web/site.html),Tailwind 以项目目录为 @source。
11
+ * 2. vite build 发布站入口(packages/web/site.html),Tailwind 只扫描最终公开载荷的字符串与播放器样式来源。
11
12
  * 3. 后处理:IR 内联到 index.html;入口脚本内联为 <script type="module">、去掉 crossorigin,
12
13
  * 这样直接双击 index.html(file://)也能离线运行。产物是普通静态目录,可 `wrangler deploy --assets` 或任何静态托管发布。
13
14
  *
@@ -23,23 +24,35 @@ import os from 'node:os';
23
24
  import path from 'node:path';
24
25
  import tailwindcss from '@tailwindcss/vite';
25
26
  import { build as viteBuild, createServer } from 'vite';
26
- import { stepIdentity, hasScope, JoploError, orderedFeatures, pruneMessages, resolveScope, scopeProject } from '@joplo-app/core';
27
+ import { stepIdentity, hasScope, JoploError, entriesOf, entryOf, visibleRoutes, pruneMessages, resolveScope, scopeProject } from '@joplo-app/core';
27
28
  import { compileProject } from "./project.js";
28
29
  import { joploProjectPlugin, kitAliases, locateWebAssets, realProjectDir } from "./vite-shared.js";
29
30
  import { subsetSiteFonts } from "./site-fonts.js";
30
31
  import { joploHome } from "./home.js";
31
32
  import { ProfileStore, bundleVoice, reuseSharedVoice } from "./voice.js";
32
- /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级、镜头、角色(说话人、过渡卡、层级的 role)与 featureIds 顺序属于演示,保留(D43 / D56 / D61)。 */
33
+ /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级、镜头、角色(说话人、过渡卡、层级的 role)与 entryIds 顺序属于演示,保留(D43 / D56 / D61)。 */
33
34
  export function publishPayload(project, home) {
34
35
  // voiceConfig(D74):profile 名与音色属于作者本机的设置,发布站只需要 build 写进的 voiceIndex
35
36
  const { rules: _r, cases: _c, issues: _i, voiceConfig: _v, ...rest } = project;
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 }]));
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 } : {}) }]));
37
+ const features = Object.fromEntries(project.entryIds.flatMap(id => {
38
+ const f = project.features[id];
39
+ return f ? [[id, {
40
+ id: f.id, name: f.name, goal: f.goal, roles: f.roles, workIds: f.workIds, pick: f.pick,
41
+ alternatives: Object.fromEntries(f.workIds.map(workId => [workId, { decisionFocus: '', tradeoffs: [], coverage: {} }])),
42
+ }]] : [];
43
+ }));
44
+ const works = Object.fromEntries(Object.entries(project.works).map(([id, w]) => [id, {
45
+ id: w.id, key: w.key, title: w.title, summary: w.summary, roles: w.roles,
46
+ ...(w.featureId !== undefined ? { featureId: w.featureId } : {}),
47
+ ...(w.audience !== undefined ? { audience: w.audience } : {}),
48
+ routes: w.routes, layers: w.layers ?? {},
49
+ ...(w.sequencing ? { sequencing: w.sequencing } : {}), ...(w.free ? { free: w.free } : {}),
50
+ }]));
38
51
  const scenarios = Object.fromEntries(Object.entries(project.scenarios).map(([id, s]) => {
39
52
  const { caseIds: _ci, ...sr } = s;
40
53
  return [id, { ...sr, caseIds: [], steps: s.steps.map(({ ruleIds: _ri, key: _key, ...st }) => ({ ...st, ruleIds: [] })) }];
41
54
  }));
42
- const out = { ...rest, features, options, scenarios };
55
+ const out = { ...rest, features, works, scenarios };
43
56
  // 译文(D84)在去掉创作侧字段之后再裁剪一次:约束等只给作者看的原文不能作为译文的键留在站点里
44
57
  return { project: rest.i18n ? pruneMessages(out) : out, home: home && project.routes[home] ? home : null };
45
58
  }
@@ -120,6 +133,29 @@ export async function buildSite(opts) {
120
133
  let compiled;
121
134
  try {
122
135
  compiled = await compileProject(loader, projectDir, opts.review === true ? 'review' : 'publish');
136
+ // 发布编译已跳过草稿与未选功能;范围的公开校验需要原始条目,避免误报不存在。
137
+ if (opts.scope?.entryIds?.length || opts.scope?.scenarios?.length && compiled.diagnostics.some(d => d.code === 'WORK_DRAFT_SKIPPED')) {
138
+ const dev = await compileProject(loader, projectDir, 'dev');
139
+ if (dev.project) {
140
+ for (const id of opts.scope?.entryIds ?? []) {
141
+ const entry = entryOf(dev.project, id);
142
+ if (!entry)
143
+ throw new JoploError('NOT_FOUND', `Unknown work "${id}". Works: ${entriesOf(dev.project).map(e => e.id).join(', ') || 'none'}`);
144
+ if (entry.featureId === null && !entry.slices.length)
145
+ throw new JoploError('USAGE', `Work "${id}" has no slices and cannot be published or reviewed. Add at least one flow() or chapter() in scenarios`);
146
+ if (entry.draft)
147
+ throw new JoploError('USAGE', `Work "${id}" is a draft and cannot be published or reviewed. Remove draft: true when it is ready`);
148
+ }
149
+ for (const id of opts.scope?.scenarios ?? []) {
150
+ const slice = dev.project.scenarios[id];
151
+ const entry = slice && entryOf(dev.project, dev.project.works[slice.workId]?.featureId ?? slice.workId);
152
+ if (entry?.draft)
153
+ throw new JoploError('USAGE', `Work "${entry.id}" is a draft and cannot be published or reviewed. Remove draft: true when it is ready`);
154
+ }
155
+ // 同时保留原有功能未选定、场景拼错与空范围的恢复提示。
156
+ resolveScope(dev.project, opts.scope, opts.review === true ? 'review' : 'publish');
157
+ }
158
+ }
123
159
  }
124
160
  finally {
125
161
  await loader.close();
@@ -128,6 +164,8 @@ export async function buildSite(opts) {
128
164
  const errs = compiled.diagnostics.filter((d) => d.severity === 'error');
129
165
  throw new JoploError('EXPORT_FAILED', `Project compilation failed; no published site was generated: \n${errs.map((d) => `${d.at ?? ''} ${d.message}`).join('\n')}`, { diagnostics: compiled.diagnostics });
130
166
  }
167
+ if (!entriesOf(compiled.project).length && compiled.diagnostics.some(d => d.code === 'WORK_DRAFT_SKIPPED' || d.code === 'WORK_EMPTY'))
168
+ throw new JoploError('USAGE', compiled.diagnostics.some(d => d.code === 'WORK_EMPTY') ? 'There is no picked option or publishable work. Add at least one flow() or chapter() to an empty work before building' : 'There is no picked option or publishable work. All independent works are drafts; remove draft: true when ready', { diagnostics: compiled.diagnostics });
131
169
  // 按场景保密分享(D75):先裁剪 IR,再生成产物;写错范围在写任何文件之前报错
132
170
  let project = compiled.project;
133
171
  let scope;
@@ -154,15 +192,19 @@ export async function buildSite(opts) {
154
192
  inline.scoped = true;
155
193
  // 2. vite build 到临时目录
156
194
  const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'joplo-build-'));
195
+ const cssSources = fs.mkdtempSync(path.join(os.tmpdir(), 'joplo-public-css-'));
196
+ const publicCssSource = path.join(cssSources, 'public-ir.html');
157
197
  let voiceReport;
158
198
  // React 与 plugin-react 依据 NODE_ENV 判断生产构建(测试运行器会把它设为 test);构建期间强制 production。
159
199
  const prevEnv = process.env.NODE_ENV;
160
200
  process.env.NODE_ENV = 'production';
161
201
  try {
202
+ // 内容文件与 Vite outDir 分离,避免 emptyOutDir 在扫描前删除它;永不复制进产物。
203
+ fs.writeFileSync(publicCssSource, publishCssContent(inline.project), { mode: 0o600 });
162
204
  if (web.mode === 'dist')
163
- await stageDistSite(web, projectDir, staging);
205
+ await stageDistSite(web, projectDir, staging, publicCssSource);
164
206
  else
165
- await buildSourceSite(web, projectDir, staging);
207
+ await buildSourceSite(web, projectDir, staging, publicCssSource);
166
208
  // 朗读(D74):当前声音已生成的音频拷进 voice/,IR 带上 voiceIndex;Key 不进产物
167
209
  const store = new ProfileStore(opts.home ?? joploHome());
168
210
  // 重新发布(D84):先从上一次的分享沿用本机没有的音频(同样的文字与声音),不重新生成
@@ -212,19 +254,21 @@ export async function buildSite(opts) {
212
254
  else
213
255
  process.env.NODE_ENV = prevEnv;
214
256
  fs.rmSync(staging, { recursive: true, force: true });
257
+ fs.rmSync(cssSources, { recursive: true, force: true });
215
258
  }
216
259
  return {
217
260
  outDir,
218
261
  files: listFiles(outDir),
219
- routes: Object.keys(project.routes).sort(),
262
+ routes: visibleRoutes(project).map(r => r.path).sort(),
220
263
  scenarios: Object.keys(project.scenarios),
221
264
  diagnostics: compiled.diagnostics,
265
+ ...(entriesOf(project).some(e => e.featureId === null || e.sequencing === 'linear') ? { entries: entriesOf(project).map(e => ({ id: e.id, title: e.title, slices: e.slices.length, sequencing: e.sequencing })) } : {}),
222
266
  ...(voiceReport && (voiceReport.clips || voiceReport.profile) ? { voice: voiceReport } : {}),
223
267
  ...(scope ? { scope } : {}),
224
268
  };
225
269
  }
226
270
  /** 仓库里:直接编译 packages/web 的发布站入口。 */
227
- async function buildSourceSite(web, projectDir, staging) {
271
+ async function buildSourceSite(web, projectDir, staging, publicCssSource) {
228
272
  const { default: react } = await import('@vitejs/plugin-react');
229
273
  await viteBuild({
230
274
  configFile: false,
@@ -235,7 +279,7 @@ async function buildSourceSite(web, projectDir, staging) {
235
279
  logLevel: 'error',
236
280
  resolve: { alias: [{ find: /^@joplo-app\/core(?:\/runtime)?$/, replacement: path.join(web.webDir, 'src/site/core-lite.ts') }, ...kitAliases(web, projectDir)] },
237
281
  define: { 'process.env.NODE_ENV': '"production"' },
238
- plugins: [joploProjectPlugin(projectDir, web), react(), tailwindcss()],
282
+ plugins: [joploProjectPlugin(projectDir, web, publicCssSource), react(), tailwindcss()],
239
283
  build: {
240
284
  minify: true,
241
285
  sourcemap: false,
@@ -250,7 +294,7 @@ async function buildSourceSite(web, projectDir, staging) {
250
294
  });
251
295
  }
252
296
  /** 从 npm 安装时:复制预构建的发布站,单独编译作者 className 的 CSS 并在 site.html 里引用。 */
253
- export async function stageDistSite(web, projectDir, staging) {
297
+ export async function stageDistSite(web, projectDir, staging, publicCssSource) {
254
298
  for (const rel of web.siteFiles) {
255
299
  const to = path.join(staging, rel);
256
300
  fs.mkdirSync(path.dirname(to), { recursive: true });
@@ -265,7 +309,7 @@ export async function stageDistSite(web, projectDir, staging) {
265
309
  base: './',
266
310
  mode: 'production',
267
311
  logLevel: 'error',
268
- plugins: [joploProjectPlugin(projectDir, web), tailwindcss()],
312
+ plugins: [joploProjectPlugin(projectDir, web, publicCssSource), tailwindcss()],
269
313
  build: { outDir: cssOut, emptyOutDir: true, minify: true, sourcemap: false, reportCompressedSize: false, write: true, rolldownOptions: { input: { project: web.projectCss } } },
270
314
  }));
271
315
  const files = (Array.isArray(out) ? out : [out]).flatMap((o) => o.output.map((x) => x.fileName)).filter((f) => f.endsWith('.css'));
package/dist/cloud.d.ts CHANGED
@@ -137,7 +137,7 @@ export type CloudPublishRequest = {
137
137
  visibility?: CloudVisibility;
138
138
  review?: boolean;
139
139
  scenarios?: string[];
140
- features?: string[];
140
+ entryIds?: string[];
141
141
  };
142
142
  export type CloudPublishResult = {
143
143
  passwordProtected?: boolean;
package/dist/cloud.js CHANGED
@@ -65,12 +65,12 @@ export class CloudHub {
65
65
  try {
66
66
  const body = (b.body ?? {});
67
67
  const scenarios = strings(body.scenarios, 'scenarios');
68
- const features = strings(body.features, 'features');
68
+ const entryIds = strings(body.entryIds, 'entryIds');
69
69
  if (body.visibility !== 'public' && body.visibility !== 'private')
70
70
  throw new Error('Choose visibility: public / private');
71
71
  if (typeof body.review !== 'boolean')
72
72
  throw new Error('Choose review: true / false');
73
- if (body.visibility === 'public' && (scenarios?.length || features?.length))
73
+ if (body.visibility === 'public' && (scenarios?.length || entryIds?.length))
74
74
  throw new Error('Scoped shares must be private');
75
75
  if (body.password !== undefined) {
76
76
  if (body.visibility !== 'private')
@@ -78,7 +78,7 @@ export class CloudHub {
78
78
  if (body.password !== null && (typeof body.password !== 'string' || Array.from(body.password).length < 8 || Array.from(body.password).length > 128))
79
79
  throw new Error('Access password must contain 8–128 characters');
80
80
  }
81
- request = { ...(body.password !== undefined ? { password: body.password } : {}), visibility: body.visibility, review: body.review, ...(scenarios?.length ? { scenarios } : {}), ...(features?.length ? { features } : {}) };
81
+ request = { ...(body.password !== undefined ? { password: body.password } : {}), visibility: body.visibility, review: body.review, ...(scenarios?.length ? { scenarios } : {}), ...(entryIds?.length ? { entryIds } : {}) };
82
82
  }
83
83
  catch (e) {
84
84
  return ctx.send(400, { error: { code: 'USAGE', message: e instanceof Error ? e.message : String(e) } }), true;
@@ -40,7 +40,7 @@ export type BuildOptions = {
40
40
  /** 本机目录(缺省 JOPLO_HOME 或 ~/.joplo):读声音供应商 profile(D74);测试指向临时目录。 */
41
41
  home?: string;
42
42
  /**
43
- * 按场景保密分享(D75,`--scenario` / `--feature`):构建时把 IR 裁剪到这些场景,产物里不出现范围外的功能、方案、场景。
43
+ * 按场景保密分享(D75,`--scenario` / `--work`):构建时把 IR 裁剪到这些场景,产物里不出现范围外的功能、方案、场景。
44
44
  * 缺省(或两个数组都为空)时与原来完全一致。写错场景 / 功能时报错,不写任何文件。
45
45
  */
46
46
  scope?: ScopeRequest;
@@ -64,6 +64,12 @@ export type BuildOptions = {
64
64
  * profile = 选用的声音供应商名。没有选用供应商、也没有音频时省略。
65
65
  */
66
66
  export type BuildResult = {
67
+ entries?: {
68
+ id: string;
69
+ title: string;
70
+ slices: number;
71
+ sequencing: 'linear' | 'independent';
72
+ }[];
67
73
  outDir: string;
68
74
  files: string[];
69
75
  routes: string[];
@@ -89,7 +95,7 @@ export type RenderOptions = {
89
95
  stepId?: string;
90
96
  /** 主题名(D51):内置主题或项目 themes/<name>.css;缺省用项目配置的主题。 */
91
97
  theme?: string;
92
- /** UI language for the standalone render route. Unsupported values are ignored. */
98
+ /** UI language for the independent render route. Unsupported values are ignored. */
93
99
  locale?: string;
94
100
  /** Author content language (D84): one of config locales; the screenshot shows that translation. */
95
101
  content?: string;
package/dist/dev.js CHANGED
@@ -484,10 +484,10 @@ export async function createHub(opts = {}) {
484
484
  if (slot.compiling || slot.dirty || slot.timer || !slot.payload.ok || !slot.payload.project || slot.payload.diagnostics.some(d => d.severity === 'error'))
485
485
  throw new JoploError('REVISION_CONFLICT', 'Wait for the project to compile successfully before reviewing');
486
486
  if (method === 'GET') {
487
- const optionId = new URL(req.url, baseUrl()).searchParams.get('option');
488
- if (!optionId)
489
- throw new JoploError('USAGE', 'option is required');
490
- return sendJson(res, 200, reviewHub.state(slot.dir, optionId));
487
+ const workId = new URL(req.url, baseUrl()).searchParams.get('workId');
488
+ if (!workId)
489
+ throw new JoploError('USAGE', 'workId is required');
490
+ return sendJson(res, 200, reviewHub.state(slot.dir, workId));
491
491
  }
492
492
  const body = await jsonBody(req, res);
493
493
  if (!body.ok)
@@ -1,4 +1,4 @@
1
- /** Public diff shell. Keep this standalone: embedded verbatim, never executed by the publisher. */
1
+ /** Public diff shell. Keep this independent: embedded verbatim, never executed by the publisher. */
2
2
  "use strict";
3
3
  // Self-contained so the same function works from source and packed server builds.
4
4
  function viewer() {
@@ -203,7 +203,7 @@ function viewer() {
203
203
  $('players').replaceChildren();
204
204
  $('sides').replaceChildren();
205
205
  const s = m.scenarios[i];
206
- $('feature').textContent = s.featureName;
206
+ $('feature').textContent = s.entryTitle;
207
207
  $('title').textContent = s.name;
208
208
  $('badge').textContent = labels[s.status];
209
209
  $('badge').className = `badge ${s.status}`;
@@ -307,9 +307,9 @@ function viewer() {
307
307
  hidden++;
308
308
  return;
309
309
  }
310
- if (!group || group.id !== s.featureId) {
311
- group = { id: s.featureId };
312
- nav.append(el('p', 'group', s.featureName));
310
+ if (!group || group.id !== s.entryId) {
311
+ group = { id: s.entryId };
312
+ nav.append(el('p', 'group', s.entryTitle));
313
313
  }
314
314
  const b = el('button', 'scenario');
315
315
  const changes = s.steps.filter(x => x.status !== 'unchanged').length;
@@ -16,7 +16,7 @@ const ICONS = {
16
16
  hidden: icon('<path d="M10.7 5.1A10 10 0 0 1 22 12a13 13 0 0 1-1.7 2.7M6.6 6.6A13.5 13.5 0 0 0 2 12s3 7 10 7a9.7 9.7 0 0 0 5.4-1.6M9.9 9.9a3 3 0 0 0 4.2 4.2M2 2l20 20"/>'),
17
17
  };
18
18
  const MARK = '<svg width="24" height="24" viewBox="0 0 128 128" aria-hidden="true"><rect x="4" y="4" width="120" height="120" rx="30" fill="#FFD23F"/><circle cx="40" cy="40" r="9" fill="#1E1E1E"/><circle cx="43" cy="36" r="3" fill="#fff"/><circle cx="87" cy="40" r="9" fill="#1E1E1E"/><circle cx="90" cy="36" r="3" fill="#fff"/><path d="M93 60V72Q93 100 63 100Q41 100 31 82" fill="none" stroke="#1E1E1E" stroke-width="11" stroke-linecap="round" stroke-linejoin="round"/></svg>';
19
- /** Tab icon: the same mark, standalone SVG so the viewer needs no extra file. */
19
+ /** Tab icon: the same mark, independent SVG so the viewer needs no extra file. */
20
20
  const FAVICON = 'data:image/svg+xml,' + encodeURIComponent(MARK.replace('<svg width="24" height="24"', '<svg xmlns="http://www.w3.org/2000/svg"').replace(' aria-hidden="true"', ''));
21
21
  // Tokens mirror design/joplo-board.pen「设计 Token v1」; layout follows「功能差异 · 单画面(默认)」.
22
22
  const CSS = `
@@ -9,7 +9,7 @@ async function checkFiles(dir, prefix = '') {
9
9
  for (const e of await readdir(dir, { withFileTypes: true })) {
10
10
  const relative = prefix + e.name;
11
11
  if (e.isSymbolicLink() || /[\\?#%\x00-\x1f\x7f]/.test(e.name) || (!prefix && !['index.html', 'assets', 'fonts', 'voice', '_joplo'].includes(e.name)))
12
- throw new JoploError('INVALID_SCHEMA', `Not a standalone public build: ${relative}`);
12
+ throw new JoploError('INVALID_SCHEMA', `Not a self-contained public build: ${relative}`);
13
13
  if (e.isDirectory())
14
14
  await checkFiles(join(dir, e.name), relative + '/');
15
15
  else if (!e.isFile())
@@ -75,7 +75,11 @@ export class LocalResources {
75
75
  throw new Error('Local entry could not be bundled');
76
76
  return output.output.filter(x => x.type === 'chunk').map(x => x.code).join('\n');
77
77
  })());
78
- return this.bundles.get(plugin);
78
+ // 宿主在热更新之间复用:失败的结果不留在缓存里,下一次编译重试
79
+ const pending = this.bundles.get(plugin);
80
+ pending.catch(() => { if (this.bundles.get(plugin) === pending)
81
+ this.bundles.delete(plugin); });
82
+ return pending;
79
83
  }
80
84
  async describe(request) {
81
85
  const code = await this.bundle(request.plugin), dir = path.join(this.directory, '.joplo', 'resources');
@@ -115,7 +119,10 @@ export class LocalResources {
115
119
  child.stdin.on('error', () => { });
116
120
  child.stdin.end(JSON.stringify({ entry, compiler: request.compiler, input: request.input }));
117
121
  }));
118
- return this.descriptions.get(key);
122
+ const pending = this.descriptions.get(key);
123
+ pending.catch(() => { if (this.descriptions.get(key) === pending)
124
+ this.descriptions.delete(key); });
125
+ return pending;
119
126
  }
120
127
  /** Lightweight author-only metadata. No rendering, bank download or provider spend. */
121
128
  async inspect(request) {
@@ -1,6 +1,6 @@
1
1
  import { type LocalReviewContext, type LocalReviewLocation, type LocalReviewState, type LocalReviewWrite, type Project } from '@joplo-app/core';
2
- export declare function localReviewRevision(project: Project, optionId: string): string;
3
- export declare function localReviewContext(project: Project, optionId: string, input: LocalReviewLocation): LocalReviewContext;
2
+ export declare function localReviewRevision(project: Project, workId: string): string;
3
+ export declare function localReviewContext(project: Project, workId: string, input: LocalReviewLocation): LocalReviewContext;
4
4
  /** 一个 Hub 是一个不可复用的实例身份;不同 Hub 即使打开同一项目,也写不同的会话文件。 */
5
5
  export declare class LocalReviewHub {
6
6
  private baseUrl;
@@ -13,6 +13,6 @@ export declare class LocalReviewHub {
13
13
  private closeSession;
14
14
  sync(dir: string, projectId: string, project: Project): void;
15
15
  invalidate(dir: string, reason: 'source_changed' | 'compile_error' | 'server_stopped'): void;
16
- state(dir: string, optionId: string): LocalReviewState;
16
+ state(dir: string, workId: string): LocalReviewState;
17
17
  write(dir: string, project: Project, input: LocalReviewWrite): LocalReviewState;
18
18
  }
@@ -1,6 +1,6 @@
1
- import { projectThemes } from '@joplo-app/core';
1
+ import { entriesOf, projectThemes } from '@joplo-app/core';
2
2
  import crypto from 'node:crypto';
3
- import { JoploError, LOCAL_REVIEW_MAX_EVENTS, LOCAL_REVIEW_MAX_FILE_BYTES, LocalReviewSession, localReviewStatus, stateAt } from '@joplo-app/core';
3
+ import { JoploError, LOCAL_REVIEW_VERSION, LOCAL_REVIEW_MAX_EVENTS, LOCAL_REVIEW_MAX_FILE_BYTES, LocalReviewSession, localReviewStatus, stateAt } from '@joplo-app/core';
4
4
  import { localReviewFile, localReviewWatcherCount, writeLocalReview } from '@joplo-app/core/node';
5
5
  /** 对象键的插入顺序不构成新版本;数组顺序属于方案内容。 */
6
6
  function stable(value) {
@@ -10,18 +10,18 @@ function stable(value) {
10
10
  return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, stable(v)]));
11
11
  return value;
12
12
  }
13
- export function localReviewRevision(project, optionId) {
14
- const option = project.options[optionId];
15
- const feature = project.features[option.featureId];
16
- const own = (values) => Object.fromEntries(Object.entries(values).filter(([, v]) => v.optionId === optionId || (v.optionId == null && (v.featureId == null || v.featureId === option.featureId))));
13
+ export function localReviewRevision(project, workId) {
14
+ const option = project.works[workId];
15
+ const feature = option.featureId ? project.features[option.featureId] : undefined;
16
+ const own = (values) => Object.fromEntries(Object.entries(values).filter(([, v]) => v.workId === workId || (v.workId == null && (v.featureId == null || v.featureId === option.featureId))));
17
17
  const value = { name: project.name, description: project.description, theme: project.theme, themes: projectThemes(project), autoFocus: project.autoFocus,
18
- feature, option, scenes: own(project.scenes), scenarios: own(project.scenarios), rules: own(project.rules), issues: own(project.issues),
18
+ feature, work: option, scenes: own(project.scenes), scenarios: own(project.scenarios), rules: own(project.rules), issues: own(project.issues),
19
19
  cases: Object.fromEntries(Object.entries(project.cases).filter(([, c]) => c.featureId === option.featureId)),
20
20
  };
21
21
  return crypto.createHash('sha256').update(JSON.stringify(stable(value))).digest('hex');
22
22
  }
23
- export function localReviewContext(project, optionId, input) {
24
- const option = project.options[optionId];
23
+ export function localReviewContext(project, workId, input) {
24
+ const option = project.works[workId];
25
25
  const scene = project.scenes[input.sceneId];
26
26
  if (!option || !scene)
27
27
  throw new JoploError('INVALID_REFERENCE', 'Review page or option no longer exists');
@@ -31,7 +31,7 @@ export function localReviewContext(project, optionId, input) {
31
31
  let scenarioName = null;
32
32
  if (input.scenarioId !== null) {
33
33
  const scenario = project.scenarios[input.scenarioId];
34
- if (!scenario || scenario.optionId !== optionId || input.position > scenario.steps.length)
34
+ if (!scenario || scenario.workId !== workId || input.position > scenario.steps.length)
35
35
  throw new JoploError('INVALID_REFERENCE', 'Review scenario or step does not belong to this option');
36
36
  const state = stateAt(project, scenario.id, input.position);
37
37
  if (state.sceneId !== scene.id && !layerScenes.includes(scene.id))
@@ -41,7 +41,7 @@ export function localReviewContext(project, optionId, input) {
41
41
  source = step?.source ?? source;
42
42
  scenarioName = scenario.name;
43
43
  }
44
- else if (input.position !== 0 || (scene.optionId !== optionId && !layerScenes.includes(scene.id))) {
44
+ else if (input.position !== 0 || (scene.workId !== workId && !layerScenes.includes(scene.id))) {
45
45
  throw new JoploError('INVALID_REFERENCE', 'Review page does not belong to this option');
46
46
  }
47
47
  return { ...input, route: scene.route, pageTitle: scene.name, stepId, source, scenarioName };
@@ -63,7 +63,7 @@ export class LocalReviewHub {
63
63
  throw new JoploError('USAGE', 'Local review storage limit reached. Confirm this review before starting another');
64
64
  writeLocalReview(localReviewFile(session.projectDir, session.id), session);
65
65
  this.sessions.set(session.id, session);
66
- this.current.set(this.key(session.projectDir, session.optionId), session);
66
+ this.current.set(this.key(session.projectDir, session.workId), session);
67
67
  return session;
68
68
  }
69
69
  closeSession(session, reason) {
@@ -73,33 +73,38 @@ export class LocalReviewHub {
73
73
  }
74
74
  sync(dir, projectId, project) {
75
75
  for (const s of [...this.current.values()])
76
- if (s.projectDir === dir && !project.options[s.optionId]) {
77
- this.closeSession(s, 'option_removed');
78
- this.current.delete(this.key(dir, s.optionId));
76
+ if (s.projectDir === dir && !project.works[s.workId]) {
77
+ this.closeSession(s, 'work_removed');
78
+ this.current.delete(this.key(dir, s.workId));
79
+ }
80
+ for (const entry of entriesOf(project))
81
+ for (const workId of entry.featureId === null ? [entry.workId] : project.features[entry.featureId].workIds) {
82
+ const option = workId ? project.works[workId] : undefined;
83
+ if (!option)
84
+ continue;
85
+ const revision = localReviewRevision(project, option.id);
86
+ const old = this.current.get(this.key(dir, option.id));
87
+ if (old?.revision === revision && localReviewStatus(old) !== 'closed')
88
+ continue;
89
+ if (old)
90
+ this.closeSession(old, 'source_changed');
91
+ const id = `rv_${crypto.randomBytes(16).toString('hex')}`;
92
+ this.persist({ v: LOCAL_REVIEW_VERSION, id, instanceId: this.instanceId, ownerPid: process.pid, projectId, projectDir: dir, projectName: project.name,
93
+ featureId: entry.featureId, featureName: entry.featureId === null ? null : entry.title, workId: option.id, workTitle: option.title,
94
+ revision, createdAt: new Date().toISOString(), url: `${this.baseUrl()}#/${encodeURIComponent(projectId)}/f/${encodeURIComponent(entry.id)}?o=${encodeURIComponent(option.id)}`,
95
+ events: [],
96
+ });
79
97
  }
80
- for (const option of Object.values(project.options)) {
81
- const revision = localReviewRevision(project, option.id);
82
- const old = this.current.get(this.key(dir, option.id));
83
- if (old?.revision === revision && localReviewStatus(old) !== 'closed')
84
- continue;
85
- if (old)
86
- this.closeSession(old, 'source_changed');
87
- const id = `rv_${crypto.randomBytes(16).toString('hex')}`;
88
- this.persist({ v: 1, id, instanceId: this.instanceId, ownerPid: process.pid, projectId, projectDir: dir, projectName: project.name,
89
- featureId: option.featureId, featureName: project.features[option.featureId].name, optionId: option.id, optionName: option.name,
90
- revision, createdAt: new Date().toISOString(), url: `${this.baseUrl()}#/${encodeURIComponent(projectId)}/f/${encodeURIComponent(option.featureId)}?o=${encodeURIComponent(option.id)}`,
91
- events: [], });
92
- }
93
98
  }
94
99
  invalidate(dir, reason) {
95
100
  for (const session of [...this.current.values()])
96
101
  if (session.projectDir === dir) {
97
102
  this.closeSession(session, reason);
98
- this.current.delete(this.key(dir, session.optionId));
103
+ this.current.delete(this.key(dir, session.workId));
99
104
  }
100
105
  }
101
- state(dir, optionId) {
102
- const session = this.current.get(this.key(dir, optionId));
106
+ state(dir, workId) {
107
+ const session = this.current.get(this.key(dir, workId));
103
108
  if (!session)
104
109
  throw new JoploError('NOT_FOUND', 'No current review for this option. Wait for a successful compilation');
105
110
  return { session, watchers: localReviewWatcherCount(dir, session.id) };
@@ -116,19 +121,19 @@ export class LocalReviewHub {
116
121
  throw new JoploError('IDEMPOTENCY_MISMATCH', 'Request id was already used for different feedback');
117
122
  return { session, watchers: localReviewWatcherCount(dir, session.id) };
118
123
  }
119
- if (this.current.get(this.key(dir, session.optionId))?.id !== session.id || localReviewRevision(project, session.optionId) !== session.revision)
124
+ if (this.current.get(this.key(dir, session.workId))?.id !== session.id || localReviewRevision(project, session.workId) !== session.revision)
120
125
  throw new JoploError('REVISION_CONFLICT', 'The option changed. Open its current review before submitting');
121
126
  if (input.type === 'approved' && localReviewStatus(session) === 'approved')
122
- return this.state(dir, session.optionId);
127
+ return this.state(dir, session.workId);
123
128
  if (localReviewStatus(session) !== 'open')
124
129
  throw new JoploError('REVISION_CONFLICT', 'This review has ended');
125
130
  if (input.type === 'feedback' && session.events.length >= LOCAL_REVIEW_MAX_EVENTS - 1)
126
131
  throw new JoploError('USAGE', 'This review has reached its feedback limit. Confirm it before starting a new review');
127
132
  const base = { sessionId: session.id, seq: session.events.length + 1, requestId: input.requestId, createdAt: new Date().toISOString() };
128
133
  const event = input.type === 'feedback'
129
- ? { ...base, type: 'feedback', body: input.body, context: localReviewContext(project, session.optionId, input.context) }
134
+ ? { ...base, type: 'feedback', body: input.body, context: localReviewContext(project, session.workId, input.context) }
130
135
  : { ...base, type: 'approved' };
131
136
  this.persist({ ...session, events: [...session.events, event] });
132
- return this.state(dir, session.optionId);
137
+ return this.state(dir, session.workId);
133
138
  }
134
139
  }
@@ -1,4 +1,4 @@
1
- import { mediaResourceIds, nodeResourceIds, stepAnchorMs } from '@joplo-app/core';
1
+ import { mediaResourceIds, nodeResourceIds, commitGapMs } from '@joplo-app/core';
2
2
  export async function inspectResources(project, requests, host) {
3
3
  const used = project ? mediaResourceIds(project) : new Set();
4
4
  for (const id of nodeResourceIds(project))
@@ -33,7 +33,9 @@ export function mediaDiagnostics(project, info) {
33
33
  if (code)
34
34
  diagnostics.push({ code, severity: 'warning', source: 'structure', at: run.at, message: `${sc.name}: music ${(length / 1000).toFixed(2)} s, starts ${(run.offset / 1000).toFixed(2)} s, scene playback ${(run.duration / 1000).toFixed(2)} s${run.loop ? '; short loop may become repetitive' : '; music ends well before this run finishes'}` });
35
35
  };
36
- for (const step of sc.steps) {
36
+ for (const [index, step] of sc.steps.entries()) {
37
+ // 这一步提交之后到下一步提交(或场景播完)的计划时长:与编译期推进配乐快照用同一个函数
38
+ const gap = commitGapMs(project, sc.steps, index);
37
39
  const tracks = step.media ?? {};
38
40
  for (const key of [...runs.keys()])
39
41
  if (!tracks[key])
@@ -44,8 +46,8 @@ export function mediaDiagnostics(project, info) {
44
46
  finish(key);
45
47
  if (!runs.has(key))
46
48
  runs.set(key, { resource: t.resource, offset: t.offsetMs, duration: 0, loop: t.loop, at: step.source });
47
- runs.get(key).duration += Math.min(stepAnchorMs(step), t.stopAfterMs ?? Infinity);
48
- if (t.stopAfterMs !== undefined && t.stopAfterMs <= stepAnchorMs(step))
49
+ runs.get(key).duration += Math.min(gap, t.stopAfterMs ?? Infinity);
50
+ if (t.stopAfterMs !== undefined && t.stopAfterMs <= gap)
49
51
  finish(key);
50
52
  }
51
53
  }
package/dist/project.js CHANGED
@@ -78,12 +78,38 @@ export async function compileProject(server, projectDir, mode) {
78
78
  if (diagnostics.some((d) => d.severity === 'error'))
79
79
  return { project: null, diagnostics, home, pluginRuntimes };
80
80
  // Enabled plugins derive their own layout and drawing snapshots; the host schedules resources.
81
- const requests = [];
82
81
  const entries = Object.fromEntries(enabledPlugins(loaded.authoring.config.plugins).filter(isPluginDef).filter(p => p.local).map(p => [p.id, p.local]));
83
- const resources = { requests, host: new LocalResources(projectDir, entries, Object.fromEntries(enabledPlugins(loaded.authoring.config.plugins).filter(isPluginDef).map(p => [p.id, p.keys ?? []]))) };
84
- const first = compile(loaded.authoring, mode, { onResource: request => requests.push(request) });
85
- const inspected = await inspectResources(first.project, requests, resources.host);
86
- const r = Object.keys(inspected.resourceInfo).length ? compile(loaded.authoring, mode, { resourceInfo: inspected.resourceInfo }) : first;
82
+ const host = resourceHost(projectDir, entries, Object.fromEntries(enabledPlugins(loaded.authoring.config.plugins).filter(isPluginDef).map(p => [p.id, p.keys ?? []])));
83
+ // 资源元数据(时长、marker)要先编译一遍才知道有哪些资源,再异步检查,再带着元数据编译一遍。
84
+ // 上一次检查到的元数据按请求内容记着,只当作提示:带着它编译一遍,然后照常重新检查——
85
+ // 只有“这一遍编译成功,并且每个资源重新检查到的元数据都和提示一致”时才直接用这一遍的结果。
86
+ // 其余情况(提示过期、提示让编译报错、多了或少了资源)一律退回不带提示的两遍流程,
87
+ // 所以提示永远不会改变结果,也不会让过期的元数据产生一个看起来成功的错误编译(D101 评审 P1)。
88
+ const known = knownInfo.get(projectDir);
89
+ let requests = [];
90
+ let inspected = null;
91
+ let r = null;
92
+ if (known?.size) {
93
+ const hinted = [];
94
+ const fast = compile(loaded.authoring, mode, { onResource: request => hinted.push(request), resourceInfoFor: request => known.get(requestKey(request)) });
95
+ if (fast.project) {
96
+ const seen = await inspectResources(fast.project, hinted, host);
97
+ if (hinted.every(request => JSON.stringify(known.get(requestKey(request))) === JSON.stringify(seen.resourceInfo[request.id]))) {
98
+ r = fast;
99
+ requests = hinted;
100
+ inspected = seen;
101
+ }
102
+ }
103
+ }
104
+ if (!r || !inspected) {
105
+ requests = [];
106
+ const first = compile(loaded.authoring, mode, { onResource: request => requests.push(request) });
107
+ inspected = await inspectResources(first.project, requests, host);
108
+ r = Object.keys(inspected.resourceInfo).length ? compile(loaded.authoring, mode, { resourceInfo: inspected.resourceInfo }) : first;
109
+ }
110
+ const checked = inspected;
111
+ knownInfo.set(projectDir, new Map(requests.flatMap(request => checked.resourceInfo[request.id] ? [[requestKey(request), checked.resourceInfo[request.id]]] : [])));
112
+ const resources = { requests, host };
87
113
  diagnostics.push(...inspected.diagnostics, ...(r.project ? mediaDiagnostics(r.project, inspected.resourceInfo) : []));
88
114
  const missing = Object.keys(r.project?.plugins ?? {}).filter((id) => !pluginRuntimes[id]);
89
115
  const extra = missing.map((id) => ({ severity: 'error', code: 'PLUGIN_RUNTIME_MISSING', message: `Plugin ${id}: runtime file not found; reinstall the plugin package`, source: 'reference', at: `${loaded.authoring.config.file}:1:1` }));
@@ -95,6 +121,54 @@ export async function compileProject(server, projectDir, mode) {
95
121
  }
96
122
  return { project: extra.length ? null : r.project, diagnostics: [...diagnostics, ...r.diagnostics, ...extra], home, pluginRuntimes, resources };
97
123
  }
124
+ const requestKey = (request) => JSON.stringify([request.plugin, request.compiler, request.input]);
125
+ /** 项目目录 → 上一次编译检查到的资源元数据(按请求内容)。只是让第一遍编译用得上的提示;每次编译仍会重新检查并核对。 */
126
+ const knownInfo = new Map();
127
+ /**
128
+ * 项目目录 → 本机资源宿主。打包插件的本机入口、在子进程里读取编译器描述都只做一次,热更新时复用;
129
+ * 插件入口文件或密钥声明变了(路径、修改时间、大小)就换一个新的。
130
+ */
131
+ const hosts = new Map();
132
+ function resourceHost(projectDir, entries, keys) {
133
+ // 入口所在目录里的源文件都算进签名(入口会 import 同目录的模块);不进 node_modules,最多看 400 个文件
134
+ const stamp = (entry) => {
135
+ const out = [];
136
+ const walk = (dir) => {
137
+ let names = [];
138
+ try {
139
+ names = fs.readdirSync(dir, { withFileTypes: true });
140
+ }
141
+ catch {
142
+ return;
143
+ }
144
+ for (const d of names.sort((a, b) => a.name.localeCompare(b.name))) {
145
+ if (out.length >= 400 || d.name === 'node_modules' || d.name.startsWith('.'))
146
+ continue;
147
+ const file = path.join(dir, d.name);
148
+ if (d.isDirectory())
149
+ walk(file);
150
+ else {
151
+ try {
152
+ const s = fs.statSync(file);
153
+ out.push(`${file}:${s.mtimeMs}:${s.size}`);
154
+ }
155
+ catch { /* removed meanwhile */ }
156
+ }
157
+ }
158
+ };
159
+ if (!fs.existsSync(entry))
160
+ return ['missing'];
161
+ walk(path.dirname(entry));
162
+ return out;
163
+ };
164
+ const signature = JSON.stringify([Object.entries(entries).sort(([a], [b]) => a.localeCompare(b)).map(([id, file]) => [id, file, stamp(file)]), keys]);
165
+ const hit = hosts.get(projectDir);
166
+ if (hit?.signature === signature)
167
+ return hit.host;
168
+ const host = new LocalResources(projectDir, entries, keys);
169
+ hosts.set(projectDir, { signature, host });
170
+ return host;
171
+ }
98
172
  /** 让项目源文件在下次载入时重新转译、重新求值。 */
99
173
  export function invalidateProjectModules(server, projectDir) {
100
174
  for (const env of Object.values(server.environments)) {
@@ -0,0 +1,6 @@
1
+ /**
2
+ * 只从白名单与范围裁剪后的公开载荷生成 Tailwind 内容。
3
+ * 原样保存每个字符串:JSON 的引号/反斜杠转义会破坏任意值类名,不能直接扫描 JSON.stringify 的结果。
4
+ * 不限于 className:初始状态、步骤效果、free 反应和插件快照也可能提供运行时类名。
5
+ */
6
+ export declare function publishCssContent(payload: unknown): string;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * 只从白名单与范围裁剪后的公开载荷生成 Tailwind 内容。
3
+ * 原样保存每个字符串:JSON 的引号/反斜杠转义会破坏任意值类名,不能直接扫描 JSON.stringify 的结果。
4
+ * 不限于 className:初始状态、步骤效果、free 反应和插件快照也可能提供运行时类名。
5
+ */
6
+ export function publishCssContent(payload) {
7
+ const strings = new Set();
8
+ const visit = (value) => {
9
+ if (typeof value === 'string')
10
+ strings.add(value);
11
+ else if (Array.isArray(value))
12
+ value.forEach(visit);
13
+ else if (value && typeof value === 'object')
14
+ Object.values(value).forEach(visit);
15
+ };
16
+ visit(payload);
17
+ return [...strings].join('\n');
18
+ }
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  import { type Project, type Selection } from '@joplo-app/core';
3
3
  /** 浏览器提交的选中(服务端补全其余字段)。 */
4
4
  export declare const SelectionInput: z.ZodObject<{
5
- optionId: z.ZodNullable<z.ZodString>;
5
+ workId: z.ZodNullable<z.ZodString>;
6
6
  scenarioId: z.ZodNullable<z.ZodString>;
7
7
  position: z.ZodNumber;
8
8
  sceneId: z.ZodString;
@@ -12,7 +12,7 @@ export declare const SelectionInput: z.ZodObject<{
12
12
  export type SelectionInput = z.infer<typeof SelectionInput>;
13
13
  export declare const SelectionBody: z.ZodObject<{
14
14
  selection: z.ZodNullable<z.ZodObject<{
15
- optionId: z.ZodNullable<z.ZodString>;
15
+ workId: z.ZodNullable<z.ZodString>;
16
16
  scenarioId: z.ZodNullable<z.ZodString>;
17
17
  position: z.ZodNumber;
18
18
  sceneId: z.ZodString;
package/dist/selection.js CHANGED
@@ -14,7 +14,7 @@ import { z } from 'zod';
14
14
  import { findNode, nodeLabel, stateAt, walkNodes } from '@joplo-app/core';
15
15
  /** 浏览器提交的选中(服务端补全其余字段)。 */
16
16
  export const SelectionInput = z.strictObject({
17
- optionId: z.string().min(1).max(256).nullable(),
17
+ workId: z.string().min(1).max(256).nullable(),
18
18
  scenarioId: z.string().min(1).max(256).nullable(),
19
19
  position: z.number().int().nonnegative().max(10000),
20
20
  sceneId: z.string().min(1).max(256),
@@ -28,19 +28,19 @@ export function resolveSelection(project, input, now = new Date()) {
28
28
  let sceneId = input.sceneId;
29
29
  let stepId = null;
30
30
  let featureId = null;
31
- const optionId = input.optionId;
32
- if (optionId !== null) {
33
- const opt = project.options[optionId];
31
+ const workId = input.workId;
32
+ if (workId !== null) {
33
+ const opt = project.works[workId];
34
34
  if (!opt)
35
- return { ok: false, problem: `Option ${optionId} does not exist` };
36
- featureId = opt.featureId;
35
+ return { ok: false, problem: `Option ${workId} does not exist` };
36
+ featureId = opt.featureId ?? null;
37
37
  }
38
38
  if (input.scenarioId !== null) {
39
39
  const sc = project.scenarios[input.scenarioId];
40
40
  if (!sc)
41
41
  return { ok: false, problem: `Scenario ${input.scenarioId} does not exist` };
42
- if (optionId !== sc.optionId)
43
- return { ok: false, problem: `Scenario ${sc.id} does not belong to option ${optionId ?? '(none)'}` };
42
+ if (workId !== sc.workId)
43
+ return { ok: false, problem: `Scenario ${sc.id} does not belong to option ${workId ?? '(none)'}` };
44
44
  if (input.position > sc.steps.length)
45
45
  return { ok: false, problem: `Position ${input.position} is outside scenario ${sc.id} range 0..${sc.steps.length}` };
46
46
  try {
@@ -50,7 +50,7 @@ export function resolveSelection(project, input, now = new Date()) {
50
50
  return { ok: false, problem: `Scenario ${sc.id} cannot replay to position ${input.position}: ${e instanceof Error ? e.message : String(e)}` };
51
51
  }
52
52
  // 有层级的方案:用户看的是某一层的画面(各层共享同一份状态),也接受
53
- const layerScenes = Object.values(project.options[sc.optionId]?.layers ?? {}).map((l) => l.sceneId);
53
+ const layerScenes = Object.values(project.works[sc.workId]?.layers ?? {}).map((l) => l.sceneId);
54
54
  if (layerScenes.includes(input.sceneId))
55
55
  sceneId = input.sceneId;
56
56
  if (input.sceneId !== sceneId)
@@ -67,8 +67,8 @@ export function resolveSelection(project, input, now = new Date()) {
67
67
  const scene = project.scenes[sceneId];
68
68
  if (!scene)
69
69
  return { ok: false, problem: `Stage ${sceneId} does not exist` };
70
- if (input.scenarioId === null && optionId !== null && scene.optionId !== optionId && scene.optionId !== null)
71
- return { ok: false, problem: `Stage ${sceneId} does not belong to option ${optionId}` };
70
+ if (input.scenarioId === null && workId !== null && scene.workId !== workId && scene.workId !== null)
71
+ return { ok: false, problem: `Stage ${sceneId} does not belong to option ${workId}` };
72
72
  let at = null;
73
73
  let label = null;
74
74
  if (input.nodeId) {
@@ -89,7 +89,7 @@ export function resolveSelection(project, input, now = new Date()) {
89
89
  ok: true,
90
90
  selection: {
91
91
  featureId,
92
- optionId,
92
+ workId,
93
93
  scenarioId: input.scenarioId,
94
94
  position: input.position,
95
95
  stepId,
@@ -23,7 +23,7 @@ export declare function parseErrorLoc(message: string, file: string): {
23
23
  /** 作者 className 的 CSS 入口:追加每个项目目录为 Tailwind @source(看板进程同时服务多个项目)。 */
24
24
  export declare function cssSourcePlugin(dirs: () => string[], web?: WebAssets): Plugin;
25
25
  /**
26
- * 转译项目源文件(TSX → 收集数据的 JS);把 Tailwind @source 指向项目目录。
26
+ * 转译项目源文件(TSX → 收集数据的 JS)。看板默认扫描项目目录;发布时必须传入公开内容文件。
27
27
  * dist 形态下 CSS 入口是 @joplo-app/web/dist/project.css,其中的 `@import "tailwindcss"` 改为从 server 的依赖解析。
28
28
  */
29
- export declare function joploProjectPlugin(projectDir: string, web?: WebAssets): Plugin;
29
+ export declare function joploProjectPlugin(projectDir: string, web?: WebAssets, publicCssSource?: string): Plugin;
@@ -4,7 +4,7 @@
4
4
  * - 看板与发布站的界面源码在 packages/web(Vite root)。
5
5
  * - 项目源文件(作者的 TSX)只在服务端经 ssrLoadModule 载入:用 automatic JSX、
6
6
  * jsxImportSource '@joplo-app/kit'、development=true 转译,jsxDEV 因此拿到 文件:行:列。
7
- * - Tailwind 需要编译项目源文件里出现的 className:把项目目录追加为 index.css 的 @source。
7
+ * - 看板扫描项目源码;发布构建显式传入只来自公开 IR 的临时内容文件,不扫描作者目录。
8
8
  */
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
@@ -60,10 +60,10 @@ export function cssSourcePlugin(dirs, web = locateWebAssets()) {
60
60
  };
61
61
  }
62
62
  /**
63
- * 转译项目源文件(TSX → 收集数据的 JS);把 Tailwind @source 指向项目目录。
63
+ * 转译项目源文件(TSX → 收集数据的 JS)。看板默认扫描项目目录;发布时必须传入公开内容文件。
64
64
  * dist 形态下 CSS 入口是 @joplo-app/web/dist/project.css,其中的 `@import "tailwindcss"` 改为从 server 的依赖解析。
65
65
  */
66
- export function joploProjectPlugin(projectDir, web = locateWebAssets()) {
66
+ export function joploProjectPlugin(projectDir, web = locateWebAssets(), publicCssSource) {
67
67
  const entry = cssEntry(web);
68
68
  return {
69
69
  name: 'joplo:project',
@@ -72,8 +72,16 @@ export function joploProjectPlugin(projectDir, web = locateWebAssets()) {
72
72
  const file = id.split('?')[0];
73
73
  if (file === entry) {
74
74
  // Tailwind v4:@source 绝对路径;JSON.stringify 负责转义引号与反斜杠
75
- const css = web.mode === 'dist' ? code.replace(/@import\s+["']tailwindcss["']/, `@import ${JSON.stringify(tailwindIndexCss())}`) : code;
76
- return { code: `${css}\n@source ${JSON.stringify(projectDir)};\n`, map: null };
75
+ let css = code;
76
+ if (publicCssSource) {
77
+ css = css.replace(/(@import\s+["']tailwindcss["'])(?:\s+source\([^)]*\))?\s*;/, '$1 source(none);');
78
+ // 明确保留播放器自身的工具类与入口已有的插件样式来源。
79
+ if (web.mode === 'source')
80
+ css += `\n@source ${JSON.stringify(path.join(web.webDir, 'src'))};`;
81
+ }
82
+ if (web.mode === 'dist')
83
+ css = css.replace(/@import\s+["']tailwindcss["']/, `@import ${JSON.stringify(tailwindIndexCss())}`);
84
+ return { code: `${css}\n@source ${JSON.stringify(publicCssSource ?? projectDir)};\n`, map: null };
77
85
  }
78
86
  if (!isProjectSource(projectDir, file) || !/\.(tsx|ts|jsx|js|mts)$/.test(file))
79
87
  return;
@@ -121,6 +121,8 @@ export declare class VoiceHub {
121
121
  private cloudBlocked;
122
122
  /** cloud 请求的内容语言(D84):项目写了 locales 时是当前内容语言(没传时是默认语言);没写时不带,由云端按文字判断。 */
123
123
  private speechLocaleOf;
124
+ /** dev IR 的草稿仍能本地播放,但不能把它的朗读文字发送给任何供应商。 */
125
+ private draftSegments;
124
126
  /** /__joplo/p/:id/voice[/…];不认识的路径返回 false。 */
125
127
  handleProject(projectId: string, dir: string, project: Project | null, rest: string, req: http.IncomingMessage, res: http.ServerResponse, ctx: Ctx): Promise<boolean>;
126
128
  /** 关闭看板时停掉正在生成的任务。 */
@@ -251,6 +251,11 @@ export class VoiceHub {
251
251
  speechLocaleOf(project, content) {
252
252
  return project?.i18n ? (content ?? project.i18n.default) : null;
253
253
  }
254
+ /** dev IR 的草稿仍能本地播放,但不能把它的朗读文字发送给任何供应商。 */
255
+ draftSegments(project, segments) {
256
+ const privateIds = new Set(Object.values(project?.scenarios ?? {}).filter(s => project?.works[s.workId]?.draft).flatMap(s => s.steps.map(st => st.id)));
257
+ return segments.some(s => privateIds.has(s.stepId));
258
+ }
254
259
  /** /__joplo/p/:id/voice[/…];不认识的路径返回 false。 */
255
260
  async handleProject(projectId, dir, project, rest, req, res, ctx) {
256
261
  const method = req.method ?? 'GET';
@@ -281,6 +286,8 @@ export class VoiceHub {
281
286
  const ok = segs && segs.length <= MAX_SEGMENTS && segs.every((s) => s && typeof s.stepId === 'string' && typeof s.text === 'string' && s.text.length <= MAX_TEXT && (s.role === null || typeof s.role === 'string'));
282
287
  if (!ok)
283
288
  return ctx.send(400, { error: { code: 'USAGE', message: `segments must be up to ${MAX_SEGMENTS} items of { stepId, text, role }` } }), true;
289
+ if (this.draftSegments(project, segs))
290
+ return ctx.send(403, { error: { code: 'USAGE', message: 'Draft narration stays on this computer. Remove draft: true before sending it to a voice service' } }), true;
284
291
  if (this.jobs.has(projectId))
285
292
  return ctx.send(409, { error: { code: 'BUSY', message: 'Narration is already being generated for this project' } }), true;
286
293
  const cache = new VoiceCache(dir);
@@ -329,6 +336,8 @@ export class VoiceHub {
329
336
  const seg = body.segment;
330
337
  if (!seg || typeof seg.stepId !== 'string' || typeof seg.text !== 'string' || seg.text.length > MAX_TEXT || (seg.role !== null && typeof seg.role !== 'string'))
331
338
  return ctx.send(400, { error: { code: 'USAGE', message: 'segment must be { stepId, text, role }' } }), true;
339
+ if (this.draftSegments(project, [seg]))
340
+ return ctx.send(403, { error: { code: 'USAGE', message: 'Draft narration stays on this computer. Remove draft: true before sending it to a voice service' } }), true;
332
341
  const cache = new VoiceCache(dir);
333
342
  const content = contentLocaleOf(project, body.contentLocale);
334
343
  const resolved = await this.resolveFor(dir, project, content);
package/dist/voice-run.js CHANGED
@@ -3,13 +3,10 @@ import { joploHome } from "./home.js";
3
3
  import { ProfileStore, UNSUPPORTED_MESSAGE, VoiceCache, VoiceError, estimateVoice, resolveVoices, voiceLocaleOf } from "./voice.js";
4
4
  /** 选定方案的全部场景里,每一步要读的段(文字为空的跳过)。 */
5
5
  export function projectSegments(project) {
6
- const picked = new Set(Object.values(project.features ?? {}).map((f) => f.pick).filter((x) => !!x));
6
+ const picked = new Set(Object.values(project.works).filter(w => !w.draft && (!w.featureId || project.features[w.featureId]?.pick === w.id)).map(w => w.id));
7
7
  const out = [];
8
8
  for (const sc of Object.values(project.scenarios)) {
9
- const fid = project.options[sc.optionId]?.featureId;
10
- const pick = fid ? project.features?.[fid]?.pick : null;
11
- // 选定方案的 id 可能是 “功能.方案” 或只有方案名:两种都认
12
- if (!(picked.has(sc.optionId) || (pick && sc.optionId === `${fid}.${pick}`)))
9
+ if (!picked.has(sc.workId))
13
10
  continue;
14
11
  sc.steps.forEach((st, i) => {
15
12
  const line = spokenLine(st, st.caption, speakerRoleAt(project, sc.id, i + 1));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@joplo-app/server",
3
- "version": "0.5.0",
4
- "description": "Joplo 本地服务:dev 看板、build 发布站、render 截图",
3
+ "version": "0.6.0",
4
+ "description": "Joplo 作品本地服务:dev 看板、build 静态发布站、render 截图,服务链接与嵌入交付",
5
5
  "license": "PolyForm-Shield-1.0.0",
6
6
  "type": "module",
7
7
  "exports": {
@@ -15,9 +15,9 @@
15
15
  "dist"
16
16
  ],
17
17
  "dependencies": {
18
- "@joplo-app/core": "0.5.0",
19
- "@joplo-app/kit": "0.5.0",
20
- "@joplo-app/web": "0.5.0",
18
+ "@joplo-app/core": "0.6.0",
19
+ "@joplo-app/kit": "0.6.0",
20
+ "@joplo-app/web": "0.6.0",
21
21
  "@tailwindcss/vite": "4.3.4",
22
22
  "mediabunny": "1.65.2",
23
23
  "tailwindcss": "4.3.4",