nerdgram1337 1.4.6 → 1.4.8

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,13 @@
1
+ import {
2
+ isMermaidEnvironmentError,
3
+ locateParseError
4
+ } from "./chunk-54BVSMKR.js";
5
+ import {
6
+ diagramTargetExists,
7
+ isDiagramLink,
8
+ parseClickLine,
9
+ resolveDiagramTarget
10
+ } from "./chunk-5C6VO4LC.js";
1
11
  import {
2
12
  ELK_NODE_PLACEMENTS,
3
13
  FLOWCHART_CURVES,
@@ -5,103 +15,15 @@ import {
5
15
  MERMAID_LOOKS,
6
16
  MERMAID_THEMES,
7
17
  diagramConfigKey,
8
- isMermaidEnvironmentError,
9
- locateParseError,
10
18
  matchFrontMatter,
11
19
  parseDiagram
12
- } from "./chunk-KO565WWM.js";
20
+ } from "./chunk-AFGGIQ22.js";
13
21
 
14
22
  // server/src/mermaidSyntax.ts
15
23
  import mermaid from "mermaid";
16
24
 
17
25
  // server/src/diagramLint.ts
18
26
  import { parseDocument } from "yaml";
19
-
20
- // server/src/diagramLinks.ts
21
- var DIAGRAM_SCHEME = /^(nerdgram|diagram):/i;
22
- var ANY_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
23
- function isDiagramLink(url) {
24
- if (!url || url.startsWith("//")) return false;
25
- if (ANY_SCHEME.test(url) && !DIAGRAM_SCHEME.test(url)) return false;
26
- const pathPart = url.split(/[?#]/)[0] ?? "";
27
- return DIAGRAM_SCHEME.test(url) || /\.mmd$/i.test(pathPart) || pathPart.startsWith("./") || pathPart.includes("/");
28
- }
29
- function parentPath(filePath) {
30
- const parts = filePath.replace(/\\/g, "/").split("/").filter(Boolean);
31
- parts.pop();
32
- return parts.join("/");
33
- }
34
- function resolveDiagramTarget(raw, sourcePath = "") {
35
- const trimmed = raw.trim();
36
- if (!isDiagramLink(trimmed)) return { ok: false, reason: "not-diagram" };
37
- let target = trimmed.replace(/\\/g, "/");
38
- const scheme = DIAGRAM_SCHEME.exec(target);
39
- if (scheme) target = target.slice(scheme[0].length);
40
- const cut = target.search(/[?#]/);
41
- if (cut >= 0) target = target.slice(0, cut);
42
- target = target.replace(/^\/+/, "");
43
- if (!target || target.includes("\0")) return { ok: false, reason: "invalid" };
44
- const base = scheme ? "" : parentPath(sourcePath);
45
- const combined = base ? `${base}/${target}` : target;
46
- const parts = [];
47
- for (const part of combined.split("/")) {
48
- if (!part || part === ".") continue;
49
- if (part === "..") {
50
- if (parts.length === 0) return { ok: false, reason: "escape" };
51
- parts.pop();
52
- continue;
53
- }
54
- if (part.startsWith(".")) return { ok: false, reason: "invalid" };
55
- parts.push(part);
56
- }
57
- const path = parts.join("/");
58
- if (!path.toLowerCase().endsWith(".mmd")) return { ok: false, reason: "not-diagram" };
59
- return { ok: true, path };
60
- }
61
- function normalizeWorkspacePath(raw) {
62
- const trimmed = raw.trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
63
- if (!trimmed) return "";
64
- const parts = [];
65
- for (const part of trimmed.split("/")) {
66
- if (!part || part === ".") continue;
67
- if (part === "..") {
68
- if (parts.length === 0) return trimmed.replace(/^\.\//, "");
69
- parts.pop();
70
- continue;
71
- }
72
- parts.push(part);
73
- }
74
- return parts.join("/");
75
- }
76
- function diagramTargetExists(target, paths, sourcePath = "") {
77
- const resolved = resolveDiagramTarget(target, sourcePath);
78
- if (!resolved.ok) return false;
79
- return paths.some((path) => normalizeWorkspacePath(path) === resolved.path);
80
- }
81
- function parseClickLine(line, lineStart, lineNo) {
82
- const match = /^\s*click\s+([A-Za-z_][\w-]*)\s+(.*)$/i.exec(line);
83
- if (!match || match[1] == null || match[2] == null) return null;
84
- const nodeId = match[1];
85
- const rest = match[2];
86
- if (/^\s*call\b/i.test(rest)) return null;
87
- const href = /^\s*href\s+/i.exec(rest);
88
- const urlPart = href ? rest.slice(href[0].length) : rest;
89
- const urlPartStart = line.length - rest.length + (href ? href[0].length : 0);
90
- const quoted = /"([^"]*)"/.exec(urlPart);
91
- if (!quoted || quoted[1] == null || quoted.index == null) return null;
92
- const quoteAt = urlPartStart + quoted.index;
93
- const from = lineStart + quoteAt + 1;
94
- return {
95
- nodeId,
96
- target: quoted[1],
97
- from,
98
- to: from + quoted[1].length,
99
- line: lineNo,
100
- column: quoteAt + 2
101
- };
102
- }
103
-
104
- // server/src/diagramLint.ts
105
27
  var LINT_RULES = [
106
28
  {
107
29
  id: "duplicate-id",
@@ -116,7 +38,7 @@ var LINT_RULES = [
116
38
  {
117
39
  id: "unlabeled-endpoint",
118
40
  label: "Unlabeled endpoints",
119
- description: "A connection names a node that was never given a label, which is usually a typo."
41
+ description: "A connection names a node that was never given a label, which is usually a typo. A subgraph id is a known endpoint."
120
42
  },
121
43
  {
122
44
  id: "unused-class",
@@ -231,7 +153,7 @@ function scanDiagram(source) {
231
153
  const parsed = parseDiagram(source);
232
154
  const start = bodyStart(source);
233
155
  const kind = diagramKind(parsed.body);
234
- const model = { kind, nodes: [], edges: [], classDefs: [], classUses: [], clicks: [] };
156
+ const model = { kind, nodes: [], edges: [], classDefs: [], classUses: [], clicks: [], subgraphs: [] };
235
157
  eachLine(source, start, start + parsed.body.length, (line, lineStart, lineNo) => {
236
158
  if (!line.trim() || line.trimStart().startsWith("%%")) return;
237
159
  if (readClassDef(line, lineStart, lineNo, source, model)) return;
@@ -302,15 +224,19 @@ function duplicateIds(model) {
302
224
  }
303
225
  return diagnostics;
304
226
  }
227
+ function subgraphIds(model) {
228
+ return new Set(model.subgraphs.map((item) => item.id));
229
+ }
305
230
  function unconnectedNodes(model) {
306
231
  const linked = /* @__PURE__ */ new Set();
307
232
  for (const edge of model.edges) {
308
233
  linked.add(edge.fromId);
309
234
  linked.add(edge.toId);
310
235
  }
236
+ const graphs = subgraphIds(model);
311
237
  const defined = /* @__PURE__ */ new Map();
312
238
  for (const node of model.nodes) {
313
- if (node.defined && !defined.has(node.id)) defined.set(node.id, node);
239
+ if (node.defined && !defined.has(node.id) && !graphs.has(node.id)) defined.set(node.id, node);
314
240
  }
315
241
  if (model.edges.length === 0 && defined.size < 2) return [];
316
242
  const diagnostics = [];
@@ -341,6 +267,10 @@ function unlabeledEndpoints(model) {
341
267
  if (!text) continue;
342
268
  if (!labels.has(node.id)) labels.set(node.id, text);
343
269
  }
270
+ for (const subgraph of model.subgraphs) {
271
+ const text = subgraph.label.trim() || subgraph.id;
272
+ if (!labels.has(subgraph.id)) labels.set(subgraph.id, text);
273
+ }
344
274
  if (labels.size === 0 && model.kind === "flowchart") return [];
345
275
  if (model.kind === "sequence" || model.kind === "state") {
346
276
  const declared = model.nodes.some((node) => node.defined);
@@ -364,17 +294,50 @@ function unlabeledEndpoints(model) {
364
294
  }
365
295
  if (candidates.length > labeledEndpoints.size) return [];
366
296
  }
367
- return candidates.map((endpoint) => ({
368
- ruleId: "unlabeled-endpoint",
369
- severity: "warning",
370
- subject: endpoint.id,
371
- message: `This connection uses "${endpoint.id}", which has no label. That is often a typo.`,
372
- from: endpoint.from,
373
- to: endpoint.to,
374
- line: endpoint.line,
375
- column: endpoint.column,
376
- fixes: []
377
- }));
297
+ const known = [...labels.keys()];
298
+ return candidates.map((endpoint) => {
299
+ const suggestion = closestId(endpoint.id, known);
300
+ const hint = suggestion ? ` Did you mean "${suggestion}"?` : "";
301
+ return {
302
+ ruleId: "unlabeled-endpoint",
303
+ severity: "warning",
304
+ subject: endpoint.id,
305
+ message: `This connection uses "${endpoint.id}", which has no label. That is often a typo.${hint}`,
306
+ from: endpoint.from,
307
+ to: endpoint.to,
308
+ line: endpoint.line,
309
+ column: endpoint.column,
310
+ fixes: []
311
+ };
312
+ });
313
+ }
314
+ function closestId(id, known) {
315
+ const lower = id.toLowerCase();
316
+ const caseHit = known.find((name) => name !== id && name.toLowerCase() === lower);
317
+ if (caseHit) return caseHit;
318
+ let best = null;
319
+ for (const name of known) {
320
+ if (name === id || Math.abs(name.length - id.length) > 2) continue;
321
+ const distance = editDistance(lower, name.toLowerCase());
322
+ if (distance < 1 || distance > 2) continue;
323
+ if (!best || distance < best.distance || distance === best.distance && name.localeCompare(best.name) < 0) {
324
+ best = { name, distance };
325
+ }
326
+ }
327
+ return best?.name ?? null;
328
+ }
329
+ function editDistance(left, right) {
330
+ const prev = Array.from({ length: right.length + 1 }, (_, index) => index);
331
+ const next = Array.from({ length: right.length + 1 }, () => 0);
332
+ for (let row = 1; row <= left.length; row += 1) {
333
+ next[0] = row;
334
+ for (let col = 1; col <= right.length; col += 1) {
335
+ const cost = left[row - 1] === right[col - 1] ? 0 : 1;
336
+ next[col] = Math.min(next[col - 1] + 1, prev[col] + 1, prev[col - 1] + cost);
337
+ }
338
+ for (let col = 0; col <= right.length; col += 1) prev[col] = next[col] ?? 0;
339
+ }
340
+ return prev[right.length] ?? left.length;
378
341
  }
379
342
  function unusedClasses(model) {
380
343
  const used = new Set(model.classUses.map((use) => use.name));
@@ -638,7 +601,12 @@ function collectInlineClasses(line, lineStart, lineNo, model) {
638
601
  }
639
602
  function scanFlowchartLine(line, lineStart, lineNo, model) {
640
603
  const trimmed = line.trim();
641
- if (/^(?:flowchart(?:-elk)?|graph|direction|style|linkStyle|subgraph|end)\b/i.test(trimmed)) return;
604
+ if (/^subgraph\b/i.test(trimmed)) {
605
+ const subgraph = readSubgraph(line, lineStart, lineNo);
606
+ if (subgraph) model.subgraphs.push(subgraph);
607
+ return;
608
+ }
609
+ if (/^(?:flowchart(?:-elk)?|graph|direction|style|linkStyle|end)\b/i.test(trimmed)) return;
642
610
  for (const statement of splitStatements(line)) {
643
611
  const absolute = lineStart + statement.offset;
644
612
  const pieces = splitArrows(statement.text);
@@ -659,6 +627,36 @@ function scanFlowchartLine(line, lineStart, lineNo, model) {
659
627
  }
660
628
  }
661
629
  }
630
+ function readSubgraph(line, lineStart, lineNo) {
631
+ const header = /^\s*subgraph\b(.*)$/i.exec(line);
632
+ if (!header) return null;
633
+ let rest = (header[1] ?? "").trim().replace(/@\{[\s\S]*\}\s*$/, "").trim();
634
+ if (!rest) return null;
635
+ const quoted = /^(?:"([^"]+)"|'([^']+)'|`([^`]+)`)\s*$/.exec(rest);
636
+ if (quoted) {
637
+ const id2 = (quoted[1] ?? quoted[2] ?? quoted[3] ?? "").trim();
638
+ if (!id2) return null;
639
+ return subgraphHit(line, lineStart, lineNo, id2, id2);
640
+ }
641
+ const titled = /^([A-Za-z_][\w-]*)\s*(?:\[\s*(?:"([^"]*)"|'([^']*)'|([^\]\n]*?))\s*\])?\s*$/.exec(rest);
642
+ if (!titled?.[1]) return null;
643
+ const id = titled[1];
644
+ const raw = titled[2] ?? titled[3] ?? titled[4];
645
+ const label = raw == null ? id : raw.trim() || id;
646
+ return subgraphHit(line, lineStart, lineNo, id, label);
647
+ }
648
+ function subgraphHit(line, lineStart, lineNo, id, label) {
649
+ const at = line.indexOf(id);
650
+ const from = lineStart + Math.max(0, at);
651
+ return {
652
+ id,
653
+ label,
654
+ from,
655
+ to: from + id.length,
656
+ line: lineNo,
657
+ column: Math.max(1, at + 1)
658
+ };
659
+ }
662
660
  function scanSequenceLine(line, lineStart, lineNo, model) {
663
661
  const declared = /^\s*(?:participant|actor)\s+(\S+?)(?:\s+as\s+(.+?))?\s*$/i.exec(line);
664
662
  if (declared && declared[1]) {
package/dist/cli.js CHANGED
@@ -14,6 +14,7 @@ var BOOL_FLAGS = /* @__PURE__ */ new Set([
14
14
  "no-update-links",
15
15
  "dry-run",
16
16
  "yes",
17
+ "replace",
17
18
  "match-case",
18
19
  "whole-word",
19
20
  "regex",
@@ -94,6 +95,11 @@ file is not modified.
94
95
  baseline saves the current diagram as a named baseline. --id names an
95
96
  existing revision instead. Names are kept when the 20-revision limit drops
96
97
  older saves.
98
+ template save <diagram> copies that diagram into <data>/.templates as a
99
+ User created template. It does not change the diagram. --name sets the
100
+ template name. --replace overwrites a user template with the same id.
101
+ template rm <id> deletes a user template. Built-in templates are refused.
102
+ These two write the data directory on this computer. They do not call the API.
97
103
  replace prints a preview. --yes applies it and saves each diagram, so the
98
104
  previous text is a revision. --dry-run is the default. --folder limits the
99
105
  scope. --no-recursive stays in that folder. The diagram body is searched
@@ -102,11 +108,45 @@ not changed. --undo restores that replace and skips a file edited since.
102
108
  `;
103
109
  var renderModule = null;
104
110
  function loadRender() {
105
- renderModule ??= import("./chunk-BOMYBBJ6.js");
111
+ renderModule ??= import("./chunk-GQKUFF4P.js");
106
112
  return renderModule;
107
113
  }
108
114
  async function loadLint() {
109
- return import("./chunk-EGA2UGTF.js");
115
+ return import("./chunk-XJTF2GUE.js");
116
+ }
117
+ async function templateCommand(parsed, io) {
118
+ const sub = parsed.positionals[0] ?? "";
119
+ const target = parsed.positionals[1] ?? "";
120
+ const templates = await import("./chunk-TQHP2K7Q.js");
121
+ try {
122
+ if (sub === "save") {
123
+ if (!target) throw new CliError("Usage: nerdgram template save <diagram> [--name name] [--replace]");
124
+ const created = await templates.createUserTemplate({
125
+ path: target,
126
+ name: flagString(parsed.flags, "name"),
127
+ replace: parsed.flags.get("replace") === true
128
+ });
129
+ writeOut(
130
+ io,
131
+ isJson(parsed.flags),
132
+ { id: created.id, origin: created.origin, title: created.title, category: created.category },
133
+ `Saved template ${created.id}`
134
+ );
135
+ return;
136
+ }
137
+ if (sub === "rm" || sub === "delete") {
138
+ if (!target) throw new CliError("Usage: nerdgram template rm <id>");
139
+ await templates.deleteUserTemplate(target);
140
+ writeOut(io, isJson(parsed.flags), { id: target }, `Deleted template ${target}`);
141
+ return;
142
+ }
143
+ throw new CliError("Usage: nerdgram template save <diagram> | nerdgram template rm <id>");
144
+ } catch (err) {
145
+ if (err instanceof CliError) throw err;
146
+ const status = err && typeof err === "object" && "status" in err && typeof err.status === "number" ? err.status : void 0;
147
+ const message = err instanceof Error ? err.message : String(err);
148
+ throw new CliError(message, status);
149
+ }
110
150
  }
111
151
  async function shutdownCli() {
112
152
  if (!renderModule) return;
@@ -794,6 +834,9 @@ async function main(argv, io = {}) {
794
834
  case "replace":
795
835
  await replaceCommand(parsed, streams);
796
836
  return 0;
837
+ case "template":
838
+ await templateCommand(parsed, streams);
839
+ return 0;
797
840
  default:
798
841
  throw new CliError(`Unknown command ${parsed.command}. Run nerdgram --help.`);
799
842
  }
@@ -831,5 +874,5 @@ if (isDirectRun()) {
831
874
  export {
832
875
  formatRowIssues,
833
876
  main,
834
- shutdownCli
877
+ templateCommand
835
878
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nerdgram1337",
3
- "version": "1.4.6",
3
+ "version": "1.4.8",
4
4
  "description": "Command-line client for a local NerdGram1337 server",
5
5
  "type": "module",
6
6
  "license": "MIT",