nerdgram1337 1.4.8 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  buildTree,
3
3
  readFile
4
- } from "./chunk-I5EOFHBL.js";
4
+ } from "./chunk-MKB7YAGA.js";
5
5
  import {
6
6
  atomicWriteJson,
7
7
  getDataRoot,
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readFile,
3
3
  writeFile
4
- } from "./chunk-I5EOFHBL.js";
4
+ } from "./chunk-MKB7YAGA.js";
5
5
  import {
6
6
  REPO_ROOT,
7
7
  ensureDataRoot,
@@ -1469,7 +1469,7 @@ async function writeFile(relativePath, content, options = {}) {
1469
1469
  await atomicWriteText(abs, content);
1470
1470
  await dropThumbnail(relative);
1471
1471
  const stat = await fs2.stat(abs);
1472
- const search = await import("./chunk-WSGEBKT4.js");
1472
+ const search = await import("./chunk-FIQWTTCY.js");
1473
1473
  await search.rememberSearchEntry(relative, content, stat.mtimeMs, stat.size);
1474
1474
  await noteDiagramSighting({ path: relative, hash: hashContent(content) });
1475
1475
  noteSync({ kind: "content", summary: `Update ${relative}` });
@@ -1482,7 +1482,7 @@ async function writeFile(relativePath, content, options = {}) {
1482
1482
  };
1483
1483
  }
1484
1484
  function noteSync(change) {
1485
- void import("./chunk-JUCAQ6EJ.js").then((mod) => mod.noteLocalChange(change)).catch(() => {
1485
+ void import("./chunk-ORJTKOL4.js").then((mod) => mod.noteLocalChange(change)).catch(() => {
1486
1486
  console.error("GitHub sync could not record a local change");
1487
1487
  });
1488
1488
  }
@@ -1,4 +1,4 @@
1
- import "./chunk-I5EOFHBL.js";
1
+ import "./chunk-MKB7YAGA.js";
2
2
  import {
3
3
  ensureDataRoot,
4
4
  getMetaPath,
@@ -799,24 +799,66 @@ async function copyDataToMirror(dataRoot, dir) {
799
799
  async function commitMirror(dir, message, parents) {
800
800
  const matrix = await git.statusMatrix({ fs: nodeFs, dir });
801
801
  let dirty = false;
802
- for (const [filepath, head, workdir, stage] of matrix) {
803
- if (head === 1 && workdir === 1 && stage === 1) continue;
804
- if (head === 0 && workdir === 0) continue;
802
+ for (const [filepath, head2, workdir, stage] of matrix) {
803
+ if (head2 === 1 && workdir === 1 && stage === 1) continue;
804
+ if (head2 === 0 && workdir === 0) continue;
805
805
  dirty = true;
806
806
  if (workdir === 0) await git.remove({ fs: nodeFs, dir, filepath });
807
807
  else await git.add({ fs: nodeFs, dir, filepath });
808
808
  }
809
809
  if (!dirty && !parents) return null;
810
+ const head = await headOid(dir);
811
+ const parentOids = parents && parents.length > 0 ? parents : head ? [head] : [];
812
+ const text = message.trim() || "Update diagrams";
813
+ const onlyParentIsHead = parentOids.length === 1 && parentOids[0] === head;
814
+ if (!parents || onlyParentIsHead) {
815
+ try {
816
+ return await git.commit({
817
+ fs: nodeFs,
818
+ dir,
819
+ message: text,
820
+ author: PERSON,
821
+ committer: PERSON,
822
+ parent: parents,
823
+ disallowEmpty: parentOids.length === 1
824
+ });
825
+ } catch (err) {
826
+ if (isEmptyCommit(err)) return null;
827
+ throw err;
828
+ }
829
+ }
810
830
  const oid = await git.commit({
811
831
  fs: nodeFs,
812
832
  dir,
813
- message: message.trim() || "Update diagrams",
833
+ message: text,
814
834
  author: PERSON,
815
835
  committer: PERSON,
816
- parent: parents
836
+ parent: parents,
837
+ noUpdateBranch: true
838
+ });
839
+ if (parentOids.length === 1) {
840
+ const [created, parentCommit] = await Promise.all([
841
+ git.readCommit({ fs: nodeFs, dir, oid }),
842
+ git.readCommit({ fs: nodeFs, dir, oid: parentOids[0] })
843
+ ]);
844
+ if (created.commit.tree === parentCommit.commit.tree) return null;
845
+ }
846
+ const branch = await git.currentBranch({ fs: nodeFs, dir, fullname: true });
847
+ await git.writeRef({
848
+ fs: nodeFs,
849
+ dir,
850
+ ref: typeof branch === "string" ? branch : "HEAD",
851
+ value: oid,
852
+ force: true
817
853
  });
818
854
  return oid;
819
855
  }
856
+ function isEmptyCommit(err) {
857
+ if (!err || typeof err !== "object") return false;
858
+ const code = "code" in err ? String(err.code) : "";
859
+ const name = "name" in err ? String(err.name) : "";
860
+ return code === "EmptyCommitError" || name === "EmptyCommitError";
861
+ }
820
862
  async function fetchRemote(dir) {
821
863
  try {
822
864
  await git.fetch({
@@ -956,6 +998,7 @@ async function deleteExtra(mirror, dir, desired) {
956
998
 
957
999
  // server/src/sync/engine.ts
958
1000
  var suppress = 0;
1001
+ var noteGeneration = 0;
959
1002
  var timer = null;
960
1003
  var summaries = [];
961
1004
  var structuralPending = false;
@@ -971,8 +1014,12 @@ function noteLocalChange(change) {
971
1014
  }
972
1015
  async function recordChange(change) {
973
1016
  if (suppress > 0) return;
1017
+ const generation = noteGeneration;
974
1018
  const config = await loadConfig();
975
1019
  if (!config.enabled || suppress > 0) return;
1020
+ if (!await workspaceDiffersFromHead()) return;
1021
+ if (suppress > 0) return;
1022
+ if (generation !== noteGeneration && !await workspaceDiffersFromHead()) return;
976
1023
  if (change.summary && !summaries.includes(change.summary)) summaries.push(change.summary);
977
1024
  if (change.kind === "structural") {
978
1025
  structuralPending = true;
@@ -981,6 +1028,13 @@ async function recordChange(change) {
981
1028
  }
982
1029
  if (!structuralPending) schedule(idleMs());
983
1030
  }
1031
+ async function workspaceDiffersFromHead() {
1032
+ try {
1033
+ return await copyWouldChange();
1034
+ } catch {
1035
+ return true;
1036
+ }
1037
+ }
984
1038
  async function syncNow() {
985
1039
  return exclusive(async () => {
986
1040
  const config = await loadConfig();
@@ -12,6 +12,119 @@ import {
12
12
  // server/src/renderDiagram.ts
13
13
  import { createRequire } from "node:module";
14
14
  import puppeteer from "puppeteer";
15
+
16
+ // server/src/edgeLabelPadding.ts
17
+ function repairSvgMarkup(svg) {
18
+ let next = svg;
19
+ if (next.includes("xlink:") && !/xmlns:xlink\s*=/.test(next)) {
20
+ next = next.replace(/<svg\b/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
21
+ }
22
+ return next.replace(/<br\b([^>]*?)>/gi, (_full, attrs) => {
23
+ const body = attrs.replace(/\s*\/\s*$/, "");
24
+ return `<br${body}/>`;
25
+ });
26
+ }
27
+ function padEdgeLabelBoxes(root) {
28
+ const pad = 6;
29
+ const mark = "data-nerdgram-pad";
30
+ const readPx = (value) => {
31
+ if (!value) return 0;
32
+ const n = Number.parseFloat(value);
33
+ return Number.isFinite(n) ? n : 0;
34
+ };
35
+ const trimNum = (value) => String(Math.round(value * 100) / 100);
36
+ const writePx = (current, next) => {
37
+ const unit = current?.trim().toLowerCase().endsWith("px") ? "px" : "";
38
+ return `${trimNum(next)}${unit}`;
39
+ };
40
+ const shiftTranslateX = (el, dx) => {
41
+ const raw = el.getAttribute("transform") ?? "";
42
+ const match = /translate\(\s*(-?[\d.]+)(?:[,\s]+(-?[\d.]+))?\s*\)/.exec(raw);
43
+ if (!match || match[1] == null) return;
44
+ const x = Number(match[1]) + dx;
45
+ const y = match[2] ?? "0";
46
+ el.setAttribute("transform", raw.replace(match[0], `translate(${trimNum(x)}, ${y})`));
47
+ };
48
+ const appendStyle = (el, addition) => {
49
+ const style = el.getAttribute("style") ?? "";
50
+ if (/padding\s*:/.test(style)) return;
51
+ el.setAttribute("style", style.trim() ? `${style.replace(/;\s*$/, "")};${addition}` : addition);
52
+ };
53
+ for (const group of root.querySelectorAll("g.edgeLabel")) {
54
+ if (group.getAttribute(mark) === "1") continue;
55
+ const foreign = group.querySelector("foreignObject");
56
+ if (foreign) {
57
+ const widthAttr2 = foreign.getAttribute("width");
58
+ const width2 = readPx(widthAttr2);
59
+ if (!(width2 > 0)) continue;
60
+ foreign.setAttribute("width", writePx(widthAttr2, width2 + pad * 2));
61
+ shiftTranslateX(group.querySelector("g.label") ?? group, -pad);
62
+ const tagged = foreign.getElementsByTagName?.("p");
63
+ const paragraphs = tagged ? [...tagged] : [...foreign.querySelectorAll("*")].filter((el) => (el.localName ?? "").toLowerCase() === "p");
64
+ if (paragraphs.length > 0) {
65
+ for (const paragraph of paragraphs) appendStyle(paragraph, `padding:0 ${pad}px`);
66
+ } else {
67
+ const background = foreign.querySelector(".labelBkg") ?? foreign.querySelector("div");
68
+ if (background) appendStyle(background, `padding:0 ${pad}px`);
69
+ }
70
+ group.setAttribute(mark, "1");
71
+ continue;
72
+ }
73
+ const rect = group.querySelector("rect");
74
+ if (!rect) continue;
75
+ const widthAttr = rect.getAttribute("width");
76
+ const width = readPx(widthAttr);
77
+ if (!(width > 0)) continue;
78
+ const xAttr = rect.getAttribute("x");
79
+ const x = readPx(xAttr);
80
+ const text = group.querySelector("text");
81
+ const box = text && typeof text.getBBox === "function" ? text.getBBox() : null;
82
+ let extra = pad;
83
+ if (box && box.width > 1) {
84
+ extra = pad - (width - box.width) / 2;
85
+ if (extra <= 0.5) {
86
+ group.setAttribute(mark, "1");
87
+ continue;
88
+ }
89
+ }
90
+ rect.setAttribute("x", writePx(xAttr, x - extra));
91
+ rect.setAttribute("width", writePx(widthAttr, width + extra * 2));
92
+ group.setAttribute(mark, "1");
93
+ }
94
+ }
95
+ function padEdgeLabelSvg(svg) {
96
+ if (!svg.includes("edgeLabel")) return repairSvgMarkup(svg);
97
+ const prepared = repairSvgMarkup(svg);
98
+ const g = globalThis;
99
+ if (!g.DOMParser || !g.XMLSerializer) return prepared;
100
+ const doc = new g.DOMParser().parseFromString(prepared, "image/svg+xml");
101
+ if (doc.querySelector("parsererror")) return prepared;
102
+ padEdgeLabelBoxes(doc);
103
+ return repairSvgMarkup(new g.XMLSerializer().serializeToString(doc.documentElement));
104
+ }
105
+ function svgXmlError(svg) {
106
+ const text = svg.trim();
107
+ if (!text.includes("<svg") || text.includes("<parsererror")) {
108
+ return "Rendered SVG is not well-formed XML.";
109
+ }
110
+ if (/<br\b(?![^>]*\/>)[^>]*>/i.test(text)) {
111
+ return "Rendered SVG is not well-formed XML. Opening and ending tag mismatch: br and p.";
112
+ }
113
+ const g = globalThis;
114
+ if (!g.DOMParser) return null;
115
+ const doc = new g.DOMParser().parseFromString(text, "image/svg+xml");
116
+ const err = doc.querySelector("parsererror");
117
+ if (err) {
118
+ const message = (err.textContent ?? "").replace(/\s+/g, " ").trim();
119
+ return message.slice(0, 300) || "Rendered SVG is not well-formed XML.";
120
+ }
121
+ if (doc.documentElement?.localName && doc.documentElement.localName !== "svg") {
122
+ return "Rendered SVG is not well-formed XML.";
123
+ }
124
+ return null;
125
+ }
126
+
127
+ // server/src/renderDiagram.ts
15
128
  var require2 = createRequire(import.meta.url);
16
129
  var MAX_RENDER_SOURCE_CHARS = 512 * 1024;
17
130
  var MAX_RENDER_SVG_CHARS = 2e6;
@@ -107,14 +220,20 @@ async function draw(page, source, background) {
107
220
  );
108
221
  await page.addScriptTag({ path: mermaidScript() });
109
222
  const drawn = await page.evaluate(
110
- async (code, mermaidConfig, fill) => {
223
+ async (code, mermaidConfig, fill, padSource) => {
224
+ const padSvg = new Function(
225
+ "svg",
226
+ `var __name = function (target) { return target; };
227
+ ${padSource}
228
+ return padEdgeLabelSvg(svg);`
229
+ );
111
230
  const api = window.mermaid;
112
231
  if (!api) return { ok: false, message: "Mermaid did not load", loc: null, token: void 0 };
113
232
  document.body.style.background = fill;
114
233
  api.initialize(mermaidConfig);
115
234
  try {
116
235
  const rendered = await api.render("nerdgram-render", code);
117
- return { ok: true, svg: rendered.svg };
236
+ return { ok: true, svg: padSvg(rendered.svg) };
118
237
  } catch (err) {
119
238
  const hash = err && typeof err === "object" && "hash" in err ? err.hash : void 0;
120
239
  const loc = hash?.loc;
@@ -133,7 +252,10 @@ async function draw(page, source, background) {
133
252
  },
134
253
  source,
135
254
  config,
136
- background
255
+ background,
256
+ `${repairSvgMarkup.toString()}
257
+ ${padEdgeLabelBoxes.toString()}
258
+ ${padEdgeLabelSvg.toString()}`
137
259
  );
138
260
  if (!drawn.ok) {
139
261
  const parsed = drawn.loc != null || /parse error on line/i.test(drawn.message);
@@ -170,6 +292,18 @@ async function rasterize(page, svg, background) {
170
292
  const png = await frame.screenshot({ type: "png", omitBackground: false });
171
293
  return Buffer.from(png);
172
294
  }
295
+ async function xmlErrorOnPage(page, svg) {
296
+ const message = await page.evaluate((markup) => {
297
+ const g = globalThis;
298
+ const doc = new g.DOMParser().parseFromString(markup, "image/svg+xml");
299
+ const err = doc.querySelector("parsererror");
300
+ if (err || doc.documentElement?.localName !== "svg") {
301
+ return (err?.textContent || "Rendered SVG is not well-formed XML.").replace(/\s+/g, " ").trim().slice(0, 300);
302
+ }
303
+ return "";
304
+ }, svg);
305
+ return message || null;
306
+ }
173
307
  async function renderOnce(input) {
174
308
  const source = assertSource(input.source);
175
309
  if (input.format !== "svg" && input.format !== "png") {
@@ -194,6 +328,8 @@ async function renderOnce(input) {
194
328
  if (/<script[\s>/]/i.test(cleaned)) {
195
329
  throw httpFail(400, "Rendered SVG was rejected.", "invalid");
196
330
  }
331
+ const markupError = svgXmlError(cleaned) ?? await xmlErrorOnPage(page, cleaned);
332
+ if (markupError) throw httpFail(500, markupError, "invalid");
197
333
  if (input.format === "svg") {
198
334
  return { format: "svg", contentType: "image/svg+xml; charset=utf-8", body: Buffer.from(cleaned, "utf8") };
199
335
  }
package/dist/cli.js CHANGED
@@ -26,6 +26,7 @@ var BOOL_FLAGS = /* @__PURE__ */ new Set([
26
26
  "with-data",
27
27
  "keep-data",
28
28
  "include-down",
29
+ "create-only",
29
30
  "version"
30
31
  ]);
31
32
  var HELP = `nerdgram \u2014 automation client for NerdGram1337
@@ -68,11 +69,14 @@ Flags
68
69
  diagnostics, folders, files, and the rest of the payload).
69
70
  Failure is {"ok":false,"error","status"} on stdout.
70
71
  --include-down Network data. Draw shutdown and down interfaces. Off by default.
72
+ --create-only Create the diagram and return 409 when the path exists.
73
+ Without this flag, generate creates the diagram or updates
74
+ the generated block and the data file beside it.
71
75
  --vlan <1-4094> Layer 2 network view. Keep links that carry this VLAN id.
72
76
  --group-by <value>
73
77
  cdp and lldp: platform or capability.
74
78
  network with --view l3: vrf.
75
- network with --view l2: site or role.
79
+ network with --view l2: site, role, or platform.
76
80
  --view <l3|l2> generate --format network only. l3 is subnets. l2 is VLANs,
77
81
  trunks, and LAGs. refresh rejects --view. The view is stored
78
82
  in the diagram.
@@ -108,7 +112,7 @@ not changed. --undo restores that replace and skips a file edited since.
108
112
  `;
109
113
  var renderModule = null;
110
114
  function loadRender() {
111
- renderModule ??= import("./chunk-GQKUFF4P.js");
115
+ renderModule ??= import("./chunk-WORJPG5T.js");
112
116
  return renderModule;
113
117
  }
114
118
  async function loadLint() {
@@ -117,7 +121,7 @@ async function loadLint() {
117
121
  async function templateCommand(parsed, io) {
118
122
  const sub = parsed.positionals[0] ?? "";
119
123
  const target = parsed.positionals[1] ?? "";
120
- const templates = await import("./chunk-TQHP2K7Q.js");
124
+ const templates = await import("./chunk-M434Z7CG.js");
121
125
  try {
122
126
  if (sub === "save") {
123
127
  if (!target) throw new CliError("Usage: nerdgram template save <diagram> [--name name] [--replace]");
@@ -554,8 +558,9 @@ async function generateCommand(parsed, io) {
554
558
  const vlanText = flagString(parsed.flags, "vlan");
555
559
  if (vlanText != null && !/^\d+$/.test(vlanText)) throw new CliError("vlan must be an integer from 1 to 4094.");
556
560
  const text = await fs.readFile(dataFile, "utf8");
561
+ const createOnly = parsed.flags.get("create-only") === true;
557
562
  const { base, token } = configOf(parsed.flags, io.env);
558
- const result = await callApi(base, requireToken(token), "POST", "/api/v1/generate", {
563
+ const result = await callApi(base, requireToken(token), "POST", createOnly ? "/api/v1/generate" : "/api/v1/generate/upsert", {
559
564
  path: diagramPath,
560
565
  text,
561
566
  format,
@@ -569,7 +574,8 @@ async function generateCommand(parsed, io) {
569
574
  ...vlanText != null ? { vlan: Number(vlanText) } : {}
570
575
  });
571
576
  const body = result.json;
572
- writeOut(io, isJson(parsed.flags), body, `Created ${body.path}${body.dataPath ? ` from ${body.dataPath}` : ""}`);
577
+ const verb = body.created === false ? "Updated" : "Created";
578
+ writeOut(io, isJson(parsed.flags), body, `${verb} ${body.path}${body.dataPath ? ` from ${body.dataPath}` : ""}`);
573
579
  }
574
580
  async function diffCommand(parsed, io) {
575
581
  const itemPath = parsed.positionals[0];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nerdgram1337",
3
- "version": "1.4.8",
3
+ "version": "1.5.0",
4
4
  "description": "Command-line client for a local NerdGram1337 server",
5
5
  "type": "module",
6
6
  "license": "MIT",