nerdgram1337 1.6.1 → 1.8.5

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,32 +1,464 @@
1
1
  import {
2
- LOCK_STALE_MS,
3
- META_DIR_NAME,
4
- REVISION_RETENTION,
5
- atomicWriteJson,
6
- atomicWriteText,
7
- createId,
8
- dropThumbnail,
9
- ensureDataRoot,
10
- evaluateWrite,
11
- getInstanceIdentity,
12
- getLocksRoot,
13
- getMetaPath,
14
- getVersionsRoot,
15
- hashContent,
16
- httpFail,
17
- isProcessAlive,
18
- normalizeRelative,
19
- readJsonFile,
20
- resolveSafePath,
21
- rethrowKnownReadError,
22
- safeStorageKey,
23
- textFiles,
24
- toRelativePath
25
- } from "./chunk-KA5X3YY6.js";
2
+ isDataFileName
3
+ } from "./chunk-M63FV47T.js";
4
+ import {
5
+ clickTargetKind,
6
+ resolveDiagramTarget
7
+ } from "./chunk-BW6ANOTX.js";
8
+ import {
9
+ matchFrontMatter
10
+ } from "./chunk-6LCHDAAN.js";
11
+
12
+ // server/src/network/ip.ts
13
+ function parseIpv4(address) {
14
+ const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(address.trim());
15
+ if (!match) return null;
16
+ let value = 0;
17
+ for (let index = 1; index <= 4; index += 1) {
18
+ const octet = match[index] ?? "";
19
+ if (octet.length > 1 && octet.startsWith("0")) return null;
20
+ const number = Number(octet);
21
+ if (!Number.isInteger(number) || number < 0 || number > 255) return null;
22
+ value = value << 8 | number;
23
+ }
24
+ return value >>> 0;
25
+ }
26
+ function formatIpv4(value) {
27
+ return `${value >>> 24 & 255}.${value >>> 16 & 255}.${value >>> 8 & 255}.${value & 255}`;
28
+ }
29
+ function parseIpv6(address) {
30
+ let text = address.trim().toLowerCase();
31
+ if (!text || text.length > 64 || text.includes("%") || /\s/.test(text)) return null;
32
+ if (text.includes(".")) {
33
+ const lastColon = text.lastIndexOf(":");
34
+ if (lastColon < 0) return null;
35
+ const v4 = parseIpv4(text.slice(lastColon + 1));
36
+ if (v4 == null) return null;
37
+ const hi = (v4 >>> 16 & 65535).toString(16);
38
+ const lo = (v4 & 65535).toString(16);
39
+ text = `${text.slice(0, lastColon)}:${hi}:${lo}`;
40
+ }
41
+ if (text.includes(":::")) return null;
42
+ const pieces = text.split("::");
43
+ if (pieces.length > 2) return null;
44
+ const parseSide = (part) => {
45
+ if (!part) return [];
46
+ const groups = part.split(":");
47
+ const out = [];
48
+ for (const group of groups) {
49
+ if (!/^[0-9a-f]{1,4}$/.test(group)) return null;
50
+ out.push(Number.parseInt(group, 16));
51
+ }
52
+ return out;
53
+ };
54
+ const left = parseSide(pieces[0] ?? "");
55
+ if (!left) return null;
56
+ if (pieces.length === 1) {
57
+ if (left.length !== 8) return null;
58
+ return Uint16Array.from(left);
59
+ }
60
+ const right = parseSide(pieces[1] ?? "");
61
+ if (!right) return null;
62
+ const missing = 8 - left.length - right.length;
63
+ if (missing < 1) return null;
64
+ return Uint16Array.from([...left, ...new Array(missing).fill(0), ...right]);
65
+ }
66
+ function formatIpv6(groups) {
67
+ let bestStart = -1;
68
+ let bestLength = 0;
69
+ let runStart = -1;
70
+ for (let index = 0; index <= groups.length; index += 1) {
71
+ const zero = index < groups.length && groups[index] === 0;
72
+ if (zero && runStart < 0) runStart = index;
73
+ if (!zero && runStart >= 0) {
74
+ const length = index - runStart;
75
+ if (length > bestLength) {
76
+ bestStart = runStart;
77
+ bestLength = length;
78
+ }
79
+ runStart = -1;
80
+ }
81
+ }
82
+ const hex = (group) => group.toString(16);
83
+ if (bestLength < 2) return [...groups].map(hex).join(":");
84
+ const left = [...groups.slice(0, bestStart)].map(hex).join(":");
85
+ const right = [...groups.slice(bestStart + bestLength)].map(hex).join(":");
86
+ return `${left}::${right}`;
87
+ }
88
+ function canonicalIp(address, family) {
89
+ if (family === "ipv4") {
90
+ const value = parseIpv4(address);
91
+ return value == null ? null : formatIpv4(value);
92
+ }
93
+ const groups = parseIpv6(address);
94
+ return groups ? formatIpv6(groups) : null;
95
+ }
26
96
 
