@joplo-app/core 0.2.17 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/actions.d.ts +6 -0
  2. package/dist/actions.js +34 -0
  3. package/dist/agent-skill.d.ts +10 -13
  4. package/dist/agent-skill.js +52 -31
  5. package/dist/auto-caption.d.ts +22 -0
  6. package/dist/auto-caption.js +166 -0
  7. package/dist/catalog.d.ts +38 -41
  8. package/dist/catalog.js +26 -317
  9. package/dist/compile.d.ts +2 -8
  10. package/dist/compile.js +302 -353
  11. package/dist/content-i18n.js +27 -16
  12. package/dist/feature-diff.d.ts +3 -3
  13. package/dist/feature-diff.js +28 -6
  14. package/dist/focus.d.ts +3 -1
  15. package/dist/focus.js +16 -34
  16. package/dist/guide.d.ts +10 -12
  17. package/dist/guide.js +419 -519
  18. package/dist/index.d.ts +4 -1
  19. package/dist/index.js +4 -1
  20. package/dist/media.d.ts +10 -0
  21. package/dist/media.js +43 -0
  22. package/dist/node.d.ts +1 -2
  23. package/dist/node.js +1 -2
  24. package/dist/outline.d.ts +1 -1
  25. package/dist/outline.js +3 -3
  26. package/dist/pace.d.ts +9 -1
  27. package/dist/pace.js +23 -3
  28. package/dist/player.d.ts +8 -41
  29. package/dist/player.js +85 -148
  30. package/dist/playground.d.ts +38 -0
  31. package/dist/playground.js +111 -0
  32. package/dist/plugin-data.d.ts +11 -0
  33. package/dist/plugin-data.js +96 -0
  34. package/dist/plugins/compiler.d.ts +66 -0
  35. package/dist/plugins/compiler.js +428 -0
  36. package/dist/plugins/data.d.ts +12 -0
  37. package/dist/plugins/data.js +120 -0
  38. package/dist/result.d.ts +1 -1
  39. package/dist/result.js +1 -0
  40. package/dist/runtime.d.ts +22 -0
  41. package/dist/runtime.js +18 -0
  42. package/dist/schema.d.ts +566 -82
  43. package/dist/schema.js +65 -53
  44. package/dist/scope.js +14 -5
  45. package/dist/step-identity.d.ts +1 -1
  46. package/dist/step-identity.js +1 -1
  47. package/dist/themes.d.ts +7 -0
  48. package/dist/themes.js +5 -0
  49. package/dist/traits.d.ts +7 -0
  50. package/dist/traits.js +26 -0
  51. package/dist/validate.js +17 -4
  52. package/dist/voice.d.ts +8 -2
  53. package/dist/voice.js +14 -2
  54. package/package.json +7 -4
  55. package/dist/diagram/elk.d.ts +0 -6
  56. package/dist/diagram/elk.js +0 -56
  57. package/dist/diagram/graph-layout.d.ts +0 -123
  58. package/dist/diagram/graph-layout.js +0 -620
  59. package/dist/diagram/index.d.ts +0 -41
  60. package/dist/diagram/index.js +0 -92
  61. package/dist/diagram/model.d.ts +0 -217
  62. package/dist/diagram/model.js +0 -189
  63. package/dist/diagram/sequence-layout.d.ts +0 -12
  64. package/dist/diagram/sequence-layout.js +0 -185
package/dist/compile.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { validActionData, pluginActionSpec } from "./actions.js";
1
2
  /**
2
3
  * 编译:作者的源文件(经 @joplo-app/kit 收集成数据)→ IR v2。组件词汇对齐 Mantine(D35),见 catalog.ts。
3
4
  *
@@ -8,13 +9,14 @@
8
9
  * - review 模式(评审版,D63):画面与场景同 dev(所有功能的所有方案),创作侧信息按 publish 的规则去掉。
9
10
  */
10
11
  import { isBind, isNode, bindPath, toCondition } from '@joplo-app/kit/node';
11
- import { BUILTIN_THEMES, COMPONENT_TYPES, DIRECTOR_LAYER, INTERACTIVE_TYPES, PAGE_LAYER, matchChoice, nodeLabel } from "./catalog.js";
12
+ import { BUILTIN_THEMES, COMPONENT_TYPES, DIRECTOR_LAYER, PAGE_LAYER, isInteractiveType, matchChoice, nodeLabel, pluginSpec, splitPluginType } from "./catalog.js";
12
13
  import { HOLD_MAX_SECONDS, HOLD_MIN_SECONDS, inShotFrame } from "./focus.js";
13
- import { choicesOf, commonPrefix } from "./player.js";
14
- import { CALLOUT_SIDES, LAYER_ICONS, Project, SCHEMA_VERSION } from "./schema.js";
14
+ import { cameraAt, choicesOf, commonPrefix, stateAt } from "./player.js";
15
+ import { Action, Effect, CALLOUT_SIDES, LAYER_ICONS, Project, SCHEMA_VERSION } from "./schema.js";
15
16
  import { schemaDiagnostics } from "./schema-issues.js";
16
17
  import { CONTENT_LOCALES, collectMessages, isContentLocale, nearestKey, pruneMessages } from "./content-i18n.js";
17
- import { DIAGRAM_GROUP_ICONS, DIAGRAM_NODE_KINDS, DIAGRAM_PINS, DIAGRAM_TONES, GRAPH_FAMILY, SEQUENCE_BLOCK_KINDS, SEQUENCE_FAMILY, attachLayouts, diagramsIn, isDiagramRoot } from "./diagram/index.js";
18
+ import { PluginCompiler } from "./plugins/compiler.js";
19
+ import { materialize, errorMessage } from "./plugins/data.js";
18
20
  const KNOWN = new Set(COMPONENT_TYPES);
19
21
  const OVERLAY = 'overlay';
20
22
  const MOCK_LABEL = { success: 'Mock success', failure: 'Mock failure', denied: 'Mock permission denied', other: 'Mock' };
@@ -37,6 +39,8 @@ export function compile(src, mode, opts = {}) {
37
39
  seenHints.add(key);
38
40
  diags.push({ severity, code, message, source: 'structure', ...(at ? { at: rel(at) } : {}) });
39
41
  };
42
+ /** flow({ from }) 接力:所有场景编译完后,按回放结果替换初始状态(见文末)。 */
43
+ const pendingFrom = new Map();
40
44
  const out = {
41
45
  schemaVersion: SCHEMA_VERSION,
42
46
  name: src.config.name,
@@ -58,6 +62,12 @@ export function compile(src, mode, opts = {}) {
58
62
  scenarios: {},
59
63
  issues: {},
60
64
  };
65
+ // ---------- 0. 插件(D86):只取清单里的组件声明,运行时代码不进 IR ----------
66
+ const host = new PluginCompiler(src.config.plugins, report, src.config.source ?? `${src.config.file}:1:1`, opts);
67
+ const plugins = host.info;
68
+ if (Object.keys(plugins).length)
69
+ out.plugins = plugins;
70
+ const nodeCtx = { plugins, host, report, rel };
61
71
  // ---------- 1. 选出参与的方案 ----------
62
72
  // 排序只在编译时决定;显式列表不依赖对象键的枚举顺序,发布模式也保留这份演示内容。
63
73
  for (const [fid, f] of Object.entries(src.features)) {
@@ -203,10 +213,13 @@ export function compile(src, mode, opts = {}) {
203
213
  }
204
214
  }
205
215
  const base = tree;
206
- const rootJ = { ...base, type: base.type === '#fragment' ? 'div' : base.type, children: [...base.children, ...overlays] };
216
+ const rootJ = { ...base, type: base.type, children: [...base.children, ...overlays] };
207
217
  const ids = new Map();
208
- const root = toSceneNode(rootJ, 'root', ids, report, rel);
209
- return { id: sceneId, optionId: ctx?.qid ?? null, route: route.path, name: `${page.title}${ctx ? ` · ${ctx.def.name}` : ''}`, viewport: page.viewport ?? 'desktop', root };
218
+ const root = toSceneNode(rootJ, 'root', ids, nodeCtx, null);
219
+ const scene = { id: sceneId, optionId: ctx?.qid ?? null, route: route.path, name: `${page.title}${ctx ? ` · ${ctx.def.name}` : ''}`, viewport: page.viewport ?? 'desktop', root };
220
+ if (!diags.some(d => d.severity === 'error'))
221
+ host.derive(scene);
222
+ return scene;
210
223
  };
