All files / src puml.ts

18.37% Statements 9/49
0% Branches 0/21
0% Functions 0/10
19.15% Lines 9/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 1301x 1x 1x 1x   1x               1x         1x         1x                                                                                                                                                       1x                                                            
import { spawn } from "child_process";
import * as path from "path";
import { extensionDirectoryPath } from "./utility";
import { getExtensionConfigPath } from "./mume";
 
const PlantUMLJarPath = path.resolve(
  extensionDirectoryPath,
  "./dependencies/plantuml/plantuml.jar",
);
 
/**
 * key is fileDirectoryPath, value is PlantUMLTask
 */
const TASKS: { [key: string]: PlantUMLTask } = {};
 
/**
 * key is fileDirectoryPath, value is String
 */
const CHUNKS: { [key: string]: string } = {};
 
/**
 * key is fileDirectoryPath, value is Array
 */
const CALLBACKS: { [key: string]: ((result: string) => void)[] } = {};
 
class PlantUMLTask {
  private fileDirectoryPath: string;
  private chunks: string;
  private callbacks: ((result: string) => void)[];
  private task;
 
  constructor(fileDirectoryPath: string) {
    this.fileDirectoryPath = fileDirectoryPath;
    this.chunks = CHUNKS[this.fileDirectoryPath] || "";
    this.callbacks = CALLBACKS[this.fileDirectoryPath] || [];
    this.task = null;
 
    this.startTask();
  }
 
  public generateSVG(content: string): Promise<string> {
    return new Promise((resolve, reject) => {
      this.callbacks.push(resolve);
      this.task.stdin.write(content + "\n");
    });
  }
 
  private startTask() {
    this.task = spawn("java", [
      "-Djava.awt.headless=true",
      "-Dfile.encoding=UTF-8",
      "-Dplantuml.include.path=" +
        [this.fileDirectoryPath, getExtensionConfigPath()].join(path.delimiter),
      "-jar",
      PlantUMLJarPath,
      // '-graphvizdot', 'exe'
      "-pipe",
      "-tsvg",
      "-charset",
      "UTF-8",
    ]);
 
    this.task.stdout.on("data", (chunk) => {
      let data = chunk.toString();
      this.chunks += data;
      if (
        this.chunks.trimRight().endsWith("</svg>") &&
        this.chunks.match(/<svg/g).length ===
          this.chunks.match(/<\/svg>/g).length
      ) {
        data = this.chunks;
        this.chunks = ""; // clear CHUNKS
        const diagrams = data.split("<?xml ");
        diagrams.forEach((diagram, i) => {
          if (diagram.length) {
            const callback = this.callbacks.shift();
            if (callback) {
              callback("<?xml " + diagram);
            }
          }
        });
      }
    });
 
    this.task.on("error", () => this.closeSelf());
    this.task.on("exit", () => this.closeSelf());
  }
 
  /**
   * stop this.task and store this.chunks and this.callbacks
   */
  private closeSelf() {
    TASKS[this.fileDirectoryPath] = null;
    CHUNKS[this.fileDirectoryPath] = this.chunks;
    CALLBACKS[this.fileDirectoryPath] = this.callbacks;
  }
}
 
// async call
export async function render(
  content: string,
  fileDirectoryPath: string = "",
): Promise<string> {
  content = content.trim();
  // ' @mume_file_directory_path:/fileDirectoryPath
  // fileDirectoryPath
  const match = content.match(/^'\s@mume_file_directory_path:(.+)$/m);
  if (match) {
    fileDirectoryPath = match[1];
  }
 
  const startMatch = content.match(/^\@start(.+?)\s+/m);
  if (startMatch) {
    if (!content.match(new RegExp(`^\\@end${startMatch[1]}`, "m"))) {
      content = "@startuml\n@enduml"; // error
    }
  } else {
    content = `@startuml
${content}
@enduml`;
  }
 
  if (!TASKS[fileDirectoryPath]) {
    // init `plantuml.jar` task
    TASKS[fileDirectoryPath] = new PlantUMLTask(fileDirectoryPath);
  }
 
  return await TASKS[fileDirectoryPath].generateSVG(content);
}