@webpieces/nx-webpieces-rules 0.3.340 → 0.3.342

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/nx-webpieces-rules",
3
- "version": "0.3.340",
3
+ "version": "0.3.342",
4
4
  "description": "Nx-specific webpieces validation rules and graph tooling. Bundles all @webpieces rule packages with Nx graph validators and an inference plugin.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -21,11 +21,11 @@
21
21
  "README.md"
22
22
  ],
23
23
  "dependencies": {
24
- "@webpieces/ai-hook-rules": "0.3.340",
25
- "@webpieces/code-rules": "0.3.340",
26
- "@webpieces/eslint-rules": "0.3.340",
27
- "@webpieces/pr-gate": "0.3.340",
28
- "@webpieces/rules-config": "0.3.340",
24
+ "@webpieces/ai-hook-rules": "0.3.342",
25
+ "@webpieces/code-rules": "0.3.342",
26
+ "@webpieces/eslint-rules": "0.3.342",
27
+ "@webpieces/pr-gate": "0.3.342",
28
+ "@webpieces/rules-config": "0.3.342",
29
29
  "madge": "8.0.0"
30
30
  },
31
31
  "peerDependencies": {
@@ -16,24 +16,17 @@ const graph_loader_1 = require("../../lib/graph-loader");
16
16
  const graph_metadata_1 = require("../../lib/graph-metadata");
17
17
  const api_scanner_1 = require("../../lib/api-usage/api-scanner");
18
18
  const graph_visualizer_1 = require("../../lib/graph-visualizer");
19
- const runtime_markers_1 = require("../../lib/runtime-markers");
20
19
  const runtime_graph_1 = require("../../lib/runtime-graph");
21
- const runtime_config_1 = require("../../lib/runtime-config");
22
20
  const toError_1 = require("../../toError");
23
21
  /**
24
- * Generate the runtime microservice graph alongside the compile-time graph, so
25
- * one regenerate produces both committed files. Skipped when the
26
- * runtime-architecture rule is OFF or no apiProjectPaths are configured.
22
+ * Generate the runtime microservice graph alongside the compile-time graph, from the SAME source
23
+ * scan (the derived apiRelations) — one regenerate produces both committed files. rpc APIs become
24
+ * direct runtime edges; pubsub APIs become edges the viz draws through a queue.
27
25
  */
28
- async function generateRuntimeGraph(workspaceRoot) {
29
- const config = (0, runtime_config_1.loadRuntimeConfig)(workspaceRoot);
30
- if (config.off || config.servicePaths.length === 0) {
31
- console.log('⏭️ Runtime graph skipped (runtime-architecture OFF or no servicePaths)');
32
- return;
33
- }
34
- console.log('📡 Generating runtime graph from service-contract.json files...');
35
- const model = await (0, runtime_markers_1.buildWorkspaceModel)(workspaceRoot, config.apiProjectPaths, config.servicePaths);
36
- const runtimeGraph = (0, runtime_graph_1.assembleRuntimeGraph)(model, workspaceRoot);
26
+ // webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file
27
+ function generateRuntimeGraph(workspaceRoot, scan) {
28
+ console.log('📡 Generating runtime graph from the source scan (implements × uses per API)...');
29
+ const runtimeGraph = (0, runtime_graph_1.assembleRuntimeGraphFromScan)(scan);
37
30
  (0, runtime_graph_1.saveRuntimeGraph)(runtimeGraph, workspaceRoot);
38
31
  const serviceCount = Object.keys(runtimeGraph.services).length;
39
32
  console.log(`✅ Runtime graph saved (${serviceCount} services, ${runtimeGraph.runtimeEdges.length} runtime edges)`);
@@ -60,7 +53,7 @@ async function runExecutor(options, context) {
60
53
  // scanning source, so dependencies.json + the viz + the runtime graph all
61
54
  // read the same derived truth.
62
55
  console.log('🔎 Scanning source for implements/uses API relations...');
63
- (0, api_scanner_1.scanAndAttachApiRelations)(workspaceRoot, enhancedGraph, projectInfos);
56
+ const scanResult = (0, api_scanner_1.scanAndAttachApiRelations)(workspaceRoot, enhancedGraph, projectInfos);
64
57
  // Step 4: Save the graph
65
58
  console.log('💾 Saving graph to architecture/dependencies.json...');
66
59
  (0, graph_loader_1.saveGraph)(enhancedGraph, workspaceRoot, graphPath);
@@ -69,8 +62,8 @@ async function runExecutor(options, context) {
69
62
  // dependencies.html regenerates in lock-step with dependencies.json.
70
63
  const vizPaths = new graph_visualizer_1.GraphVisualizer().writeVisualization(enhancedGraph, workspaceRoot);
71
64
  console.log(`✅ Wrote ${vizPaths.htmlPath}`);
72
- // Step 5: Generate the runtime microservice graph at the same time
73
- await generateRuntimeGraph(workspaceRoot);
65
+ // Step 5: Generate the runtime microservice graph from the same scan
66
+ generateRuntimeGraph(workspaceRoot, scanResult);
74
67
  // Print summary
75
68
  const projectCount = Object.keys(enhancedGraph).length;
76
69
  const levels = new Set(Object.values(enhancedGraph).map((e) => e.level));
@@ -1 +1 @@
1
- {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/generate/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;AA4CH,8BA+DC;AAxGD,0DAAwD;AACxD,+DAAiE;AACjE,yDAAgE;AAChE,yDAAmD;AACnD,6DAAoG;AACpG,iEAA4E;AAC5E,iEAA6D;AAC7D,+DAAgE;AAChE,2DAAiF;AACjF,6DAA6D;AAC7D,2CAAwC;AAUxC;;;;GAIG;AACH,KAAK,UAAU,oBAAoB,CAAC,aAAqB;IACrD,MAAM,MAAM,GAAG,IAAA,kCAAiB,EAAC,aAAa,CAAC,CAAC;IAChD,IAAI,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACjD,OAAO,CAAC,GAAG,CAAC,yEAAyE,CAAC,CAAC;QACvF,OAAO;IACX,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,iEAAiE,CAAC,CAAC;IAC/E,MAAM,KAAK,GAAG,MAAM,IAAA,qCAAmB,EAAC,aAAa,EAAE,MAAM,CAAC,eAAe,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC;IACpG,MAAM,YAAY,GAAG,IAAA,oCAAoB,EAAC,KAAK,EAAE,aAAa,CAAC,CAAC;IAChE,IAAA,gCAAgB,EAAC,YAAY,EAAE,aAAa,CAAC,CAAC;IAC9C,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ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AAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Generate Executor\n *\n * Generates the architecture dependency graph and saves it to architecture/dependencies.json.\n *\n * Usage:\n * nx run architecture:generate\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { writeTemplate } from '@webpieces/rules-config';\nimport { generateReducedGraph } from '../../lib/graph-generator';\nimport { sortGraphTopologically } from '../../lib/graph-sorter';\nimport { saveGraph } from '../../lib/graph-loader';\nimport { collectProjectInfo, enrichGraph, MetadataValidationError } from '../../lib/graph-metadata';\nimport { scanAndAttachApiRelations } from '../../lib/api-usage/api-scanner';\nimport { GraphVisualizer } from '../../lib/graph-visualizer';\nimport { buildWorkspaceModel } from '../../lib/runtime-markers';\nimport { assembleRuntimeGraph, saveRuntimeGraph } from '../../lib/runtime-graph';\nimport { loadRuntimeConfig } from '../../lib/runtime-config';\nimport { toError } from '../../toError';\n\nexport interface GenerateExecutorOptions {\n graphPath?: string;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n/**\n * Generate the runtime microservice graph alongside the compile-time graph, so\n * one regenerate produces both committed files. Skipped when the\n * runtime-architecture rule is OFF or no apiProjectPaths are configured.\n */\nasync function generateRuntimeGraph(workspaceRoot: string): Promise<void> {\n const config = loadRuntimeConfig(workspaceRoot);\n if (config.off || config.servicePaths.length === 0) {\n console.log('⏭️ Runtime graph skipped (runtime-architecture OFF or no servicePaths)');\n return;\n }\n console.log('📡 Generating runtime graph from service-contract.json files...');\n const model = await buildWorkspaceModel(workspaceRoot, config.apiProjectPaths, config.servicePaths);\n const runtimeGraph = assembleRuntimeGraph(model, workspaceRoot);\n saveRuntimeGraph(runtimeGraph, workspaceRoot);\n const serviceCount = Object.keys(runtimeGraph.services).length;\n console.log(\n `✅ Runtime graph saved (${serviceCount} services, ${runtimeGraph.runtimeEdges.length} runtime edges)`,\n );\n}\n\nexport default async function runExecutor(\n options: GenerateExecutorOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const graphPath = options.graphPath;\n const workspaceRoot = context.root;\n\n console.log('\\n📊 Architecture Graph Generator\\n');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Step 1: Build the full graph from nx, then transitively reduce it to the view\n console.log(\"📊 Generating dependency graph from nx's project graph...\");\n const reducedGraph = await generateReducedGraph();\n\n // Step 2: Topological sort (to assign levels for visualization)\n console.log('🔄 Computing topological layers...');\n const enhancedGraph = sortGraphTopologically(reducedGraph);\n\n // Step 3: Enrich with AI metadata (framework, shortDescription, file\n // pointers). This VALIDATES (responsibilities.md required per project)\n // and throws before any write, so a failure never clobbers the file.\n console.log('🏷️ Enriching graph with framework + responsibilities metadata...');\n const projectInfos = await collectProjectInfo();\n enrichGraph(enhancedGraph, projectInfos, workspaceRoot);\n\n // Step 3b: Classify each api-lib edge (implements/uses + rpc/pubsub) by\n // scanning source, so dependencies.json + the viz + the runtime graph all\n // read the same derived truth.\n console.log('🔎 Scanning source for implements/uses API relations...');\n scanAndAttachApiRelations(workspaceRoot, enhancedGraph, projectInfos);\n\n // Step 4: Save the graph\n console.log('💾 Saving graph to architecture/dependencies.json...');\n saveGraph(enhancedGraph, workspaceRoot, graphPath);\n console.log('✅ Graph saved successfully');\n\n // Step 4b: Write the committed, clickable HTML view next to the JSON so\n // dependencies.html regenerates in lock-step with dependencies.json.\n const vizPaths = new GraphVisualizer().writeVisualization(enhancedGraph, workspaceRoot);\n console.log(`✅ Wrote ${vizPaths.htmlPath}`);\n\n // Step 5: Generate the runtime microservice graph at the same time\n await generateRuntimeGraph(workspaceRoot);\n\n // Print summary\n const projectCount = Object.keys(enhancedGraph).length;\n const levels = new Set(Object.values(enhancedGraph).map((e) => e.level));\n console.log(`\\n📈 Graph Summary:`);\n console.log(` Projects: ${projectCount}`);\n console.log(` Levels: ${levels.size} (0-${Math.max(...levels)})`);\n\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n console.error('❌ Graph generation failed:', error.message);\n if (error instanceof MetadataValidationError) {\n const mdPath = writeTemplate(workspaceRoot, 'webpieces.responsibilities.md');\n console.error('');\n console.error('⚠️ *** Refer to ' + mdPath + ' for how to author responsibilities.md files *** ⚠️');\n }\n return { success: false };\n }\n}\n"]}
1
+ {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/generate/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;AAsCH,8BA+DC;AAlGD,0DAAwD;AACxD,+DAAiE;AACjE,yDAAgE;AAChE,yDAAmD;AACnD,6DAAoG;AACpG,iEAA4E;AAE5E,iEAA6D;AAC7D,2DAAyF;AACzF,2CAAwC;AAUxC;;;;GAIG;AACH,2GAA2G;AAC3G,SAAS,oBAAoB,CAAC,aAAqB,EAAE,IAAmB;IACpE,OAAO,CAAC,GAAG,CAAC,iFAAiF,CAAC,CAAC;IAC/F,MAAM,YAAY,GAAG,IAAA,4CAA4B,EAAC,IAAI,CAAC,CAAC;IACxD,IAAA,gCAAgB,EAAC,YAAY,EAAE,aAAa,CAAC,CAAC;IAC9C,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC;IAC/D,OAAO,CAAC,GAAG,CACP,0BAA0B,YAAY,cAAc,YAAY,CAAC,YAAY,CAAC,MAAM,iBAAiB,CACxG,CAAC;AACN,CAAC;AAEc,KAAK,UAAU,WAAW,CACrC,OAAgC,EAChC,OAAwB;IAExB,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;IACpC,MAAM,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;IAEnC,OAAO,CAAC,GAAG,CAAC,qCAAqC,CAAC,CAAC;IAEnD,8DAA8D;IAC9D,IAAI,CAAC;QACD,gFAAgF;QAChF,OAAO,CAAC,GAAG,CAAC,2DAA2D,CAAC,CAAC;QACzE,MAAM,YAAY,GAAG,MAAM,IAAA,sCAAoB,GAAE,CAAC;QAElD,gEAAgE;QAChE,O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GAAG,CAAC,qBAAqB,CAAC,CAAC;QACnC,OAAO,CAAC,GAAG,CAAC,gBAAgB,YAAY,EAAE,CAAC,CAAC;QAC5C,OAAO,CAAC,GAAG,CAAC,cAAc,MAAM,CAAC,IAAI,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAEpE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,KAAK,CAAC,4BAA4B,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAC3D,IAAI,KAAK,YAAY,wCAAuB,EAAE,CAAC;YAC3C,MAAM,MAAM,GAAG,IAAA,4BAAa,EAAC,aAAa,EAAE,+BAA+B,CAAC,CAAC;YAC7E,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAClB,OAAO,CAAC,KAAK,CAAC,mBAAmB,GAAG,MAAM,GAAG,qDAAqD,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Generate Executor\n *\n * Generates the architecture dependency graph and saves it to architecture/dependencies.json.\n *\n * Usage:\n * nx run architecture:generate\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { writeTemplate } from '@webpieces/rules-config';\nimport { generateReducedGraph } from '../../lib/graph-generator';\nimport { sortGraphTopologically } from '../../lib/graph-sorter';\nimport { saveGraph } from '../../lib/graph-loader';\nimport { collectProjectInfo, enrichGraph, MetadataValidationError } from '../../lib/graph-metadata';\nimport { scanAndAttachApiRelations } from '../../lib/api-usage/api-scanner';\nimport type { ApiScanResult } from '../../lib/api-usage/api-scanner';\nimport { GraphVisualizer } from '../../lib/graph-visualizer';\nimport { assembleRuntimeGraphFromScan, saveRuntimeGraph } from '../../lib/runtime-graph';\nimport { toError } from '../../toError';\n\nexport interface GenerateExecutorOptions {\n graphPath?: string;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n/**\n * Generate the runtime microservice graph alongside the compile-time graph, from the SAME source\n * scan (the derived apiRelations) — one regenerate produces both committed files. rpc APIs become\n * direct runtime edges; pubsub APIs become edges the viz draws through a queue.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nfunction generateRuntimeGraph(workspaceRoot: string, scan: ApiScanResult): void {\n console.log('📡 Generating runtime graph from the source scan (implements × uses per API)...');\n const runtimeGraph = assembleRuntimeGraphFromScan(scan);\n saveRuntimeGraph(runtimeGraph, workspaceRoot);\n const serviceCount = Object.keys(runtimeGraph.services).length;\n console.log(\n `✅ Runtime graph saved (${serviceCount} services, ${runtimeGraph.runtimeEdges.length} runtime edges)`,\n );\n}\n\nexport default async function runExecutor(\n options: GenerateExecutorOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const graphPath = options.graphPath;\n const workspaceRoot = context.root;\n\n console.log('\\n📊 Architecture Graph Generator\\n');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Step 1: Build the full graph from nx, then transitively reduce it to the view\n console.log(\"📊 Generating dependency graph from nx's project graph...\");\n const reducedGraph = await generateReducedGraph();\n\n // Step 2: Topological sort (to assign levels for visualization)\n console.log('🔄 Computing topological layers...');\n const enhancedGraph = sortGraphTopologically(reducedGraph);\n\n // Step 3: Enrich with AI metadata (framework, shortDescription, file\n // pointers). This VALIDATES (responsibilities.md required per project)\n // and throws before any write, so a failure never clobbers the file.\n console.log('🏷️ Enriching graph with framework + responsibilities metadata...');\n const projectInfos = await collectProjectInfo();\n enrichGraph(enhancedGraph, projectInfos, workspaceRoot);\n\n // Step 3b: Classify each api-lib edge (implements/uses + rpc/pubsub) by\n // scanning source, so dependencies.json + the viz + the runtime graph all\n // read the same derived truth.\n console.log('🔎 Scanning source for implements/uses API relations...');\n const scanResult = scanAndAttachApiRelations(workspaceRoot, enhancedGraph, projectInfos);\n\n // Step 4: Save the graph\n console.log('💾 Saving graph to architecture/dependencies.json...');\n saveGraph(enhancedGraph, workspaceRoot, graphPath);\n console.log('✅ Graph saved successfully');\n\n // Step 4b: Write the committed, clickable HTML view next to the JSON so\n // dependencies.html regenerates in lock-step with dependencies.json.\n const vizPaths = new GraphVisualizer().writeVisualization(enhancedGraph, workspaceRoot);\n console.log(`✅ Wrote ${vizPaths.htmlPath}`);\n\n // Step 5: Generate the runtime microservice graph from the same scan\n generateRuntimeGraph(workspaceRoot, scanResult);\n\n // Print summary\n const projectCount = Object.keys(enhancedGraph).length;\n const levels = new Set(Object.values(enhancedGraph).map((e) => e.level));\n console.log(`\\n📈 Graph Summary:`);\n console.log(` Projects: ${projectCount}`);\n console.log(` Levels: ${levels.size} (0-${Math.max(...levels)})`);\n\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n console.error('❌ Graph generation failed:', error.message);\n if (error instanceof MetadataValidationError) {\n const mdPath = writeTemplate(workspaceRoot, 'webpieces.responsibilities.md');\n console.error('');\n console.error('⚠️ *** Refer to ' + mdPath + ' for how to author responsibilities.md files *** ⚠️');\n }\n return { success: false };\n }\n}\n"]}
@@ -10,6 +10,8 @@
10
10
  * dependencies.json (both Z and X only compile-depend on the api library Y).
11
11
  */
12
12
  import type { WorkspaceModel } from './runtime-markers';
13
+ import type { ApiScanResult } from './api-usage/api-scanner';
14
+ import type { ApiTransport } from './api-usage/api-relations';
13
15
  export declare const DEFAULT_RUNTIME_GRAPH_PATH = "architecture/runtime-dependencies.json";
14
16
  export interface RuntimeService {
15
17
  level: number;
@@ -20,11 +22,19 @@ export interface RuntimeService {
20
22
  export interface RuntimeApi {
21
23
  implementedBy: string[];
22
24
  usedBy: string[];
25
+ /** Transport of this API — 'rpc' (direct call) or 'pubsub' (delivered through a queue). */
26
+ type?: ApiTransport;
23
27
  }
24
28
  export interface RuntimeEdge {
25
29
  from: string;
26
30
  to: string;
27
31
  via: string[];
32
+ /**
33
+ * Transport of this edge. 'rpc' → a direct call arrow. 'pubsub' → the producer enqueues and the
34
+ * consumer is delivered later, so the runtime viz draws it as producer → QUEUE → consumer.
35
+ * Edges are split by transport, so every edge is a single kind.
36
+ */
37
+ type?: ApiTransport;
28
38
  }
29
39
  export interface RuntimeUnresolved {
30
40
  service: string;
@@ -40,6 +50,8 @@ export interface RuntimeGraph {
40
50
  export declare function runtimeAdjacency(graph: RuntimeGraph): Record<string, string[]>;
41
51
  /** Assemble the full runtime graph from the workspace model + service contracts. */
42
52
  export declare function assembleRuntimeGraph(model: WorkspaceModel, workspaceRoot: string): RuntimeGraph;
53
+ /** Assemble the runtime graph from the source scan (the derived apiRelations). */
54
+ export declare function assembleRuntimeGraphFromScan(scan: ApiScanResult): RuntimeGraph;
43
55
  export declare function saveRuntimeGraph(graph: RuntimeGraph, workspaceRoot: string, graphPath?: string): void;
44
56
  export declare function runtimeGraphFileExists(workspaceRoot: string, graphPath?: string): boolean;
45
57
  export declare function loadRuntimeGraph(workspaceRoot: string, graphPath?: string): RuntimeGraph | null;
@@ -14,6 +14,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
14
14
  exports.DEFAULT_RUNTIME_GRAPH_PATH = void 0;
15
15
  exports.runtimeAdjacency = runtimeAdjacency;
16
16
  exports.assembleRuntimeGraph = assembleRuntimeGraph;
17
+ exports.assembleRuntimeGraphFromScan = assembleRuntimeGraphFromScan;
17
18
  exports.saveRuntimeGraph = saveRuntimeGraph;
18
19
  exports.runtimeGraphFileExists = runtimeGraphFileExists;
19
20
  exports.loadRuntimeGraph = loadRuntimeGraph;
@@ -23,6 +24,7 @@ const fs = tslib_1.__importStar(require("fs"));
23
24
  const path = tslib_1.__importStar(require("path"));
24
25
  const graph_sorter_1 = require("./graph-sorter");
25
26
  const runtime_markers_1 = require("./runtime-markers");
27
+ const api_relations_1 = require("./api-usage/api-relations");
26
28
  const toError_1 = require("../toError");
27
29
  exports.DEFAULT_RUNTIME_GRAPH_PATH = 'architecture/runtime-dependencies.json';
28
30
  /** Collect every service project (servicePaths), with its declarations resolved to projects. */
@@ -152,6 +154,124 @@ function assembleRuntimeGraph(model, workspaceRoot) {
152
154
  unresolvedUses: edgeResult.unresolved,
153
155
  };
154
156
  }
157
+ /**
158
+ * Assembles the runtime microservice graph from the SOURCE SCAN (apiRelations) instead of
159
+ * service-contract.json: implementers × users per API, split by transport. An rpc edge is a direct
160
+ * call; a pubsub edge flows through a queue (drawn producer → queue → consumer by the visualizer).
161
+ */
162
+ class ScanRuntimeAssembler {
163
+ scan;
164
+ constructor(scan) {
165
+ this.scan = scan;
166
+ }
167
+ assemble() {
168
+ const decls = this.collectDecls();
169
+ const apis = this.buildApis(decls);
170
+ const edgeResult = this.buildEdges(decls, apis);
171
+ const services = this.buildServices(decls, edgeResult.edges);
172
+ const apisObj = {};
173
+ for (const api of Array.from(apis.keys()).sort())
174
+ apisObj[api] = apis.get(api);
175
+ return { services, apis: apisObj, runtimeEdges: edgeResult.edges, unresolvedUses: edgeResult.unresolved };
176
+ }
177
+ /** Flatten each project's api-lib relations into implements/uses ApiRef lists. */
178
+ collectDecls() {
179
+ const decls = [];
180
+ for (const name of Array.from(this.scan.relationsByProject.keys()).sort()) {
181
+ const relations = this.scan.relationsByProject.get(name);
182
+ const implementsApis = [];
183
+ const usesApis = [];
184
+ for (const owner of Object.keys(relations)) {
185
+ implementsApis.push(...relations[owner].implements);
186
+ usesApis.push(...relations[owner].uses);
187
+ }
188
+ if (implementsApis.length > 0 || usesApis.length > 0) {
189
+ decls.push({ name, implementsApis: (0, api_relations_1.sortApiRefs)(implementsApis), usesApis: (0, api_relations_1.sortApiRefs)(usesApis) });
190
+ }
191
+ }
192
+ return decls;
193
+ }
194
+ /** apiClassName -> { implementedBy, usedBy, type }. */
195
+ buildApis(decls) {
196
+ const apis = new Map();
197
+ const ensure = (api, type) => {
198
+ let entry = apis.get(api);
199
+ if (!entry) {
200
+ entry = { implementedBy: [], usedBy: [], type };
201
+ apis.set(api, entry);
202
+ }
203
+ return entry;
204
+ };
205
+ for (const decl of decls) {
206
+ for (const ref of decl.implementsApis)
207
+ ensure(ref.api, ref.type).implementedBy.push(decl.name);
208
+ for (const ref of decl.usesApis)
209
+ ensure(ref.api, ref.type).usedBy.push(decl.name);
210
+ }
211
+ for (const entry of apis.values()) {
212
+ entry.implementedBy.sort();
213
+ entry.usedBy.sort();
214
+ }
215
+ return apis;
216
+ }
217
+ /** Inferred edges U -> I via api A, split by transport; plus uses with no implementer. */
218
+ buildEdges(decls, apis) {
219
+ const viaByKey = new Map();
220
+ const unresolved = [];
221
+ for (const decl of decls) {
222
+ for (const ref of decl.usesApis) {
223
+ const implementers = apis.get(ref.api)?.implementedBy ?? [];
224
+ if (implementers.length === 0) {
225
+ unresolved.push({ service: decl.name, api: ref.api });
226
+ continue;
227
+ }
228
+ for (const target of implementers) {
229
+ if (target === decl.name)
230
+ continue;
231
+ const key = `${decl.name}${target}${ref.type}`;
232
+ if (!viaByKey.has(key))
233
+ viaByKey.set(key, new Set());
234
+ viaByKey.get(key).add(ref.api);
235
+ }
236
+ }
237
+ }
238
+ return { edges: this.edgesFromKeys(viaByKey), unresolved: sortUnresolved(unresolved) };
239
+ }
240
+ edgesFromKeys(viaByKey) {
241
+ const edges = [];
242
+ for (const key of viaByKey.keys()) {
243
+ const parts = key.split('');
244
+ edges.push({ from: parts[0], to: parts[1], via: Array.from(viaByKey.get(key)).sort(), type: parts[2] });
245
+ }
246
+ edges.sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to) || (a.type ?? '').localeCompare(b.type ?? ''));
247
+ return edges;
248
+ }
249
+ buildServices(decls, edges) {
250
+ const services = {};
251
+ for (const decl of decls) {
252
+ const dependsOn = Array.from(new Set(edges.filter((e) => e.from === decl.name).map((e) => e.to))).sort();
253
+ services[decl.name] = {
254
+ level: 0,
255
+ implements: decl.implementsApis.map((r) => r.api),
256
+ uses: decl.usesApis.map((r) => r.api),
257
+ dependsOn,
258
+ };
259
+ }
260
+ const levels = assignLevels(adjacencyFromEdges(Object.keys(services), edges));
261
+ for (const name of Object.keys(services))
262
+ services[name].level = levels[name] ?? 0;
263
+ return services;
264
+ }
265
+ }
266
+ /** Assemble the runtime graph from the source scan (the derived apiRelations). */
267
+ // webpieces-disable no-function-outside-class -- module entry point, mirrors assembleRuntimeGraph
268
+ function assembleRuntimeGraphFromScan(scan) {
269
+ return new ScanRuntimeAssembler(scan).assemble();
270
+ }
271
+ // webpieces-disable no-function-outside-class -- pure sort helper, matches the sibling helpers in this file
272
+ function sortUnresolved(unresolved) {
273
+ return [...unresolved].sort((a, b) => a.service.localeCompare(b.service) || a.api.localeCompare(b.api));
274
+ }
155
275
  /** Deterministic JSON (sorted keys + arrays already sorted during assembly). */
156
276
  function formatRuntimeJson(graph) {
157
277
  return JSON.stringify(graph, null, 4) + '\n';
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-graph.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/runtime-graph.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AA2IH,4CAEC;AAkBD,oDAyBC;AAOD,4CASC;AAED,wDAKC;AAED,4CAaC;AAGD,sDAEC;;AAjOD,+CAAyB;AACzB,mDAA6B;AAC7B,iDAAwD;AACxD,uDAA6E;AAE7E,wCAAqC;AAExB,QAAA,0BAA0B,GAAG,wCAAwC,CAAC;AA4CnF,gGAAgG;AAChG,SAAS,mBAAmB,CAAC,KAAqB,EAAE,aAAqB;IACrE,MAAM,KAAK,GAAkB,EAAE,CAAC;IAChC,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;QACzC,IAAI,CAAC,IAAI,CAAC,SAAS;YAAE,SAAS;QAC9B,wEAAwE;QACxE,qEAAqE;QACrE,MAAM,QAAQ,GAAG,IAAA,qCAAmB,EAAC,aAAa,EAAE,IAAI,CAAC,IAAI,CAA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iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,MAAM,IAAI,KAAK,CAAC,qCAAqC,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACvF,CAAC;AACL,CAAC;AAED,8EAA8E;AAC9E,SAAgB,qBAAqB,CAAC,KAAmB;IACrD,OAAO,iBAAiB,CAAC,KAAK,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * Runtime Graph\n *\n * Assembles the runtime microservice graph from the per-service\n * `service-contract.json` files, and saves/loads the committed\n * `architecture/runtime-dependencies.json`.\n *\n * The runtime edge Z -> X (Z depends on X at runtime) is INFERRED: Z `uses` api\n * Y and X `implements` api Y. This edge does not exist in the compile-time\n * dependencies.json (both Z and X only compile-depend on the api library Y).\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { sortGraphTopologically } from './graph-sorter';\nimport { readServiceContract, resolvePackageNames } from './runtime-markers';\nimport type { WorkspaceModel } from './runtime-markers';\nimport { toError } from '../toError';\n\nexport const DEFAULT_RUNTIME_GRAPH_PATH = 'architecture/runtime-dependencies.json';\n\nexport interface RuntimeService {\n level: number;\n implements: string[];\n uses: string[];\n dependsOn: string[];\n}\n\nexport interface RuntimeApi {\n implementedBy: string[];\n usedBy: string[];\n}\n\nexport interface RuntimeEdge {\n from: string;\n to: string;\n via: string[];\n}\n\nexport interface RuntimeUnresolved {\n service: string;\n api: string;\n}\n\nexport interface RuntimeGraph {\n services: Record<string, RuntimeService>;\n apis: Record<string, RuntimeApi>;\n runtimeEdges: RuntimeEdge[];\n unresolvedUses: RuntimeUnresolved[];\n}\n\n/** One service's declared relationships, resolved to workspace project names. */\ninterface ServiceDecl {\n name: string;\n implements: string[];\n uses: string[];\n}\n\ninterface EdgeResult {\n edges: RuntimeEdge[];\n unresolved: RuntimeUnresolved[];\n}\n\n/** Collect every service project (servicePaths), with its declarations resolved to projects. */\nfunction collectServiceDecls(model: WorkspaceModel, workspaceRoot: string): ServiceDecl[] {\n const decls: ServiceDecl[] = [];\n for (const info of model.projects.values()) {\n if (!info.isService) continue;\n // A service missing its contract still appears as a node (empty edges);\n // validate-runtime-markers fails it separately for the missing file.\n const contract = readServiceContract(workspaceRoot, info.root);\n const implementsPkgs = contract ? contract.implements : [];\n const usesPkgs = contract ? contract.uses : [];\n decls.push({\n name: info.name,\n implements: resolvePackageNames(model, implementsPkgs).projects.sort(),\n uses: resolvePackageNames(model, usesPkgs).projects.sort(),\n });\n }\n return decls.sort((a: ServiceDecl, b: ServiceDecl) => a.name.localeCompare(b.name));\n}\n\nfunction buildApiIndex(decls: ServiceDecl[]): Map<string, RuntimeApi> {\n const apis = new Map<string, RuntimeApi>();\n const ensure = (api: string): RuntimeApi => {\n let entry = apis.get(api);\n if (!entry) {\n entry = { implementedBy: [], usedBy: [] };\n apis.set(api, entry);\n }\n return entry;\n };\n for (const decl of decls) {\n for (const api of decl.implements) ensure(api).implementedBy.push(decl.name);\n for (const api of decl.uses) ensure(api).usedBy.push(decl.name);\n }\n for (const entry of apis.values()) {\n entry.implementedBy.sort();\n entry.usedBy.sort();\n }\n return apis;\n}\n\n/** Build inferred runtime edges (Z -> X via Y) and the unresolved-uses list. */\nfunction buildEdges(decls: ServiceDecl[], apis: Map<string, RuntimeApi>): EdgeResult {\n const viaByEdge = new Map<string, Set<string>>();\n const unresolved: RuntimeUnresolved[] = [];\n\n for (const decl of decls) {\n for (const api of decl.uses) {\n const implementers = apis.get(api)?.implementedBy ?? [];\n if (implementers.length === 0) {\n unresolved.push({ service: decl.name, api });\n continue;\n }\n for (const target of implementers) {\n if (target === decl.name) continue;\n const key = `${decl.name} ${target}`;\n if (!viaByEdge.has(key)) viaByEdge.set(key, new Set());\n viaByEdge.get(key)!.add(api);\n }\n }\n }\n\n const edges: RuntimeEdge[] = [];\n for (const key of viaByEdge.keys()) {\n const parts = key.split(' ');\n edges.push({ from: parts[0], to: parts[1], via: Array.from(viaByEdge.get(key)!).sort() });\n }\n edges.sort((a: RuntimeEdge, b: RuntimeEdge) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to));\n unresolved.sort(\n (a: RuntimeUnresolved, b: RuntimeUnresolved) =>\n a.service.localeCompare(b.service) || a.api.localeCompare(b.api),\n );\n return { edges, unresolved };\n}\n\n/** Adjacency (service -> [targets]) used for leveling + cycle checks. */\nfunction adjacencyFromEdges(serviceNames: string[], edges: RuntimeEdge[]): Record<string, string[]> {\n const adj: Record<string, string[]> = {};\n for (const name of serviceNames) adj[name] = [];\n for (const edge of edges) {\n if (!adj[edge.from]) adj[edge.from] = [];\n adj[edge.from].push(edge.to);\n }\n return adj;\n}\n\n/** Adjacency (service -> [targets]) from a loaded runtime graph. */\nexport function runtimeAdjacency(graph: RuntimeGraph): Record<string, string[]> {\n return adjacencyFromEdges(Object.keys(graph.services), graph.runtimeEdges);\n}\n\n/** Assign levels via topological sort; falls back to level 0 when a cycle exists. */\nfunction assignLevels(adjacency: Record<string, string[]>): Record<string, number> {\n const levels: Record<string, number> = {};\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const sorted = sortGraphTopologically(adjacency);\n for (const name of Object.keys(sorted)) levels[name] = sorted[name].level;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n for (const name of Object.keys(adjacency)) levels[name] = 0;\n }\n return levels;\n}\n\n/** Assemble the full runtime graph from the workspace model + service contracts. */\nexport function assembleRuntimeGraph(model: WorkspaceModel, workspaceRoot: string): RuntimeGraph {\n const decls = collectServiceDecls(model, workspaceRoot);\n const apis = buildApiIndex(decls);\n const edgeResult = buildEdges(decls, apis);\n\n const services: Record<string, RuntimeService> = {};\n for (const decl of decls) {\n const dependsOn = Array.from(\n new Set(edgeResult.edges.filter((e: RuntimeEdge) => e.from === decl.name).map((e: RuntimeEdge) => e.to)),\n ).sort();\n services[decl.name] = { level: 0, implements: decl.implements, uses: decl.uses, dependsOn };\n }\n\n const levels = assignLevels(adjacencyFromEdges(Object.keys(services), edgeResult.edges));\n for (const name of Object.keys(services)) services[name].level = levels[name] ?? 0;\n\n const apisObj: Record<string, RuntimeApi> = {};\n for (const api of Array.from(apis.keys()).sort()) apisObj[api] = apis.get(api)!;\n\n return {\n services,\n apis: apisObj,\n runtimeEdges: edgeResult.edges,\n unresolvedUses: edgeResult.unresolved,\n };\n}\n\n/** Deterministic JSON (sorted keys + arrays already sorted during assembly). */\nfunction formatRuntimeJson(graph: RuntimeGraph): string {\n return JSON.stringify(graph, null, 4) + '\\n';\n}\n\nexport function saveRuntimeGraph(\n graph: RuntimeGraph,\n workspaceRoot: string,\n graphPath: string = DEFAULT_RUNTIME_GRAPH_PATH,\n): void {\n const fullPath = path.join(workspaceRoot, graphPath);\n const dir = path.dirname(fullPath);\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(fullPath, formatRuntimeJson(graph), 'utf-8');\n}\n\nexport function runtimeGraphFileExists(\n workspaceRoot: string,\n graphPath: string = DEFAULT_RUNTIME_GRAPH_PATH,\n): boolean {\n return fs.existsSync(path.join(workspaceRoot, graphPath));\n}\n\nexport function loadRuntimeGraph(\n workspaceRoot: string,\n graphPath: string = DEFAULT_RUNTIME_GRAPH_PATH,\n): RuntimeGraph | null {\n const fullPath = path.join(workspaceRoot, graphPath);\n if (!fs.existsSync(fullPath)) return null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return JSON.parse(fs.readFileSync(fullPath, 'utf-8')) as RuntimeGraph;\n } catch (err: unknown) {\n const error = toError(err);\n throw new Error(`Failed to load runtime graph from ${fullPath}`, { cause: error });\n }\n}\n\n/** Serialize for an in-memory equality check (matches the on-disk format). */\nexport function serializeRuntimeGraph(graph: RuntimeGraph): string {\n return formatRuntimeJson(graph);\n}\n"]}
1
+ {"version":3,"file":"runtime-graph.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/runtime-graph.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AAsJH,4CAEC;AAkBD,oD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CAAC,QAAQ,EAAE,iBAAiB,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;AAClE,CAAC;AAED,SAAgB,sBAAsB,CAClC,aAAqB,EACrB,YAAoB,kCAA0B;IAE9C,OAAO,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC,CAAC;AAC9D,CAAC;AAED,SAAgB,gBAAgB,CAC5B,aAAqB,EACrB,YAAoB,kCAA0B;IAE9C,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;IACrD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1C,8DAA8D;IAC9D,IAAI,CAAC;QACD,OAAO,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAiB,CAAC;IAC1E,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,MAAM,IAAI,KAAK,CAAC,qCAAqC,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACvF,CAAC;AACL,CAAC;AAED,8EAA8E;AAC9E,SAAgB,qBAAqB,CAAC,KAAmB;IACrD,OAAO,iBAAiB,CAAC,KAAK,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * Runtime Graph\n *\n * Assembles the runtime microservice graph from the per-service\n * `service-contract.json` files, and saves/loads the committed\n * `architecture/runtime-dependencies.json`.\n *\n * The runtime edge Z -> X (Z depends on X at runtime) is INFERRED: Z `uses` api\n * Y and X `implements` api Y. This edge does not exist in the compile-time\n * dependencies.json (both Z and X only compile-depend on the api library Y).\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { sortGraphTopologically } from './graph-sorter';\nimport { readServiceContract, resolvePackageNames } from './runtime-markers';\nimport type { WorkspaceModel } from './runtime-markers';\nimport type { ApiScanResult } from './api-usage/api-scanner';\nimport type { ApiRef, ApiTransport } from './api-usage/api-relations';\nimport { sortApiRefs } from './api-usage/api-relations';\nimport { toError } from '../toError';\n\nexport const DEFAULT_RUNTIME_GRAPH_PATH = 'architecture/runtime-dependencies.json';\n\nexport interface RuntimeService {\n level: number;\n implements: string[];\n uses: string[];\n dependsOn: string[];\n}\n\nexport interface RuntimeApi {\n implementedBy: string[];\n usedBy: string[];\n /** Transport of this API — 'rpc' (direct call) or 'pubsub' (delivered through a queue). */\n type?: ApiTransport;\n}\n\nexport interface RuntimeEdge {\n from: string;\n to: string;\n via: string[];\n /**\n * Transport of this edge. 'rpc' → a direct call arrow. 'pubsub' → the producer enqueues and the\n * consumer is delivered later, so the runtime viz draws it as producer → QUEUE → consumer.\n * Edges are split by transport, so every edge is a single kind.\n */\n type?: ApiTransport;\n}\n\nexport interface RuntimeUnresolved {\n service: string;\n api: string;\n}\n\nexport interface RuntimeGraph {\n services: Record<string, RuntimeService>;\n apis: Record<string, RuntimeApi>;\n runtimeEdges: RuntimeEdge[];\n unresolvedUses: RuntimeUnresolved[];\n}\n\n/** One service's declared relationships, resolved to workspace project names. */\ninterface ServiceDecl {\n name: string;\n implements: string[];\n uses: string[];\n}\n\ninterface EdgeResult {\n edges: RuntimeEdge[];\n unresolved: RuntimeUnresolved[];\n}\n\n/** Collect every service project (servicePaths), with its declarations resolved to projects. */\nfunction collectServiceDecls(model: WorkspaceModel, workspaceRoot: string): ServiceDecl[] {\n const decls: ServiceDecl[] = [];\n for (const info of model.projects.values()) {\n if (!info.isService) continue;\n // A service missing its contract still appears as a node (empty edges);\n // validate-runtime-markers fails it separately for the missing file.\n const contract = readServiceContract(workspaceRoot, info.root);\n const implementsPkgs = contract ? contract.implements : [];\n const usesPkgs = contract ? contract.uses : [];\n decls.push({\n name: info.name,\n implements: resolvePackageNames(model, implementsPkgs).projects.sort(),\n uses: resolvePackageNames(model, usesPkgs).projects.sort(),\n });\n }\n return decls.sort((a: ServiceDecl, b: ServiceDecl) => a.name.localeCompare(b.name));\n}\n\nfunction buildApiIndex(decls: ServiceDecl[]): Map<string, RuntimeApi> {\n const apis = new Map<string, RuntimeApi>();\n const ensure = (api: string): RuntimeApi => {\n let entry = apis.get(api);\n if (!entry) {\n entry = { implementedBy: [], usedBy: [] };\n apis.set(api, entry);\n }\n return entry;\n };\n for (const decl of decls) {\n for (const api of decl.implements) ensure(api).implementedBy.push(decl.name);\n for (const api of decl.uses) ensure(api).usedBy.push(decl.name);\n }\n for (const entry of apis.values()) {\n entry.implementedBy.sort();\n entry.usedBy.sort();\n }\n return apis;\n}\n\n/** Build inferred runtime edges (Z -> X via Y) and the unresolved-uses list. */\nfunction buildEdges(decls: ServiceDecl[], apis: Map<string, RuntimeApi>): EdgeResult {\n const viaByEdge = new Map<string, Set<string>>();\n const unresolved: RuntimeUnresolved[] = [];\n\n for (const decl of decls) {\n for (const api of decl.uses) {\n const implementers = apis.get(api)?.implementedBy ?? [];\n if (implementers.length === 0) {\n unresolved.push({ service: decl.name, api });\n continue;\n }\n for (const target of implementers) {\n if (target === decl.name) continue;\n const key = `${decl.name} ${target}`;\n if (!viaByEdge.has(key)) viaByEdge.set(key, new Set());\n viaByEdge.get(key)!.add(api);\n }\n }\n }\n\n const edges: RuntimeEdge[] = [];\n for (const key of viaByEdge.keys()) {\n const parts = key.split(' ');\n edges.push({ from: parts[0], to: parts[1], via: Array.from(viaByEdge.get(key)!).sort() });\n }\n edges.sort((a: RuntimeEdge, b: RuntimeEdge) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to));\n unresolved.sort(\n (a: RuntimeUnresolved, b: RuntimeUnresolved) =>\n a.service.localeCompare(b.service) || a.api.localeCompare(b.api),\n );\n return { edges, unresolved };\n}\n\n/** Adjacency (service -> [targets]) used for leveling + cycle checks. */\nfunction adjacencyFromEdges(serviceNames: string[], edges: RuntimeEdge[]): Record<string, string[]> {\n const adj: Record<string, string[]> = {};\n for (const name of serviceNames) adj[name] = [];\n for (const edge of edges) {\n if (!adj[edge.from]) adj[edge.from] = [];\n adj[edge.from].push(edge.to);\n }\n return adj;\n}\n\n/** Adjacency (service -> [targets]) from a loaded runtime graph. */\nexport function runtimeAdjacency(graph: RuntimeGraph): Record<string, string[]> {\n return adjacencyFromEdges(Object.keys(graph.services), graph.runtimeEdges);\n}\n\n/** Assign levels via topological sort; falls back to level 0 when a cycle exists. */\nfunction assignLevels(adjacency: Record<string, string[]>): Record<string, number> {\n const levels: Record<string, number> = {};\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const sorted = sortGraphTopologically(adjacency);\n for (const name of Object.keys(sorted)) levels[name] = sorted[name].level;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n for (const name of Object.keys(adjacency)) levels[name] = 0;\n }\n return levels;\n}\n\n/** Assemble the full runtime graph from the workspace model + service contracts. */\nexport function assembleRuntimeGraph(model: WorkspaceModel, workspaceRoot: string): RuntimeGraph {\n const decls = collectServiceDecls(model, workspaceRoot);\n const apis = buildApiIndex(decls);\n const edgeResult = buildEdges(decls, apis);\n\n const services: Record<string, RuntimeService> = {};\n for (const decl of decls) {\n const dependsOn = Array.from(\n new Set(edgeResult.edges.filter((e: RuntimeEdge) => e.from === decl.name).map((e: RuntimeEdge) => e.to)),\n ).sort();\n services[decl.name] = { level: 0, implements: decl.implements, uses: decl.uses, dependsOn };\n }\n\n const levels = assignLevels(adjacencyFromEdges(Object.keys(services), edgeResult.edges));\n for (const name of Object.keys(services)) services[name].level = levels[name] ?? 0;\n\n const apisObj: Record<string, RuntimeApi> = {};\n for (const api of Array.from(apis.keys()).sort()) apisObj[api] = apis.get(api)!;\n\n return {\n services,\n apis: apisObj,\n runtimeEdges: edgeResult.edges,\n unresolvedUses: edgeResult.unresolved,\n };\n}\n\n/** One project's implements/uses at api-CLASS granularity, from the source scan. */\ninterface ScanDecl {\n name: string;\n implementsApis: ApiRef[];\n usesApis: ApiRef[];\n}\n\n/**\n * Assembles the runtime microservice graph from the SOURCE SCAN (apiRelations) instead of\n * service-contract.json: implementers × users per API, split by transport. An rpc edge is a direct\n * call; a pubsub edge flows through a queue (drawn producer → queue → consumer by the visualizer).\n */\nclass ScanRuntimeAssembler {\n constructor(private readonly scan: ApiScanResult) {}\n\n assemble(): RuntimeGraph {\n const decls = this.collectDecls();\n const apis = this.buildApis(decls);\n const edgeResult = this.buildEdges(decls, apis);\n const services = this.buildServices(decls, edgeResult.edges);\n const apisObj: Record<string, RuntimeApi> = {};\n for (const api of Array.from(apis.keys()).sort()) apisObj[api] = apis.get(api)!;\n return { services, apis: apisObj, runtimeEdges: edgeResult.edges, unresolvedUses: edgeResult.unresolved };\n }\n\n /** Flatten each project's api-lib relations into implements/uses ApiRef lists. */\n private collectDecls(): ScanDecl[] {\n const decls: ScanDecl[] = [];\n for (const name of Array.from(this.scan.relationsByProject.keys()).sort()) {\n const relations = this.scan.relationsByProject.get(name)!;\n const implementsApis: ApiRef[] = [];\n const usesApis: ApiRef[] = [];\n for (const owner of Object.keys(relations)) {\n implementsApis.push(...relations[owner].implements);\n usesApis.push(...relations[owner].uses);\n }\n if (implementsApis.length > 0 || usesApis.length > 0) {\n decls.push({ name, implementsApis: sortApiRefs(implementsApis), usesApis: sortApiRefs(usesApis) });\n }\n }\n return decls;\n }\n\n /** apiClassName -> { implementedBy, usedBy, type }. */\n private buildApis(decls: ScanDecl[]): Map<string, RuntimeApi> {\n const apis = new Map<string, RuntimeApi>();\n const ensure = (api: string, type: ApiTransport): RuntimeApi => {\n let entry = apis.get(api);\n if (!entry) {\n entry = { implementedBy: [], usedBy: [], type };\n apis.set(api, entry);\n }\n return entry;\n };\n for (const decl of decls) {\n for (const ref of decl.implementsApis) ensure(ref.api, ref.type).implementedBy.push(decl.name);\n for (const ref of decl.usesApis) ensure(ref.api, ref.type).usedBy.push(decl.name);\n }\n for (const entry of apis.values()) {\n entry.implementedBy.sort();\n entry.usedBy.sort();\n }\n return apis;\n }\n\n /** Inferred edges U -> I via api A, split by transport; plus uses with no implementer. */\n private buildEdges(decls: ScanDecl[], apis: Map<string, RuntimeApi>): EdgeResult {\n const viaByKey = new Map<string, Set<string>>();\n const unresolved: RuntimeUnresolved[] = [];\n for (const decl of decls) {\n for (const ref of decl.usesApis) {\n const implementers = apis.get(ref.api)?.implementedBy ?? [];\n if (implementers.length === 0) {\n unresolved.push({ service: decl.name, api: ref.api });\n continue;\n }\n for (const target of implementers) {\n if (target === decl.name) continue;\n const key = `${decl.name}\u0000${target}\u0000${ref.type}`;\n if (!viaByKey.has(key)) viaByKey.set(key, new Set());\n viaByKey.get(key)!.add(ref.api);\n }\n }\n }\n return { edges: this.edgesFromKeys(viaByKey), unresolved: sortUnresolved(unresolved) };\n }\n\n private edgesFromKeys(viaByKey: Map<string, Set<string>>): RuntimeEdge[] {\n const edges: RuntimeEdge[] = [];\n for (const key of viaByKey.keys()) {\n const parts = key.split('\u0000');\n edges.push({ from: parts[0], to: parts[1], via: Array.from(viaByKey.get(key)!).sort(), type: parts[2] as ApiTransport });\n }\n edges.sort(\n (a: RuntimeEdge, b: RuntimeEdge) =>\n a.from.localeCompare(b.from) || a.to.localeCompare(b.to) || (a.type ?? '').localeCompare(b.type ?? ''),\n );\n return edges;\n }\n\n private buildServices(decls: ScanDecl[], edges: RuntimeEdge[]): Record<string, RuntimeService> {\n const services: Record<string, RuntimeService> = {};\n for (const decl of decls) {\n const dependsOn = Array.from(\n new Set(edges.filter((e: RuntimeEdge) => e.from === decl.name).map((e: RuntimeEdge) => e.to)),\n ).sort();\n services[decl.name] = {\n level: 0,\n implements: decl.implementsApis.map((r: ApiRef) => r.api),\n uses: decl.usesApis.map((r: ApiRef) => r.api),\n dependsOn,\n };\n }\n const levels = assignLevels(adjacencyFromEdges(Object.keys(services), edges));\n for (const name of Object.keys(services)) services[name].level = levels[name] ?? 0;\n return services;\n }\n}\n\n/** Assemble the runtime graph from the source scan (the derived apiRelations). */\n// webpieces-disable no-function-outside-class -- module entry point, mirrors assembleRuntimeGraph\nexport function assembleRuntimeGraphFromScan(scan: ApiScanResult): RuntimeGraph {\n return new ScanRuntimeAssembler(scan).assemble();\n}\n\n// webpieces-disable no-function-outside-class -- pure sort helper, matches the sibling helpers in this file\nfunction sortUnresolved(unresolved: RuntimeUnresolved[]): RuntimeUnresolved[] {\n return [...unresolved].sort(\n (a: RuntimeUnresolved, b: RuntimeUnresolved) => a.service.localeCompare(b.service) || a.api.localeCompare(b.api),\n );\n}\n\n/** Deterministic JSON (sorted keys + arrays already sorted during assembly). */\nfunction formatRuntimeJson(graph: RuntimeGraph): string {\n return JSON.stringify(graph, null, 4) + '\\n';\n}\n\nexport function saveRuntimeGraph(\n graph: RuntimeGraph,\n workspaceRoot: string,\n graphPath: string = DEFAULT_RUNTIME_GRAPH_PATH,\n): void {\n const fullPath = path.join(workspaceRoot, graphPath);\n const dir = path.dirname(fullPath);\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(fullPath, formatRuntimeJson(graph), 'utf-8');\n}\n\nexport function runtimeGraphFileExists(\n workspaceRoot: string,\n graphPath: string = DEFAULT_RUNTIME_GRAPH_PATH,\n): boolean {\n return fs.existsSync(path.join(workspaceRoot, graphPath));\n}\n\nexport function loadRuntimeGraph(\n workspaceRoot: string,\n graphPath: string = DEFAULT_RUNTIME_GRAPH_PATH,\n): RuntimeGraph | null {\n const fullPath = path.join(workspaceRoot, graphPath);\n if (!fs.existsSync(fullPath)) return null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return JSON.parse(fs.readFileSync(fullPath, 'utf-8')) as RuntimeGraph;\n } catch (err: unknown) {\n const error = toError(err);\n throw new Error(`Failed to load runtime graph from ${fullPath}`, { cause: error });\n }\n}\n\n/** Serialize for an in-memory equality check (matches the on-disk format). */\nexport function serializeRuntimeGraph(graph: RuntimeGraph): string {\n return formatRuntimeJson(graph);\n}\n"]}
@@ -18,9 +18,28 @@ const LEVEL_COLORS = {
18
18
  2: '#FFF3E0',
19
19
  3: '#FCE4EC',
20
20
  };
21
+ const QUEUE_FILL = '#FFF3E0';
21
22
  function getShortName(name) {
22
23
  return name.includes('/') ? name.split('/').pop() : name;
23
24
  }
25
+ /**
26
+ * DOT for ONE runtime edge. rpc → a direct labeled arrow (producer calls consumer). pubsub → the
27
+ * producer enqueues and the consumer is delivered later, so we draw producer → QUEUE → consumer
28
+ * with a cylinder queue node and dashed enqueue/deliver arrows.
29
+ */
30
+ // webpieces-disable no-function-outside-class -- DOT string builder, matching getShortName in this file
31
+ function edgeDot(edge) {
32
+ const from = getShortName(edge.from);
33
+ const to = getShortName(edge.to);
34
+ const via = edge.via.map((v) => getShortName(v)).join(', ');
35
+ if (edge.type !== 'pubsub') {
36
+ return ` "${from}" -> "${to}" [label="${via}"];\n`;
37
+ }
38
+ const queueId = `queue__${from}__${to}`;
39
+ return (` "${queueId}" [shape=cylinder, style="filled", fillcolor="${QUEUE_FILL}", label="${via}\\nqueue"];\n` +
40
+ ` "${from}" -> "${queueId}" [label="enqueue", style=dashed];\n` +
41
+ ` "${queueId}" -> "${to}" [label="deliver", style=dashed];\n`);
42
+ }
24
43
  /** Build the Graphviz DOT for the runtime service graph. */
25
44
  function generateRuntimeDot(graph, title = 'WebPieces Runtime Architecture') {
26
45
  let dot = 'digraph RuntimeArchitecture {\n';
@@ -35,8 +54,7 @@ function generateRuntimeDot(graph, title = 'WebPieces Runtime Architecture') {
35
54
  }
36
55
  dot += '\n';
37
56
  for (const edge of graph.runtimeEdges) {
38
- const via = edge.via.map((v) => getShortName(v)).join(', ');
39
- dot += ` "${getShortName(edge.from)}" -> "${getShortName(edge.to)}" [label="${via}"];\n`;
57
+ dot += edgeDot(edge);
40
58
  }
41
59
  dot += '\n labelloc="t";\n';
42
60
  dot += ` label="${title}\\n(from architecture/runtime-dependencies.json)";\n`;
@@ -67,7 +85,7 @@ function generateRuntimeHtml(dot, title) {
67
85
  </head>
68
86
  <body>
69
87
  <h1>${title}</h1>
70
- <div class="note">Edges are runtime calls (client &rarr; server), labeled with the api project they flow over.</div>
88
+ <div class="note">Runtime calls between services. <strong>rpc</strong> = a direct arrow (synchronous call, labeled with the api). <strong>pubsub</strong> = producer &rarr; <em>queue</em> (cylinder) &rarr; consumer: the producer enqueues a Cloud Task and the consumer is delivered it later.</div>
71
89
  <div id="graph"></div>
72
90
  <script>${script}</script>
73
91
  </body>
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-visualizer.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/runtime-visualizer.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAkBH,gDAyBC;AAsCD,8DAgBC;;AA/FD,+CAAyB;AACzB,mDAA6B;AAG7B,MAAM,YAAY,GAA2B;IACzC,CAAC,EAAE,SAAS;IACZ,CAAC,EAAE,SAAS;IACZ,CAAC,EAAE,SAAS;IACZ,CAAC,EAAE,SAAS;CACf,CAAC;AAEF,SAAS,YAAY,CAAC,IAAY;IAC9B,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC9D,CAAC;AAED,4DAA4D;AAC5D,SAAgB,kBAAkB,CAAC,KAAmB,EAAE,QAAgB,gCAAgC;IACpG,IAAI,GAAG,GAAG,iCAAiC,CAAC;IAC5C,GAAG,IAAI,iBAAiB,CAAC;IACzB,GAAG,IAAI,iEAAiE,CAAC;IACzE,GAAG,IAAI,6CAA6C,CAAC;IAErD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC7C,MAAM,GAAG,GAAG,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACjC,MAAM,KAAK,GAAG,YAAY,CAAC,GAAG,CAAC,KA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AAK,EAAE,WAAW,CAAC,CAAC;IAC/D,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,SAAS,CAAC;QAAE,EAAE,CAAC,SAAS,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAE5E,MAAM,GAAG,GAAG,kBAAkB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAC7C,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,0BAA0B,CAAC,CAAC;IACjE,EAAE,CAAC,aAAa,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;IAExC,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,2BAA2B,CAAC,CAAC;IACnE,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,mBAAmB,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;IAErE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;AACjC,CAAC","sourcesContent":["/**\n * Runtime Visualizer\n *\n * Renders the runtime microservice graph (services + inferred Z -> X edges,\n * each labeled with the api(s) they flow over) to DOT + interactive HTML in\n * tmp/webpieces/runtime-architecture.{dot,html}.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { RuntimeGraph } from './runtime-graph';\n\nconst LEVEL_COLORS: Record<number, string> = {\n 0: '#E8F5E9',\n 1: '#E3F2FD',\n 2: '#FFF3E0',\n 3: '#FCE4EC',\n};\n\nfunction getShortName(name: string): string {\n return name.includes('/') ? name.split('/').pop()! : name;\n}\n\n/** Build the Graphviz DOT for the runtime service graph. */\nexport function generateRuntimeDot(graph: RuntimeGraph, title: string = 'WebPieces Runtime Architecture'): string {\n let dot = 'digraph RuntimeArchitecture {\\n';\n dot += ' rankdir=TB;\\n';\n dot += ' node [shape=box, style=\"filled,rounded\", fontname=\"Arial\"];\\n';\n dot += ' edge [fontname=\"Arial\", fontsize=10];\\n\\n';\n\n for (const name of Object.keys(graph.services)) {\n const svc = graph.services[name];\n const color = LEVEL_COLORS[svc.level] || '#F5F5F5';\n const role = svc.implements.length > 0 ? 'server' : 'client';\n dot += ` \"${getShortName(name)}\" [fillcolor=\"${color}\", label=\"${getShortName(name)}\\\\n(${role}, L${svc.level})\"];\\n`;\n }\n\n dot += '\\n';\n\n for (const edge of graph.runtimeEdges) {\n const via = edge.via.map((v: string) => getShortName(v)).join(', ');\n dot += ` \"${getShortName(edge.from)}\" -> \"${getShortName(edge.to)}\" [label=\"${via}\"];\\n`;\n }\n\n dot += '\\n labelloc=\"t\";\\n';\n dot += ` label=\"${title}\\\\n(from architecture/runtime-dependencies.json)\";\\n`;\n dot += ' fontsize=20;\\n';\n dot += '}\\n';\n return dot;\n}\n\nfunction generateRuntimeHtml(dot: string, title: string): string {\n const script = `\n const dot = ${JSON.stringify(dot)};\n const viz = new Viz();\n viz.renderSVGElement(dot)\n .then(el => document.getElementById('graph').appendChild(el))\n .catch(err => { document.getElementById('graph').innerHTML = '<pre>' + err + '</pre>'; });\n `;\n return `<!DOCTYPE html>\n<html>\n<head>\n <title>${title}</title>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/viz.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/full.render.js\"></script>\n <style>\n body { margin: 0; padding: 20px; font-family: Arial, sans-serif; background: #f5f5f5; }\n h1 { text-align: center; color: #333; }\n #graph { text-align: center; background: white; padding: 20px; border-radius: 8px; }\n .note { max-width: 700px; margin: 12px auto; color: #555; text-align: center; }\n </style>\n</head>\n<body>\n <h1>${title}</h1>\n <div class=\"note\">Edges are runtime calls (client &rarr; server), labeled with the api project they flow over.</div>\n <div id=\"graph\"></div>\n <script>${script}</script>\n</body>\n</html>`;\n}\n\nexport interface RuntimeVisualizationPaths {\n dotPath: string;\n htmlPath: string;\n}\n\n/** Write the DOT + HTML renderings to tmp/webpieces/. */\nexport function writeRuntimeVisualization(\n graph: RuntimeGraph,\n workspaceRoot: string,\n title: string = 'WebPieces Runtime Architecture',\n): RuntimeVisualizationPaths {\n const outputDir = path.join(workspaceRoot, 'tmp', 'webpieces');\n if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });\n\n const dot = generateRuntimeDot(graph, title);\n const dotPath = path.join(outputDir, 'runtime-architecture.dot');\n fs.writeFileSync(dotPath, dot, 'utf-8');\n\n const htmlPath = path.join(outputDir, 'runtime-architecture.html');\n fs.writeFileSync(htmlPath, generateRuntimeHtml(dot, title), 'utf-8');\n\n return { dotPath, htmlPath };\n}\n"]}
1
+ {"version":3,"file":"runtime-visualizer.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/runtime-visualizer.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAyCH,gDAwBC;AAsCD,8DAgBC;;AArHD,+CAAyB;AACzB,mDAA6B;AAG7B,MAAM,YAAY,GAA2B;IACzC,CAAC,EAAE,SAAS;IACZ,CAAC,EAAE,SAAS;IACZ,CAAC,EAAE,SAAS;IACZ,CAAC,EAAE,SAAS;CACf,CAAC;AAEF,MAAM,UAAU,GAAG,SAAS,CAAC;AAE7B,SAAS,YAAY,CAAC,IAAY;IAC9B,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC9D,CAAC;AAED;;;;GAIG;AACH,wGAAwG;AACxG,SAAS,OAAO,CAAC,IAAiB;IAC9B,MAAM,IAAI,GAAG,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACrC,MAAM,EAAE,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACjC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAS,EAAE,EAAE,CAAC,YAAY,CAAC,C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":["/**\n * Runtime Visualizer\n *\n * Renders the runtime microservice graph (services + inferred Z -> X edges,\n * each labeled with the api(s) they flow over) to DOT + interactive HTML in\n * tmp/webpieces/runtime-architecture.{dot,html}.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { RuntimeGraph, RuntimeEdge } from './runtime-graph';\n\nconst LEVEL_COLORS: Record<number, string> = {\n 0: '#E8F5E9',\n 1: '#E3F2FD',\n 2: '#FFF3E0',\n 3: '#FCE4EC',\n};\n\nconst QUEUE_FILL = '#FFF3E0';\n\nfunction getShortName(name: string): string {\n return name.includes('/') ? name.split('/').pop()! : name;\n}\n\n/**\n * DOT for ONE runtime edge. rpc → a direct labeled arrow (producer calls consumer). pubsub → the\n * producer enqueues and the consumer is delivered later, so we draw producer → QUEUE → consumer\n * with a cylinder queue node and dashed enqueue/deliver arrows.\n */\n// webpieces-disable no-function-outside-class -- DOT string builder, matching getShortName in this file\nfunction edgeDot(edge: RuntimeEdge): string {\n const from = getShortName(edge.from);\n const to = getShortName(edge.to);\n const via = edge.via.map((v: string) => getShortName(v)).join(', ');\n if (edge.type !== 'pubsub') {\n return ` \"${from}\" -> \"${to}\" [label=\"${via}\"];\\n`;\n }\n const queueId = `queue__${from}__${to}`;\n return (\n ` \"${queueId}\" [shape=cylinder, style=\"filled\", fillcolor=\"${QUEUE_FILL}\", label=\"${via}\\\\nqueue\"];\\n` +\n ` \"${from}\" -> \"${queueId}\" [label=\"enqueue\", style=dashed];\\n` +\n ` \"${queueId}\" -> \"${to}\" [label=\"deliver\", style=dashed];\\n`\n );\n}\n\n/** Build the Graphviz DOT for the runtime service graph. */\nexport function generateRuntimeDot(graph: RuntimeGraph, title: string = 'WebPieces Runtime Architecture'): string {\n let dot = 'digraph RuntimeArchitecture {\\n';\n dot += ' rankdir=TB;\\n';\n dot += ' node [shape=box, style=\"filled,rounded\", fontname=\"Arial\"];\\n';\n dot += ' edge [fontname=\"Arial\", fontsize=10];\\n\\n';\n\n for (const name of Object.keys(graph.services)) {\n const svc = graph.services[name];\n const color = LEVEL_COLORS[svc.level] || '#F5F5F5';\n const role = svc.implements.length > 0 ? 'server' : 'client';\n dot += ` \"${getShortName(name)}\" [fillcolor=\"${color}\", label=\"${getShortName(name)}\\\\n(${role}, L${svc.level})\"];\\n`;\n }\n\n dot += '\\n';\n\n for (const edge of graph.runtimeEdges) {\n dot += edgeDot(edge);\n }\n\n dot += '\\n labelloc=\"t\";\\n';\n dot += ` label=\"${title}\\\\n(from architecture/runtime-dependencies.json)\";\\n`;\n dot += ' fontsize=20;\\n';\n dot += '}\\n';\n return dot;\n}\n\nfunction generateRuntimeHtml(dot: string, title: string): string {\n const script = `\n const dot = ${JSON.stringify(dot)};\n const viz = new Viz();\n viz.renderSVGElement(dot)\n .then(el => document.getElementById('graph').appendChild(el))\n .catch(err => { document.getElementById('graph').innerHTML = '<pre>' + err + '</pre>'; });\n `;\n return `<!DOCTYPE html>\n<html>\n<head>\n <title>${title}</title>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/viz.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/full.render.js\"></script>\n <style>\n body { margin: 0; padding: 20px; font-family: Arial, sans-serif; background: #f5f5f5; }\n h1 { text-align: center; color: #333; }\n #graph { text-align: center; background: white; padding: 20px; border-radius: 8px; }\n .note { max-width: 700px; margin: 12px auto; color: #555; text-align: center; }\n </style>\n</head>\n<body>\n <h1>${title}</h1>\n <div class=\"note\">Runtime calls between services. <strong>rpc</strong> = a direct arrow (synchronous call, labeled with the api). <strong>pubsub</strong> = producer &rarr; <em>queue</em> (cylinder) &rarr; consumer: the producer enqueues a Cloud Task and the consumer is delivered it later.</div>\n <div id=\"graph\"></div>\n <script>${script}</script>\n</body>\n</html>`;\n}\n\nexport interface RuntimeVisualizationPaths {\n dotPath: string;\n htmlPath: string;\n}\n\n/** Write the DOT + HTML renderings to tmp/webpieces/. */\nexport function writeRuntimeVisualization(\n graph: RuntimeGraph,\n workspaceRoot: string,\n title: string = 'WebPieces Runtime Architecture',\n): RuntimeVisualizationPaths {\n const outputDir = path.join(workspaceRoot, 'tmp', 'webpieces');\n if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });\n\n const dot = generateRuntimeDot(graph, title);\n const dotPath = path.join(outputDir, 'runtime-architecture.dot');\n fs.writeFileSync(dotPath, dot, 'utf-8');\n\n const htmlPath = path.join(outputDir, 'runtime-architecture.html');\n fs.writeFileSync(htmlPath, generateRuntimeHtml(dot, title), 'utf-8');\n\n return { dotPath, htmlPath };\n}\n"]}