libpetri 2.3.0 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,6 @@
1
+ // src/viewer/render.ts
2
+ import { instance as vizInstance } from "@viz-js/viz";
3
+
1
4
  // src/viewer/layout/preprocess.ts
2
5
  function classifyKind(id) {
3
6
  if (id.startsWith("p_")) return "place";
@@ -409,11 +412,67 @@ function writeBack(graph, layout) {
409
412
  return lines.join("\n");
410
413
  }
411
414
 
415
+ // src/viewer/render.ts
416
+ var vizPromise = null;
417
+ function getViz() {
418
+ if (!vizPromise) vizPromise = vizInstance();
419
+ return vizPromise;
420
+ }
421
+ async function renderDotToSvg(dotSource) {
422
+ const viz = await getViz();
423
+ return viz.renderSVGElement(dotSource, { engine: "dot" });
424
+ }
425
+ function fnv1a(input) {
426
+ let h = 2166136261;
427
+ for (let i = 0; i < input.length; i++) {
428
+ h ^= input.charCodeAt(i);
429
+ h = Math.imul(h, 16777619);
430
+ }
431
+ return (h >>> 0).toString(16);
432
+ }
433
+ var PINNED_DOT_CACHE_CAP = 16;
434
+ var pinnedDotCache = /* @__PURE__ */ new Map();
435
+ function getCachedPinnedDot(key) {
436
+ const hit = pinnedDotCache.get(key);
437
+ if (hit !== void 0) {
438
+ pinnedDotCache.delete(key);
439
+ pinnedDotCache.set(key, hit);
440
+ }
441
+ return hit;
442
+ }
443
+ function setCachedPinnedDot(key, value) {
444
+ pinnedDotCache.set(key, value);
445
+ while (pinnedDotCache.size > PINNED_DOT_CACHE_CAP) {
446
+ const oldest = pinnedDotCache.keys().next().value;
447
+ if (oldest === void 0) break;
448
+ pinnedDotCache.delete(oldest);
449
+ }
450
+ }
451
+ function _clearElkLayoutCache() {
452
+ pinnedDotCache.clear();
453
+ }
454
+ async function renderDotToSvgWithElkLayout(dotSource) {
455
+ const key = fnv1a(dotSource);
456
+ let pinnedDot = getCachedPinnedDot(key);
457
+ if (pinnedDot === void 0) {
458
+ const graph = replicateShared(
459
+ foldOrphans(parseLibpetriDot(dotSource), 0.7),
460
+ { max: Infinity }
461
+ );
462
+ const layout = await elkLayout(graph);
463
+ pinnedDot = writeBack(graph, layout);
464
+ setCachedPinnedDot(key, pinnedDot);
465
+ }
466
+ const viz = await getViz();
467
+ return viz.renderSVGElement(pinnedDot, {
468
+ engine: "nop",
469
+ yInvert: true
470
+ });
471
+ }
412
472
  export {
413
- parseLibpetriDot,
414
- foldOrphans,
415
- replicateShared,
416
- elkLayout,
417
- writeBack
473
+ _clearElkLayoutCache,
474
+ getViz,
475
+ renderDotToSvg,
476
+ renderDotToSvgWithElkLayout
418
477
  };
419
- //# sourceMappingURL=chunk-RNWTYK5B.js.map
478
+ //# sourceMappingURL=render-UY4OKXXQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/viewer/render.ts","../src/viewer/layout/preprocess.ts","../src/viewer/layout/elk-place.ts"],"sourcesContent":["/**\n * DOT → SVG rendering for the canonical libpetri viewer.\n *\n * Two render paths:\n *\n * renderDotToSvg(dot) — plain Graphviz `dot` engine.\n * renderDotToSvgWithElkLayout(dot) — C0 pipeline: parse → fold →\n * replicate → ELK → writeBack →\n * Graphviz `neato` with `nop=1`\n * (pin mode). Cached by DOT hash.\n *\n * The ELK path is the default for {@link mount}; the plain-Graphviz path\n * remains as a fallback for callers that want stock layout (or for\n * environments where elkjs isn't installed).\n *\n * @module viewer/render\n */\n\nimport { instance as vizInstance } from '@viz-js/viz';\nimport {\n foldOrphans,\n parseLibpetriDot,\n replicateShared,\n} from './layout/preprocess.js';\nimport { elkLayout, writeBack } from './layout/elk-place.js';\n\ntype Viz = Awaited<ReturnType<typeof vizInstance>>;\n\nlet vizPromise: Promise<Viz> | null = null;\n\n/** Memoize the viz.js instance so the wasm loads only once per page. */\nexport function getViz(): Promise<Viz> {\n if (!vizPromise) vizPromise = vizInstance();\n return vizPromise;\n}\n\n/**\n * Render a DOT source string to an SVGSVGElement using the plain `dot`\n * engine. Deterministic across runs; libpetri exporters emit byte-stable\n * DOT per spec EXP-014 so the same DOT yields the same SVG.\n */\nexport async function renderDotToSvg(dotSource: string): Promise<SVGSVGElement> {\n const viz = await getViz();\n return viz.renderSVGElement(dotSource, { engine: 'dot' });\n}\n\n// ---- C0 / ELK pin-mode cache ---------------------------------------------\n\n/** FNV-1a 32-bit hash. Fast enough that a SHA isn't worth the import. */\nfunction fnv1a(input: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16);\n}\n\nconst PINNED_DOT_CACHE_CAP = 16;\nconst pinnedDotCache = new Map<string, string>();\n\nfunction getCachedPinnedDot(key: string): string | undefined {\n const hit = pinnedDotCache.get(key);\n if (hit !== undefined) {\n // LRU touch: re-insert moves to most-recent position in Map ordering.\n pinnedDotCache.delete(key);\n pinnedDotCache.set(key, hit);\n }\n return hit;\n}\n\nfunction setCachedPinnedDot(key: string, value: string): void {\n pinnedDotCache.set(key, value);\n while (pinnedDotCache.size > PINNED_DOT_CACHE_CAP) {\n const oldest = pinnedDotCache.keys().next().value;\n if (oldest === undefined) break;\n pinnedDotCache.delete(oldest);\n }\n}\n\n/** Test helper — clears the pinned-DOT LRU cache between mounts. */\nexport function _clearElkLayoutCache(): void {\n pinnedDotCache.clear();\n}\n\n/**\n * Run the C0 layout pipeline against a libpetri DOT source and return the\n * rendered SVG. The expensive steps (preprocess + ELK layout + DOT rewrite)\n * are cached keyed on the input DOT's hash, so re-mounts on the same net\n * structure skip everything except the Graphviz pin-mode draw.\n *\n * Per-tick marking updates do NOT call this — they toggle classes on the\n * already-mounted SVG. ELK only runs when the net structure changes.\n */\nexport async function renderDotToSvgWithElkLayout(\n dotSource: string,\n): Promise<SVGSVGElement> {\n const key = fnv1a(dotSource);\n let pinnedDot = getCachedPinnedDot(key);\n if (pinnedDot === undefined) {\n const graph = replicateShared(\n foldOrphans(parseLibpetriDot(dotSource), 0.7),\n { max: Infinity },\n );\n const layout = await elkLayout(graph);\n pinnedDot = writeBack(graph, layout);\n setCachedPinnedDot(key, pinnedDot);\n }\n const viz = await getViz();\n return viz.renderSVGElement(pinnedDot, {\n engine: 'nop',\n yInvert: true,\n });\n}\n","/**\n * Graph pre-processing for the C0-replicate-default layout pipeline.\n *\n * Three pure-ish transforms operate on a {@link GraphModel} parsed from a\n * libpetri-exported DOT string:\n *\n * parseLibpetriDot(dot) → GraphModel\n * foldOrphans(graph, threshold) → GraphModel (REASSIGN_ORPHANS)\n * replicateShared(graph, opts) → GraphModel (REPLICATE_SHARED)\n *\n * The pipeline turns a flat cluster soup into a cluster-internal one by\n * (a) folding orphan nodes whose edges concentrate in one cluster into that\n * cluster, and (b) cloning shared places into every foreign cluster they\n * touch so cross-cluster spaghetti disappears. The resulting GraphModel is\n * what ELK lays out (Stage 2) and Graphviz then renders in pin-mode.\n *\n * Algorithm lineage: ported from\n * `/home/db/otto-repos/nucleus_marvin/.scratch/javadoc-layout-exp/CHECKPOINTS/run16_GOOD_v3_skip-junctions.mjs`\n * lines 14–220. The arc-type detection, replica naming\n * (`${placeId}__rep__${clusterShortName}`), and the `__replica` /\n * `replicaOf` markers are load-bearing — downstream stages key off them.\n *\n * @module viewer/layout/preprocess\n */\n\nexport type ArcType = 'normal' | 'reset' | 'inhibitor' | 'read';\nexport type NodeKind = 'place' | 'transition' | 'junction';\n\nexport interface ParsedNode {\n readonly id: string;\n readonly kind: NodeKind;\n readonly attrs: Record<string, string>;\n /** True iff this node was emitted by replicateShared. */\n readonly replica?: boolean;\n /** For a replica, the id of the original logical place. */\n readonly replicaOf?: string;\n}\n\nexport interface ParsedEdge {\n readonly src: string;\n readonly dst: string;\n readonly arc: ArcType;\n /**\n * Raw attribute body from the libpetri DOT (between the `[…]` brackets,\n * brackets stripped). Carries style/penwidth/label that we want to\n * round-trip verbatim so the rendered output matches `DotExporter`'s\n * native look.\n */\n readonly rawAttrs: string;\n}\n\nexport interface ParsedCluster {\n readonly id: string; // \"cluster_productSearch\"\n readonly shortName: string; // \"productSearch\"\n readonly nodes: readonly string[];\n}\n\nexport interface GraphModel {\n readonly nodes: ReadonlyMap<string, ParsedNode>;\n readonly clusters: ReadonlyMap<string, ParsedCluster>;\n readonly nodeToCluster: ReadonlyMap<string, string>;\n /** Node ids not in any cluster (rendered at the orchestrator root). */\n readonly orphans: readonly string[];\n readonly edges: readonly ParsedEdge[];\n}\n\nfunction classifyKind(id: string): NodeKind {\n if (id.startsWith('p_')) return 'place';\n if (id.startsWith('t_')) return 'transition';\n return 'junction';\n}\n\n/**\n * Recover key=value attributes from inside a DOT `[...]` block.\n *\n * Mirrors v3 line 29. The regex is intentionally permissive about quoted\n * values containing escaped quotes; it does not validate DOT syntax.\n */\nfunction parseAttrs(body: string): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const m of body.matchAll(/(\\w+)=(\"(?:[^\"]|\\\\.)*\"|\\S+?)(?=[\\s,]|$)/g)) {\n const [, key, raw] = m as unknown as [string, string, string];\n const v = raw.startsWith('\"') && raw.endsWith('\"') ? raw.slice(1, -1) : raw;\n attrs[key] = v;\n }\n return attrs;\n}\n\n/**\n * Parse a libpetri-exported DOT string into a {@link GraphModel}.\n *\n * Tolerates the current exporter shape (see\n * `java/src/main/java/org/libpetri/export/StyleConstants.java`):\n * - inhibitor arcs use `arrowhead=\"odot\"` + color `#dc3545`\n * - reset arcs use `label=\"reset\"` + color `#fd7e14`\n * - read arcs use `label=\"read\"` + color `#6c757d`\n *\n * Mirrors v3 lines 24–103.\n */\nexport function parseLibpetriDot(dot: string): GraphModel {\n const nodes = new Map<string, ParsedNode>();\n // Greedy `.*` (no /s flag) consumes the full attrs body up to the line's\n // trailing `];`. The v3 reference used `[^\\]]*` which silently dropped\n // transitions whose label contained `[…]` text (e.g., `\"[0, ∞]ms\"`); we\n // can't tolerate that here because the typed model wants every cluster\n // member to have a Node entry.\n for (const m of dot.matchAll(/^\\s*([pjt]_[A-Za-z0-9_]+)\\s*\\[(.*)\\];\\s*$/gm)) {\n const [, id, body] = m as unknown as [string, string, string];\n nodes.set(id, { id, kind: classifyKind(id), attrs: parseAttrs(body) });\n }\n\n const clusters = new Map<string, ParsedCluster>();\n const nodeToCluster = new Map<string, string>();\n for (const cm of dot.matchAll(/subgraph (cluster_\\w+)\\s*\\{([^]*?)^\\s*\\}/gm)) {\n const [, clusterId, body] = cm as unknown as [string, string, string];\n const memberIds = [...body.matchAll(/^\\s*([pjt]_[A-Za-z0-9_]+)\\s*\\[/gm)]\n .map(m => (m as unknown as [string, string])[1]);\n clusters.set(clusterId, {\n id: clusterId,\n shortName: clusterId.replace(/^cluster_/, ''),\n nodes: memberIds,\n });\n for (const n of memberIds) nodeToCluster.set(n, clusterId);\n }\n\n // Catch nodes declared at root (orphans) — strip cluster bodies, then scan\n const stripped = dot.replace(/subgraph cluster_\\w+\\s*\\{[^]*?^\\s*\\}/gm, '');\n for (const m of stripped.matchAll(/^\\s*([pjt]_[A-Za-z0-9_]+)\\s*\\[/gm)) {\n const id = (m as unknown as [string, string])[1];\n if (!nodes.has(id)) {\n // Root-declared node without full attrs (rare); seed with empty attrs.\n nodes.set(id, { id, kind: classifyKind(id), attrs: {} });\n }\n }\n\n const orphans = [...nodes.keys()].filter(n => !nodeToCluster.has(n));\n\n const edges: ParsedEdge[] = [];\n for (const m of dot.matchAll(/([pjt]_[A-Za-z0-9_]+)\\s*->\\s*([pjt]_[A-Za-z0-9_]+)\\s*(\\[[^\\]]*\\])?/g)) {\n const [, src, dst, rawAttrs] = m as unknown as [string, string, string, string | undefined];\n const attrs = rawAttrs ?? '';\n // Cluster-anchor edges (lhead/ltail) are exporter-internal routing hints,\n // not real arcs in the Petri net — skip per v3 line 97.\n if (attrs.includes('lhead=') || attrs.includes('ltail=')) continue;\n let arc: ArcType = 'normal';\n if (attrs.includes('label=\"reset\"') || attrs.includes('#fd7e14')) arc = 'reset';\n else if (attrs.includes('arrowhead=\"odot\"') || attrs.includes('#dc3545')) arc = 'inhibitor';\n else if (attrs.includes('label=\"read\"')) arc = 'read';\n // Strip the `[…]` brackets so writeBack can splice the body into a new\n // attr list. Empty if libpetri emitted a bare `src -> dst;`.\n const stripped = attrs.startsWith('[') && attrs.endsWith(']')\n ? attrs.slice(1, -1)\n : '';\n edges.push({ src, dst, arc, rawAttrs: stripped });\n }\n\n return { nodes, clusters, nodeToCluster, orphans, edges };\n}\n\n/**\n * Adopt orphan nodes into the cluster their edges most prefer.\n *\n * For each orphan, tally how many of its edges touch each cluster. If the\n * dominant cluster gets at least `threshold` of the orphan's cluster-touching\n * edges, the orphan is reassigned to that cluster.\n *\n * Mirrors v3 lines 105–136. Default threshold 0.7 matches REASSIGN_ORPHANS.\n */\nexport function foldOrphans(graph: GraphModel, threshold = 0.7): GraphModel {\n if (threshold <= 0) return graph;\n\n const nodeToCluster = new Map(graph.nodeToCluster);\n const clusterMembers = new Map<string, string[]>();\n for (const [id, c] of graph.clusters) clusterMembers.set(id, [...c.nodes]);\n\n const tally = new Map<string, Map<string, number>>();\n const bump = (orphan: string, other: string): void => {\n const oc = nodeToCluster.get(other);\n if (!oc) return;\n let t = tally.get(orphan);\n if (!t) { t = new Map(); tally.set(orphan, t); }\n t.set(oc, (t.get(oc) ?? 0) + 1);\n };\n\n for (const e of graph.edges) {\n const sIsOrphan = !nodeToCluster.has(e.src);\n const dIsOrphan = !nodeToCluster.has(e.dst);\n if (sIsOrphan && !dIsOrphan) bump(e.src, e.dst);\n if (dIsOrphan && !sIsOrphan) bump(e.dst, e.src);\n }\n\n for (const id of graph.orphans) {\n const t = tally.get(id);\n if (!t) continue;\n let total = 0;\n let bestCluster: string | null = null;\n let bestCount = 0;\n for (const [c, n] of t) {\n total += n;\n if (n > bestCount) { bestCount = n; bestCluster = c; }\n }\n if (bestCluster && total > 0 && bestCount / total >= threshold) {\n clusterMembers.get(bestCluster)!.push(id);\n nodeToCluster.set(id, bestCluster);\n }\n }\n\n const clusters = new Map<string, ParsedCluster>();\n for (const [id, c] of graph.clusters) {\n clusters.set(id, { ...c, nodes: clusterMembers.get(id)! });\n }\n const orphans = [...graph.nodes.keys()].filter(n => !nodeToCluster.has(n));\n return { ...graph, clusters, nodeToCluster, orphans };\n}\n\nexport interface ReplicateOptions {\n /**\n * Skip places that touch more than this many foreign clusters. Per the\n * plan's \"no cap\" decision, default is `Infinity`. Set to a finite value\n * to suppress replication of hub places that would otherwise produce many\n * copies.\n */\n readonly max?: number;\n /** If true, replicate transitions as well as places. Default false. */\n readonly replicateTransitions?: boolean;\n}\n\nexport interface ReplicateStats {\n readonly replicatedPlaces: number;\n readonly totalCopies: number;\n}\n\n/**\n * For each place P, replicate it into every foreign cluster touched by its\n * edges, and redirect those cross-cluster edges to the local copy.\n *\n * Replica id convention is load-bearing: `${placeId}__rep__${shortClusterName}`.\n * Downstream stages (mount-time tagging, overlay highlight, click-all-copies)\n * key off this naming and the `replica: true` / `replicaOf` markers.\n *\n * If P has a home cluster (folded earlier), the original stays as the primary\n * copy and is also marked as a replica so the ⇄ glyph renders consistently.\n * If P is an orphan with all its edges redirected, the original is dropped.\n *\n * Mirrors v3 lines 138–221.\n */\nexport function replicateShared(\n graph: GraphModel,\n opts: ReplicateOptions = {},\n): GraphModel & { readonly replicateStats: ReplicateStats } {\n const max = opts.max ?? Infinity;\n const replicateTransitions = opts.replicateTransitions ?? false;\n\n const nodes = new Map(graph.nodes);\n const nodeToCluster = new Map(graph.nodeToCluster);\n const clusterMembers = new Map<string, string[]>();\n for (const [id, c] of graph.clusters) clusterMembers.set(id, [...c.nodes]);\n const edges = graph.edges.map(e => ({ ...e }));\n\n // 1. Compute foreign-cluster set per replicable node.\n const foreignByNode = new Map<string, Set<string>>();\n const noteForeign = (nodeId: string, otherId: string): void => {\n if (!nodeId.startsWith('p_') && !(replicateTransitions && nodeId.startsWith('t_'))) return;\n const home = nodeToCluster.get(nodeId);\n const otherCluster = nodeToCluster.get(otherId);\n if (!otherCluster) return;\n if (otherCluster === home) return;\n let s = foreignByNode.get(nodeId);\n if (!s) { s = new Set(); foreignByNode.set(nodeId, s); }\n s.add(otherCluster);\n };\n for (const e of edges) {\n noteForeign(e.src, e.dst);\n noteForeign(e.dst, e.src);\n }\n\n // 2. Emit replicas for nodes within the cap.\n const replicaMap = new Map<string, Map<string, string>>(); // orig → cluster → replicaId\n let replicatedPlaces = 0;\n let totalCopies = 0;\n for (const [placeId, foreigns] of foreignByNode) {\n if (foreigns.size === 0) continue;\n if (foreigns.size > max) continue;\n const perCluster = new Map<string, string>();\n const orig = nodes.get(placeId);\n if (!orig) continue;\n for (const clusterId of foreigns) {\n const shortName = clusterId.replace(/^cluster_/, '');\n const repId = `${placeId}__rep__${shortName}`;\n perCluster.set(clusterId, repId);\n clusterMembers.get(clusterId)!.push(repId);\n nodeToCluster.set(repId, clusterId);\n nodes.set(repId, {\n id: repId,\n kind: orig.kind,\n attrs: { ...orig.attrs },\n replica: true,\n replicaOf: placeId,\n });\n totalCopies++;\n }\n replicaMap.set(placeId, perCluster);\n replicatedPlaces++;\n // Mark the original as a shared place so the ⇄ glyph renders uniformly.\n nodes.set(placeId, { ...orig, replica: true, replicaOf: placeId });\n }\n\n // 3. Redirect cross-cluster edges to the local replica on each end.\n for (const e of edges) {\n const sMap = replicaMap.get(e.src);\n const dMap = replicaMap.get(e.dst);\n if (sMap) {\n const dCl = nodeToCluster.get(e.dst);\n if (dCl && sMap.has(dCl)) e.src = sMap.get(dCl)!;\n }\n if (dMap) {\n const sCl = nodeToCluster.get(e.src);\n if (sCl && dMap.has(sCl)) e.dst = dMap.get(sCl)!;\n }\n }\n\n // 4. Drop orphan originals whose edges all got redirected away.\n for (const [origId] of replicaMap) {\n if (nodeToCluster.has(origId)) continue; // folded — keep as primary\n const stillHasEdge = edges.some(e => e.src === origId || e.dst === origId);\n if (!stillHasEdge) nodes.delete(origId);\n }\n\n const clusters = new Map<string, ParsedCluster>();\n for (const [id, c] of graph.clusters) {\n clusters.set(id, { ...c, nodes: clusterMembers.get(id)! });\n }\n const orphans = [...nodes.keys()].filter(n => !nodeToCluster.has(n));\n\n return {\n nodes,\n clusters,\n nodeToCluster,\n orphans,\n edges,\n replicateStats: { replicatedPlaces, totalCopies },\n };\n}\n","/**\n * ELK placement + DOT pin-mode rewrite.\n *\n * Stage 2 of the C0 pipeline. Takes the {@link GraphModel} produced by\n * {@link parseLibpetriDot} → {@link foldOrphans} → {@link replicateShared},\n * runs ELKjs to compute absolute `(x, y)` per node and bounding boxes per\n * cluster, then emits a fresh DOT string with positions pinned via\n * `pos=\"x,y!\"` and `bb=\"…\"`. Downstream callers render the result through\n * `@viz-js/viz` with `engine: 'neato'` + `graphAttributes: { nop: '1' }` —\n * Graphviz uses the pinned positions verbatim and routes edges around the\n * pinned cluster boundaries.\n *\n * The two functions are pure: `elkLayout` takes only the graph; `writeBack`\n * takes (graph, layout). Neither touches the original DOT text — the model\n * after replication has nodes the original DOT doesn't, so patching the\n * original would be incorrect.\n *\n * @module viewer/layout/elk-place\n */\n\nimport ELK from 'elkjs/lib/elk.bundled.js';\nimport type {\n ElkExtendedEdge,\n ElkNode,\n} from 'elkjs/lib/elk-api.js';\nimport type { GraphModel, ParsedNode } from './preprocess.js';\n\nconst ORCHESTRATOR_CLUSTER_ID = 'cluster_orchestrator';\n\n// Visual sizing — kept proportional to the v3 reference renderer so the\n// resulting bounding box is comparable to C0-GOOD_v3.svg.\nconst PLACE_RADIUS = 22;\nconst PLACE_CHARW = 7.4;\nconst PLACE_PAD_BELOW = 16;\nconst FONT_PLACE = 13;\nconst TRANSITION_MIN_W = 180;\nconst TRANSITION_H = 40;\nconst TRANSITION_CHARW = 8.5;\nconst JUNCTION_SIZE = 28;\nconst FONT_CLUSTER = 17;\nconst ROOT_SPACING = 90;\nconst CLUSTER_SPACING = 16;\n\n/**\n * Width/height in points that ELK should reserve for a node. Mirrors\n * `nodeDims` in v3 lines 66–78 — places get extra height to leave room for\n * the xlabel underneath the circle.\n */\nfunction nodeDims(node: ParsedNode): { width: number; height: number } {\n if (node.kind === 'place') {\n const label = (node.attrs.xlabel ?? node.attrs.label ?? node.id).replace(/\\\\n/g, ' ');\n const labelWidth = label.length * PLACE_CHARW;\n const circleD = PLACE_RADIUS * 2 + 4;\n return {\n width: Math.max(circleD, labelWidth),\n height: circleD + PLACE_PAD_BELOW + FONT_PLACE,\n };\n }\n if (node.kind === 'junction') {\n return { width: JUNCTION_SIZE, height: JUNCTION_SIZE };\n }\n const label = (node.attrs.label ?? node.id).replace(/\\\\n/g, ' ');\n return {\n width: Math.max(TRANSITION_MIN_W, label.length * TRANSITION_CHARW),\n height: TRANSITION_H,\n };\n}\n\nexport interface NodePosition {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface ClusterBox {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface EdgePath {\n readonly start: { x: number; y: number };\n readonly end: { x: number; y: number };\n readonly bends: ReadonlyArray<{ x: number; y: number }>;\n}\n\nexport interface LayoutResult {\n readonly nodePositions: ReadonlyMap<string, NodePosition>;\n readonly clusterBoxes: ReadonlyMap<string, ClusterBox>;\n /** Keyed on `${src}->${dst}` — ELK-computed edge routes for `nop=2`. */\n readonly edgePaths: ReadonlyMap<string, EdgePath>;\n readonly totalWidth: number;\n readonly totalHeight: number;\n}\n\nconst CLUSTER_OPTIONS: Record<string, string> = {\n 'elk.padding': `[top=${FONT_CLUSTER + 16},left=16,bottom=16,right=16]`,\n 'elk.algorithm': 'layered',\n 'elk.direction': 'DOWN',\n 'elk.spacing.nodeNode': String(CLUSTER_SPACING),\n 'elk.layered.spacing.nodeNodeBetweenLayers': String(CLUSTER_SPACING + 6),\n 'elk.edgeRouting': 'ORTHOGONAL',\n};\n\nconst ROOT_OPTIONS: Record<string, string> = {\n 'elk.algorithm': 'org.eclipse.elk.rectpacking',\n 'elk.aspectRatio': '1.4',\n 'elk.padding': '[top=24,left=24,bottom=24,right=24]',\n 'elk.spacing.nodeNode': String(ROOT_SPACING),\n};\n\nconst ORCHESTRATOR_OPTIONS: Record<string, string> = {\n ...CLUSTER_OPTIONS,\n 'elk.aspectRatio': '2.4',\n 'elk.spacing.nodeNode': '10',\n};\n\n/**\n * Group edges by the cluster that contains both endpoints (or 'root' if\n * the edge crosses cluster boundaries).\n *\n * Orphans count as living in `cluster_orchestrator` for routing purposes,\n * matching v3's `ownerOf` (line 223).\n */\nfunction partitionEdges(graph: GraphModel): {\n byCluster: Map<string, ElkExtendedEdge[]>;\n cross: ElkExtendedEdge[];\n /** edgeId → \"src->dst\" so the layout walk can recover the original key. */\n edgeIdToKey: Map<string, string>;\n} {\n const byCluster = new Map<string, ElkExtendedEdge[]>();\n const cross: ElkExtendedEdge[] = [];\n const edgeIdToKey = new Map<string, string>();\n const ownerOf = (id: string): string =>\n graph.nodeToCluster.get(id) ?? ORCHESTRATOR_CLUSTER_ID;\n\n graph.edges.forEach((e, i) => {\n const so = ownerOf(e.src);\n const dt = ownerOf(e.dst);\n const id = `e${i}`;\n edgeIdToKey.set(id, `${e.src}->${e.dst}`);\n const elkEdge: ElkExtendedEdge = {\n id,\n sources: [e.src],\n targets: [e.dst],\n };\n if (so === dt) {\n let list = byCluster.get(so);\n if (!list) { list = []; byCluster.set(so, list); }\n list.push(elkEdge);\n } else {\n cross.push(elkEdge);\n }\n });\n return { byCluster, cross, edgeIdToKey };\n}\n\n/**\n * Run ELK layout against the C0 graph and return absolute positions.\n *\n * Orphan nodes are wrapped in a synthetic `cluster_orchestrator` so ELK\n * lays them out as a single block alongside the real subnets, which the\n * `rectpacking` root algorithm then packs.\n */\nexport async function elkLayout(graph: GraphModel): Promise<LayoutResult> {\n const { byCluster, cross, edgeIdToKey } = partitionEdges(graph);\n\n const elkChildren: ElkNode[] = [];\n for (const [clusterId, cluster] of graph.clusters) {\n elkChildren.push({\n id: clusterId,\n layoutOptions: CLUSTER_OPTIONS,\n children: cluster.nodes\n .map(id => graph.nodes.get(id))\n .filter((n): n is ParsedNode => n !== undefined)\n .map(n => ({ id: n.id, ...nodeDims(n) })),\n edges: byCluster.get(clusterId) ?? [],\n });\n }\n // Synthetic orchestrator cluster holds the remaining orphans\n elkChildren.push({\n id: ORCHESTRATOR_CLUSTER_ID,\n layoutOptions: ORCHESTRATOR_OPTIONS,\n children: graph.orphans\n .map(id => graph.nodes.get(id))\n .filter((n): n is ParsedNode => n !== undefined)\n .map(n => ({ id: n.id, ...nodeDims(n) })),\n edges: byCluster.get(ORCHESTRATOR_CLUSTER_ID) ?? [],\n });\n\n const elk = new ELK();\n const rootGraph: ElkNode = {\n id: 'root',\n layoutOptions: ROOT_OPTIONS,\n children: elkChildren,\n edges: cross,\n };\n const layout: ElkNode = await elk.layout(rootGraph);\n\n const nodePositions = new Map<string, NodePosition>();\n const clusterBoxes = new Map<string, ClusterBox>();\n const edgePaths = new Map<string, EdgePath>();\n\n const walk = (node: ElkNode, parentX: number, parentY: number): void => {\n const ax = parentX + (node.x ?? 0);\n const ay = parentY + (node.y ?? 0);\n const isCluster = node.id !== 'root' && (node.children?.length ?? 0) > 0;\n if (isCluster) {\n clusterBoxes.set(node.id, {\n x: ax, y: ay,\n width: node.width ?? 0,\n height: node.height ?? 0,\n });\n }\n if (node.id !== 'root' && !isCluster) {\n nodePositions.set(node.id, {\n x: ax, y: ay,\n width: node.width ?? 0,\n height: node.height ?? 0,\n });\n }\n // Edges inside this node — their section coords are in the parent's\n // coordinate frame, so the offset to absolutize is (parentX, parentY)\n // for root edges, or (ax, ay) for cluster-internal edges.\n const edgeOffsetX = node.id === 'root' ? parentX : ax;\n const edgeOffsetY = node.id === 'root' ? parentY : ay;\n for (const edge of node.edges ?? []) {\n const key = edge.id ? edgeIdToKey.get(edge.id) : undefined;\n const section = edge.sections?.[0];\n if (!key || !section) continue;\n edgePaths.set(key, {\n start: {\n x: edgeOffsetX + section.startPoint.x,\n y: edgeOffsetY + section.startPoint.y,\n },\n end: {\n x: edgeOffsetX + section.endPoint.x,\n y: edgeOffsetY + section.endPoint.y,\n },\n bends: (section.bendPoints ?? []).map(p => ({\n x: edgeOffsetX + p.x,\n y: edgeOffsetY + p.y,\n })),\n });\n }\n for (const child of node.children ?? []) walk(child, ax, ay);\n };\n walk(layout, 0, 0);\n\n return {\n nodePositions,\n clusterBoxes,\n edgePaths,\n totalWidth: layout.width ?? 0,\n totalHeight: layout.height ?? 0,\n };\n}\n\n/**\n * Escape an attribute value for inclusion in a DOT string literal.\n *\n * Quotes are doubled (per the DOT escape convention `\\\"`).\n */\nfunction quote(value: string): string {\n return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/**\n * Render a node's attribute list — preserving the parsed attrs (including\n * libpetri's `width`/`height`, which are the *visual* shape dimensions)\n * and adding the ELK-computed `pos` so Graphviz `nop` can pin it.\n *\n * The `pos=\"x,y!\"` form (with trailing `!`) is the neato pin-mode marker.\n * Do NOT emit ELK's layout-reserved width/height to Graphviz — those are\n * the bounding boxes needed for ELK packing (which account for xlabel\n * spillover), not the visible shape sizes. libpetri's standard styles use\n * `width=0.35` for places (25pt circles); overriding with ELK's\n * ~3 inch label-padded box made Graphviz render 114pt-radius circles.\n */\nfunction nodeAttrLine(node: ParsedNode, pos: NodePosition): string {\n const attrs: string[] = [];\n // Center the pinned position on the node's bbox (ELK gives the top-left).\n const cx = pos.x + pos.width / 2;\n const cy = pos.y + pos.height / 2;\n attrs.push(`pos=${quote(`${cx.toFixed(2)},${cy.toFixed(2)}!`)}`);\n for (const [k, v] of Object.entries(node.attrs)) {\n if (k === 'pos') continue;\n attrs.push(`${k}=${quote(v)}`);\n }\n return `${node.id} [${attrs.join(', ')}];`;\n}\n\nfunction edgeAttrLine(src: string, dst: string, rawAttrs: string): string {\n // Splice libpetri's original attrs verbatim so style/penwidth/label/color\n // match `DotExporter` 1:1. We do NOT emit `pos=` for edges — under engine\n // `nop` Graphviz routes edges itself around the pinned node positions,\n // which gives proper boundary clipping (arrowheads land at the visual\n // node edge) and avoids needing a custom polyline-to-spline converter.\n // The only \"custom\" arrowhead is `arrowhead=\"odot\"` for inhibitor edges,\n // which libpetri's exporter already writes into rawAttrs.\n const body = rawAttrs.trim();\n return `${src} -> ${dst}` + (body ? ` [${body}];` : ';');\n}\n\n/**\n * Emit a Graphviz DOT string with positions pinned. Render the result with\n * `@viz-js/viz` using:\n *\n * ```ts\n * viz.renderSVGElement(dot, {\n * engine: 'nop',\n * yInvert: true,\n * });\n * ```\n *\n * `engine: 'nop'` (a.k.a. `nop1`) honours the pinned `pos=` on every node\n * and routes edges around them. We use this rather than `nop2` because\n * `nop2` would force us to provide a spline for every edge ourselves (no\n * routing) — and Graphviz's own routing produces correctly-clipped\n * arrowheads at the visual node boundary, which our ELK polylines did not\n * (ELK uses the layout-reserved bbox, our visual circle is much smaller).\n *\n * `yInvert: true` matches ELK's Y-down convention to Graphviz's Y-up.\n */\nexport function writeBack(graph: GraphModel, layout: LayoutResult): string {\n const lines: string[] = [];\n lines.push('digraph LibpetriPinned {');\n lines.push(' rankdir=TB;');\n lines.push(' overlap=\"false\";');\n lines.push(' compound=\"true\";');\n lines.push(' fontname=\"Helvetica,Arial,sans-serif\";');\n lines.push(' outputorder=\"edgesfirst\";');\n lines.push(' node [fontname=\"Helvetica,Arial,sans-serif\", fontsize=10];');\n lines.push(' edge [fontname=\"Helvetica,Arial,sans-serif\", fontsize=9];');\n\n // Clusters with their pinned bounding boxes\n for (const [clusterId, cluster] of graph.clusters) {\n const box = layout.clusterBoxes.get(clusterId);\n lines.push(` subgraph ${clusterId} {`);\n lines.push(` label=${quote(cluster.shortName)};`);\n lines.push(` style=\"rounded,dashed\";`);\n lines.push(` bgcolor=\"#FAFAFA\";`);\n lines.push(` penwidth=1.5;`);\n if (box) {\n const x1 = box.x.toFixed(2);\n const y1 = box.y.toFixed(2);\n const x2 = (box.x + box.width).toFixed(2);\n const y2 = (box.y + box.height).toFixed(2);\n lines.push(` bb=${quote(`${x1},${y1},${x2},${y2}`)};`);\n }\n for (const nodeId of cluster.nodes) {\n const node = graph.nodes.get(nodeId);\n const pos = layout.nodePositions.get(nodeId);\n if (!node || !pos) continue;\n lines.push(' ' + nodeAttrLine(node, pos));\n }\n lines.push(' }');\n }\n\n // Orphans (root-level nodes) — laid out inside the synthetic\n // orchestrator cluster but emitted at root so they sit alongside the\n // real subnets without their own labelled box.\n for (const orphanId of graph.orphans) {\n const node = graph.nodes.get(orphanId);\n const pos = layout.nodePositions.get(orphanId);\n if (!node || !pos) continue;\n lines.push(' ' + nodeAttrLine(node, pos));\n }\n\n // Edges — emit just the source -> dest pair plus libpetri's original\n // styling attrs. Graphviz `nop` routes the line itself and clips arrow\n // heads to the visual node boundary.\n for (const edge of graph.edges) {\n lines.push(' ' + edgeAttrLine(edge.src, edge.dst, edge.rawAttrs));\n }\n\n lines.push('}');\n return lines.join('\\n');\n}\n"],"mappings":";AAkBA,SAAS,YAAY,mBAAmB;;;ACgDxC,SAAS,aAAa,IAAsB;AAC1C,MAAI,GAAG,WAAW,IAAI,EAAG,QAAO;AAChC,MAAI,GAAG,WAAW,IAAI,EAAG,QAAO;AAChC,SAAO;AACT;AAQA,SAAS,WAAW,MAAsC;AACxD,QAAM,QAAgC,CAAC;AACvC,aAAW,KAAK,KAAK,SAAS,0CAA0C,GAAG;AACzE,UAAM,CAAC,EAAE,KAAK,GAAG,IAAI;AACrB,UAAM,IAAI,IAAI,WAAW,GAAG,KAAK,IAAI,SAAS,GAAG,IAAI,IAAI,MAAM,GAAG,EAAE,IAAI;AACxE,UAAM,GAAG,IAAI;AAAA,EACf;AACA,SAAO;AACT;AAaO,SAAS,iBAAiB,KAAyB;AACxD,QAAM,QAAQ,oBAAI,IAAwB;AAM1C,aAAW,KAAK,IAAI,SAAS,6CAA6C,GAAG;AAC3E,UAAM,CAAC,EAAE,IAAI,IAAI,IAAI;AACrB,UAAM,IAAI,IAAI,EAAE,IAAI,MAAM,aAAa,EAAE,GAAG,OAAO,WAAW,IAAI,EAAE,CAAC;AAAA,EACvE;AAEA,QAAM,WAAW,o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AM,QAAQ;AAAA,MACZ,YAAY,iBAAiB,SAAS,GAAG,GAAG;AAAA,MAC5C,EAAE,KAAK,SAAS;AAAA,IAClB;AACA,UAAM,SAAS,MAAM,UAAU,KAAK;AACpC,gBAAY,UAAU,OAAO,MAAM;AACnC,uBAAmB,KAAK,SAAS;AAAA,EACnC;AACA,QAAM,MAAM,MAAM,OAAO;AACzB,SAAO,IAAI,iBAAiB,WAAW;AAAA,IACrC,QAAQ;AAAA,IACR,SAAS;AAAA,EACX,CAAC;AACH;","names":["stripped","label"]}
@@ -244,19 +244,8 @@ interface MountOptions {
244
244
  * and surface cluster overlay controls.
245
245
  *
246
246
  * The container's existing children are removed before the new SVG is
247
- * appended (the same teardown behaviour `renderDotToContainer` used to provide).
248
- *
249
- * Pass `dotSource === null` to adopt an SVG already present as a direct child
250
- * of `container` (pre-rendered SVG path — e.g. the Java javadoc taglet emits
251
- * `dot -Tsvg` at build time). In that mode the viewer never imports the
252
- * runtime DOT renderer, which lets the static IIFE bundle drop `@viz-js/viz`
253
- * entirely.
254
- *
255
- * NOTE: when shipping a pre-rendered SVG (`dotSource === null`), do NOT also
256
- * pass `previousHandle` — the handle's `dispose()` runs before SVG detection
257
- * and would orphan the host. The Java taglet mounts once per page so this is
258
- * a non-issue in practice.
247
+ * appended.
259
248
  */
260
- declare function mount(dotSource: string | null, container: HTMLElement, opts?: MountOptions): Promise<ViewerHandle>;
249
+ declare function mount(dotSource: string, container: HTMLElement, opts?: MountOptions): Promise<ViewerHandle>;
261
250
 
262
251
  export { type ClusterDescriptor, DEFAULT_PANZOOM_OPTS, type MountOptions, type PanzoomInstance, type PanzoomOptions, type SubnetVisibility, VIEWER_CSS_VARIABLES, type ViewerHandle, colorForPrefix, discoverClusters, mount };
@@ -698,21 +698,12 @@ async function mount(dotSource, container, opts = {}) {
698
698
  if (previousHandle) {
699
699
  previousHandle.dispose();
700
700
  }
701
- let svg;
702
- const existing = container.querySelector(":scope > svg");
703
- if (dotSource == null) {
704
- if (!(existing instanceof SVGSVGElement)) {
705
- throw new Error("mount: no DOT source and no pre-rendered SVG");
706
- }
707
- svg = existing;
708
- } else {
709
- const renderModule = await import("../render-QK57X4TP.js");
710
- const useElk = (opts.layout ?? "elk") === "elk";
711
- const renderedDot = subnetsMode === "hide" ? flattenClusters(dotSource) : dotSource;
712
- svg = useElk ? await renderModule.renderDotToSvgWithElkLayout(renderedDot) : await renderModule.renderDotToSvg(renderedDot);
713
- container.innerHTML = "";
714
- container.appendChild(svg);
715
- }
701
+ const renderModule = await import("../render-UY4OKXXQ.js");
702
+ const useElk = (opts.layout ?? "elk") === "elk";
703
+ const renderedDot = subnetsMode === "hide" ? flattenClusters(dotSource) : dotSource;
704
+ const svg = useElk ? await renderModule.renderDotToSvgWithElkLayout(renderedDot) : await renderModule.renderDotToSvg(renderedDot);
705
+ container.innerHTML = "";
706
+ container.appendChild(svg);
716
707
  container.classList.add("libpetri-viewer");
717
708
  const panzoomInstance = attachPanzoom(svg, opts.panzoom);
718
709
  const clusters = discoverClusters(svg);
@@ -757,10 +748,6 @@ async function mount(dotSource, container, opts = {}) {
757
748
  subnetsBtn.className = "diagram-btn btn-subnets";
758
749
  subnetsBtn.title = subnetsMode === "show" ? "Hide subnet groupings" : "Show subnet groupings";
759
750
  subnetsBtn.textContent = subnetsMode === "show" ? "Flat view" : "Subnets view";
760
- if (dotSource == null) {
761
- subnetsBtn.disabled = true;
762
- subnetsBtn.title = "Subnet toggle unavailable for pre-rendered SVG";
763
- }
764
751
  subnetsBtn.addEventListener("click", () => {
765
752
  void handle.toggleSubnets();
766
753
  });
@@ -801,7 +788,6 @@ async function mount(dotSource, container, opts = {}) {
801
788
  return subnetsMode;
802
789
  },
803
790
  setSubnets(mode) {
804
- if (dotSource == null) return Promise.resolve(handle);
805
791
  if (mode === subnetsMode) return Promise.resolve(handle);
806
792
  return mount(dotSource, container, {
807
793
  ...opts,