211
224
  if (src.config.voice !== undefined && !voiceConfigOf(src.config.voice, true))
212
225
  err('VOICE_CONFIG_INVALID', `config({ voice }) must be { profile?: string, narrator?: string, roles?: { [roleKey]: string }, locales?: { [locale]: { narrator?: string, roles?: { [roleKey]: string } } } } with non-empty strings; got ${JSON.stringify(src.config.voice)}`, src.config.source ?? `${src.config.file}:1:1`);
@@ -218,7 +231,7 @@ export function compile(src, mode, opts = {}) {
218
231
  // 主题(D51):config.theme 必须是内置主题或 themes/<name>.css
219
232
  {
220
233
  const t = src.config.theme ?? 'sketch';
221
- const authorThemes = Object.keys(src.themes ?? {});
234
+ const authorThemes = [...Object.keys(out.themes), ...Object.keys(host.themes)];
222
235
  if (!BUILTIN_THEMES.includes(t) && !authorThemes.includes(t))
223
236
  err('THEME_UNKNOWN', `config({ theme: '${t}' }) is not a built-in theme (${BUILTIN_THEMES.join(', ')}), and the project has no themes/${t}.css${authorThemes.length ? ` (author themes: ${authorThemes.join(', ')})` : ''}`, src.config.source ?? `${src.config.file}:1:1`);
224
237
  }
@@ -275,11 +288,13 @@ export function compile(src, mode, opts = {}) {
275
288
  err('LAYER_UNKNOWN', `Layer "${ld.title}" has no content: layer(title, <Page />)`, at);
276
289
  continue;
277
290
  }
278
- const rootJ = nodes.length === 1 ? nodes[0] : { ...nodes[0], type: 'div', props: {}, children: nodes };
291
+ const rootJ = nodes.length === 1 ? nodes[0] : { ...nodes[0], type: '#fragment', props: {}, children: nodes };
279
292
  const ids = new Map();
280
- const root = toSceneNode(rootJ, `layer_${lk}`, ids, report, rel);
293
+ const root = toSceneNode(rootJ, `layer_${lk}`, ids, nodeCtx, null);
281
294
  const sceneId = `${qid}~${lk}`;
282
295
  const scene = { id: sceneId, optionId: qid, route: layerRoute, name: `${ld.title} · ${def.name}`, viewport: ld.viewport ?? 'desktop', root, layer: lk };
296
+ if (!diags.some(d => d.severity === 'error'))
297
+ host.derive(scene);
283
298
  addScene(scene);
284
299
  layerScenes.push({ key: lk, scene });
285
300
  if (ld.role !== undefined && !roleKeys.has(ld.role))
@@ -294,97 +309,36 @@ export function compile(src, mode, opts = {}) {
294
309
  /** 元素在哪些层级里(多层都有同名 id 时都算)。 */
295
310
  const layersWith = (id) => layerScenes.filter((l) => findIn(l.scene.root, id)).map((l) => l.key);
296
311
  const layerSceneWith = (id) => layerScenes.find((l) => findIn(l.scene.root, id))?.scene;
297
- // ---------- 调用链(D48):trace 在这个方案能看到的 Diagram 里解析 ----------
298
- const diagrams = [...layerScenes.map((l) => l.scene), ...[...sceneFor.values()].filter((x) => x.optionId === qid || x.optionId === null || x.optionId === undefined)].flatMap((x) => diagramsIn(x.root));
299
- const resolveTrace = (ids, tmode, at) => {
300
- const shown = `trace(${ids.map((x) => JSON.stringify(x)).join(', ')})`;
301
- if (!ids.length) {
302
- err('TRACE_UNKNOWN', `${shown} requires at least one node or edge id`, at);
303
- return null;
304
- }
305
- const has = (d, t) => d.nodes.has(t) || d.edges.some((e) => e.id === t);
306
- const d = diagrams.find((x) => ids.every((t) => has(x, t)));
307
- if (!d) {
308
- const missing = ids.find((t) => !diagrams.some((x) => has(x, t)));
309
- err('TRACE_UNKNOWN', missing ? `${shown} contains "${missing}", which is not a node, group, edge, state, transition, actor or message id in any Diagram / StateMachine / Sequence` : `${shown} mixes elements from different diagrams; trace one diagram at a time`, at);
310
- return null;
311
- }
312
- const nodes = [];
313
- const edges = [];
314
- const addNode = (n) => {
315
- if (!nodes.includes(n))
316
- nodes.push(n);
317
- };
318
- /** 节点(或分组)自己是分组时连同它算进去,再加上它的各级父分组。 */
319
- const groupsOfNode = (n) => [...(d.groupIds.has(n) ? [n] : []), ...(d.groupsOf.get(n) ?? [])];
320
- const finishTrace = () => {
321
- if (tmode === 'skip')
322
- return { mode: tmode, nodes, edges, ...(d.type === 'Sequence' ? { targets: [] } : {}) };
323
- const all = [...new Set(nodes.flatMap(groupsOfNode))];
324
- const last = nodes[nodes.length - 1];
325
- // 失败只标红终点所在的最内层分组(终点本身是分组时就是它);外层分组照常 active,不把整个云账号都标红
326
- const errorGroups = tmode === 'fail' && last ? groupsOfNode(last).slice(0, 1) : [];
327
- return {
328
- mode: tmode,
329
- nodes,
330
- edges,
331
- ...(all.some((g) => !errorGroups.includes(g)) ? { groups: all.filter((g) => !errorGroups.includes(g)) } : {}),
332
- ...(errorGroups.length ? { errorGroups } : {}),
333
- // 时序图的镜头对准消息所在的行(参与者头部在最上面,对准它们会把镜头拉离正在讲的那一行)
334
- ...(d.type === 'Sequence' ? { targets: edges.map((e) => e.id) } : {}),
335
- };
336
- };
337
- // trace.skip 标记“这次没被调用”的一组元素,不是路径:节点和连线各自 dim,不要求彼此相连
338
- if (tmode === 'skip') {
339
- for (const t of ids) {
340
- if (d.nodes.has(t))
341
- addNode(t);
342
- else
343
- edges.push({ id: t, reverse: false });
344
- }
345
- return finishTrace();
346
- }
347
- const kind = d.type === 'Sequence' ? 'Sequence.Message' : d.type === 'StateMachine' ? 'StateMachine.Transition' : 'Diagram.Edge';
348
- let prev = null;
349
- for (const t of ids) {
350
- const edge = d.edges.find((e) => e.id === t);
351
- if (edge) {
352
- // 写连线 id:方向由上一个节点决定(从 to 端接上时逆向走);时序图的消息各自独立,连续写几条消息 id 不要求首尾相接
353
- const reverse = prev !== null && prev === edge.to && prev !== edge.from;
354
- if (d.type !== 'Sequence' && prev !== null && prev !== edge.from && prev !== edge.to) {
355
- err('TRACE_UNKNOWN', `${shown}: edge "${t}"(${edge.from} → ${edge.to}) is not connected to the previous node "${prev}"`, at);
356
- return null;
357
- }
358
- edges.push({ id: edge.id, reverse });
359
- addNode(reverse ? edge.to : edge.from);
360
- addNode(reverse ? edge.from : edge.to);
361
- prev = reverse ? edge.from : edge.to;
362
- continue;
363
- }
364
- if (prev !== null && prev !== t) {
365
- // 一段:先找同向的连线,没有再找反向的;同一方向有多条时要写连线 id
366
- const fwd = d.edges.filter((e) => e.from === prev && e.to === t);
367
- const back = d.edges.filter((e) => e.from === t && e.to === prev);
368
- const pick = fwd.length ? fwd : back;
369
- if (pick.length > 1) {
370
- err('TRACE_AMBIGUOUS', `${shown}: "${prev}" and "${t}" have ${pick.length} ${d.type === 'Sequence' ? 'messages' : 'edges'} (${pick.map((e) => e.id).join(', ')}), use an id instead, for example trace('${pick[0].id}')`, at);
371
- return null;
372
- }
373
- if (!pick.length) {
374
- err('TRACE_UNKNOWN', `${shown}: "${prev}" and "${t}" have no connecting ${kind} (each segment needs one in the same diagram; either direction is allowed)`, at);
375
- return null;
376
- }
377
- edges.push({ id: pick[0].id, reverse: !fwd.length });
378
- }
379
- addNode(t);
380
- prev = t;
381
- }
382
- return finishTrace();
383
- };
312
+ const effectRoots = [...layerScenes.map(l => l.scene), ...[...sceneFor.values()].filter(x => x.optionId === qid || x.optionId == null)];
384
313
  const scenarioIds = {};
385
- for (const [skey, fl] of Object.entries(def.scenarios ?? {})) {
314
+ // flow({ from }) 接力:按依赖顺序编译,被接的场景先编译,记下它结尾的路径与导演层;
315
+ // 接力场景的逐步校验(页面里找目标、焦点提示、镜头、自动字幕)都从那里开始,而不是默认起点
316
+ const scenarioDefs = def.scenarios ?? {};
317
+ const orderedKeys = [];
318
+ {
319
+ const placed = new Set();
320
+ const place = (k, seen) => {
321
+ if (placed.has(k) || seen.has(k))
322
+ return;
323
+ seen.add(k);
324
+ const dep = scenarioDefs[k]?.opts.from;
325
+ if (dep !== undefined && dep !== k && Object.hasOwn(scenarioDefs, dep))
326
+ place(dep, seen);
327
+ placed.add(k);
328
+ orderedKeys.push(k);
329
+ };
330
+ for (const k of Object.keys(scenarioDefs))
331
+ place(k, new Set());
332
+ }
333
+ /** 每个场景编译完之后的结尾:路径(按 go / back 推算)与导演层。 */
334
+ const scenarioEnd = new Map();
335
+ for (const skey of orderedKeys) {
336
+ const fl = scenarioDefs[skey];
386
337
  const sid = `${qid}.${skey}`;
387
- const start = fl.opts.start ?? touched[0] ?? src.config.home ?? [...ctxRoutes][0];
338
+ const fromEnd = fl.opts.from !== undefined && fl.opts.from !== skey ? scenarioEnd.get(fl.opts.from) : undefined;
339
+ if (fl.opts.from !== undefined && fl.opts.start !== undefined)
340
+ err('FROM_WITH_START', `flow({ from: ${JSON.stringify(fl.opts.from)}, start: ${JSON.stringify(fl.opts.start)} }): a scenario that continues another starts where that one ended; remove start (or remove from to start fresh)`, fl.source);
341
+ const start = fromEnd?.route ?? fl.opts.start ?? touched[0] ?? src.config.home ?? [...ctxRoutes][0];
388
342
  if (!start || !ctxRoutes.has(start)) {
389
343
  err('UNKNOWN_ROUTE', `Scenario ${sid} starts at unknown route ${start ?? '(none)'}`, fl.source);
390
344
  continue;
@@ -397,7 +351,19 @@ export function compile(src, mode, opts = {}) {
397
351
  }
398
352
  // 镜头状态(与 player.cameraAt 同一规则,逐步累积):判断焦点提示的目标在不在当前镜头里(D70)
399
353
  const frame = new Map();
400
- let director = hasLayers ? Object.keys(layers)[0] : PAGE_LAYER;
354
+ let director = fromEnd?.director ?? (hasLayers ? Object.keys(layers)[0] : PAGE_LAYER);
355
+ if (fl.opts.layer !== undefined) {
356
+ if (!hasLayers || !Object.hasOwn(layers, fl.opts.layer))
357
+ err('LAYER_UNKNOWN', `flow({ layer: ${JSON.stringify(fl.opts.layer)} }) is not a layer of option ${qid}${hasLayers ? ` (layers: ${Object.keys(layers).join(', ')})` : '; this option declares no layers'}`, fl.source);
358
+ else
359
+ director = fl.opts.layer;
360
+ }
361
+ if (fl.opts.from !== undefined) {
362
+ if (!Object.hasOwn(def.scenarios ?? {}, fl.opts.from) || fl.opts.from === skey)
363
+ err('FROM_UNKNOWN', `flow({ from: ${JSON.stringify(fl.opts.from)} }) must name another scenario key of option ${qid} (available: ${Object.keys(def.scenarios ?? {}).filter((k) => k !== skey).join(', ') || 'none'})`, fl.source);
364
+ else
365
+ pendingFrom.set(sid, { from: `${qid}.${fl.opts.from}`, state: fl.opts.state, layer: fl.opts.layer, at: fl.source });
366
+ }
401
367
  const stepKeys = new Set();
402
368
  const steps = fl.steps.map((st, i) => {
403
369
  if (st.key !== undefined) {
@@ -412,11 +378,14 @@ export function compile(src, mode, opts = {}) {
412
378
  const explains = [];
413
379
  const says = [];
414
380
  const narrates = [];
415
- const traces = [];
381
+ const ext = {};
382
+ const references = [];
383
+ const pluginFocus = [];
384
+ const directorTargets = [];
416
385
  const forks = [];
417
386
  const marks = [];
418
- /** 每个 trace 效果解析出的节点(作为镜头目标,与 shot 合并)。 */
419
- const traceTargets = new Map();
387
+ /** 每个插件效果贡献的节点(作为镜头目标,与 shot 合并)。 */
388
+ const pluginTargets = new Map();
420
389
  for (const e of st.effects) {
421
390
  if (e.type === 'go') {
422
391
  if (!ctxRoutes.has(e.route))
@@ -454,21 +423,34 @@ export function compile(src, mode, opts = {}) {
454
423
  if (e.text.trim())
455
424
  explains.push(e.text.trim());
456
425
  }
457
- else if (e.type === 'trace') {
458
- const t = resolveTrace(e.ids, e.mode, st.source);
459
- if (t) {
460
- traces.push(t);
461
- // trace 相当于一个 shot(trace.skip 只标记没被调用,不移动镜头)
462
- if (t.mode !== 'skip')
463
- traceTargets.set(e, t.targets ?? t.nodes);
426
+ else if (e.type === 'plugin') {
427
+ const lowered = host.effect(e, effectRoots.filter(scene => scene.layer || scene.id === sceneOf(stepRouteBefore(fl.steps, i + 1, start))), ext[e.plugin], st.source);
428
+ if (lowered) {
429
+ effects.push(...(lowered.writes ?? []).map(w => ({ type: 'set', path: w.path, value: w.value })));
430
+ if (lowered.directorTarget)
431
+ directorTargets.push(lowered.directorTarget);
432
+ if (lowered.media?.length) {
433
+ const key = `${sid}#${i + 1}`;
434
+ host.mediaCommands.set(key, [...(host.mediaCommands.get(key) ?? []), ...lowered.media]);
435
+ }
436
+ if (lowered.data !== undefined)
437
+ ext[e.plugin] = lowered.data;
438
+ if (lowered.targets?.length) {
439
+ pluginTargets.set(e, lowered.targets);
440
+ pluginFocus.push(...lowered.targets);
441
+ }
442
+ references.push(...lowered.references ?? []);
464
443
  }
465
444
  }
466
- else
445
+ else if (e.type === 'complete')
467
446
  effects.push({ type: 'complete', text: e.text, outcome: e.outcome });
447
+ else
448
+ err('EFFECT_INVALID', 'Unknown step effect; use a documented effect helper instead of constructing effect objects', st.source);
468
449
  }
469
450
  const sceneBefore = sceneFor.get(sceneOf(stepRouteBefore(fl.steps, i, start)));
470
451
  const sceneAfter = sceneFor.get(sceneOf(stepRouteBefore(fl.steps, i + 1, start)));
471
452
  const actionTarget = 'target' in st.action ? st.action.target : null;
453
+ validateNewAction(st.action, hasLayers ? layerScenes.map(l => l.scene) : sceneBefore ? [sceneBefore] : [], out, (code, message) => err(code, message, st.source));
472
454
  for (const e of st.effects) {
473
455
  if (e.type === 'fork') {
474
456
  if (!Object.hasOwn(def.scenarios, e.scenario) || e.scenario === skey)
@@ -539,10 +521,10 @@ export function compile(src, mode, opts = {}) {
539
521
  const perLayer = new Map();
540
522
  let directorLayer = null;
541
523
  for (const e of st.effects) {
542
- if (e.type !== 'shot' && !traceTargets.has(e))
524
+ if (e.type !== 'shot' && !pluginTargets.has(e))
543
525
  continue;
544
- const fromTrace = e.type !== 'shot';
545
- const targets = e.type === 'shot' ? e.targets : traceTargets.get(e);
526
+ const fromPlugin = e.type !== 'shot';
527
+ const targets = e.type === 'shot' ? e.targets : pluginTargets.get(e);
546
528
  if (targets.length === 0) {
547
529
  // shot():导演所在层回到整体(不推近)
548
530
  const lk = hasLayers ? DIRECTOR_LAYER : PAGE_LAYER;
@@ -552,8 +534,8 @@ export function compile(src, mode, opts = {}) {
552
534
  for (const id of targets) {
553
535
  const where = hasLayers ? layersWith(id) : [sceneAfter, sceneBefore].some((sc) => sc && findIn(sc.root, id)) ? [PAGE_LAYER] : [];
554
536
  if (!where.length) {
555
- if (fromTrace)
556
- continue; // trace 的节点已在 Diagram 里校验过;不在这一步的画面里时不移动镜头
537
+ if (fromPlugin)
538
+ continue; // 插件目标已经校验过;不在这一步的画面里时不移动镜头
557
539
  err('SHOT_UNKNOWN', hasLayers ? `shot("${id}") references an element absent from all layers (layers: ${Object.keys(layers).join(', ')})` : `shot("${id}") references an element absent from this step's stage (${sceneAfter?.route ?? sceneBefore?.route ?? '?'})`, st.source);
558
540
  continue;
559
541
  }
@@ -566,6 +548,9 @@ export function compile(src, mode, opts = {}) {
566
548
  }
567
549
  }
568
550
  }
551
+ // 插件的导演目标只选择层,不自动加入聚焦框或推进视角。
552
+ if (hasLayers && !directorLayer && directorTargets.length)
553
+ directorLayer = layersWith(directorTargets[0])[0] ?? null;
569
554
  // 没写 shot、写了焦点提示(D70):导演切到第一个提示目标所在的层(提示要被看见)
570
555
  if (hasLayers && !directorLayer && focusTargets.length)
571
556
  directorLayer = layersWith(focusTargets[0])[0] ?? null;
@@ -599,7 +584,7 @@ export function compile(src, mode, opts = {}) {
599
584
  director = directorLayer;
600
585
  for (const s of shots)
601
586
  frame.set(s.layer === DIRECTOR_LAYER ? director : s.layer, [...s.targets]);
602
- const generated = st.caption === undefined ? autoCaption(st, (hasLayers && actionTarget ? layerSceneWith(actionTarget) : undefined) ?? sceneBefore) : null;
587
+ const generated = st.caption === undefined ? autoCaption(st, (hasLayers && actionTarget ? layerSceneWith(actionTarget) : undefined) ?? sceneBefore, out) : null;
603
588
  return {
604
589
  id: `${sid}#${i + 1}`,
605
590
  ...(st.key !== undefined ? { key: st.key } : {}),
@@ -612,7 +597,9 @@ export function compile(src, mode, opts = {}) {
612
597
  shots,
613
598
  directorLayer,
614
599
  ...(explains.length ? { explain: explains.join('\n') } : {}),
615
- traces,
600
+ ...(Object.keys(ext).length ? { ext } : {}),
601
+ ...(references.length ? { references: [...new Set(references)] } : {}),
602
+ ...(pluginFocus.length ? { focusTargets: [...new Set(pluginFocus)] } : {}),
616
603
  forks,
617
604
  marks,
618
605
  ...(cues.length ? { cues } : {}),
@@ -631,18 +618,33 @@ export function compile(src, mode, opts = {}) {
631
618
  const outcome = fl.opts.outcome ?? fromDone ?? 'success';
632
619
  const state = mergeState(def.state, fl.opts.state);
633
620
  const sc = {
621
+ ...(fl.opts.actionEntry !== undefined ? { actionEntry: fl.opts.actionEntry } : {}),
634
622
  id: sid,
635
623
  optionId: qid,
636
624
  name: fl.name,
625
+ ...(fl.opts.autoplay !== undefined ? { autoplay: fl.opts.autoplay } : {}),
637
626
  description: fl.opts.description ?? '',
638
627
  caseIds: strip ? [] : (fl.opts.cases ?? []).filter((c) => fdef.cases?.[c]).map((c) => `${fid}.${c}`),
639
628
  mock: { label: fl.opts.mock ?? MOCK_LABEL[outcome], outcome, ...(fl.opts.mock === undefined ? { auto: true } : {}) },
640
- initial: { sceneId: sceneOf(start), ui: state.ui, data: state.data, inputs: state.inputs },
629
+ initial: { sceneId: sceneOf(start), ui: state.ui, data: state.data, inputs: state.inputs, ...(hasLayers && fl.opts.layer !== undefined && Object.hasOwn(layers, fl.opts.layer) ? { layer: fl.opts.layer } : {}) },
641
630
  steps,
642
631
  expected: fl.opts.expected ?? '',
643
632
  ...(fl.source ? { source: rel(fl.source) } : {}),
644
633
  };
645
634
  out.scenarios[sid] = sc;
635
+ scenarioEnd.set(skey, { route: stepRouteBefore(fl.steps, fl.steps.length, start), director });
636
+ }
637
+ // 按依赖顺序编译后,恢复作者声明的顺序(发布站按它当章节播放,情况里的场景列表也按它排)
638
+ {
639
+ const declared = Object.keys(scenarioDefs).map((k) => `${qid}.${k}`);
640
+ for (const id of declared)
641
+ if (Object.hasOwn(out.scenarios, id)) {
642
+ const v = out.scenarios[id];
643
+ delete out.scenarios[id];
644
+ out.scenarios[id] = v;
645
+ }
646
+ for (const list of Object.values(scenarioIds))
647
+ list.sort((a, b) => declared.indexOf(a) - declared.indexOf(b));
646
648
  }
647
649
  // 所有场景完成后再解析分叉(允许向后声明的场景),不把创作信息参与前缀比较。
648
650
  for (const sc of Object.values(out.scenarios)) {
@@ -671,7 +673,40 @@ export function compile(src, mode, opts = {}) {
671
673
  if (!fdef.cases?.[ck])
672
674
  err('UNKNOWN_CASE', `Option ${qid} coverage declares unknown case "${ck}"`, def.source);
673
675
  }
676
+ const free = {};
677
+ for (const [key, reaction] of Object.entries(def.free ?? {})) {
678
+ const a = Action.safeParse(reaction.action);
679
+ if (!a.success || !('target' in reaction.action)) {
680
+ err('FREE_ACTION_INVALID', `Free reaction ${key} needs a targeted action`, reaction.source);
681
+ continue;
682
+ }
683
+ const roots = effectRoots.filter(scene => scene.optionId === qid || mode === 'publish' && scene.optionId === null);
684
+ const target = reaction.action.target;
685
+ if (!roots.some(scene => findIn(scene.root, target)))
686
+ err('FREE_TARGET_MISSING', `Free reaction ${key}: target ${reaction.action.target} is not in option ${qid}`, reaction.source);
687
+ const targets = roots.map(scene => findIn(scene.root, target)).filter((n) => !!n);
688
+ if (reaction.action.type === 'click' && targets.length && !targets.some(n => isInteractiveType(n.type, out.plugins)))
689
+ err('FREE_ACTION_INVALID', `Free reaction ${key}: ${target} is not interactive`, reaction.source);
690
+ if (['type', 'toggle', 'select'].includes(reaction.action.type) && targets.length && !targets.some(n => n.traits?.input))
691
+ err('FREE_ACTION_INVALID', `Free reaction ${key}: ${target} cannot accept values`, reaction.source);
692
+ validateNewAction(reaction.action, roots, out, (code, message) => err(code, message, reaction.source));
693
+ const effects = [];
694
+ for (const effect of reaction.effects) {
695
+ if (!['set', 'append', 'toast'].includes(effect.type)) {
696
+ err('FREE_EFFECT_INVALID', `Free reaction ${key}: ${effect.type} is not local state. Use set, append or toast; navigation, completion and timeline animation belong in steps`, reaction.source);
697
+ continue;
698
+ }
699
+ const { kind: _kind, ...raw } = effect;
700
+ const parsed = Effect.safeParse(raw);
701
+ if (!parsed.success || 'path' in raw && (!/^(ui|data|inputs)\.[A-Za-z0-9_.-]+$/.test(String(raw.path)) || String(raw.path).split('.').some(k => ['__proto__', 'constructor', 'prototype'].includes(k))))
702
+ err('FREE_EFFECT_INVALID', `Free reaction ${key}: invalid local effect`, reaction.source);
703
+ else
704
+ effects.push(parsed.data);
705
+ }
706
+ free[key] = { action: a.data, effects, ...(reaction.source ? { source: rel(reaction.source) } : {}) };
707
+ }
674
708
  out.options[qid] = {
709
+ ...(Object.keys(free).length ? { free } : {}),
675
710
  id: qid,
676
711
  featureId: fid,
677
712
  key: o.key,
@@ -695,17 +730,53 @@ export function compile(src, mode, opts = {}) {
695
730
  err('UNKNOWN_CASE', `Rule "${r.text}" links unknown case ${c}`, r.source);
696
731
  }
697
732
  }
698
- // ---------- 7. 图表布局(D69):每张图在编译期布局一次,写进 IR;同一结构只算一次(引擎自带缓存) ----------
699
- if (!diags.some((d) => d.severity === 'error')) {
700
- const failed = new Set();
701
- for (const sc of Object.values(out.scenes))
702
- attachLayouts(sc.root, opts.layout, (n, m) => {
703
- if (failed.has(`${n.source}|${n.id}`))
704
- return;
705
- failed.add(`${n.source}|${n.id}`);
706
- warn('DIAGRAM_LAYOUT_FAILED', `<${n.type}> "${n.id}" could not be laid out (${m}); showing a simple grid instead. Check the edges and groups of this diagram`, n.source, { kind: 'element', id: n.id });
707
- }, sc.viewport);
733
+ // flow({ from }) 接力:初始状态 = 被接的场景最后一步之后的状态(路径、ui / data / inputs、导演层),再叠上本场景写的 state。
734
+ // 链式接力按依赖顺序解析;成环或被接的场景回放失败时报错。
735
+ if (pendingFrom.size) {
736
+ const done = new Set();
737
+ const visiting = new Set();
738
+ const resolve = (sid) => {
739
+ const p = pendingFrom.get(sid);
740
+ if (!p || done.has(sid))
741
+ return true;
742
+ if (visiting.has(sid)) {
743
+ err('FROM_CYCLE', `Scenario ${sid} continues from itself through flow({ from }); break the cycle`, p.at);
744
+ return false;
745
+ }
746
+ visiting.add(sid);
747
+ const ok = resolve(p.from);
748
+ visiting.delete(sid);
749
+ if (!ok)
750
+ return false;
751
+ const target = out.scenarios[sid];
752
+ const prev = out.scenarios[p.from];
753
+ if (!target || !prev)
754
+ return false;
755
+ try {
756
+ const end = stateAt(out, p.from, prev.steps.length);
757
+ const hasLayers = Object.keys(out.options[target.optionId]?.layers ?? {}).length > 0;
758
+ const layer = p.layer ?? (hasLayers ? cameraAt(out, p.from, prev.steps.length).directorLayer : undefined);
759
+ const merged = mergeState({ ui: end.ui, data: end.data, inputs: end.inputs }, p.state);
760
+ target.initial = { sceneId: end.sceneId, ui: merged.ui, data: merged.data, inputs: merged.inputs, ...(layer ? { layer } : {}) };
761
+ target.from = p.from;
762
+ }
763
+ catch (e) {
764
+ err('FROM_FAILED', `Scenario ${sid} continues from ${p.from}, which does not replay: ${e.message}`, p.at);
765
+ return false;
766
+ }
767
+ done.add(sid);
768
+ return true;
769
+ };
770
+ for (const sid of pendingFrom.keys())
771
+ resolve(sid);
772
+ if (diags.some((d) => d.severity === 'error'))
773
+ return { project: null, diagnostics: diags };
708
774
  }
775
+ // 逐步派生数据只在编译期计算,播放器读取快照。
776
+ if (!diags.some(d => d.severity === 'error'))
777
+ host.frames(out);
778
+ if (diags.some(d => d.severity === 'error'))
779
+ return { project: null, diagnostics: diags };
709
780
  // ---------- 8. 发布视图与评审版:去掉设计备注与源位置 ----------
710
781
  if (strip) {
711
782
  for (const s of Object.values(out.scenes))
@@ -720,11 +791,22 @@ export function compile(src, mode, opts = {}) {
720
791
  diags.push(...schemaDiagnostics(out, parsed.error.issues, { limit: 20, rel }));
721
792
  return { project: null, diagnostics: diags };
722
793
  }
723
- const project = pruneMessages(parsed.data);
794
+ let project = pruneMessages(parsed.data);
724
795
  if (mode === 'dev' && project.i18n) {
725
796
  const stale = localeDiagnostics(project, src, diags);
726
797
  project.i18n = { ...project.i18n, stale };
727
798
  }
799
+ // A slot can fit on its own but exceed the public reader's limit once wrapped in
800
+ // scenes/scenarios/steps/ext. Validate that final depth before reporting success.
801
+ if (mode === 'publish') {
802
+ try {
803
+ project = materialize(project);
804
+ }
805
+ catch (e) {
806
+ err('PLUGIN_DATA_INVALID', `Published IR is not readable JSON data: ${errorMessage(e)}`, src.config.source ?? `${src.config.file}:1:1`);
807
+ return { project: null, diagnostics: diags };
808
+ }
809
+ }
728
810
  return { project, diagnostics: diags };
729
811
  }
730
812
  /** config.locales(D84):非空、不重复、都是支持的语言;第一个是默认语言。没写时为 null。 */
@@ -855,36 +937,34 @@ function expandSlots(n, fill, outlet) {
855
937
  function tagFrom(n, from) {
856
938
  return { ...n, props: { ...n.props, __from: from } };
857
939
  }
858
- /** JNode → IR 节点:展开 Fragment、文本变 #text、分离 Joplo 属性、生成非交互元素的 ID、检查 ID 唯一。 */
859
- function toSceneNode(n, fallbackId, ids, err, rel) {
860
- if (n.type === 'Menu')
861
- n = menuWithOpened(n);
862
- const children = flatten(n.children).map((c, i) => isNode(c) ? toSceneNode(c, `${fallbackId}_${i}`, ids, err, rel) : textNode(c, `${fallbackId}_${i}`));
940
+ function toSceneNode(n, fallbackId, ids, nc, parentType) {
941
+ const { report: err, rel } = nc;
942
+ n = { ...n, props: n.props ?? {}, children: n.children ?? [] };
943
+ n = { ...n, type: nc.host.intrinsic.get(n.type) ?? n.type };
944
+ n = inheritProps(n, nc.host.inherits.get(n.type) ?? []);
945
+ const children = flatten(n.children).map((c, i) => isNode(c) ? toSceneNode(c, `${fallbackId}_${i}`, ids, nc, n.type) : textNode(c, `${fallbackId}_${i}`));
946
+ n = nc.host.node(n, ids);
863
947
  const { id: rawId, when, disabled, disabledReason, unmodeled, note, redact, __from, ...rest } = n.props;
864
948
  const at = n.source;
865
- if (!KNOWN.has(n.type))
866
- err('UNKNOWN_COMPONENT', `Component <${n.type}> is not in the catalog (use Mantine component names; run joplo skill components to list them; use <Custom kind="…"> as a placeholder for missing components)`, at);
867
- const interactive = INTERACTIVE_TYPES.has(n.type);
949
+ const plug = splitPluginType(n.type);
950
+ if (plug) {
951
+ const spec = pluginSpec(nc.plugins, n.type);
952
+ if (!nc.plugins[plug.plugin])
953
+ err('UNKNOWN_PLUGIN', `<${n.type}> comes from plugin ${plug.plugin}, which is not enabled: ${n.packageName ? `install ${n.packageName}; import plugin from ${JSON.stringify(n.packageName)}; ` : `install its author package; `}add plugin to config({ plugins: [plugin] }) in joplo.config.ts (npx joplo skill plugins)`, at);
954
+ else if (!spec)
955
+ err('UNKNOWN_COMPONENT', `Plugin ${plug.plugin} has no component ${plug.name} (available: ${Object.keys(nc.plugins[plug.plugin].components).join(', ')}; npx joplo skill ${plug.plugin})`, at);
956
+ else if (spec.parent && parentType !== `${plug.plugin}:${spec.parent}`)
957
+ err('PLUGIN_PARENT', `<${n.type}> must be written directly inside <${plug.plugin}:${spec.parent}> (npx joplo skill ${plug.plugin})`, at);
958
+ }
959
+ else if (!KNOWN.has(n.type))
960
+ err('UNKNOWN_COMPONENT', `No enabled plugin declares <${n.type}>. Install a plugin that provides this element and list it in config.plugins; run joplo skill to discover the installed plugin guides`, at);
961
+ const interactive = isInteractiveType(n.type, nc.plugins);
868
962
  if (interactive && typeof rawId !== 'string')
869
963
  err('MISSING_ID', `Interactive component <${n.type}> "${labelOf(n)}" requires an id for steps and selection`, at);
870
- const needsId = n.type === 'Diagram.Node' ? 'Diagram node <Diagram.Node>' : n.type === 'StateMachine.State' ? 'State <StateMachine.State>' : n.type === 'Sequence.Actor' ? 'Participant <Sequence.Actor>' : null;
871
- if (needsId && typeof rawId !== 'string')
872
- err('MISSING_ID', `${needsId} "${labelOf(n)}" requires an id for edge from / to and trace`, at);
873
- if (isDiagramRoot(n.type))
874
- checkDiagramRoot(n, err);
875
- if (n.type === 'Image')
876
- checkImage(n, err);
877
- // 连线没写 id 时用「from->to」:⌥+单击检查与 rules 的 elements 都能引用它。
878
- // 状态机的转换与时序图的消息常有同一对端点的多条(请求、重试、回复),重复的依次加「~2」「~3」。
879
- const linkLike = n.type === 'Diagram.Edge' || n.type === 'StateMachine.Transition' || n.type === 'Sequence.Message';
880
- let edgeId = linkLike && typeof rest.from === 'string' && typeof rest.to === 'string' ? `${rest.from}->${rest.to}` : null;
881
- if (edgeId && n.type !== 'Diagram.Edge' && ids.has(edgeId)) {
882
- let k = 2;
883
- while (ids.has(`${edgeId}~${k}`))
884
- k++;
885
- edgeId = `${edgeId}~${k}`;
886
- }
887
- const id = typeof rawId === 'string' ? rawId : (edgeId ?? `_${fallbackId}`);
964
+ const spec = pluginSpec(nc.plugins, n.type);
965
+ if (spec?.needsId && typeof rawId !== 'string' && !interactive)
966
+ err('MISSING_ID', `<${n.type}> "${labelOf(n)}" requires an id`, at);
967
+ const id = typeof rawId === 'string' ? rawId : `_${fallbackId}`;
888
968
  if (ids.has(id))
889
969
  err('DUPLICATE_ID', `Duplicate id "${id}" in the same stage (other location: ${rel(ids.get(id)) ?? 'unknown'})`, at);
890
970
  ids.set(id, at);
@@ -903,6 +983,11 @@ function toSceneNode(n, fallbackId, ids, err, rel) {
903
983
  props[k] = toPropValue(v);
904
984
  }
905
985
  const node = { id, type: n.type };
986
+ if (spec?.traits) {
987
+ const { text: _text, textPaths: _paths, ...runtime } = spec.traits;
988
+ if (Object.keys(runtime).length)
989
+ node.traits = runtime;
990
+ }
906
991
  if (Object.keys(props).length)
907
992
  node.props = props;
908
993
  if (children.length)
@@ -936,202 +1021,26 @@ function toSceneNode(n, fallbackId, ids, err, rel) {
936
1021
  node.source = s;
937
1022
  return node;
938
1023
  }
939
- /**
940
- * <Image>:只画内嵌的图片(asset() 生成的 data:image/… URI),本地看板、build、share 都带着它,不依赖外网。
941
- * 网址或文件路径不会去加载:画成占位,并提示用 asset() 内嵌;状态绑定在运行时取值,不在这里判断。
942
- */
943
- const IMAGE_FITS = ['cover', 'contain'];
944
- function checkImage(n, err) {
945
- const { src, fit } = n.props;
946
- if (typeof src === 'string' && src && !src.startsWith('data:image/'))
947
- err('IMAGE_PLACEHOLDER', `<Image src="${src.length > 60 ? `${src.slice(0, 57)}...` : src}"> is drawn as a placeholder: only embedded images are shown. Put the file in the project and write src={asset('./photo.jpg')} (path relative to this file; import asset from @joplo-app/kit)`, n.source, 'warning');
948
- if (fit !== undefined && !(typeof fit === 'string' && IMAGE_FITS.includes(fit)))
949
- err('INVALID_IMAGE_FIT', `<Image> fit="${String(fit)}" is not supported (available: ${IMAGE_FITS.join(', ')})`, n.source);
950
- }
951
- /**
952
- * Menu(D68):opened 写在 Menu 上(与 Mantine 一致),可见性由 Menu.Dropdown 门控(GATED_CONTAINERS)。
953
- * 把 Menu 的 opened 抄到它自己的 Menu.Dropdown 上(不进嵌套的另一个 Menu;Dropdown 自己写了 opened 时不覆盖)。
954
- * Menu 没写 opened 时下拉保持关闭。
955
- */
956
- function menuWithOpened(menu) {
957
- const opened = menu.props.opened;
958
- if (opened === undefined)
959
- return menu;
960
- const visit = (c) => {
961
- if (Array.isArray(c))
962
- return c.map(visit);
963
- if (!isNode(c) || c.type === 'Menu')
964
- return c;
965
- if (c.type === 'Menu.Dropdown')
966
- return c.props.opened === undefined ? { ...c, props: { ...c.props, opened } } : c;
967
- return { ...c, children: c.children.map(visit) };
968
- };
969
- return { ...menu, children: menu.children.map(visit) };
970
- }
971
- /**
972
- * 关系类图表的校验(D69):在作者元素上报错,带源位置。
973
- * - Diagram / StateMachine:连线两端必须是同一张图里的节点或(有 id 的)分组;group="…" 必须引用存在的分组、与嵌套不矛盾、不成环;
974
- * 连线不能连到包含它端点的分组;icon / tone / pin 取预设值。节点多却没有分组时给一条 info(D69:按业务域分组)。
975
- * - Sequence:消息两端必须是参与者;Sequence.Group 里只放参与者,Sequence.Block 里只放消息或片段。
976
- * 嵌套的另一张图表自成一体,不参与本图的校验。
977
- */
978
- function checkDiagramRoot(d, err) {
979
- const type = d.type;
980
- const strOf = (v) => (typeof v === 'string' ? v : String(v));
981
- const oneOf = (el, prop, allowed, severity = 'error') => {
982
- const v = el.props[prop];
983
- if (v !== undefined && (typeof v !== 'string' || !allowed.includes(v)))
984
- err(prop === 'icon' ? 'ICON_UNKNOWN' : 'INVALID_DIAGRAM_PROP', `<${el.type}> ${prop}="${strOf(v)}" is not supported (available: ${allowed.join(', ')})${severity === 'warning' ? '; it is drawn as the default' : ''}`, el.source, severity);
985
- };
986
- if (type === 'Sequence') {
987
- const actors = new Set();
988
- const messages = [];
989
- const walk = (cs, inside) => {
990
- for (const c of flatten(cs)) {
991
- if (!isNode(c) || isDiagramRoot(c.type))
992
- continue;
993
- if (c.type === SEQUENCE_FAMILY.actor) {
994
- if (inside === 'block')
995
- err('INVALID_DIAGRAM_CHILD', `<Sequence.Actor> "${labelOf(c)}" cannot be inside <Sequence.Block>; declare participants at the top (optionally in <Sequence.Group>) and put messages in blocks`, c.source);
996
- if (typeof c.props.id === 'string')
997
- actors.add(c.props.id);
998
- }
999
- else if (c.type === SEQUENCE_FAMILY.message) {
1000
- if (inside === 'group')
1001
- err('INVALID_DIAGRAM_CHILD', '<Sequence.Message> cannot be inside <Sequence.Group> (a group boxes participants); put it after the participants, or in a <Sequence.Block>', c.source);
1002
- messages.push(c);
1003
- }
1004
- else if (c.type === SEQUENCE_FAMILY.group) {
1005
- if (inside !== 'root')
1006
- err('INVALID_DIAGRAM_CHILD', '<Sequence.Group> must be a direct child of <Sequence>', c.source);
1007
- oneOf(c, 'icon', DIAGRAM_GROUP_ICONS);
1008
- walk(c.children, 'group');
1009
- }
1010
- else if (c.type === SEQUENCE_FAMILY.block) {
1011
- if (inside === 'group')
1012
- err('INVALID_DIAGRAM_CHILD', '<Sequence.Block> cannot be inside <Sequence.Group>', c.source);
1013
- oneOf(c, 'kind', SEQUENCE_BLOCK_KINDS);
1014
- walk(c.children, 'block');
1015
- }
1016
- else if (c.type.startsWith('Diagram.') || c.type.startsWith('StateMachine.')) {
1017
- err('INVALID_DIAGRAM_CHILD', `<${c.type}> cannot be used inside <Sequence>; use Sequence.Actor / Sequence.Message / Sequence.Group / Sequence.Block`, c.source);
1018
- }
1019
- }
1020
- };
1021
- walk(d.children, 'root');
1022
- const known = [...actors].join(', ') || '(no participants)';
1023
- for (const m of messages)
1024
- for (const k of ['from', 'to']) {
1025
- const v = m.props[k];
1026
- if (typeof v !== 'string' || !actors.has(v))
1027
- err('UNKNOWN_DIAGRAM_NODE', `<Sequence.Message> ${k} "${strOf(v)}" is not a participant id in this Sequence (available: ${known})`, m.source);
1028
- }
1029
- return;
1030
- }
1031
- const fam = GRAPH_FAMILY[type];
1032
- const nodes = new Set();
1033
- const groups = new Map();
1034
- /** 元素 → 它的父分组(嵌套或 group= 引用);记录嵌套父分组,用来查冲突。 */
1035
- const parentOf = new Map();
1036
- const edges = [];
1037
- const refs = [];
1038
- let nodeCount = 0;
1039
- const walk = (cs, nested) => {
1040
- for (const c of flatten(cs)) {
1041
- if (!isNode(c) || isDiagramRoot(c.type))
1042
- continue;
1043
- const id = typeof c.props.id === 'string' ? c.props.id : null;
1044
- const ref = typeof c.props.group === 'string' ? c.props.group : null;
1045
- if (c.props.group !== undefined && ref === null)
1046
- err('UNKNOWN_DIAGRAM_GROUP', `<${c.type}> group must be a group id string`, c.source);
1047
- if (c.type === fam.node) {
1048
- nodeCount++;
1049
- if (id) {
1050
- nodes.add(id);
1051
- parentOf.set(id, ref ?? nested);
1052
- }
1053
- if (ref)
1054
- refs.push({ el: c, ref, nested });
1055
- oneOf(c, 'pin', DIAGRAM_PINS);
1056
- // kind 以前没有校验(未知值画成 service):保持兼容,只给 warning
1057
- if (type === 'Diagram')
1058
- oneOf(c, 'kind', DIAGRAM_NODE_KINDS, 'warning');
1059
- }
1060
- else if (c.type === fam.group) {
1061
- if (id) {
1062
- groups.set(id, c);
1063
- parentOf.set(id, ref ?? nested);
1064
- }
1065
- if (ref)
1066
- refs.push({ el: c, ref, nested });
1067
- oneOf(c, 'icon', DIAGRAM_GROUP_ICONS);
1068
- oneOf(c, 'tone', DIAGRAM_TONES);
1069
- oneOf(c, 'pin', DIAGRAM_PINS);
1070
- walk(c.children, id ?? nested);
1071
- }
1072
- else if (c.type === fam.edge) {
1073
- edges.push(c);
1074
- }
1075
- else if (c.type.startsWith('Diagram.') || c.type.startsWith('StateMachine.') || c.type.startsWith('Sequence.')) {
1076
- err('INVALID_DIAGRAM_CHILD', `<${c.type}> cannot be used inside <${type}>; use ${fam.node} / ${fam.edge} / ${fam.group}`, c.source);
1077
- }
1024
+ /** Forward declared properties before descending; nested owners establish their own scope. */
1025
+ function inheritProps(owner, declarations) {
1026
+ if (!declarations.length)
1027
+ return owner;
1028
+ const visit = (child) => {
1029
+ if (Array.isArray(child))
1030
+ return child.map(visit);
1031
+ if (!isNode(child) || child.type === owner.type)
1032
+ return child;
1033
+ const spec = declarations.find(d => d.target === child.type);
1034
+ if (spec) {
1035
+ const props = { ...child.props };
1036
+ for (const key of spec.props)
1037
+ if (props[key] === undefined && owner.props[key] !== undefined)
1038
+ props[key] = owner.props[key];
1039
+ return { ...child, props };
1078
1040
  }
1041
+ return { ...child, children: child.children.map(visit) };
1079
1042
  };
1080
- walk(d.children, null);
1081
- const groupList = [...groups.keys()].join(', ') || '(no groups with an id)';
1082
- for (const { el, ref, nested } of refs) {
1083
- if (!groups.has(ref))
1084
- err('UNKNOWN_DIAGRAM_GROUP', `<${el.type}> group="${ref}" is not a ${fam.group} id in this ${type} (available: ${groupList})`, el.source);
1085
- else if (nested && nested !== ref)
1086
- err('DIAGRAM_GROUP_CONFLICT', `<${el.type}> is nested in group "${nested}" but declares group="${ref}"; use one of the two`, el.source);
1087
- }
1088
- // 分组成环(只可能来自 group= 引用)
1089
- const reported = new Set();
1090
- for (const gid of groups.keys()) {
1091
- const seen = [gid];
1092
- for (let q = parentOf.get(gid) ?? null; q && groups.has(q); q = parentOf.get(q) ?? null) {
1093
- if (seen.includes(q)) {
1094
- const cycle = seen.slice(seen.indexOf(q));
1095
- const key = [...cycle].sort().join(',');
1096
- if (!reported.has(key)) {
1097
- reported.add(key);
1098
- err('DIAGRAM_GROUP_CYCLE', `Groups ${[...cycle, q].map((x) => `"${x}"`).join(' → ')} contain each other; remove one group= reference`, groups.get(gid).source);
1099
- }
1100
- break;
1101
- }
1102
- seen.push(q);
1103
- }
1104
- }
1105
- const ancestors = (id) => {
1106
- const out = [];
1107
- for (let q = parentOf.get(id) ?? null; q && !out.includes(q); q = parentOf.get(q) ?? null)
1108
- out.push(q);
1109
- return out;
1110
- };
1111
- const known = [...nodes, ...groups.keys()].join(', ') || '(no nodes)';
1112
- for (const e of edges) {
1113
- let ok = true;
1114
- for (const k of ['from', 'to']) {
1115
- const v = e.props[k];
1116
- if (typeof v !== 'string' || (!nodes.has(v) && !groups.has(v))) {
1117
- ok = false;
1118
- err('UNKNOWN_DIAGRAM_NODE', `<${fam.edge}> ${k} "${strOf(v)}" is not a ${type === 'StateMachine' ? 'state' : 'node'} or group id in this ${type} (available: ${known})`, e.source);
1119
- }
1120
- }
1121
- if (!ok)
1122
- continue;
1123
- const from = e.props.from;
1124
- const to = e.props.to;
1125
- if (ancestors(from).includes(to) || ancestors(to).includes(from))
1126
- err('DIAGRAM_EDGE_INTO_OWN_GROUP', `<${fam.edge}> ${from} → ${to} connects an element to a group that contains it; connect to another element inside the group, or to a group outside`, e.source);
1127
- }
1128
- // 按业务域分组的提示:节点多,却没有分组(或只有一个把所有节点都包起来的分组)
1129
- if (type === 'Diagram' && nodeCount >= 6) {
1130
- const top = [...groups.values()].filter((g) => !parentOf.get(String(g.props.id)));
1131
- const allInOne = groups.size === 1 && top.length === 1 && [...nodes].every((n) => parentOf.get(n) === String(top[0].props.id));
1132
- if (groups.size === 0 || allInOne)
1133
- err('DIAGRAM_UNGROUPED', `<Diagram> has ${nodeCount} nodes but ${groups.size === 0 ? 'no groups' : 'a single group around all of them'}; group nodes by business domain (gateway, runtime, storage…) with <Diagram.Group label icon> so viewers can tell what belongs where. See npx joplo skill diagram`, d.source, 'info');
1134
- }
1043
+ return { ...owner, children: owner.children.map(visit) };
1135
1044
  }
1136
1045
  /** 展开数组与 Fragment(含插槽展开后的 Fragment),丢弃 null/布尔。 */
1137
1046
  function flatten(cs) {
@@ -1202,12 +1111,16 @@ function findIn(node, id) {
1202
1111
  }
1203
1112
  const NO_STATE = { ui: {}, data: {}, inputs: {} };
1204
1113
  /** 自动字幕:元素名取 Mantine 的 label 属性(其次 title / aria-label / placeholder / 文字);select 显示选项的 label。 */
1205
- function autoCaption(st, scene) {
1114
+ function autoCaption(st, scene, project) {
1206
1115
  const a = st.action;
1207
1116
  const node = 'target' in a && scene ? findIn(scene.root, a.target) : null;
1208
1117
  const label = node ? nodeLabel(node) : 'target' in a ? a.target : '';
1209
1118
  const result = (kind, caption, extra = {}) => ({ caption, captionAuto: { kind, label, ...extra } });
1210
1119
  switch (a.type) {
1120
+ case 'drag': return result('drag', `Drag “${label}” to ${typeof a.to === 'string' ? a.to : `${a.to.x}, ${a.to.y}`}`, { value: typeof a.to === 'string' ? (scene && findIn(scene.root, a.to) ? nodeLabel(findIn(scene.root, a.to)) : a.to) : `${a.to.x}, ${a.to.y}` });
1121
+ case 'hover': return result('hover', `Hover over “${label}”`);
1122
+ case 'scroll': return result('scroll', `Scroll “${label}” to ${typeof a.to === 'string' ? a.to : `${a.to.x}, ${a.to.y}`}`, { value: typeof a.to === 'string' ? (scene && findIn(scene.root, a.to) ? nodeLabel(findIn(scene.root, a.to)) : a.to) : `${a.to.x}, ${a.to.y}` });
1123
+ case 'plugin': return { caption: (pluginActionSpec(project, a.name)?.caption ?? a.name).replaceAll('{label}', label).replace(/\{data\.([A-Za-z0-9_-]+)\}/g, (_, k) => String(a.data[k] ?? '')) };
1211
1124
  case 'click': return result('click', `Click “${label}”`);
1212
1125
  case 'type': return result('type', `Type “${a.value}” in “${label}”`, { value: a.value });
1213
1126
  case 'select': {
@@ -1216,7 +1129,7 @@ function autoCaption(st, scene) {
1216
1129
  return result('select', `Select “${value}” in “${label}”`, { value });
1217
1130
  }
1218
1131
  case 'toggle': {
1219
- const kind = node?.type === 'Checkbox' ? (a.value ? 'check' : 'uncheck') : (a.value ? 'switch_on' : 'switch_off');
1132
+ const kind = node?.traits?.toggleCaption === 'check' ? (a.value ? 'check' : 'uncheck') : (a.value ? 'switch_on' : 'switch_off');
1220
1133
  const verb = { check: 'Check', uncheck: 'Uncheck', switch_on: 'Turn on', switch_off: 'Turn off' }[kind];
1221
1134
  return result(kind, `${verb} “${label}”`);
1222
1135
  }
@@ -1226,12 +1139,48 @@ function autoCaption(st, scene) {
1226
1139
  case 'card': return { caption: a.title };
1227
1140
  }
1228
1141
  }
1142
+ /** Validate extension actions while all scene anchors and enabled declarations are available. */
1143
+ function validateNewAction(action, scenes, project, report) {
1144
+ if (!['drag', 'hover', 'scroll', 'plugin'].includes(action.type))
1145
+ return;
1146
+ const parsed = Action.safeParse(action);
1147
+ if (!parsed.success) {
1148
+ report('ACTION_INVALID', `Invalid ${action.type} action: ${parsed.error.message}`);
1149
+ return;
1150
+ }
1151
+ if (!('target' in action))
1152
+ return;
1153
+ const nodes = scenes.map(s => findIn(s.root, action.target)).filter((n) => !!n);
1154
+ if (!nodes.length)
1155
+ report('MISSING_TARGET', `Action target ${action.target} is not in the current stage`);
1156
+ if (action.type === 'drag' || action.type === 'scroll') {
1157
+ if (typeof action.to === 'string' && !scenes.some(s => findIn(s.root, action.target) && findIn(s.root, action.to)))
1158
+ report('ACTION_DESTINATION_MISSING', `${action.type} destination ${action.to} must be in the same stage as ${action.target}`);
1159
+ else if (action.type === 'scroll' && typeof action.to === 'string' && !nodes.some(n => findIn(n, action.to)))
1160
+ report('ACTION_DESTINATION_INVALID', `Scroll destination ${action.to} must be inside ${action.target}`);
1161
+ }
1162
+ if (action.type === 'plugin') {
1163
+ const spec = pluginActionSpec(project, action.name);
1164
+ if (!spec)
1165
+ report('ACTION_UNKNOWN', `Plugin action ${action.name} is not declared by an enabled plugin`);
1166
+ else {
1167
+ if (!validActionData(spec, action.data))
1168
+ report('ACTION_DATA_INVALID', `Plugin action ${action.name} payload does not match its declared fields`);
1169
+ if (spec.targets && nodes.some(n => !spec.targets.includes(n.type)))
1170
+ report('ACTION_TARGET_INVALID', `Plugin action ${action.name} does not accept this target type`);
1171
+ }
1172
+ }
1173
+ }
1229
1174
  function stripSources(o) {
1230
1175
  if (Array.isArray(o))
1231
1176
  return o.forEach(stripSources);
1232
1177
  if (o && typeof o === 'object') {
1233
1178
  delete o.source;
1234
- Object.values(o).forEach(stripSources);
1179
+ // Plugin slots are already validated public data. Stripping their own fields would
1180
+ // invalidate the plugin schema after validation (e.g. a public provenance `source`).
1181
+ for (const [key, value] of Object.entries(o))
1182
+ if (key !== 'ext')
1183
+ stripSources(value);
1235
1184
  }
1236
1185
  }
1237
1186
  function stripNotes(n) {