27
- // server/src/fsStore.ts
28
- import fs2 from "node:fs/promises";
29
- import path4 from "node:path";
97
+ // server/src/network/validate.ts
98
+ var DEVICE_FIELDS = /* @__PURE__ */ new Set(["name", "platform", "model", "role", "site", "managementIp", "diagram"]);
99
+ var INTERFACE_FIELDS = /* @__PURE__ */ new Set([
100
+ "device",
101
+ "name",
102
+ "description",
103
+ "speed",
104
+ "adminStatus",
105
+ "operStatus",
106
+ "ipv4",
107
+ "ipv6",
108
+ "vrf",
109
+ "switchportMode",
110
+ "accessVlan",
111
+ "trunkVlans",
112
+ "nativeVlan",
113
+ "lag"
114
+ ]);
115
+ var ADDRESS_FIELDS = /* @__PURE__ */ new Set(["address", "prefix"]);
116
+ var LINK_FIELDS = /* @__PURE__ */ new Set(["a", "b", "label", "inferred"]);
117
+ var ENDPOINT_FIELDS = /* @__PURE__ */ new Set(["device", "interface"]);
118
+ var VLAN_FIELDS = /* @__PURE__ */ new Set(["id", "name"]);
119
+ var ROOT_FIELDS = /* @__PURE__ */ new Set(["schemaVersion", "format", "devices", "interfaces", "links", "vlans", "neighbors"]);
120
+ var NEIGHBOR_FIELDS = /* @__PURE__ */ new Set(["cdp", "lldp", "localDevice"]);
121
+ function validateNetwork(value) {
122
+ const issues = [];
123
+ if (!isRecord(value)) {
124
+ issues.push({ path: "", message: "Network data must be a JSON object." });
125
+ return { document: null, issues };
126
+ }
127
+ rejectUnknown(value, ROOT_FIELDS, "", issues);
128
+ if (value.schemaVersion !== 1) {
129
+ issues.push({ path: "/schemaVersion", message: "schemaVersion must be 1." });
130
+ }
131
+ if (value.format != null && value.format !== "network") {
132
+ issues.push({ path: "/format", message: 'format must be "network" when it is set.' });
133
+ }
134
+ const devices = readDevices(value.devices, issues);
135
+ const interfaces = readInterfaces(value.interfaces, issues);
136
+ const links = value.links == null ? [] : readLinks(value.links, issues);
137
+ const vlans = value.vlans == null ? [] : readVlans(value.vlans, issues);
138
+ const neighbors = readNeighbors(value.neighbors, issues);
139
+ if (issues.length > 0 || !devices || !interfaces || !links || !vlans || !neighbors) {
140
+ return { document: null, issues };
141
+ }
142
+ const names = /* @__PURE__ */ new Map();
143
+ devices.forEach((device, index) => {
144
+ const key = device.name.toLowerCase();
145
+ const previous = names.get(key);
146
+ if (previous != null) {
147
+ issues.push({ path: `/devices/${index}/name`, message: `duplicate device "${previous}".` });
148
+ return;
149
+ }
150
+ names.set(key, device.name);
151
+ });
152
+ interfaces.forEach((item, index) => {
153
+ if (!names.has(item.device.toLowerCase())) {
154
+ issues.push({ path: `/interfaces/${index}/device`, message: `no device named "${item.device}".` });
155
+ }
156
+ });
157
+ links.forEach((link, index) => {
158
+ for (const side of ["a", "b"]) {
159
+ const end = link[side];
160
+ if (!names.has(end.device.toLowerCase())) {
161
+ issues.push({ path: `/links/${index}/${side}/device`, message: `no device named "${end.device}".` });
162
+ }
163
+ }
164
+ });
165
+ if (issues.length > 0) return { document: null, issues };
166
+ return {
167
+ document: { schemaVersion: 1, devices, interfaces, links, vlans, neighbors },
168
+ issues: []
169
+ };
170
+ }
171
+ function readDevices(value, issues) {
172
+ if (!Array.isArray(value)) {
173
+ issues.push({ path: "/devices", message: "devices must be an array." });
174
+ return null;
175
+ }
176
+ let ok = true;
177
+ const devices = [];
178
+ value.forEach((item, index) => {
179
+ const path = `/devices/${index}`;
180
+ if (!isRecord(item)) {
181
+ issues.push({ path, message: "must be an object." });
182
+ ok = false;
183
+ return;
184
+ }
185
+ rejectUnknown(item, DEVICE_FIELDS, path, issues);
186
+ const name = requiredString(item.name, `${path}/name`, "name", issues);
187
+ if (!name) {
188
+ ok = false;
189
+ return;
190
+ }
191
+ const diagram = childDiagram(item.diagram, `${path}/diagram`, issues);
192
+ if (diagram == null) {
193
+ ok = false;
194
+ return;
195
+ }
196
+ devices.push({
197
+ name,
198
+ platform: optionalString(item.platform, `${path}/platform`, "platform", issues),
199
+ model: optionalString(item.model, `${path}/model`, "model", issues),
200
+ role: optionalString(item.role, `${path}/role`, "role", issues),
201
+ site: optionalString(item.site, `${path}/site`, "site", issues),
202
+ managementIp: optionalString(item.managementIp, `${path}/managementIp`, "managementIp", issues),
203
+ diagram
204
+ });
205
+ });
206
+ return ok && !issues.some((issue) => issue.path.startsWith("/devices/")) ? devices : null;
207
+ }
208
+ function readInterfaces(value, issues) {
209
+ if (!Array.isArray(value)) {
210
+ issues.push({ path: "/interfaces", message: "interfaces must be an array." });
211
+ return null;
212
+ }
213
+ const interfaces = [];
214
+ let ok = true;
215
+ value.forEach((item, index) => {
216
+ const path = `/interfaces/${index}`;
217
+ if (!isRecord(item)) {
218
+ issues.push({ path, message: "must be an object." });
219
+ ok = false;
220
+ return;
221
+ }
222
+ rejectUnknown(item, INTERFACE_FIELDS, path, issues);
223
+ const device = requiredString(item.device, `${path}/device`, "device", issues);
224
+ const name = requiredString(item.name, `${path}/name`, "name", issues);
225
+ const adminStatus = statusOf(item.adminStatus, `${path}/adminStatus`, "adminStatus", issues);
226
+ const operStatus = statusOf(item.operStatus, `${path}/operStatus`, "operStatus", issues);
227
+ const ipv4 = item.ipv4 == null ? [] : readAddresses(item.ipv4, `${path}/ipv4`, "ipv4", issues);
228
+ const ipv6 = item.ipv6 == null ? [] : readAddresses(item.ipv6, `${path}/ipv6`, "ipv6", issues);
229
+ const mode = switchportOf(item.switchportMode, `${path}/switchportMode`, issues);
230
+ const accessVlan = item.accessVlan == null ? null : vlanId(item.accessVlan, `${path}/accessVlan`, issues);
231
+ const nativeVlan = item.nativeVlan == null ? null : vlanId(item.nativeVlan, `${path}/nativeVlan`, issues);
232
+ const trunkVlans = item.trunkVlans == null ? null : readVlanList(item.trunkVlans, `${path}/trunkVlans`, issues);
233
+ if (!device || !name || adminStatus == null || operStatus == null || !ipv4 || !ipv6 || mode == null) {
234
+ ok = false;
235
+ return;
236
+ }
237
+ if (item.accessVlan != null && accessVlan == null || item.nativeVlan != null && nativeVlan == null) ok = false;
238
+ if (item.trunkVlans != null && !trunkVlans) ok = false;
239
+ interfaces.push({
240
+ device,
241
+ name,
242
+ description: optionalString(item.description, `${path}/description`, "description", issues),
243
+ speed: optionalString(item.speed, `${path}/speed`, "speed", issues),
244
+ adminStatus,
245
+ operStatus,
246
+ ipv4,
247
+ ipv6,
248
+ vrf: optionalString(item.vrf, `${path}/vrf`, "vrf", issues),
249
+ switchportMode: mode,
250
+ accessVlan,
251
+ trunkVlans,
252
+ nativeVlan,
253
+ lag: optionalString(item.lag, `${path}/lag`, "lag", issues)
254
+ });
255
+ });
256
+ return ok ? interfaces : null;
257
+ }
258
+ function readAddresses(value, path, family, issues) {
259
+ if (!Array.isArray(value)) {
260
+ issues.push({ path, message: `${family} must be an array.` });
261
+ return null;
262
+ }
263
+ const max = family === "ipv4" ? 32 : 128;
264
+ const addresses = [];
265
+ let ok = true;
266
+ value.forEach((item, index) => {
267
+ const itemPath = `${path}/${index}`;
268
+ if (!isRecord(item)) {
269
+ issues.push({ path: itemPath, message: "must be an object with address and prefix." });
270
+ ok = false;
271
+ return;
272
+ }
273
+ rejectUnknown(item, ADDRESS_FIELDS, itemPath, issues);
274
+ const address = requiredString(item.address, `${itemPath}/address`, "address", issues);
275
+ const prefixOk = Number.isInteger(item.prefix) && item.prefix >= 0 && item.prefix <= max;
276
+ if (!prefixOk) {
277
+ issues.push({ path: `${itemPath}/prefix`, message: `prefix must be an integer from 0 to ${max}.` });
278
+ ok = false;
279
+ }
280
+ if (!address) {
281
+ ok = false;
282
+ return;
283
+ }
284
+ if (!canonicalIp(address, family)) {
285
+ issues.push({
286
+ path: `${itemPath}/address`,
287
+ message: family === "ipv4" ? "address must be an IPv4 address." : "address must be an IPv6 address."
288
+ });
289
+ ok = false;
290
+ return;
291
+ }
292
+ if (prefixOk) addresses.push({ address, prefix: item.prefix });
293
+ });
294
+ return ok ? addresses : null;
295
+ }
296
+ function readLinks(value, issues) {
297
+ if (!Array.isArray(value)) {
298
+ issues.push({ path: "/links", message: "links must be an array." });
299
+ return null;
300
+ }
301
+ const links = [];
302
+ let ok = true;
303
+ value.forEach((item, index) => {
304
+ const path = `/links/${index}`;
305
+ if (!isRecord(item)) {
306
+ issues.push({ path, message: "must be an object with a and b." });
307
+ ok = false;
308
+ return;
309
+ }
310
+ rejectUnknown(item, LINK_FIELDS, path, issues);
311
+ const a = readEndpoint(item.a, `${path}/a`, issues);
312
+ const b = readEndpoint(item.b, `${path}/b`, issues);
313
+ if (!a || !b) {
314
+ ok = false;
315
+ return;
316
+ }
317
+ const inferred = optionalFlag(item.inferred, `${path}/inferred`, "inferred", issues);
318
+ if (inferred == null) {
319
+ ok = false;
320
+ return;
321
+ }
322
+ links.push({
323
+ a,
324
+ b,
325
+ label: optionalString(item.label, `${path}/label`, "label", issues),
326
+ inferred
327
+ });
328
+ });
329
+ return ok ? links : null;
330
+ }
331
+ function readEndpoint(value, path, issues) {
332
+ if (!isRecord(value)) {
333
+ issues.push({ path, message: "must be an object with device and interface." });
334
+ return null;
335
+ }
336
+ rejectUnknown(value, ENDPOINT_FIELDS, path, issues);
337
+ const device = requiredString(value.device, `${path}/device`, "device", issues);
338
+ const iface = requiredString(value.interface, `${path}/interface`, "interface", issues);
339
+ if (!device || !iface) return null;
340
+ return { device, interface: iface };
341
+ }
342
+ function readVlanList(value, path, issues) {
343
+ if (!Array.isArray(value)) {
344
+ issues.push({ path, message: "trunkVlans must be an array of VLAN ids." });
345
+ return null;
346
+ }
347
+ const ids = [];
348
+ let ok = true;
349
+ value.forEach((item, index) => {
350
+ const id = vlanId(item, `${path}/${index}`, issues);
351
+ if (id == null) ok = false;
352
+ else ids.push(id);
353
+ });
354
+ return ok ? ids : null;
355
+ }
356
+ function readVlans(value, issues) {
357
+ if (!Array.isArray(value)) {
358
+ issues.push({ path: "/vlans", message: "vlans must be an array." });
359
+ return null;
360
+ }
361
+ const vlans = [];
362
+ const seen = /* @__PURE__ */ new Set();
363
+ let ok = true;
364
+ value.forEach((item, index) => {
365
+ const path = `/vlans/${index}`;
366
+ if (!isRecord(item)) {
367
+ issues.push({ path, message: "must be an object." });
368
+ ok = false;
369
+ return;
370
+ }
371
+ rejectUnknown(item, VLAN_FIELDS, path, issues);
372
+ const id = vlanId(item.id, `${path}/id`, issues);
373
+ if (id == null) {
374
+ ok = false;
375
+ return;
376
+ }
377
+ if (seen.has(id)) issues.push({ path: `${path}/id`, message: `duplicate VLAN ${id}.` });
378
+ seen.add(id);
379
+ vlans.push({ id, name: optionalString(item.name, `${path}/name`, "name", issues) });
380
+ });
381
+ return ok ? vlans : null;
382
+ }
383
+ function readNeighbors(value, issues) {
384
+ if (value == null) return { cdp: "", lldp: "", localDevice: "" };
385
+ if (!isRecord(value)) {
386
+ issues.push({ path: "/neighbors", message: "neighbors must be an object." });
387
+ return null;
388
+ }
389
+ rejectUnknown(value, NEIGHBOR_FIELDS, "/neighbors", issues);
390
+ return {
391
+ cdp: optionalString(value.cdp, "/neighbors/cdp", "cdp", issues),
392
+ lldp: optionalString(value.lldp, "/neighbors/lldp", "lldp", issues),
393
+ localDevice: optionalString(value.localDevice, "/neighbors/localDevice", "localDevice", issues)
394
+ };
395
+ }
396
+ function statusOf(value, path, label, issues) {
397
+ if (value == null || value === "") return "";
398
+ if (value === "up" || value === "down") return value;
399
+ issues.push({ path, message: `${label} must be up or down.` });
400
+ return null;
401
+ }
402
+ function switchportOf(value, path, issues) {
403
+ if (value == null || value === "") return "";
404
+ if (value === "access" || value === "trunk") return value;
405
+ issues.push({ path, message: "switchportMode must be access or trunk." });
406
+ return null;
407
+ }
408
+ function vlanId(value, path, issues) {
409
+ if (typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 4094) return value;
410
+ issues.push({ path, message: "must be an integer from 1 to 4094." });
411
+ return null;
412
+ }
413
+ function requiredString(value, path, label, issues) {
414
+ if (typeof value !== "string" || !value.trim()) {
415
+ issues.push({ path, message: `${label} is required.` });
416
+ return "";
417
+ }
418
+ return value.trim();
419
+ }
420
+ function childDiagram(value, path, issues) {
421
+ if (value == null || value === "") return "";
422
+ if (typeof value !== "string") {
423
+ issues.push({ path, message: "diagram must be a string." });
424
+ return null;
425
+ }
426
+ const trimmed = value.trim();
427
+ if (!trimmed) return "";
428
+ if (/[\u0000-\u001f"\\?#]/.test(trimmed) || clickTargetKind(trimmed) === "unsafe" || clickTargetKind(trimmed) === "external") {
429
+ issues.push({ path, message: "diagram must be a workspace .mmd path." });
430
+ return null;
431
+ }
432
+ const resolved = resolveDiagramTarget(trimmed, "");
433
+ if (!resolved.ok) {
434
+ issues.push({ path, message: "diagram must be a workspace .mmd path." });
435
+ return null;
436
+ }
437
+ return resolved.path;
438
+ }
439
+ function optionalFlag(value, path, label, issues) {
440
+ if (value == null) return false;
441
+ if (typeof value === "boolean") return value;
442
+ issues.push({ path, message: `${label} must be a boolean.` });
443
+ return null;
444
+ }
445
+ function optionalString(value, path, label, issues) {
446
+ if (value == null || value === "") return "";
447
+ if (typeof value !== "string") {
448
+ issues.push({ path, message: `${label} must be a string.` });
449
+ return "";
450
+ }
451
+ return value.trim();
452
+ }
453
+ function rejectUnknown(value, allowed, path, issues) {
454
+ for (const key of Object.keys(value)) {
455
+ if (allowed.has(key)) continue;
456
+ issues.push({ path: path ? `${path}/${key}` : `/${key}`, message: `unexpected property "${key}".` });
457
+ }
458
+ }
459
+ function isRecord(value) {
460
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
461
+ }
30
462
 
31
463
  // server/src/diagramData.ts
32
464
  import { Document, isMap, parseDocument } from "yaml";
@@ -828,7 +1260,7 @@ function parseLldpKeyvalue(text, options) {
828
1260
  const match = /^lldp\.([^.]+)\.(.+?)=(.*)$/.exec(trimmed);
829
1261
  if (!match?.[1] || !match[2]) continue;
830
1262
  const iface = match[1];
831
- const path5 = match[2];
1263
+ const path = match[2];
832
1264
  const value = match[3] ?? "";
833
1265
  if (!bag || bag.iface !== iface) {
834
1266
  flush();
@@ -846,16 +1278,16 @@ function parseLldpKeyvalue(text, options) {
846
1278
  }
847
1279
  if (!current[field]) current[field] = next;
848
1280
  };
849
- if (path5 === "chassis.name") setOnce("systemName", value);
850
- else if (path5 === "chassis.descr" || path5 === "chassis.description") setOnce("systemDescription", value);
851
- else if (path5 === "chassis.mac") setOnce("chassisId", value);
852
- else if (path5 === "port.ifname") {
1281
+ if (path === "chassis.name") setOnce("systemName", value);
1282
+ else if (path === "chassis.descr" || path === "chassis.description") setOnce("systemDescription", value);
1283
+ else if (path === "chassis.mac") setOnce("chassisId", value);
1284
+ else if (path === "port.ifname") {
853
1285
  if (current.portId && isMacAddress(current.portId)) current.portId = "";
854
1286
  setOnce("portId", value);
855
- } else if ((path5 === "port.id" || path5 === "port.mac") && !current.portId) setOnce("portId", value);
856
- else if (path5 === "port.descr" || path5 === "port.description") setOnce("portDescription", value);
857
- else if (/\.enabled$/.test(path5)) {
858
- const name = path5.split(".").slice(-2, -1)[0] ?? "";
1287
+ } else if ((path === "port.id" || path === "port.mac") && !current.portId) setOnce("portId", value);
1288
+ else if (path === "port.descr" || path === "port.description") setOnce("portDescription", value);
1289
+ else if (/\.enabled$/.test(path)) {
1290
+ const name = path.split(".").slice(-2, -1)[0] ?? "";
859
1291
  if (/^(?:on|true|yes|1)$/i.test(value) && name) {
860
1292
  current.enabledCaps = current.enabledCaps ? `${current.enabledCaps}, ${name}` : name;
861
1293
  }
@@ -864,14 +1296,14 @@ function parseLldpKeyvalue(text, options) {
864
1296
  flush();
865
1297
  return collected;
866
1298
  }
867
- function isRecord(value) {
1299
+ function isRecord2(value) {
868
1300
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
869
1301
  }
870
1302
  function textOf(value) {
871
1303
  if (typeof value === "string") return value.trim();
872
1304
  if (typeof value === "number" || typeof value === "boolean") return String(value);
873
1305
  if (Array.isArray(value)) return value.map((item) => textOf(item)).filter(Boolean).join(", ");
874
- if (isRecord(value)) {
1306
+ if (isRecord2(value)) {
875
1307
  if (typeof value.value === "string" || typeof value.value === "number") return String(value.value).trim();
876
1308
  }
877
1309
  return "";
@@ -885,7 +1317,7 @@ function capabilityFromJson(value) {
885
1317
  enabled.push(item);
886
1318
  continue;
887
1319
  }
888
- if (!isRecord(item)) continue;
1320
+ if (!isRecord2(item)) continue;
889
1321
  const type = textOf(item.type ?? item.name);
890
1322
  const flag = item.enabled;
891
1323
  if (flag === false || flag === "off" || flag === "false") continue;
@@ -894,7 +1326,7 @@ function capabilityFromJson(value) {
894
1326
  return enabled.join(", ");
895
1327
  }
896
1328
  function chassisFromJson(chassis) {
897
- if (!isRecord(chassis)) return [];
1329
+ if (!isRecord2(chassis)) return [];
898
1330
  const known = /* @__PURE__ */ new Set(["id", "name", "descr", "description", "mgmt-ip", "mgmt_ip", "capability", "capabilities"]);
899
1331
  const direct = textOf(chassis.name) || chassis.id || chassis.descr || chassis.description;
900
1332
  if (direct) {
@@ -907,7 +1339,7 @@ function chassisFromJson(chassis) {
907
1339
  }
908
1340
  ];
909
1341
  }
910
- const hosts = Object.keys(chassis).filter((key) => !known.has(key) && isRecord(chassis[key]));
1342
+ const hosts = Object.keys(chassis).filter((key) => !known.has(key) && isRecord2(chassis[key]));
911
1343
  if (hosts.length === 0) return [];
912
1344
  return hosts.map((host) => {
913
1345
  const inner = chassis[host];
@@ -920,7 +1352,7 @@ function chassisFromJson(chassis) {
920
1352
  });
921
1353
  }
922
1354
  function portFromJson(port) {
923
- if (!isRecord(port)) return { id: "", descr: "" };
1355
+ if (!isRecord2(port)) return { id: "", descr: "" };
924
1356
  return {
925
1357
  id: textOf(port.id ?? port.ifname ?? port.name),
926
1358
  descr: textOf(port.descr ?? port.description)
@@ -929,16 +1361,16 @@ function portFromJson(port) {
929
1361
  function interfaceRecords(node) {
930
1362
  if (Array.isArray(node)) {
931
1363
  return node.flatMap((item, index) => {
932
- if (!isRecord(item)) return [];
1364
+ if (!isRecord2(item)) return [];
933
1365
  const name = textOf(item.name) || `if${index + 1}`;
934
1366
  return [{ name, value: item }];
935
1367
  });
936
1368
  }
937
- if (!isRecord(node)) return [];
1369
+ if (!isRecord2(node)) return [];
938
1370
  if (node.chassis || node.port || node.name) {
939
1371
  return [{ name: textOf(node.name) || "interface", value: node }];
940
1372
  }
941
- return Object.entries(node).flatMap(([name, value]) => isRecord(value) ? [{ name, value }] : []);
1373
+ return Object.entries(node).flatMap(([name, value]) => isRecord2(value) ? [{ name, value }] : []);
942
1374
  }
943
1375
  function parseLldpJson(text, options) {
944
1376
  const collected = { raw: [], errors: [], warnings: [], preferred: [], overflow: false };
@@ -951,8 +1383,8 @@ function parseLldpJson(text, options) {
951
1383
  collected.errors.push({ row: 1, message: "This LLDP JSON could not be parsed." });
952
1384
  return collected;
953
1385
  }
954
- const root = isRecord(parsed) && parsed.lldp ? parsed.lldp : parsed;
955
- const interfaces = isRecord(root) ? interfaceRecords(root.interface ?? root.interfaces ?? root) : [];
1386
+ const root = isRecord2(parsed) && parsed.lldp ? parsed.lldp : parsed;
1387
+ const interfaces = isRecord2(root) ? interfaceRecords(root.interface ?? root.interfaces ?? root) : [];
956
1388
  if (interfaces.length === 0) {
957
1389
  collected.errors.push({ row: 1, message: "This LLDP JSON has no interface neighbors." });
958
1390
  return collected;
@@ -1030,6 +1462,30 @@ var DATA_LIMITS = {
1030
1462
  maxCellChars: 2e3,
1031
1463
  maxTitleChars: 200
1032
1464
  };
1465
+ var DATA_FIELDS = [
1466
+ "localDevice",
1467
+ "localPort",
1468
+ "remoteDevice",
1469
+ "remotePort",
1470
+ "localGroup",
1471
+ "remoteGroup",
1472
+ "localType",
1473
+ "remoteType",
1474
+ "localClass",
1475
+ "remoteClass",
1476
+ "localDiagram",
1477
+ "remoteDiagram",
1478
+ "id",
1479
+ "label",
1480
+ "group",
1481
+ "type",
1482
+ "styleClass",
1483
+ "diagram",
1484
+ "source",
1485
+ "target"
1486
+ ];
1487
+ var DIRECTIONS = /* @__PURE__ */ new Set(["TD", "TB", "LR", "RL", "BT"]);
1488
+ var SHAPES = /* @__PURE__ */ new Set(["links", "nodes", "edges", "graph"]);
1033
1489
  var SHAPE_FIELDS = {
1034
1490
  links: [
1035
1491
  { field: "localDevice", label: "Local device", required: true },
@@ -1068,427 +1524,433 @@ var SHAPE_FIELDS = {
1068
1524
  ]
1069
1525
  };
1070
1526
  var EDGE_FIELDS = SHAPE_FIELDS.edges;
1071
-
1072
- // server/src/diagramSightings.ts
1073
- import path from "node:path";
1074
- var FILE_NAME = "diagram-sightings.json";
1075
- var chain = Promise.resolve();
1076
- var depth = 0;
1077
- var suppress = 0;
1078
- function sightingsPath() {
1079
- return path.join(getMetaPath(), FILE_NAME);
1080
- }
1081
- function emptyCatalog() {
1082
- return { version: 1, updatedAt: 0, files: [], pending: [] };
1083
- }
1084
- function isPending(value) {
1085
- if (!value || typeof value !== "object") return false;
1086
- const item = value;
1087
- return typeof item.from === "string" && (item.to === null || typeof item.to === "string") && (item.match === "content" || item.match === "basename" || item.match === "ambiguous") && Array.isArray(item.candidates) && item.candidates.every((candidate) => typeof candidate === "string") && typeof item.noticedAt === "number";
1088
- }
1089
- function isSighting(value) {
1090
- if (!value || typeof value !== "object") return false;
1091
- const item = value;
1092
- return typeof item.path === "string" && typeof item.hash === "string" && typeof item.seenAt === "number" && (item.missingAt == null || typeof item.missingAt === "number");
1093
- }
1094
- function normalizeCatalog(value) {
1095
- if (!value || typeof value !== "object") return null;
1096
- const record = value;
1097
- if (record.version !== 1 || !Array.isArray(record.files) || !Array.isArray(record.pending)) return null;
1098
- if (typeof record.updatedAt !== "number") return null;
1099
- return {
1100
- version: 1,
1101
- updatedAt: record.updatedAt,
1102
- files: record.files.filter(isSighting).map((file) => ({
1103
- path: normalizeRelative(file.path),
1104
- hash: file.hash,
1105
- seenAt: file.seenAt,
1106
- ...file.missingAt != null ? { missingAt: file.missingAt } : {}
1107
- })),
1108
- pending: record.pending.filter(isPending).map((item) => ({
1109
- from: normalizeRelative(item.from),
1110
- to: item.to ? normalizeRelative(item.to) : null,
1111
- match: item.match,
1112
- candidates: item.candidates.map((candidate) => normalizeRelative(candidate)).filter(Boolean),
1113
- noticedAt: item.noticedAt
1114
- }))
1115
- };
1527
+ function dataFail(status, message, code, details) {
1528
+ return Object.assign(new Error(message), { status, code, details });
1116
1529
  }
1117
- async function load() {
1530
+ function readDataSource(source) {
1118
1531
  try {
1119
- return normalizeCatalog(await readJsonFile(sightingsPath())) ?? emptyCatalog();
1532
+ const loaded = loadYaml(source);
1533
+ if ("error" in loaded) return null;
1534
+ const raw = loaded.doc.toJS();
1535
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
1536
+ const nerdgram = raw.nerdgram;
1537
+ if (!nerdgram || typeof nerdgram !== "object" || Array.isArray(nerdgram)) return null;
1538
+ const block = nerdgram.source;
1539
+ if (!block || typeof block !== "object" || Array.isArray(block)) return null;
1540
+ return configFromPlain(block);
1120
1541
  } catch {
1121
- return emptyCatalog();
1122
- }
1123
- }
1124
- async function save(catalog) {
1125
- const files = [...catalog.files].sort((a, b) => a.path.localeCompare(b.path));
1126
- const pending = [...catalog.pending].sort((a, b) => a.from.localeCompare(b.from));
1127
- await atomicWriteJson(sightingsPath(), { ...catalog, files, pending });
1128
- }
1129
- function exclusive(fn) {
1130
- if (depth > 0) return fn();
1131
- const run = chain.then(async () => {
1132
- depth += 1;
1133
- try {
1134
- return await fn();
1135
- } finally {
1136
- depth -= 1;
1137
- }
1138
- });
1139
- chain = run.then(
1140
- () => void 0,
1141
- () => void 0
1142
- );
1143
- return run;
1144
- }
1145
- async function noteDiagramSighting(snapshot) {
1146
- if (suppress > 0) return;
1147
- const filePath = normalizeRelative(snapshot.path);
1148
- if (!filePath || !snapshot.hash) return;
1149
- await exclusive(async () => {
1150
- if (suppress > 0) return;
1151
- const now = Date.now();
1152
- const catalog = await load();
1153
- const files = catalog.files.filter((file) => file.path !== filePath && file.missingAt == null);
1154
- files.push({ path: filePath, hash: snapshot.hash, seenAt: now });
1155
- for (const old of catalog.files) {
1156
- if (old.missingAt == null || old.path === filePath) continue;
1157
- if (!catalog.pending.some((item) => item.from === old.path)) continue;
1158
- files.push(old);
1159
- }
1160
- const pending = catalog.pending.filter((item) => item.from !== filePath);
1161
- const updatedAt = catalog.updatedAt === 0 ? now : catalog.updatedAt;
1162
- await save({ version: 1, updatedAt, files, pending });
1163
- });
1164
- }
1165
-
1166
- // server/src/history.ts
1167
- import fs from "node:fs/promises";
1168
- import path2 from "node:path";
1169
- function versionDirFor(relativePath) {
1170
- return path2.join(getVersionsRoot(), safeStorageKey(relativePath));
1171
- }
1172
- function indexPath(dir) {
1173
- return path2.join(dir, "index.json");
1174
- }
1175
- async function loadIndex(dir, fallbackPath) {
1176
- const parsed = await readJsonFile(indexPath(dir));
1177
- if (!parsed || !Array.isArray(parsed.revisions)) {
1178
- return { path: fallbackPath, revisions: [] };
1542
+ return null;
1179
1543
  }
1180
- return {
1181
- path: typeof parsed.path === "string" ? parsed.path : fallbackPath,
1182
- revisions: parsed.revisions.flatMap((revision) => {
1183
- const meta = readRevisionMeta(revision);
1184
- return meta ? [meta] : [];
1185
- })
1186
- };
1187
1544
  }
1188
- function readRevisionMeta(value) {
1189
- if (!value || typeof value !== "object") return null;
1190
- const revision = value;
1191
- if (typeof revision.id !== "string" || typeof revision.createdAt !== "string" || typeof revision.mtimeMs !== "number" || typeof revision.size !== "number" || typeof revision.hash !== "string") {
1545
+ function isSafeDataPath(relativePath) {
1546
+ if (typeof relativePath !== "string" || !relativePath || relativePath.includes("\0")) return false;
1547
+ const normalized = relativePath.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
1548
+ if (!normalized) return false;
1549
+ const parts = normalized.split("/");
1550
+ if (parts.some((part) => part.length === 0 || part === "." || part === ".." || part.startsWith("."))) return false;
1551
+ const base = normalized.split("/").pop() ?? "";
1552
+ return isDataFileName(base);
1553
+ }
1554
+ function configFromPlain(block) {
1555
+ const file = typeof block.file === "string" ? block.file : "";
1556
+ if (!isSafeDataPath(file)) return null;
1557
+ if (block.format !== "csv" && block.format !== "json" && block.format !== "cdp" && block.format !== "lldp" && block.format !== "network") {
1192
1558
  return null;
1193
1559
  }
1194
- const meta = {
1195
- id: revision.id,
1196
- createdAt: revision.createdAt,
1197
- mtimeMs: revision.mtimeMs,
1198
- size: revision.size,
1199
- hash: revision.hash
1560
+ if (typeof block.shape !== "string" || !SHAPES.has(block.shape)) return null;
1561
+ const direction = typeof block.direction === "string" ? block.direction.toUpperCase() : "TD";
1562
+ if (!DIRECTIONS.has(direction)) return null;
1563
+ const mapping = mappingFromPlain(block.mapping);
1564
+ if (!mapping) return null;
1565
+ const config = {
1566
+ file,
1567
+ format: block.format,
1568
+ shape: block.shape,
1569
+ mapping,
1570
+ direction,
1571
+ grouping: block.grouping !== false,
1572
+ diagramType: "flowchart"
1200
1573
  };
1201
- if (typeof revision.name === "string" && revision.name.trim()) meta.name = revision.name;
1202
- if (typeof revision.note === "string" && revision.note.trim()) meta.note = revision.note;
1203
- if (typeof revision.namedAt === "string" && revision.namedAt.trim()) meta.namedAt = revision.namedAt;
1204
- return meta;
1205
- }
1206
- function isNamedRevision(revision) {
1207
- return typeof revision.name === "string" && revision.name.trim().length > 0;
1208
- }
1209
- async function saveIndex(dir, index) {
1210
- await atomicWriteJson(indexPath(dir), index);
1211
- }
1212
- async function prune(dir, index) {
1213
- const named = index.revisions.filter((revision) => isNamedRevision(revision));
1214
- const unnamed = index.revisions.filter((revision) => !isNamedRevision(revision));
1215
- unnamed.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
1216
- while (unnamed.length > REVISION_RETENTION) {
1217
- const dropped = unnamed.shift();
1218
- if (!dropped) break;
1219
- await fs.rm(path2.join(dir, `${dropped.id}.mmd`), { force: true });
1220
- }
1221
- index.revisions = [...named, ...unnamed];
1222
- }
1223
- async function snapshotPrevious(relativePath, previous) {
1224
- const normalized = normalizeRelative(relativePath);
1225
- const dir = versionDirFor(normalized);
1226
- await fs.mkdir(dir, { recursive: true });
1227
- const index = await loadIndex(dir, normalized);
1228
- const id = createId();
1229
- await atomicWriteText(path2.join(dir, `${id}.mmd`), previous.content);
1230
- index.path = normalized;
1231
- index.revisions.push({
1232
- id,
1233
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1234
- mtimeMs: previous.mtimeMs,
1235
- size: previous.size,
1236
- hash: previous.hash
1237
- });
1238
- await prune(dir, index);
1239
- await saveIndex(dir, index);
1240
- return id;
1574
+ if (typeof block.edgesFile === "string" && block.edgesFile) {
1575
+ if (!isSafeDataPath(block.edgesFile)) return null;
1576
+ config.edgesFile = block.edgesFile;
1577
+ }
1578
+ if (block.edgesFormat === "csv" || block.edgesFormat === "json") config.edgesFormat = block.edgesFormat;
1579
+ const edgesMapping = mappingFromPlain(block.edgesMapping);
1580
+ if (block.edgesMapping != null && !edgesMapping) return null;
1581
+ if (edgesMapping && Object.keys(edgesMapping).length > 0) config.edgesMapping = edgesMapping;
1582
+ if (block.format === "network") {
1583
+ if (block.view !== "l3" && block.view !== "l2") return null;
1584
+ config.view = block.view;
1585
+ config.includeDown = block.includeDown === true;
1586
+ if (block.vlan != null && block.vlan !== "") {
1587
+ if (typeof block.vlan !== "number" || !Number.isInteger(block.vlan) || block.vlan < 1 || block.vlan > 4094) return null;
1588
+ config.vlan = block.vlan;
1589
+ }
1590
+ if (block.groupBy != null && block.groupBy !== "") {
1591
+ if (block.groupBy !== "vrf" && block.groupBy !== "site" && block.groupBy !== "role" && block.groupBy !== "platform") {
1592
+ return null;
1593
+ }
1594
+ config.groupBy = block.groupBy;
1595
+ }
1596
+ } else if (block.groupBy != null && block.groupBy !== "") {
1597
+ if (block.groupBy !== "platform" && block.groupBy !== "capability") return null;
1598
+ config.groupBy = block.groupBy;
1599
+ }
1600
+ if (typeof block.localDevice === "string" && block.localDevice.trim()) {
1601
+ config.localDevice = block.localDevice.trim();
1602
+ }
1603
+ return config;
1604
+ }
1605
+ function mappingFromPlain(value) {
1606
+ if (value == null) return {};
1607
+ if (!isRecord3(value)) return null;
1608
+ const mapping = {};
1609
+ for (const field of DATA_FIELDS) {
1610
+ const column = value[field];
1611
+ if (column == null || column === "") continue;
1612
+ if (typeof column !== "string") return null;
1613
+ mapping[field] = column;
1614
+ }
1615
+ return mapping;
1241
1616
  }
1242
-
1243
- // server/src/locks.ts
1244
- import path3 from "node:path";
1245
- var SAME_INSTANCE_MESSAGE = "This diagram is open in another window.";
1246
- function lockStorageKey(relativePath) {
1247
- return safeStorageKey(relativePath, ".json");
1617
+ function isRecord3(value) {
1618
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1248
1619
  }
1249
- function lockFile(relativePath) {
1250
- return path3.join(getLocksRoot(), `${lockStorageKey(relativePath)}.json`);
1620
+ function yamlText(match) {
1621
+ const normalized = match.body.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1622
+ if (!match.indent) return normalized;
1623
+ return normalized.split("\n").map((line) => line.startsWith(match.indent) ? line.slice(match.indent.length) : line).join("\n");
1624
+ }
1625
+ function loadYaml(source) {
1626
+ const bom = source.startsWith("\uFEFF") ? "\uFEFF" : "";
1627
+ const text = bom ? source.slice(1) : source;
1628
+ const match = matchFrontMatter(text);
1629
+ if (!match) return { doc: new Document({}), body: text, bom };
1630
+ const doc = parseDocument(yamlText(match), { schema: "core", prettyErrors: false });
1631
+ if (doc.errors.length > 0) return { error: "The YAML header could not be parsed." };
1632
+ if (!isMap(doc.contents)) return { error: "Front matter must be a YAML mapping." };
1633
+ return { doc, body: text.slice(match.length), bom };
1251
1634
  }
1252
- function optionalText(value) {
1253
- if (typeof value !== "string") return void 0;
1254
- const trimmed = value.trim();
1255
- return trimmed || void 0;
1635
+
1636
+ // server/src/exporters/limits.ts
1637
+ var EXPORT_MAX_INPUT_BYTES = DATA_LIMITS.maxChars;
1638
+ var EXPORT_MAX_DEVICES = DATA_LIMITS.maxNodes;
1639
+ var EXPORT_MAX_LINKS = DATA_LIMITS.maxEdges;
1640
+ function exporterFail(status, message, code = "invalid") {
1641
+ return Object.assign(new Error(message), { status, code });
1642
+ }
1643
+ function assertExportInputSize(bytes) {
1644
+ if (!Number.isFinite(bytes) || bytes < 0) {
1645
+ throw exporterFail(400, "The network document size is not valid.");
1646
+ }
1647
+ if (bytes > EXPORT_MAX_INPUT_BYTES) {
1648
+ throw exporterFail(413, "The network document is larger than 512 KB.", "too_large");
1649
+ }
1256
1650
  }
1257
- function isLockRecord(value) {
1258
- if (!value || typeof value !== "object") return false;
1259
- const record = value;
1260
- return typeof record.path === "string" && typeof record.token === "string" && typeof record.sessionId === "string" && typeof record.pid === "number" && typeof record.acquiredAt === "string" && typeof record.heartbeatAt === "string";
1651
+
1652
+ // server/src/exporters/helpers.ts
1653
+ import { createHash, randomUUID } from "node:crypto";
1654
+ import { stringify as stringifyYaml, parse as parseYaml } from "yaml";
1655
+ var CHANGE_ME = "CHANGE_ME";
1656
+ var HEADER_LINES = [
1657
+ "Generated by NerdGram from this diagram's network data.",
1658
+ "Credentials, images, and other values the diagram does not know are placeholders.",
1659
+ "Missing facts were omitted or marked. NerdGram did not connect to a device.",
1660
+ "Replace every CHANGE_ME before you use this file. Do not commit a real secret."
1661
+ ];
1662
+ function isRecord4(value) {
1663
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1261
1664
  }
1262
- function normalizeLock(record) {
1263
- const instanceId = optionalText(record.instanceId);
1264
- const instanceName = optionalText(record.instanceName);
1265
- const hostname = optionalText(record.hostname);
1266
- return {
1267
- path: record.path,
1268
- token: record.token,
1269
- sessionId: record.sessionId,
1270
- pid: record.pid,
1271
- acquiredAt: record.acquiredAt,
1272
- heartbeatAt: record.heartbeatAt,
1273
- ...instanceId ? { instanceId } : {},
1274
- ...instanceName ? { instanceName } : {},
1275
- ...hostname ? { hostname } : {}
1276
- };
1665
+ function pushWarning(warnings, path, message) {
1666
+ if (warnings.some((item) => item.path === path && item.message === message)) return;
1667
+ warnings.push({ path, message });
1277
1668
  }
1278
- function lockIsStale(record, now = Date.now(), instanceId) {
1279
- const heartbeat = Date.parse(record.heartbeatAt);
1280
- if (!Number.isFinite(heartbeat) || now - heartbeat > LOCK_STALE_MS) return true;
1281
- const legacy = !optionalText(record.instanceId);
1282
- const sameInstance2 = Boolean(instanceId) && record.instanceId === instanceId;
1283
- if ((sameInstance2 || legacy) && record.pid !== process.pid && !isProcessAlive(record.pid)) return true;
1284
- return false;
1285
- }
1286
- function sameInstance(record, identity) {
1287
- return !optionalText(record.instanceId) || record.instanceId === identity.instanceId;
1288
- }
1289
- function diagramLabel(relativePath) {
1290
- const base = relativePath.split("/").pop() || relativePath;
1291
- return base.replace(/\.mmd$/i, "") || base;
1292
- }
1293
- function formatLockSince(iso) {
1294
- const date = new Date(iso);
1295
- if (Number.isNaN(date.getTime())) return iso;
1296
- return new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit" }).format(date);
1297
- }
1298
- function lockedMessage(record, identity) {
1299
- if (sameInstance(record, identity)) return SAME_INSTANCE_MESSAGE;
1300
- const name = record.instanceName || record.hostname || "another instance";
1301
- const host = record.hostname && record.instanceName && record.hostname !== record.instanceName ? ` (${record.hostname})` : "";
1302
- return `${diagramLabel(record.path)} is open on ${name}${host} since ${formatLockSince(record.acquiredAt)}. Try again when it's closed.`;
1303
- }
1304
- async function readLock(relativePath) {
1305
- const parsed = await readJsonFile(lockFile(relativePath));
1306
- if (!isLockRecord(parsed)) return null;
1307
- const record = normalizeLock(parsed);
1308
- const identity = await getInstanceIdentity();
1309
- return { ...record, stale: lockIsStale(record, Date.now(), identity.instanceId) };
1310
- }
1311
- function holderDetails(record, identity) {
1312
- return {
1313
- acquiredAt: record.acquiredAt,
1314
- heartbeatAt: record.heartbeatAt,
1315
- staleAfterMs: LOCK_STALE_MS,
1316
- instanceId: record.instanceId ?? null,
1317
- instanceName: record.instanceName ?? null,
1318
- hostname: record.hostname ?? null,
1319
- sameInstance: sameInstance(record, identity)
1320
- };
1669
+ function sortWarnings(warnings) {
1670
+ return [...warnings].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.message < b.message ? -1 : a.message > b.message ? 1 : 0);
1321
1671
  }
1322
- async function lockedError(record) {
1323
- const identity = await getInstanceIdentity();
1324
- return httpFail(423, lockedMessage(record, identity), "locked", {
1325
- lock: holderDetails(record, identity)
1326
- });
1672
+ function commentBlock(style, lines) {
1673
+ if (style === "xml") {
1674
+ const body = lines.map((line) => ` ${line}`).join("\n");
1675
+ return `<!--
1676
+ ${body}
1677
+ -->
1678
+ `;
1679
+ }
1680
+ const mark = style === "slash" ? "//" : "#";
1681
+ return lines.map((line) => line ? `${mark} ${line}` : mark).join("\n") + "\n";
1682
+ }
1683
+ function renderYaml(value) {
1684
+ return stringifyYaml(value, { lineWidth: 0 });
1685
+ }
1686
+ function assertExportShape(document) {
1687
+ if (document.devices.length > EXPORT_MAX_DEVICES || document.links.length > EXPORT_MAX_LINKS) {
1688
+ throw exporterFail(
1689
+ 413,
1690
+ `A design export can have at most ${EXPORT_MAX_DEVICES} devices and ${EXPORT_MAX_LINKS} links.`,
1691
+ "too_large"
1692
+ );
1693
+ }
1327
1694
  }
1328
- async function assertWriteAllowed(relativePath, token) {
1329
- const existing = await readLock(relativePath);
1330
- if (!existing || existing.stale) return;
1331
- if (token && existing.token === token) return;
1332
- throw await lockedError(existing);
1695
+ function safeLabel(label) {
1696
+ const trimmed = label.trim();
1697
+ if (!trimmed || /^-+$/.test(trimmed)) return "nerdgram";
1698
+ return trimmed;
1333
1699
  }
1334
-
1335
- // server/src/fsStore.ts
1336
- var DIAGRAM_EXT = ".mmd";
1337
- function isDiagramFile(name) {
1338
- return name.toLowerCase().endsWith(DIAGRAM_EXT);
1700
+ function fileName(label, extension) {
1701
+ const stem = safeLabel(label).replace(/[\\/]/g, "-");
1702
+ if (!extension) return stem;
1703
+ return `${stem}.${extension}`;
1704
+ }
1705
+ function cidr(address, prefix) {
1706
+ return `${address}/${prefix}`;
1707
+ }
1708
+ var SHORT_FOR_LONG = [
1709
+ { long: "GigabitEthernet", short: "Gi" },
1710
+ { long: "TenGigabitEthernet", short: "Te" },
1711
+ { long: "FastEthernet", short: "Fa" },
1712
+ { long: "FortyGigabitEthernet", short: "Fo" },
1713
+ { long: "HundredGigE", short: "Hu" },
1714
+ { long: "TwentyFiveGigE", short: "Twe" },
1715
+ { long: "AppGigabitEthernet", short: "Ap" },
1716
+ { long: "Port-channel", short: "Po" },
1717
+ { long: "Loopback", short: "Lo" },
1718
+ { long: "Vlan", short: "Vl" },
1719
+ { long: "Tunnel", short: "Tu" },
1720
+ { long: "Serial", short: "Se" },
1721
+ { long: "Ethernet", short: "Eth" }
1722
+ ];
1723
+ function expandInterface(name) {
1724
+ for (const pair of SHORT_FOR_LONG) {
1725
+ const match = new RegExp(`^${pair.short}(?=\\d)`, "i").exec(name);
1726
+ if (match) return `${pair.long}${name.slice(match[0].length)}`;
1727
+ }
1728
+ return name;
1339
1729
  }
1340
- async function readDirSafe(dir) {
1341
- try {
1342
- return await fs2.readdir(dir);
1343
- } catch (err) {
1344
- const code = err.code;
1345
- if (code === "ENOENT") return [];
1346
- throw err;
1347
- }
1348
- }
1349
- async function buildTree(relativePath = "") {
1350
- ensureDataRoot();
1351
- const abs = resolveSafePath(relativePath || ".");
1352
- const entries = await readDirSafe(abs);
1353
- const nodes = [];
1354
- for (const name of entries) {
1355
- if (name === META_DIR_NAME || name.startsWith(".")) continue;
1356
- const childAbs = path4.join(abs, name);
1357
- const stat = await fs2.stat(childAbs);
1358
- const rel = toRelativePath(childAbs);
1359
- if (stat.isDirectory()) {
1360
- nodes.push({
1361
- name,
1362
- path: rel,
1363
- type: "folder",
1364
- mtimeMs: stat.mtimeMs,
1365
- children: await buildTree(rel)
1366
- });
1367
- } else if (stat.isFile() && isDiagramFile(name)) {
1368
- nodes.push({
1369
- name,
1370
- path: rel,
1371
- type: "file",
1372
- mtimeMs: stat.mtimeMs,
1373
- size: stat.size
1374
- });
1730
+ function shortenInterface(name) {
1731
+ for (const pair of SHORT_FOR_LONG) {
1732
+ if (name.toLowerCase().startsWith(pair.long.toLowerCase())) {
1733
+ return `${pair.short}${name.slice(pair.long.length)}`;
1375
1734
  }
1376
1735
  }
1377
- nodes.sort((a, b) => {
1378
- if (a.type !== b.type) return a.type === "folder" ? -1 : 1;
1379
- return a.name.localeCompare(b.name, void 0, { sensitivity: "base" });
1380
- });
1381
- return nodes;
1382
- }
1383
- async function readDisk(abs) {
1384
- try {
1385
- const stat = await fs2.stat(abs);
1386
- if (!stat.isFile()) throw httpFail(400, "Not a diagram file", "invalid");
1387
- const content = await textFiles.read(abs);
1388
- return {
1389
- exists: true,
1390
- content,
1391
- mtimeMs: stat.mtimeMs,
1392
- size: stat.size,
1393
- hash: hashContent(content)
1394
- };
1395
- } catch (err) {
1396
- if (err && typeof err === "object" && "status" in err) throw err;
1397
- const code = err.code;
1398
- if (code === "ENOENT") return { exists: false };
1399
- rethrowKnownReadError(path4.basename(abs), err);
1400
- throw err;
1401
- }
1402
- }
1403
- function requireDiagram(relativePath) {
1404
- const normalized = normalizeRelative(relativePath);
1405
- if (!isDiagramFile(normalized)) {
1406
- throw httpFail(400, "Only .mmd diagram files are supported", "invalid");
1407
- }
1408
- return normalized;
1409
- }
1410
- async function readFile(relativePath) {
1411
- const normalized = requireDiagram(relativePath);
1412
- const abs = resolveSafePath(normalized);
1413
- const disk = await readDisk(abs);
1414
- if (!disk.exists) throw httpFail(404, "Not found", "not_found");
1415
- return {
1416
- path: toRelativePath(abs),
1417
- name: path4.basename(abs),
1418
- content: disk.content,
1419
- mtimeMs: disk.mtimeMs,
1420
- size: disk.size,
1421
- hash: disk.hash
1422
- };
1423
- }
1424
- async function writeFile(relativePath, content, options = {}) {
1425
- const normalized = requireDiagram(relativePath);
1426
- const abs = resolveSafePath(normalized);
1427
- const relative = toRelativePath(abs);
1428
- await assertWriteAllowed(relative, options.lockToken);
1429
- const disk = await readDisk(abs);
1430
- const decision = evaluateWrite(disk, { ...options, content });
1431
- if (decision.action === "reject") {
1432
- if (decision.code === "missing") {
1433
- throw httpFail(409, "This diagram is no longer on disk.", "missing");
1736
+ return name;
1737
+ }
1738
+ function resolveLinks(document, warnings) {
1739
+ return document.links.map((link, index) => {
1740
+ const a = resolveInterface(link.a.device, link.a.interface, document.interfaces);
1741
+ const b = resolveInterface(link.b.device, link.b.interface, document.interfaces);
1742
+ if (a.unresolved) {
1743
+ pushWarning(
1744
+ warnings,
1745
+ `/links/${index}/a/interface`,
1746
+ `Link interface "${link.a.interface}" on ${link.a.device} did not match an interface name. The link name was kept.`
1747
+ );
1434
1748
  }
1435
- if (decision.code === "exists") {
1436
- throw httpFail(
1437
- 409,
1438
- "A diagram already exists at that path. Choose a different name.",
1439
- "exists",
1440
- { path: relative }
1749
+ if (b.unresolved) {
1750
+ pushWarning(
1751
+ warnings,
1752
+ `/links/${index}/b/interface`,
1753
+ `Link interface "${link.b.interface}" on ${link.b.device} did not match an interface name. The link name was kept.`
1754
+ );
1755
+ }
1756
+ if (link.inferred) {
1757
+ pushWarning(
1758
+ warnings,
1759
+ `/links/${index}`,
1760
+ `Link ${link.a.device}:${a.name} to ${link.b.device}:${b.name} is inferred and is not a proven cable.`
1441
1761
  );
1442
1762
  }
1443
- if (!disk.exists) throw httpFail(409, "This diagram changed on disk.", "conflict");
1444
- throw httpFail(409, "This diagram changed on disk since it was last loaded.", "conflict", {
1445
- current: {
1446
- path: relative,
1447
- content: disk.content,
1448
- mtimeMs: disk.mtimeMs,
1449
- size: disk.size,
1450
- hash: disk.hash
1451
- }
1452
- });
1453
- }
1454
- if (decision.action === "unchanged" && disk.exists) {
1455
- await noteDiagramSighting({ path: relative, hash: disk.hash });
1456
1763
  return {
1457
- path: relative,
1458
- mtimeMs: disk.mtimeMs,
1459
- size: disk.size,
1460
- hash: disk.hash,
1461
- unchanged: true
1764
+ index,
1765
+ aDevice: link.a.device,
1766
+ aInterface: a.name,
1767
+ bDevice: link.b.device,
1768
+ bInterface: b.name,
1769
+ inferred: link.inferred,
1770
+ unresolved: a.unresolved || b.unresolved,
1771
+ label: link.label
1462
1772
  };
1463
- }
1464
- let revisionId;
1465
- if (decision.action === "overwrite" && disk.exists) {
1466
- revisionId = await snapshotPrevious(relative, disk);
1467
- }
1468
- await fs2.mkdir(path4.dirname(abs), { recursive: true });
1469
- await atomicWriteText(abs, content);
1470
- await dropThumbnail(relative);
1471
- const stat = await fs2.stat(abs);
1472
- const search = await import("./chunk-LYMG57VV.js");
1473
- await search.rememberSearchEntry(relative, content, stat.mtimeMs, stat.size);
1474
- await noteDiagramSighting({ path: relative, hash: hashContent(content) });
1475
- noteSync({ kind: "content", summary: `Update ${relative}` });
1476
- return {
1477
- path: relative,
1478
- mtimeMs: stat.mtimeMs,
1479
- size: stat.size,
1480
- hash: hashContent(content),
1481
- revisionId
1482
- };
1773
+ });
1483
1774
  }
1484
- function noteSync(change) {
1485
- void import("./chunk-LXSDAIF4.js").then((mod) => mod.noteLocalChange(change)).catch(() => {
1486
- console.error("GitHub sync could not record a local change");
1775
+ function resolveInterface(device, rawName, interfaces) {
1776
+ const owned = interfaces.filter((item) => item.device === device);
1777
+ const exact = owned.find((item) => item.name === rawName);
1778
+ if (exact) return { name: exact.name, unresolved: false };
1779
+ const folded = owned.find((item) => item.name.toLowerCase() === rawName.toLowerCase());
1780
+ if (folded) return { name: folded.name, unresolved: false };
1781
+ const expanded = expandInterface(rawName);
1782
+ const fromShort = owned.find((item) => item.name.toLowerCase() === expanded.toLowerCase());
1783
+ if (fromShort) return { name: fromShort.name, unresolved: false };
1784
+ const fromLong = owned.find((item) => shortenInterface(item.name).toLowerCase() === rawName.toLowerCase());
1785
+ if (fromLong) return { name: fromLong.name, unresolved: false };
1786
+ return { name: rawName, unresolved: true };
1787
+ }
1788
+ function same(left, right) {
1789
+ if (left == null || left === "") return true;
1790
+ return left.trim().toLowerCase() === right.trim().toLowerCase();
1791
+ }
1792
+ function specificity(row) {
1793
+ return (row.platform ? 1 : 0) + (row.role ? 1 : 0) + (row.model ? 1 : 0);
1794
+ }
1795
+ function lookupMapping(builtIn, device, override) {
1796
+ const extra = (override ?? []).map((row) => ({
1797
+ platform: row.platform,
1798
+ role: row.role,
1799
+ model: row.model,
1800
+ values: Object.fromEntries(Object.entries(row).filter(([key]) => key !== "platform" && key !== "role" && key !== "model"))
1801
+ }));
1802
+ const ranked = [
1803
+ ...extra.map((row, index) => ({ row, index, override: true })),
1804
+ ...builtIn.map((row, index) => ({ row, index, override: false }))
1805
+ ];
1806
+ const matches = ranked.filter(
1807
+ (item) => same(item.row.platform, device.platform) && same(item.row.role, device.role) && same(item.row.model, device.model)
1808
+ );
1809
+ if (matches.length === 0) return null;
1810
+ matches.sort((a, b) => {
1811
+ const score = specificity(b.row) - specificity(a.row);
1812
+ if (score !== 0) return score;
1813
+ if (a.override !== b.override) return a.override ? -1 : 1;
1814
+ return a.index - b.index;
1487
1815
  });
1816
+ return matches[0]?.row.values ?? null;
1817
+ }
1818
+ function mappingRowsFromUnknown(value) {
1819
+ if (value == null) return null;
1820
+ if (!Array.isArray(value)) return null;
1821
+ const rows = [];
1822
+ for (const item of value) {
1823
+ if (!isRecord4(item)) continue;
1824
+ const row = {};
1825
+ for (const [key, raw] of Object.entries(item)) {
1826
+ if (typeof raw === "string") row[key] = raw;
1827
+ else if (typeof raw === "number" || typeof raw === "boolean") row[key] = String(raw);
1828
+ }
1829
+ if (Object.keys(row).length > 0) rows.push(row);
1830
+ }
1831
+ return rows;
1832
+ }
1833
+ function mappingForTarget(document, id) {
1834
+ if (!isRecord4(document)) return null;
1835
+ return mappingRowsFromUnknown(document[id]);
1836
+ }
1837
+ function parseMappingText(text) {
1838
+ const trimmed = text.replace(/^\uFEFF/, "").trim();
1839
+ if (!trimmed) return null;
1840
+ try {
1841
+ return JSON.parse(trimmed);
1842
+ } catch {
1843
+ return parseYaml(trimmed);
1844
+ }
1845
+ }
1846
+ function safeGroupName(name) {
1847
+ const cleaned = name.trim().toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
1848
+ if (!cleaned) return "ungrouped";
1849
+ if (/^\d/.test(cleaned)) return `g_${cleaned}`;
1850
+ return cleaned;
1851
+ }
1852
+ function stableUuid(seed) {
1853
+ const hex = createHash("sha256").update(seed).digest("hex");
1854
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
1855
+ }
1856
+ function zipStore(files) {
1857
+ const locals = [];
1858
+ const centrals = [];
1859
+ let offset = 0;
1860
+ for (const file of files) {
1861
+ const name = Buffer.from(file.name.replace(/\\/g, "/"), "utf8");
1862
+ const data = Buffer.from(file.text, "utf8");
1863
+ const crc = crc32(data);
1864
+ const local = Buffer.alloc(30 + name.length);
1865
+ local.writeUInt32LE(67324752, 0);
1866
+ local.writeUInt16LE(20, 4);
1867
+ local.writeUInt16LE(0, 6);
1868
+ local.writeUInt16LE(0, 8);
1869
+ local.writeUInt16LE(0, 10);
1870
+ local.writeUInt16LE(0, 12);
1871
+ local.writeUInt32LE(crc, 14);
1872
+ local.writeUInt32LE(data.length, 18);
1873
+ local.writeUInt32LE(data.length, 22);
1874
+ local.writeUInt16LE(name.length, 26);
1875
+ local.writeUInt16LE(0, 28);
1876
+ name.copy(local, 30);
1877
+ locals.push(local, data);
1878
+ const central = Buffer.alloc(46 + name.length);
1879
+ central.writeUInt32LE(33639248, 0);
1880
+ central.writeUInt16LE(20, 4);
1881
+ central.writeUInt16LE(20, 6);
1882
+ central.writeUInt16LE(0, 8);
1883
+ central.writeUInt16LE(0, 10);
1884
+ central.writeUInt16LE(0, 12);
1885
+ central.writeUInt16LE(0, 14);
1886
+ central.writeUInt32LE(crc, 16);
1887
+ central.writeUInt32LE(data.length, 20);
1888
+ central.writeUInt32LE(data.length, 24);
1889
+ central.writeUInt16LE(name.length, 28);
1890
+ central.writeUInt16LE(0, 30);
1891
+ central.writeUInt16LE(0, 32);
1892
+ central.writeUInt16LE(0, 34);
1893
+ central.writeUInt16LE(0, 36);
1894
+ central.writeUInt32LE(0, 38);
1895
+ central.writeUInt32LE(offset, 42);
1896
+ name.copy(central, 46);
1897
+ centrals.push(central);
1898
+ offset += local.length + data.length;
1899
+ }
1900
+ const centralBuf = Buffer.concat(centrals);
1901
+ const end = Buffer.alloc(22);
1902
+ end.writeUInt32LE(101010256, 0);
1903
+ end.writeUInt16LE(0, 4);
1904
+ end.writeUInt16LE(0, 6);
1905
+ end.writeUInt16LE(files.length, 8);
1906
+ end.writeUInt16LE(files.length, 10);
1907
+ end.writeUInt32LE(centralBuf.length, 12);
1908
+ end.writeUInt32LE(offset, 16);
1909
+ end.writeUInt16LE(0, 20);
1910
+ return Buffer.concat([...locals, centralBuf, end]);
1911
+ }
1912
+ var CRC_TABLE = (() => {
1913
+ const table = new Uint32Array(256);
1914
+ for (let index = 0; index < 256; index += 1) {
1915
+ let crc = index;
1916
+ for (let bit = 0; bit < 8; bit += 1) crc = crc & 1 ? 3988292384 ^ crc >>> 1 : crc >>> 1;
1917
+ table[index] = crc >>> 0;
1918
+ }
1919
+ return table;
1920
+ })();
1921
+ function crc32(data) {
1922
+ let crc = 4294967295;
1923
+ for (const byte of data) crc = CRC_TABLE[(crc ^ byte) & 255] ^ crc >>> 8;
1924
+ return (crc ^ 4294967295) >>> 0;
1488
1925
  }
1489
1926
 
1490
1927
  export {
1491
- buildTree,
1492
- readFile,
1493
- writeFile
1928
+ canonicalIp,
1929
+ validateNetwork,
1930
+ dataFail,
1931
+ readDataSource,
1932
+ EXPORT_MAX_INPUT_BYTES,
1933
+ EXPORT_MAX_DEVICES,
1934
+ EXPORT_MAX_LINKS,
1935
+ exporterFail,
1936
+ assertExportInputSize,
1937
+ CHANGE_ME,
1938
+ HEADER_LINES,
1939
+ isRecord4 as isRecord,
1940
+ pushWarning,
1941
+ sortWarnings,
1942
+ commentBlock,
1943
+ renderYaml,
1944
+ assertExportShape,
1945
+ safeLabel,
1946
+ fileName,
1947
+ cidr,
1948
+ resolveLinks,
1949
+ lookupMapping,
1950
+ mappingRowsFromUnknown,
1951
+ mappingForTarget,
1952
+ parseMappingText,
1953
+ safeGroupName,
1954
+ stableUuid,
1955
+ zipStore
1494
1956
  };