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.
- package/dist/chunk-54BVSMKR.js +87 -0
- package/dist/chunk-5C6VO4LC.js +90 -0
- package/dist/{chunk-KO565WWM.js → chunk-AFGGIQ22.js} +252 -80
- package/dist/{chunk-BOMYBBJ6.js → chunk-GQKUFF4P.js} +8 -102
- package/dist/chunk-I5EOFHBL.js +1494 -0
- package/dist/chunk-JUCAQ6EJ.js +1265 -0
- package/dist/chunk-TQHP2K7Q.js +492 -0
- package/dist/chunk-ULY5YEBR.js +490 -0
- package/dist/chunk-WSGEBKT4.js +943 -0
- package/dist/{chunk-EGA2UGTF.js → chunk-XJTF2GUE.js} +102 -104
- package/dist/cli.js +46 -3
- package/package.json +1 -1
|
@@ -0,0 +1,1494 @@
|
|
|
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-ULY5YEBR.js";
|
|
26
|
+
|
|
27
|
+
// server/src/fsStore.ts
|
|
28
|
+
import fs2 from "node:fs/promises";
|
|
29
|
+
import path4 from "node:path";
|
|
30
|
+
|
|
31
|
+
// server/src/diagramData.ts
|
|
32
|
+
import { Document, isMap, parseDocument } from "yaml";
|
|
33
|
+
|
|
34
|
+
// server/src/neighbors/clean.ts
|
|
35
|
+
function cleanCli(text) {
|
|
36
|
+
return text.replace(/^\uFEFF/, "").replace(/\u0000/g, "").replace(/\x1b\[[0-9;]*[A-Za-z]/g, "").replace(/.\x08/g, "").replace(/\x08/g, "").replace(/--More--|\(END\)/gi, "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
37
|
+
}
|
|
38
|
+
function promptHost(line) {
|
|
39
|
+
const trimmed = line.trim();
|
|
40
|
+
if (!trimmed || trimmed.length > 200) return null;
|
|
41
|
+
const comware = /^<([A-Za-z][\w.-]{0,63})>\s*(.*)$/.exec(trimmed);
|
|
42
|
+
if (comware?.[1]) return comware[1];
|
|
43
|
+
const mikrotik = /^\[(?:[\w.+-]+@)?([A-Za-z0-9][\w.-]*)\]\s*>?\s*(.*)$/.exec(trimmed);
|
|
44
|
+
if (mikrotik?.[1]) return mikrotik[1];
|
|
45
|
+
const userHost = /^[\w.+-]+@([A-Za-z][\w.-]{0,63})\s*[>#]\s*(.*)$/.exec(trimmed);
|
|
46
|
+
if (userHost?.[1]) return userHost[1];
|
|
47
|
+
const host = /^([A-Za-z][\w.-]{0,63})\s*[>#]\s*(.*)$/.exec(trimmed);
|
|
48
|
+
if (!host?.[1]) return null;
|
|
49
|
+
const rest = host[2] ?? "";
|
|
50
|
+
if (rest === "") return host[1];
|
|
51
|
+
if (/^(?:show|display|sh|lldpctl|\/)/i.test(rest)) return host[1];
|
|
52
|
+
if (rest.length < 80 && !/[:=]/.test(rest)) return host[1];
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
function clipIssue(value) {
|
|
56
|
+
const flat = value.replace(/[\u0000-\u001f]/g, " ").replace(/\s+/g, " ").trim();
|
|
57
|
+
return flat.length > 80 ? `${flat.slice(0, 80)}\u2026` : flat;
|
|
58
|
+
}
|
|
59
|
+
function cleanSentinel(value) {
|
|
60
|
+
const trimmed = value.trim().replace(/^["']|["']$/g, "").trim();
|
|
61
|
+
if (!trimmed) return "";
|
|
62
|
+
if (/^(?:null|n\/a|na|none|unknown|not advertised|-|--)$/i.test(trimmed)) return "";
|
|
63
|
+
return trimmed;
|
|
64
|
+
}
|
|
65
|
+
function stripSubtype(value) {
|
|
66
|
+
const match = /^(?:mac|ifname|local|network|interface|ip|ipv4|ipv6)\s+(.+)$/i.exec(value.trim());
|
|
67
|
+
return match?.[1]?.trim() || value.trim();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// server/src/neighbors/normalize.ts
|
|
71
|
+
var PREFIXES = [
|
|
72
|
+
{ re: /^(?:twentyfivegigabitethernet|twentyfivegige|twe)/, display: "Twe", key: "twe" },
|
|
73
|
+
{ re: /^(?:hundredgigabitethernet|hundredgige|hu)/, display: "Hu", key: "hu" },
|
|
74
|
+
{ re: /^(?:fortygigabitethernet|fortygige|fo)/, display: "Fo", key: "fo" },
|
|
75
|
+
{ re: /^(?:tengigabitethernet|tengige|te)/, display: "Te", key: "te" },
|
|
76
|
+
{ re: /^(?:fivegigabitethernet|fivegige|fi)/, display: "Fi", key: "fi" },
|
|
77
|
+
{ re: /^(?:twogigabitethernet|twogige|tw)/, display: "Tw", key: "tw" },
|
|
78
|
+
{ re: /^(?:appgigabitethernet|appgige|ap)/, display: "Ap", key: "ap" },
|
|
79
|
+
{ re: /^(?:gigabitethernet|gig|gi)/, display: "Gi", key: "gi" },
|
|
80
|
+
{ re: /^(?:fastethernet|fas|fa)/, display: "Fa", key: "fa" },
|
|
81
|
+
{ re: /^(?:port-channel|portchannel|po)/, display: "Po", key: "po" },
|
|
82
|
+
{ re: /^(?:management|mgmt|ma)/, display: "Ma", key: "ma" },
|
|
83
|
+
{ re: /^(?:ethernet|ether|eth|et)/, display: "Eth", key: "eth" },
|
|
84
|
+
{ re: /^(?:loopback|lo)/, display: "Lo", key: "lo" },
|
|
85
|
+
{ re: /^(?:vlan|vl)/, display: "Vl", key: "vl" }
|
|
86
|
+
];
|
|
87
|
+
var CAPABILITY_ORDER = ["Router", "Switch", "Phone", "WLAN", "Station", "Cable", "Repeater", "Other"];
|
|
88
|
+
var CAPABILITY_LETTER = {
|
|
89
|
+
r: "Router",
|
|
90
|
+
b: "Switch",
|
|
91
|
+
t: "Phone",
|
|
92
|
+
w: "WLAN",
|
|
93
|
+
s: "Station",
|
|
94
|
+
c: "Cable",
|
|
95
|
+
p: "Repeater",
|
|
96
|
+
o: "Other"
|
|
97
|
+
};
|
|
98
|
+
var NOT_CAPABILITY_CODES = /* @__PURE__ */ new Set(["stp", "igmp", "cdp", "lldp", "mndp", "vlan"]);
|
|
99
|
+
var CAPABILITY_WORD = {
|
|
100
|
+
router: "Router",
|
|
101
|
+
switch: "Switch",
|
|
102
|
+
bridge: "Switch",
|
|
103
|
+
telephone: "Phone",
|
|
104
|
+
phone: "Phone",
|
|
105
|
+
wlan: "WLAN",
|
|
106
|
+
wireless: "WLAN",
|
|
107
|
+
station: "Station",
|
|
108
|
+
host: "Station",
|
|
109
|
+
docsis: "Cable",
|
|
110
|
+
cable: "Cable",
|
|
111
|
+
repeater: "Repeater",
|
|
112
|
+
other: "Other"
|
|
113
|
+
};
|
|
114
|
+
function isMacAddress(value) {
|
|
115
|
+
return macOf(value) !== "";
|
|
116
|
+
}
|
|
117
|
+
function macOf(value) {
|
|
118
|
+
const trimmed = value.trim();
|
|
119
|
+
if (!trimmed || trimmed.length > 40) return "";
|
|
120
|
+
const hex = trimmed.toLowerCase().replace(/[^0-9a-f]/g, "");
|
|
121
|
+
if (hex.length !== 12) return "";
|
|
122
|
+
const hasSep = /[:.\-\s]/.test(trimmed);
|
|
123
|
+
const hasLetter = /[a-f]/i.test(hex);
|
|
124
|
+
if (!hasSep && !hasLetter) return "";
|
|
125
|
+
if (!/^[0-9a-f:.\-\s]+$/i.test(trimmed)) return "";
|
|
126
|
+
const parts = hex.match(/.{2}/g);
|
|
127
|
+
return parts ? parts.join(":") : "";
|
|
128
|
+
}
|
|
129
|
+
function isIp(value) {
|
|
130
|
+
return /^\d{1,3}(?:\.\d{1,3}){3}$/.test(value);
|
|
131
|
+
}
|
|
132
|
+
function normalizeInterface(raw) {
|
|
133
|
+
const original = cleanSentinel(raw).replace(/\s+/g, " ").trim();
|
|
134
|
+
if (!original) return { display: "", key: "", isMac: false };
|
|
135
|
+
const mac = macOf(original);
|
|
136
|
+
if (mac) return { display: mac, key: `mac:${mac}`, isMac: true };
|
|
137
|
+
const compact = original.toLowerCase().replace(/[\s_]+/g, "");
|
|
138
|
+
if (/^(?:ge|xe|et|ae|em|fxp|irb|lo|me|vme|gr|lt)-[\d/.]+$/.test(compact) || /^(?:ae|em|lo|fxp|irb|vme|me)\d/.test(compact)) {
|
|
139
|
+
return { display: compact, key: compact, isMac: false };
|
|
140
|
+
}
|
|
141
|
+
for (const prefix of PREFIXES) {
|
|
142
|
+
const match = prefix.re.exec(compact);
|
|
143
|
+
if (!match) continue;
|
|
144
|
+
const rest = compact.slice(match[0].length).replace(/^[-_/]+/, "");
|
|
145
|
+
if (!rest || !/^[\d:.]/.test(rest)) continue;
|
|
146
|
+
return { display: `${prefix.display}${rest}`, key: `${prefix.key}${rest}`, isMac: false };
|
|
147
|
+
}
|
|
148
|
+
const plain = original.replace(/\s+/g, " ").trim();
|
|
149
|
+
return { display: plain, key: plain.toLowerCase().replace(/\s+/g, ""), isMac: false };
|
|
150
|
+
}
|
|
151
|
+
function normalizeCapability(raw) {
|
|
152
|
+
const found = /* @__PURE__ */ new Set();
|
|
153
|
+
const tokens = raw.split(/[^A-Za-z0-9]+/).map((token) => token.trim()).filter(Boolean);
|
|
154
|
+
for (const token of tokens) {
|
|
155
|
+
const lower = token.toLowerCase();
|
|
156
|
+
if (/^(?:igmp|filtering|enabled|available|supported|on|off|yes|no)$/i.test(lower)) continue;
|
|
157
|
+
if (CAPABILITY_WORD[lower]) {
|
|
158
|
+
found.add(CAPABILITY_WORD[lower]);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (/^[brtwscpo]{1,4}$/i.test(token) && !NOT_CAPABILITY_CODES.has(lower)) {
|
|
162
|
+
for (const letter of token.toLowerCase()) {
|
|
163
|
+
const label = CAPABILITY_LETTER[letter];
|
|
164
|
+
if (label) found.add(label);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return CAPABILITY_ORDER.filter((label) => found.has(label)).join(", ");
|
|
169
|
+
}
|
|
170
|
+
function platformOf(description, platformField = "") {
|
|
171
|
+
const text = `${platformField} ${description}`.toLowerCase().replace(/\s+/g, " ").trim();
|
|
172
|
+
if (!text) return "";
|
|
173
|
+
if (/nx-os|nexus|\bn[3579]k\b/.test(text)) return "Cisco NX-OS";
|
|
174
|
+
if (/ios-xe|ios xe|cat9k|iosxe|\bc9[0-9]{3}\b|\bisr\d|\basr\d/.test(text)) return "Cisco IOS-XE";
|
|
175
|
+
if (/cisco ios|\bcatalyst\b|ws-c\d|\bc3750\b|\bc2960\b/.test(text)) return "Cisco IOS";
|
|
176
|
+
if (/arista|\beos\b|\bdcs-/.test(text)) return "Arista EOS";
|
|
177
|
+
if (/junos|juniper/.test(text)) return "Junos";
|
|
178
|
+
if (/aruba|provision|aos-cx|arubaos/.test(text)) return "Aruba";
|
|
179
|
+
if (/comware|hewlett|\bhpe\b|\bhp\b/.test(text)) return "HPE";
|
|
180
|
+
if (/extreme\s*xos|\bexos\b|extremexos/.test(text)) return "Extreme";
|
|
181
|
+
if (/os10|\bdell\b|force10|\bdnos\b/.test(text)) return "Dell";
|
|
182
|
+
if (/routeros|mikrotik/.test(text)) return "MikroTik";
|
|
183
|
+
if (/ubiquiti|unifi|edgeswitch|edgeos|\buisp\b/.test(text)) return "Ubiquiti";
|
|
184
|
+
if (/lldpd|\blinux\b|debian|ubuntu/.test(text)) return "Linux";
|
|
185
|
+
const clip = (platformField || description).split("\n")[0]?.trim() ?? "";
|
|
186
|
+
if (!clip) return "";
|
|
187
|
+
return clip.length > 40 ? `${clip.slice(0, 40)}\u2026` : clip;
|
|
188
|
+
}
|
|
189
|
+
function deviceKey(name, shortNames) {
|
|
190
|
+
const lower = name.trim().toLowerCase();
|
|
191
|
+
if (isIp(lower)) return `ip:${lower}`;
|
|
192
|
+
const short = lower.split(".")[0] ?? lower;
|
|
193
|
+
if (short && shortNames.has(short)) return `host:${short}`;
|
|
194
|
+
return `host:${lower}`;
|
|
195
|
+
}
|
|
196
|
+
function chooseDisplay(variants, preferred) {
|
|
197
|
+
const prefs = variants.filter((name) => preferred.has(name.trim().toLowerCase()));
|
|
198
|
+
const pool = prefs.length > 0 ? prefs : variants;
|
|
199
|
+
return [...pool].sort((a, b) => a.length - b.length || a.localeCompare(b))[0] ?? "";
|
|
200
|
+
}
|
|
201
|
+
function finalizeNeighbors(parserId, raw, errors, warnings, preferredNames, emptyMessage2) {
|
|
202
|
+
const preferred = new Set(preferredNames.map((name) => name.trim().toLowerCase()).filter(Boolean));
|
|
203
|
+
const names = [];
|
|
204
|
+
for (const link of raw) {
|
|
205
|
+
names.push(link.localDevice, link.remoteDevice);
|
|
206
|
+
}
|
|
207
|
+
const shortNames = /* @__PURE__ */ new Set();
|
|
208
|
+
for (const name of names) {
|
|
209
|
+
const lower = name.trim().toLowerCase();
|
|
210
|
+
if (lower && !lower.includes(".") && !isIp(lower)) shortNames.add(lower);
|
|
211
|
+
}
|
|
212
|
+
for (const name of preferred) {
|
|
213
|
+
if (!name.includes(".") && !isIp(name)) shortNames.add(name);
|
|
214
|
+
}
|
|
215
|
+
const variants = /* @__PURE__ */ new Map();
|
|
216
|
+
const remember = (name) => {
|
|
217
|
+
const key = deviceKey(name, shortNames);
|
|
218
|
+
const list = variants.get(key) ?? [];
|
|
219
|
+
if (!list.includes(name)) list.push(name);
|
|
220
|
+
variants.set(key, list);
|
|
221
|
+
return key;
|
|
222
|
+
};
|
|
223
|
+
const attrs = /* @__PURE__ */ new Map();
|
|
224
|
+
const touchAttr = (key, platform, capability) => {
|
|
225
|
+
const current = attrs.get(key) ?? { platform: "", capability: "" };
|
|
226
|
+
if (!current.platform && platform) current.platform = platform;
|
|
227
|
+
if (!current.capability && capability) current.capability = capability;
|
|
228
|
+
attrs.set(key, current);
|
|
229
|
+
};
|
|
230
|
+
const prepared = [];
|
|
231
|
+
for (const link of raw) {
|
|
232
|
+
const localPort = normalizeInterface(link.localPort);
|
|
233
|
+
const remotePort = normalizeInterface(link.remotePort);
|
|
234
|
+
if (!localPort.key || !remotePort.key) continue;
|
|
235
|
+
const localKey = remember(link.localDevice);
|
|
236
|
+
const remoteKey = remember(link.remoteDevice);
|
|
237
|
+
touchAttr(remoteKey, link.remotePlatform, link.remoteCapability);
|
|
238
|
+
prepared.push({ line: link.line, localKey, remoteKey, localPort, remotePort });
|
|
239
|
+
}
|
|
240
|
+
const display = /* @__PURE__ */ new Map();
|
|
241
|
+
for (const [key, list] of variants) display.set(key, chooseDisplay(list, preferred));
|
|
242
|
+
const seen = /* @__PURE__ */ new Set();
|
|
243
|
+
const links = [];
|
|
244
|
+
let dropped = 0;
|
|
245
|
+
for (const link of prepared) {
|
|
246
|
+
const left = `${link.localKey}\0${link.localPort.key}`;
|
|
247
|
+
const right = `${link.remoteKey}\0${link.remotePort.key}`;
|
|
248
|
+
const undirected = left < right ? `${left}\0${right}` : `${right}\0${left}`;
|
|
249
|
+
if (seen.has(undirected)) {
|
|
250
|
+
dropped += 1;
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
seen.add(undirected);
|
|
254
|
+
const localAttr = attrs.get(link.localKey) ?? { platform: "", capability: "" };
|
|
255
|
+
const remoteAttr = attrs.get(link.remoteKey) ?? { platform: "", capability: "" };
|
|
256
|
+
links.push({
|
|
257
|
+
line: link.line,
|
|
258
|
+
localDevice: display.get(link.localKey) ?? link.localKey,
|
|
259
|
+
localPort: link.localPort.display,
|
|
260
|
+
remoteDevice: display.get(link.remoteKey) ?? link.remoteKey,
|
|
261
|
+
remotePort: link.remotePort.display,
|
|
262
|
+
localPlatform: localAttr.platform,
|
|
263
|
+
remotePlatform: remoteAttr.platform,
|
|
264
|
+
localCapability: localAttr.capability,
|
|
265
|
+
remoteCapability: remoteAttr.capability
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
if (dropped > 0) {
|
|
269
|
+
warnings.push({
|
|
270
|
+
row: 0,
|
|
271
|
+
message: `Combined ${dropped} duplicate link${dropped === 1 ? "" : "s"} seen from both ends.`
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
if (links.length === 0 && errors.length === 0) {
|
|
275
|
+
errors.push({ row: 1, message: emptyMessage2 });
|
|
276
|
+
}
|
|
277
|
+
return { parserId, links, errors, warnings };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// server/src/neighbors/types.ts
|
|
281
|
+
var MAX_NEIGHBOR_BLOCKS = 5e3;
|
|
282
|
+
|
|
283
|
+
// server/src/neighbors/cdp.ts
|
|
284
|
+
function emptyBag(line) {
|
|
285
|
+
return {
|
|
286
|
+
line,
|
|
287
|
+
deviceId: "",
|
|
288
|
+
platform: "",
|
|
289
|
+
capability: "",
|
|
290
|
+
localPort: "",
|
|
291
|
+
remotePort: "",
|
|
292
|
+
version: "",
|
|
293
|
+
readingVersion: false
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
function parseCdpNeighbors(text, options = {}) {
|
|
297
|
+
const cleaned = cleanCli(text);
|
|
298
|
+
if (/local intrfce/i.test(cleaned) && !/port id \(outgoing port\)/i.test(cleaned)) {
|
|
299
|
+
return {
|
|
300
|
+
parserId: "cisco-cdp",
|
|
301
|
+
links: [],
|
|
302
|
+
warnings: [],
|
|
303
|
+
errors: [
|
|
304
|
+
{
|
|
305
|
+
row: 1,
|
|
306
|
+
message: "This is the short CDP table. Paste show cdp neighbors detail."
|
|
307
|
+
}
|
|
308
|
+
]
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
const raw = [];
|
|
312
|
+
const errors = [];
|
|
313
|
+
const warnings = [];
|
|
314
|
+
const preferred = [];
|
|
315
|
+
let localDevice = cleanSentinel(options.localDevice ?? "");
|
|
316
|
+
if (localDevice) preferred.push(localDevice);
|
|
317
|
+
let bag = null;
|
|
318
|
+
let count = 0;
|
|
319
|
+
const flush = () => {
|
|
320
|
+
if (!bag) return;
|
|
321
|
+
const current = bag;
|
|
322
|
+
bag = null;
|
|
323
|
+
if (!current.deviceId && !current.localPort && !current.remotePort) return;
|
|
324
|
+
count += 1;
|
|
325
|
+
if (count > MAX_NEIGHBOR_BLOCKS) return;
|
|
326
|
+
const remote = cleanSentinel(current.deviceId).replace(/\(([A-Za-z0-9_-]{4,})\)\s*$/, "").trim();
|
|
327
|
+
const localPort = cleanSentinel(current.localPort);
|
|
328
|
+
const remotePort = cleanSentinel(current.remotePort);
|
|
329
|
+
const missing = [];
|
|
330
|
+
if (!localDevice) missing.push("local device");
|
|
331
|
+
if (!localPort) missing.push("local interface");
|
|
332
|
+
if (!remote) missing.push("remote device");
|
|
333
|
+
if (!remotePort) missing.push("remote port");
|
|
334
|
+
if (missing.length > 0) {
|
|
335
|
+
const who = remote ? ` "${clipIssue(remote)}"` : "";
|
|
336
|
+
errors.push({
|
|
337
|
+
row: current.line,
|
|
338
|
+
message: `Line ${current.line}: CDP neighbor${who} is missing ${missing.join(" and ")}.`
|
|
339
|
+
});
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
raw.push({
|
|
343
|
+
line: current.line,
|
|
344
|
+
localDevice,
|
|
345
|
+
localPort,
|
|
346
|
+
remoteDevice: remote,
|
|
347
|
+
remotePort,
|
|
348
|
+
remotePlatform: platformOf(current.version, current.platform),
|
|
349
|
+
remoteCapability: normalizeCapability(current.capability)
|
|
350
|
+
});
|
|
351
|
+
};
|
|
352
|
+
const lines = cleaned.split("\n");
|
|
353
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
354
|
+
if (count > MAX_NEIGHBOR_BLOCKS) break;
|
|
355
|
+
const lineNo = index + 1;
|
|
356
|
+
const trimmed = (lines[index] ?? "").trim();
|
|
357
|
+
if (!trimmed) {
|
|
358
|
+
if (bag?.readingVersion) bag.readingVersion = false;
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
if (/^[-=*_]{5,}$/.test(trimmed)) {
|
|
362
|
+
flush();
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
const host = promptHost(trimmed);
|
|
366
|
+
if (host) {
|
|
367
|
+
flush();
|
|
368
|
+
localDevice = host;
|
|
369
|
+
preferred.push(host);
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
const device = /^Device ID\s*:\s*(.*)$/i.exec(trimmed);
|
|
373
|
+
if (device) {
|
|
374
|
+
if (bag?.deviceId) flush();
|
|
375
|
+
bag = emptyBag(lineNo);
|
|
376
|
+
bag.deviceId = device[1]?.trim() ?? "";
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
if (!bag) continue;
|
|
380
|
+
const platform = /^Platform\s*:\s*(.*)$/i.exec(trimmed);
|
|
381
|
+
if (platform) {
|
|
382
|
+
bag.readingVersion = false;
|
|
383
|
+
const value = platform[1] ?? "";
|
|
384
|
+
const caps = /^(.*?)\s*,\s*Capabilities\s*:\s*(.*)$/i.exec(value);
|
|
385
|
+
if (caps) {
|
|
386
|
+
bag.platform = caps[1]?.trim() ?? "";
|
|
387
|
+
bag.capability = caps[2]?.trim() ?? "";
|
|
388
|
+
} else {
|
|
389
|
+
bag.platform = value.trim();
|
|
390
|
+
}
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
const capsOnly = /^Capabilities\s*:\s*(.*)$/i.exec(trimmed);
|
|
394
|
+
if (capsOnly) {
|
|
395
|
+
bag.readingVersion = false;
|
|
396
|
+
bag.capability = capsOnly[1]?.trim() ?? "";
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
const iface = /^Interface\s*:\s*(.*)$/i.exec(trimmed);
|
|
400
|
+
if (iface) {
|
|
401
|
+
bag.readingVersion = false;
|
|
402
|
+
const value = iface[1] ?? "";
|
|
403
|
+
const combined = /^(.*?)\s*,\s*Port ID \(outgoing port\)\s*:\s*(.+)$/i.exec(value);
|
|
404
|
+
if (combined) {
|
|
405
|
+
bag.localPort = combined[1]?.trim() ?? "";
|
|
406
|
+
bag.remotePort = combined[2]?.trim() ?? "";
|
|
407
|
+
} else {
|
|
408
|
+
bag.localPort = value.replace(/,\s*$/, "").trim();
|
|
409
|
+
}
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
const port = /^Port ID \(outgoing port\)\s*:\s*(.*)$/i.exec(trimmed);
|
|
413
|
+
if (port) {
|
|
414
|
+
bag.readingVersion = false;
|
|
415
|
+
bag.remotePort = port[1]?.trim() ?? "";
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
if (/^Version\s*:?\s*$/i.test(trimmed) || /^Version\s*:\s*\S/i.test(trimmed)) {
|
|
419
|
+
bag.readingVersion = true;
|
|
420
|
+
const inline = /^Version\s*:\s*(.+)$/i.exec(trimmed);
|
|
421
|
+
if (inline?.[1]) bag.version = inline[1].trim();
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
if (bag.readingVersion && !/^[A-Za-z][\w ./-]{0,40}:\s/.test(trimmed)) {
|
|
425
|
+
bag.version = bag.version ? `${bag.version} ${trimmed}` : trimmed;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
flush();
|
|
429
|
+
if (count > MAX_NEIGHBOR_BLOCKS) {
|
|
430
|
+
return {
|
|
431
|
+
parserId: "cisco-cdp",
|
|
432
|
+
links: [],
|
|
433
|
+
warnings: [],
|
|
434
|
+
errors: [{ row: 1, message: `A file can have at most ${MAX_NEIGHBOR_BLOCKS} neighbor blocks.` }]
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
return finalizeNeighbors(
|
|
438
|
+
"cisco-cdp",
|
|
439
|
+
raw,
|
|
440
|
+
errors,
|
|
441
|
+
warnings,
|
|
442
|
+
preferred,
|
|
443
|
+
"No CDP neighbors were found. Paste show cdp neighbors detail."
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
var ciscoCdpParser = {
|
|
447
|
+
id: "cisco-cdp",
|
|
448
|
+
kind: "cdp",
|
|
449
|
+
label: "Cisco CDP (IOS, IOS-XE, NX-OS)",
|
|
450
|
+
parse: parseCdpNeighbors
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
// server/src/neighbors/lldp.ts
|
|
454
|
+
var FIELDS = {
|
|
455
|
+
"local intf": "localPort",
|
|
456
|
+
localintf: "localPort",
|
|
457
|
+
"local interface": "localPort",
|
|
458
|
+
localinterface: "localPort",
|
|
459
|
+
"local port": "localPort",
|
|
460
|
+
localport: "localPort",
|
|
461
|
+
interface: "localPort",
|
|
462
|
+
intf: "localPort",
|
|
463
|
+
"chassis id": "chassisId",
|
|
464
|
+
chassisid: "chassisId",
|
|
465
|
+
"chassis identifier": "chassisId",
|
|
466
|
+
"port id": "portId",
|
|
467
|
+
portid: "portId",
|
|
468
|
+
"port info": "portId",
|
|
469
|
+
portinfo: "portId",
|
|
470
|
+
"port description": "portDescription",
|
|
471
|
+
portdescription: "portDescription",
|
|
472
|
+
"port descr": "portDescription",
|
|
473
|
+
portdescr: "portDescription",
|
|
474
|
+
"port desc": "portDescription",
|
|
475
|
+
portdesc: "portDescription",
|
|
476
|
+
"system name": "systemName",
|
|
477
|
+
systemname: "systemName",
|
|
478
|
+
sysname: "systemName",
|
|
479
|
+
"sys name": "systemName",
|
|
480
|
+
"chassis name": "systemName",
|
|
481
|
+
chassisname: "systemName",
|
|
482
|
+
"device id": "systemName",
|
|
483
|
+
deviceid: "systemName",
|
|
484
|
+
identity: "systemName",
|
|
485
|
+
"system description": "systemDescription",
|
|
486
|
+
systemdescription: "systemDescription",
|
|
487
|
+
"system descr": "systemDescription",
|
|
488
|
+
systemdescr: "systemDescription",
|
|
489
|
+
"system desc": "systemDescription",
|
|
490
|
+
sysdescr: "systemDescription",
|
|
491
|
+
"sys descr": "systemDescription",
|
|
492
|
+
"existing system capabilities": "enabledCaps",
|
|
493
|
+
existingsystemcapabilities: "enabledCaps",
|
|
494
|
+
"enabled capabilities": "enabledCaps",
|
|
495
|
+
enabledcapabilities: "enabledCaps",
|
|
496
|
+
"capabilities enabled": "enabledCaps",
|
|
497
|
+
"enabled caps": "enabledCaps",
|
|
498
|
+
enabledcaps: "enabledCaps",
|
|
499
|
+
"system capabilities enabled": "enabledCaps",
|
|
500
|
+
"system capabilities": "supportedCaps",
|
|
501
|
+
systemcapabilities: "supportedCaps",
|
|
502
|
+
"system caps": "supportedCaps",
|
|
503
|
+
systemcaps: "supportedCaps",
|
|
504
|
+
"capabilities supported": "supportedCaps",
|
|
505
|
+
"capabilities available": "supportedCaps",
|
|
506
|
+
"system capabilities supported": "supportedCaps",
|
|
507
|
+
capabilities: "supportedCaps",
|
|
508
|
+
platform: "platform"
|
|
509
|
+
};
|
|
510
|
+
var REPEAT = /* @__PURE__ */ new Set(["localPort", "chassisId", "portId", "systemName"]);
|
|
511
|
+
var PAIR_FIELDS = {
|
|
512
|
+
interface: "localPort",
|
|
513
|
+
"local-interface": "localPort",
|
|
514
|
+
"interface-name": "portId",
|
|
515
|
+
"port-id": "portId",
|
|
516
|
+
portid: "portId",
|
|
517
|
+
identity: "systemName",
|
|
518
|
+
"system-name": "systemName",
|
|
519
|
+
sysname: "systemName",
|
|
520
|
+
"system-description": "systemDescription",
|
|
521
|
+
sysdescr: "systemDescription",
|
|
522
|
+
"mac-address": "chassisId",
|
|
523
|
+
"chassis-id": "chassisId",
|
|
524
|
+
chassisid: "chassisId",
|
|
525
|
+
"port-description": "portDescription",
|
|
526
|
+
portdescr: "portDescription",
|
|
527
|
+
platform: "platform"
|
|
528
|
+
};
|
|
529
|
+
function emptyBag2(line) {
|
|
530
|
+
return {
|
|
531
|
+
line,
|
|
532
|
+
localPort: "",
|
|
533
|
+
chassisId: "",
|
|
534
|
+
portId: "",
|
|
535
|
+
portDescription: "",
|
|
536
|
+
systemName: "",
|
|
537
|
+
systemDescription: "",
|
|
538
|
+
enabledCaps: "",
|
|
539
|
+
supportedCaps: "",
|
|
540
|
+
platform: "",
|
|
541
|
+
openField: "",
|
|
542
|
+
skippedBlank: false
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
function normLabel(label) {
|
|
546
|
+
return label.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().replace(/\s+/g, " ").replace(/^(?:neighbor|neighbour|remote)\s+/, "");
|
|
547
|
+
}
|
|
548
|
+
function lookupField(label) {
|
|
549
|
+
const norm = normLabel(label);
|
|
550
|
+
if (FIELDS[norm]) return FIELDS[norm];
|
|
551
|
+
const compact = norm.replace(/ /g, "");
|
|
552
|
+
return FIELDS[compact] ?? null;
|
|
553
|
+
}
|
|
554
|
+
function splitLabel(line) {
|
|
555
|
+
const trimmed = line.trim().replace(/^[>*•]+\s*/, "").replace(/^-\s+/, "");
|
|
556
|
+
const match = /^([A-Za-z][A-Za-z0-9 ./_+-]{0,48}?)\s*[:=]\s*(.*)$/.exec(trimmed);
|
|
557
|
+
if (!match?.[1]) return null;
|
|
558
|
+
const label = match[1].trim();
|
|
559
|
+
if (label.split(/\s+/).length > 6) return null;
|
|
560
|
+
return { label, value: (match[2] ?? "").trim() };
|
|
561
|
+
}
|
|
562
|
+
function parsePairs(line) {
|
|
563
|
+
const pairs = [];
|
|
564
|
+
const pattern = /([A-Za-z][\w-]*)=(?:"([^"]*)"|(\S+))/g;
|
|
565
|
+
let match = pattern.exec(line);
|
|
566
|
+
while (match) {
|
|
567
|
+
pairs.push({ key: (match[1] ?? "").toLowerCase(), value: match[2] ?? match[3] ?? "" });
|
|
568
|
+
match = pattern.exec(line);
|
|
569
|
+
}
|
|
570
|
+
return pairs;
|
|
571
|
+
}
|
|
572
|
+
function capToken(value) {
|
|
573
|
+
const flagged = /^(.*?)\s*,\s*(on|off|enabled|disabled|yes|no)\s*$/i.exec(value.trim());
|
|
574
|
+
if (flagged?.[2] && /^(?:off|disabled|no)$/i.test(flagged[2])) return "";
|
|
575
|
+
return (flagged?.[1] ?? value).trim();
|
|
576
|
+
}
|
|
577
|
+
function looksLikeCapability(value) {
|
|
578
|
+
return normalizeCapability(value) !== "" || /bridge|router|switch|phone|station|wlan/i.test(value);
|
|
579
|
+
}
|
|
580
|
+
function clipField(value) {
|
|
581
|
+
return value.length > 500 ? value.slice(0, 500) : value;
|
|
582
|
+
}
|
|
583
|
+
var TWEAKS = [
|
|
584
|
+
(bag) => {
|
|
585
|
+
bag.chassisId = cleanSentinel(stripSubtype(bag.chassisId));
|
|
586
|
+
bag.portId = cleanSentinel(stripSubtype(bag.portId));
|
|
587
|
+
bag.portDescription = cleanSentinel(bag.portDescription);
|
|
588
|
+
bag.systemName = cleanSentinel(bag.systemName);
|
|
589
|
+
bag.localPort = cleanSentinel(bag.localPort);
|
|
590
|
+
bag.platform = cleanSentinel(bag.platform);
|
|
591
|
+
bag.systemDescription = cleanSentinel(bag.systemDescription);
|
|
592
|
+
}
|
|
593
|
+
];
|
|
594
|
+
function bagToNeighbor(bag, localDevice, pendingLocal, collected) {
|
|
595
|
+
for (const tweak of TWEAKS) tweak(bag);
|
|
596
|
+
const localPort = bag.localPort || pendingLocal;
|
|
597
|
+
const chassisId = bag.chassisId;
|
|
598
|
+
const systemName = bag.systemName;
|
|
599
|
+
let remotePort = bag.portId;
|
|
600
|
+
const portIsMac = Boolean(remotePort) && isMacAddress(remotePort);
|
|
601
|
+
if (portIsMac && bag.portDescription) {
|
|
602
|
+
collected.warnings.push({
|
|
603
|
+
row: bag.line,
|
|
604
|
+
message: `Line ${bag.line}: port ID is a MAC address. Using the port description.`
|
|
605
|
+
});
|
|
606
|
+
remotePort = bag.portDescription;
|
|
607
|
+
} else if (!remotePort && bag.portDescription) {
|
|
608
|
+
remotePort = bag.portDescription;
|
|
609
|
+
}
|
|
610
|
+
const remoteDevice = systemName || macOf(chassisId) || chassisId;
|
|
611
|
+
const hasAny = Boolean(systemName || chassisId || bag.portId || localPort || bag.systemDescription || bag.platform);
|
|
612
|
+
if (!hasAny) return;
|
|
613
|
+
if (collected.raw.length + collected.errors.length >= MAX_NEIGHBOR_BLOCKS) {
|
|
614
|
+
collected.overflow = true;
|
|
615
|
+
return;
|
|
616
|
+
}
|
|
617
|
+
if (!systemName && chassisId) {
|
|
618
|
+
collected.warnings.push({
|
|
619
|
+
row: bag.line,
|
|
620
|
+
message: `Line ${bag.line}: neighbor has no system name. Using chassis ID ${clipIssue(chassisId)}.`
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
const missing = [];
|
|
624
|
+
if (!localDevice) missing.push("local device");
|
|
625
|
+
if (!localPort) missing.push("local interface");
|
|
626
|
+
if (!remoteDevice) missing.push("remote device");
|
|
627
|
+
if (!remotePort) missing.push("remote port");
|
|
628
|
+
if (missing.length > 0) {
|
|
629
|
+
const who = remoteDevice ? ` "${clipIssue(remoteDevice)}"` : "";
|
|
630
|
+
collected.errors.push({
|
|
631
|
+
row: bag.line,
|
|
632
|
+
message: `Line ${bag.line}: LLDP neighbor${who} is missing ${missing.join(" and ")}.`
|
|
633
|
+
});
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
const capability = normalizeCapability(bag.enabledCaps || bag.supportedCaps);
|
|
637
|
+
collected.raw.push({
|
|
638
|
+
line: bag.line,
|
|
639
|
+
localDevice,
|
|
640
|
+
localPort,
|
|
641
|
+
remoteDevice,
|
|
642
|
+
remotePort,
|
|
643
|
+
remotePlatform: platformOf(bag.systemDescription, bag.platform),
|
|
644
|
+
remoteCapability: capability
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
function finish(collected, emptyMessage2) {
|
|
648
|
+
if (collected.overflow) {
|
|
649
|
+
return {
|
|
650
|
+
parserId: "lldp",
|
|
651
|
+
links: [],
|
|
652
|
+
warnings: [],
|
|
653
|
+
errors: [{ row: 1, message: `A file can have at most ${MAX_NEIGHBOR_BLOCKS} neighbor blocks.` }]
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
return finalizeNeighbors("lldp", collected.raw, collected.errors, collected.warnings, collected.preferred, emptyMessage2);
|
|
657
|
+
}
|
|
658
|
+
function parseLldpText(text, options) {
|
|
659
|
+
const collected = { raw: [], errors: [], warnings: [], preferred: [], overflow: false };
|
|
660
|
+
let localDevice = cleanSentinel(options.localDevice ?? "");
|
|
661
|
+
if (localDevice) collected.preferred.push(localDevice);
|
|
662
|
+
let pendingLocal = "";
|
|
663
|
+
const held = { bag: null };
|
|
664
|
+
const flush = () => {
|
|
665
|
+
const current = held.bag;
|
|
666
|
+
if (!current) return;
|
|
667
|
+
held.bag = null;
|
|
668
|
+
bagToNeighbor(current, localDevice, pendingLocal, collected);
|
|
669
|
+
};
|
|
670
|
+
const ensure = (line) => {
|
|
671
|
+
if (!held.bag) held.bag = emptyBag2(line);
|
|
672
|
+
return held.bag;
|
|
673
|
+
};
|
|
674
|
+
const assign = (field, value, line) => {
|
|
675
|
+
const cleaned = clipField(value.trim().replace(/^["']|["']$/g, "").trim());
|
|
676
|
+
if (!cleaned) {
|
|
677
|
+
if (field === "systemDescription" || field === "portDescription") {
|
|
678
|
+
const current2 = ensure(line);
|
|
679
|
+
current2.openField = field;
|
|
680
|
+
}
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
const current = ensure(line);
|
|
684
|
+
if (REPEAT.has(field) && current[field] && current[field] !== cleaned) {
|
|
685
|
+
flush();
|
|
686
|
+
const next = ensure(line);
|
|
687
|
+
next[field] = cleaned;
|
|
688
|
+
next.openField = "";
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
if (field === "enabledCaps" || field === "supportedCaps") {
|
|
692
|
+
const token = capToken(cleaned);
|
|
693
|
+
if (!token) return;
|
|
694
|
+
current[field] = current[field] ? `${current[field]}, ${token}` : token;
|
|
695
|
+
current.openField = "";
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
if (!current[field]) current[field] = cleaned;
|
|
699
|
+
current.openField = field === "systemDescription" || field === "portDescription" ? field : "";
|
|
700
|
+
};
|
|
701
|
+
const lines = text.split("\n");
|
|
702
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
703
|
+
if (collected.overflow) break;
|
|
704
|
+
const lineNo = index + 1;
|
|
705
|
+
const original = lines[index] ?? "";
|
|
706
|
+
const trimmed = original.trim();
|
|
707
|
+
if (!trimmed) {
|
|
708
|
+
const current = held.bag;
|
|
709
|
+
if (current?.openField === "systemDescription" && !current.systemDescription && !current.skippedBlank) {
|
|
710
|
+
current.skippedBlank = true;
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
if (current) current.openField = "";
|
|
714
|
+
continue;
|
|
715
|
+
}
|
|
716
|
+
if (/^[-=*_~]{5,}$/.test(trimmed)) {
|
|
717
|
+
flush();
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
const host = promptHost(trimmed);
|
|
721
|
+
if (host) {
|
|
722
|
+
flush();
|
|
723
|
+
localDevice = host;
|
|
724
|
+
collected.preferred.push(host);
|
|
725
|
+
continue;
|
|
726
|
+
}
|
|
727
|
+
const detected = /^(?:LLDP\s+)?(?:Port|Interface)\s+(\S+)\s+detected\s+(\d+)\s+(?:LLDP\s+)?neighbors?:?\s*$/i.exec(trimmed);
|
|
728
|
+
if (detected?.[1]) {
|
|
729
|
+
flush();
|
|
730
|
+
pendingLocal = detected[2] === "0" ? "" : detected[1];
|
|
731
|
+
continue;
|
|
732
|
+
}
|
|
733
|
+
const bracketed = /LLDP neighbor-information of port\s+\d+\s*\[([^\]]+)\]/i.exec(trimmed);
|
|
734
|
+
const comware = bracketed ?? /LLDP neighbor-information of port\s+(\S+)/i.exec(trimmed);
|
|
735
|
+
if (comware?.[1] && /neighbor-information of port/i.test(trimmed)) {
|
|
736
|
+
flush();
|
|
737
|
+
pendingLocal = (bracketed?.[1] ?? comware[1] ?? "").replace(/:\s*$/, "").trim();
|
|
738
|
+
continue;
|
|
739
|
+
}
|
|
740
|
+
const neighborStart = /^Neighbor\s+(\S+)/i.exec(trimmed);
|
|
741
|
+
if (neighborStart?.[1] && !/^Neighbor\s+(?:System|Port|Chassis|Device|Entries|Capabilities|Management)/i.test(trimmed)) {
|
|
742
|
+
const open = held.bag;
|
|
743
|
+
if (open && (open.chassisId || open.systemName || open.portId)) flush();
|
|
744
|
+
const slash = /^([^/]+)\/([^,\s]+)/.exec(neighborStart[1]);
|
|
745
|
+
if (slash?.[1] && slash[2]) {
|
|
746
|
+
const hint = ensure(lineNo);
|
|
747
|
+
if (!hint.chassisId) hint.chassisId = slash[1];
|
|
748
|
+
if (!hint.portId) hint.portId = slash[2];
|
|
749
|
+
}
|
|
750
|
+
continue;
|
|
751
|
+
}
|
|
752
|
+
const labeled = splitLabel(trimmed);
|
|
753
|
+
const pairs = parsePairs(trimmed);
|
|
754
|
+
const knownPair = pairs.some((pair) => PAIR_FIELDS[pair.key]);
|
|
755
|
+
if (knownPair) {
|
|
756
|
+
for (const pair of pairs) {
|
|
757
|
+
const field2 = PAIR_FIELDS[pair.key];
|
|
758
|
+
if (field2) assign(field2, pair.value, lineNo);
|
|
759
|
+
}
|
|
760
|
+
continue;
|
|
761
|
+
}
|
|
762
|
+
if (!labeled) {
|
|
763
|
+
const current = held.bag;
|
|
764
|
+
if (current?.openField) {
|
|
765
|
+
const field2 = current.openField;
|
|
766
|
+
current[field2] = clipField(current[field2] ? `${current[field2]} ${trimmed}` : trimmed);
|
|
767
|
+
}
|
|
768
|
+
continue;
|
|
769
|
+
}
|
|
770
|
+
const norm = normLabel(labeled.label);
|
|
771
|
+
if (norm === "local port id" || norm === "localportid") {
|
|
772
|
+
if (!/^\d+$/.test(labeled.value)) assign("localPort", labeled.value, lineNo);
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
if (norm === "interface") {
|
|
776
|
+
const local = labeled.value.split(",")[0]?.trim() ?? "";
|
|
777
|
+
if (local) assign("localPort", local, lineNo);
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
780
|
+
if (norm === "port") {
|
|
781
|
+
assign("localPort", labeled.value, lineNo);
|
|
782
|
+
continue;
|
|
783
|
+
}
|
|
784
|
+
if (norm === "capability") {
|
|
785
|
+
const token = capToken(labeled.value);
|
|
786
|
+
if (token) assign("enabledCaps", token, lineNo);
|
|
787
|
+
continue;
|
|
788
|
+
}
|
|
789
|
+
if ((norm === "enabled" || norm === "supported") && looksLikeCapability(labeled.value)) {
|
|
790
|
+
assign(norm === "enabled" ? "enabledCaps" : "supportedCaps", labeled.value, lineNo);
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
const field = lookupField(labeled.label);
|
|
794
|
+
if (!field) {
|
|
795
|
+
if (held.bag) held.bag.openField = "";
|
|
796
|
+
continue;
|
|
797
|
+
}
|
|
798
|
+
assign(field, labeled.value, lineNo);
|
|
799
|
+
}
|
|
800
|
+
flush();
|
|
801
|
+
return collected;
|
|
802
|
+
}
|
|
803
|
+
function parseLldpKeyvalue(text, options) {
|
|
804
|
+
const collected = { raw: [], errors: [], warnings: [], preferred: [], overflow: false };
|
|
805
|
+
let localDevice = cleanSentinel(options.localDevice ?? "");
|
|
806
|
+
if (localDevice) collected.preferred.push(localDevice);
|
|
807
|
+
let bag = null;
|
|
808
|
+
const flush = () => {
|
|
809
|
+
if (!bag) return;
|
|
810
|
+
const current = bag;
|
|
811
|
+
bag = null;
|
|
812
|
+
if (!current.localPort) current.localPort = current.iface;
|
|
813
|
+
bagToNeighbor(current, localDevice, "", collected);
|
|
814
|
+
};
|
|
815
|
+
const lines = text.split("\n");
|
|
816
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
817
|
+
if (collected.overflow) break;
|
|
818
|
+
const lineNo = index + 1;
|
|
819
|
+
const trimmed = (lines[index] ?? "").trim();
|
|
820
|
+
if (!trimmed) continue;
|
|
821
|
+
const host = promptHost(trimmed);
|
|
822
|
+
if (host) {
|
|
823
|
+
flush();
|
|
824
|
+
localDevice = host;
|
|
825
|
+
collected.preferred.push(host);
|
|
826
|
+
continue;
|
|
827
|
+
}
|
|
828
|
+
const match = /^lldp\.([^.]+)\.(.+?)=(.*)$/.exec(trimmed);
|
|
829
|
+
if (!match?.[1] || !match[2]) continue;
|
|
830
|
+
const iface = match[1];
|
|
831
|
+
const path5 = match[2];
|
|
832
|
+
const value = match[3] ?? "";
|
|
833
|
+
if (!bag || bag.iface !== iface) {
|
|
834
|
+
flush();
|
|
835
|
+
bag = { ...emptyBag2(lineNo), iface };
|
|
836
|
+
}
|
|
837
|
+
const current = bag;
|
|
838
|
+
const setOnce = (field, next) => {
|
|
839
|
+
if (!next) return;
|
|
840
|
+
if (REPEAT.has(field) && current[field] && current[field] !== next) {
|
|
841
|
+
const savedIface = current.iface;
|
|
842
|
+
flush();
|
|
843
|
+
bag = { ...emptyBag2(lineNo), iface: savedIface };
|
|
844
|
+
bag[field] = next;
|
|
845
|
+
return;
|
|
846
|
+
}
|
|
847
|
+
if (!current[field]) current[field] = next;
|
|
848
|
+
};
|
|
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") {
|
|
853
|
+
if (current.portId && isMacAddress(current.portId)) current.portId = "";
|
|
854
|
+
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] ?? "";
|
|
859
|
+
if (/^(?:on|true|yes|1)$/i.test(value) && name) {
|
|
860
|
+
current.enabledCaps = current.enabledCaps ? `${current.enabledCaps}, ${name}` : name;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
flush();
|
|
865
|
+
return collected;
|
|
866
|
+
}
|
|
867
|
+
function isRecord(value) {
|
|
868
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
869
|
+
}
|
|
870
|
+
function textOf(value) {
|
|
871
|
+
if (typeof value === "string") return value.trim();
|
|
872
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
873
|
+
if (Array.isArray(value)) return value.map((item) => textOf(item)).filter(Boolean).join(", ");
|
|
874
|
+
if (isRecord(value)) {
|
|
875
|
+
if (typeof value.value === "string" || typeof value.value === "number") return String(value.value).trim();
|
|
876
|
+
}
|
|
877
|
+
return "";
|
|
878
|
+
}
|
|
879
|
+
function capabilityFromJson(value) {
|
|
880
|
+
if (!value) return "";
|
|
881
|
+
const items = Array.isArray(value) ? value : [value];
|
|
882
|
+
const enabled = [];
|
|
883
|
+
for (const item of items) {
|
|
884
|
+
if (typeof item === "string") {
|
|
885
|
+
enabled.push(item);
|
|
886
|
+
continue;
|
|
887
|
+
}
|
|
888
|
+
if (!isRecord(item)) continue;
|
|
889
|
+
const type = textOf(item.type ?? item.name);
|
|
890
|
+
const flag = item.enabled;
|
|
891
|
+
if (flag === false || flag === "off" || flag === "false") continue;
|
|
892
|
+
if (type) enabled.push(type);
|
|
893
|
+
}
|
|
894
|
+
return enabled.join(", ");
|
|
895
|
+
}
|
|
896
|
+
function chassisFromJson(chassis) {
|
|
897
|
+
if (!isRecord(chassis)) return [];
|
|
898
|
+
const known = /* @__PURE__ */ new Set(["id", "name", "descr", "description", "mgmt-ip", "mgmt_ip", "capability", "capabilities"]);
|
|
899
|
+
const direct = textOf(chassis.name) || chassis.id || chassis.descr || chassis.description;
|
|
900
|
+
if (direct) {
|
|
901
|
+
return [
|
|
902
|
+
{
|
|
903
|
+
name: textOf(chassis.name),
|
|
904
|
+
id: textOf(chassis.id),
|
|
905
|
+
descr: textOf(chassis.descr ?? chassis.description),
|
|
906
|
+
caps: capabilityFromJson(chassis.capability ?? chassis.capabilities)
|
|
907
|
+
}
|
|
908
|
+
];
|
|
909
|
+
}
|
|
910
|
+
const hosts = Object.keys(chassis).filter((key) => !known.has(key) && isRecord(chassis[key]));
|
|
911
|
+
if (hosts.length === 0) return [];
|
|
912
|
+
return hosts.map((host) => {
|
|
913
|
+
const inner = chassis[host];
|
|
914
|
+
return {
|
|
915
|
+
name: host,
|
|
916
|
+
id: textOf(inner.id),
|
|
917
|
+
descr: textOf(inner.descr ?? inner.description),
|
|
918
|
+
caps: capabilityFromJson(inner.capability ?? inner.capabilities)
|
|
919
|
+
};
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
function portFromJson(port) {
|
|
923
|
+
if (!isRecord(port)) return { id: "", descr: "" };
|
|
924
|
+
return {
|
|
925
|
+
id: textOf(port.id ?? port.ifname ?? port.name),
|
|
926
|
+
descr: textOf(port.descr ?? port.description)
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
function interfaceRecords(node) {
|
|
930
|
+
if (Array.isArray(node)) {
|
|
931
|
+
return node.flatMap((item, index) => {
|
|
932
|
+
if (!isRecord(item)) return [];
|
|
933
|
+
const name = textOf(item.name) || `if${index + 1}`;
|
|
934
|
+
return [{ name, value: item }];
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
if (!isRecord(node)) return [];
|
|
938
|
+
if (node.chassis || node.port || node.name) {
|
|
939
|
+
return [{ name: textOf(node.name) || "interface", value: node }];
|
|
940
|
+
}
|
|
941
|
+
return Object.entries(node).flatMap(([name, value]) => isRecord(value) ? [{ name, value }] : []);
|
|
942
|
+
}
|
|
943
|
+
function parseLldpJson(text, options) {
|
|
944
|
+
const collected = { raw: [], errors: [], warnings: [], preferred: [], overflow: false };
|
|
945
|
+
const localDevice = cleanSentinel(options.localDevice ?? "");
|
|
946
|
+
if (localDevice) collected.preferred.push(localDevice);
|
|
947
|
+
let parsed;
|
|
948
|
+
try {
|
|
949
|
+
parsed = JSON.parse(text);
|
|
950
|
+
} catch {
|
|
951
|
+
collected.errors.push({ row: 1, message: "This LLDP JSON could not be parsed." });
|
|
952
|
+
return collected;
|
|
953
|
+
}
|
|
954
|
+
const root = isRecord(parsed) && parsed.lldp ? parsed.lldp : parsed;
|
|
955
|
+
const interfaces = isRecord(root) ? interfaceRecords(root.interface ?? root.interfaces ?? root) : [];
|
|
956
|
+
if (interfaces.length === 0) {
|
|
957
|
+
collected.errors.push({ row: 1, message: "This LLDP JSON has no interface neighbors." });
|
|
958
|
+
return collected;
|
|
959
|
+
}
|
|
960
|
+
for (const item of interfaces) {
|
|
961
|
+
const port = portFromJson(item.value.port);
|
|
962
|
+
const chassisList = chassisFromJson(item.value.chassis);
|
|
963
|
+
const bodies = chassisList.length > 0 ? chassisList : [{ name: "", id: "", descr: "", caps: "" }];
|
|
964
|
+
for (const chassis of bodies) {
|
|
965
|
+
const bag = emptyBag2(1);
|
|
966
|
+
bag.localPort = item.name;
|
|
967
|
+
bag.systemName = chassis.name;
|
|
968
|
+
bag.chassisId = chassis.id;
|
|
969
|
+
bag.systemDescription = chassis.descr;
|
|
970
|
+
bag.enabledCaps = chassis.caps;
|
|
971
|
+
bag.portId = port.id;
|
|
972
|
+
bag.portDescription = port.descr;
|
|
973
|
+
bagToNeighbor(bag, localDevice, "", collected);
|
|
974
|
+
if (collected.overflow) break;
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
return collected;
|
|
978
|
+
}
|
|
979
|
+
function looksLikeLldpJson(text) {
|
|
980
|
+
const trimmed = text.trim();
|
|
981
|
+
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return false;
|
|
982
|
+
return /"lldp"/i.test(trimmed) || /"chassis"/i.test(trimmed) && /"port"/i.test(trimmed);
|
|
983
|
+
}
|
|
984
|
+
function looksLikeKeyvalue(text) {
|
|
985
|
+
return /^lldp\./m.test(text);
|
|
986
|
+
}
|
|
987
|
+
function emptyMessage(text) {
|
|
988
|
+
if (/local interface\s+.*system name/i.test(text) && !/chassis id\s*:/i.test(text) && !/system name\s*:/i.test(text)) {
|
|
989
|
+
return "This is the short LLDP neighbor table. Paste the detail output, or lldpctl on Linux.";
|
|
990
|
+
}
|
|
991
|
+
return "No LLDP neighbors were found. Paste LLDP neighbor detail, or lldpctl output.";
|
|
992
|
+
}
|
|
993
|
+
function parseLldpNeighbors(text, options = {}) {
|
|
994
|
+
const cleaned = cleanCli(text);
|
|
995
|
+
if (looksLikeLldpJson(cleaned)) {
|
|
996
|
+
return finish(parseLldpJson(cleaned, options), emptyMessage(cleaned));
|
|
997
|
+
}
|
|
998
|
+
if (looksLikeKeyvalue(cleaned)) {
|
|
999
|
+
return finish(parseLldpKeyvalue(cleaned, options), emptyMessage(cleaned));
|
|
1000
|
+
}
|
|
1001
|
+
return finish(parseLldpText(cleaned, options), emptyMessage(cleaned));
|
|
1002
|
+
}
|
|
1003
|
+
var lldpParser = {
|
|
1004
|
+
id: "lldp",
|
|
1005
|
+
kind: "lldp",
|
|
1006
|
+
label: "LLDP neighbors (any vendor)",
|
|
1007
|
+
parse: parseLldpNeighbors
|
|
1008
|
+
};
|
|
1009
|
+
|
|
1010
|
+
// server/src/neighbors/registry.ts
|
|
1011
|
+
var parsers = [];
|
|
1012
|
+
function registerNeighborParser(parser) {
|
|
1013
|
+
const index = parsers.findIndex((item) => item.id === parser.id);
|
|
1014
|
+
if (index >= 0) parsers.splice(index, 1);
|
|
1015
|
+
parsers.push(parser);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// server/src/neighbors/index.ts
|
|
1019
|
+
registerNeighborParser(ciscoCdpParser);
|
|
1020
|
+
registerNeighborParser(lldpParser);
|
|
1021
|
+
|
|
1022
|
+
// server/src/diagramData.ts
|
|
1023
|
+
var DATA_LIMITS = {
|
|
1024
|
+
maxChars: 512 * 1024,
|
|
1025
|
+
maxRows: 5e3,
|
|
1026
|
+
maxNodes: 2e3,
|
|
1027
|
+
maxEdges: 5e3,
|
|
1028
|
+
maxColumns: 40,
|
|
1029
|
+
maxLabelChars: 240,
|
|
1030
|
+
maxCellChars: 2e3,
|
|
1031
|
+
maxTitleChars: 200
|
|
1032
|
+
};
|
|
1033
|
+
var SHAPE_FIELDS = {
|
|
1034
|
+
links: [
|
|
1035
|
+
{ field: "localDevice", label: "Local device", required: true },
|
|
1036
|
+
{ field: "localPort", label: "Local port", required: false },
|
|
1037
|
+
{ field: "remoteDevice", label: "Remote device", required: true },
|
|
1038
|
+
{ field: "remotePort", label: "Remote port", required: false },
|
|
1039
|
+
{ field: "localGroup", label: "Local group", required: false },
|
|
1040
|
+
{ field: "remoteGroup", label: "Remote group", required: false },
|
|
1041
|
+
{ field: "localType", label: "Local type", required: false },
|
|
1042
|
+
{ field: "remoteType", label: "Remote type", required: false },
|
|
1043
|
+
{ field: "localClass", label: "Local style class", required: false },
|
|
1044
|
+
{ field: "remoteClass", label: "Remote style class", required: false },
|
|
1045
|
+
{ field: "localDiagram", label: "Local child diagram", required: false },
|
|
1046
|
+
{ field: "remoteDiagram", label: "Remote child diagram", required: false }
|
|
1047
|
+
],
|
|
1048
|
+
nodes: [
|
|
1049
|
+
{ field: "id", label: "Id", required: true },
|
|
1050
|
+
{ field: "label", label: "Label", required: false },
|
|
1051
|
+
{ field: "group", label: "Group", required: false },
|
|
1052
|
+
{ field: "type", label: "Type", required: false },
|
|
1053
|
+
{ field: "styleClass", label: "Style class", required: false },
|
|
1054
|
+
{ field: "diagram", label: "Child diagram", required: false }
|
|
1055
|
+
],
|
|
1056
|
+
edges: [
|
|
1057
|
+
{ field: "source", label: "Source", required: true },
|
|
1058
|
+
{ field: "target", label: "Target", required: true },
|
|
1059
|
+
{ field: "label", label: "Label", required: false }
|
|
1060
|
+
],
|
|
1061
|
+
graph: [
|
|
1062
|
+
{ field: "id", label: "Id", required: true },
|
|
1063
|
+
{ field: "label", label: "Label", required: false },
|
|
1064
|
+
{ field: "group", label: "Group", required: false },
|
|
1065
|
+
{ field: "type", label: "Type", required: false },
|
|
1066
|
+
{ field: "styleClass", label: "Style class", required: false },
|
|
1067
|
+
{ field: "diagram", label: "Child diagram", required: false }
|
|
1068
|
+
]
|
|
1069
|
+
};
|
|
1070
|
+
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
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
async function load() {
|
|
1118
|
+
try {
|
|
1119
|
+
return normalizeCatalog(await readJsonFile(sightingsPath())) ?? emptyCatalog();
|
|
1120
|
+
} 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: [] };
|
|
1179
|
+
}
|
|
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
|
+
}
|
|
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") {
|
|
1192
|
+
return null;
|
|
1193
|
+
}
|
|
1194
|
+
const meta = {
|
|
1195
|
+
id: revision.id,
|
|
1196
|
+
createdAt: revision.createdAt,
|
|
1197
|
+
mtimeMs: revision.mtimeMs,
|
|
1198
|
+
size: revision.size,
|
|
1199
|
+
hash: revision.hash
|
|
1200
|
+
};
|
|
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;
|
|
1241
|
+
}
|
|
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");
|
|
1248
|
+
}
|
|
1249
|
+
function lockFile(relativePath) {
|
|
1250
|
+
return path3.join(getLocksRoot(), `${lockStorageKey(relativePath)}.json`);
|
|
1251
|
+
}
|
|
1252
|
+
function optionalText(value) {
|
|
1253
|
+
if (typeof value !== "string") return void 0;
|
|
1254
|
+
const trimmed = value.trim();
|
|
1255
|
+
return trimmed || void 0;
|
|
1256
|
+
}
|
|
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";
|
|
1261
|
+
}
|
|
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
|
+
};
|
|
1277
|
+
}
|
|
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
|
+
};
|
|
1321
|
+
}
|
|
1322
|
+
async function lockedError(record) {
|
|
1323
|
+
const identity = await getInstanceIdentity();
|
|
1324
|
+
return httpFail(423, lockedMessage(record, identity), "locked", {
|
|
1325
|
+
lock: holderDetails(record, identity)
|
|
1326
|
+
});
|
|
1327
|
+
}
|
|
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);
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
// server/src/fsStore.ts
|
|
1336
|
+
var DIAGRAM_EXT = ".mmd";
|
|
1337
|
+
function isDiagramFile(name) {
|
|
1338
|
+
return name.toLowerCase().endsWith(DIAGRAM_EXT);
|
|
1339
|
+
}
|
|
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
|
+
});
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
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");
|
|
1434
|
+
}
|
|
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 }
|
|
1441
|
+
);
|
|
1442
|
+
}
|
|
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
|
+
return {
|
|
1457
|
+
path: relative,
|
|
1458
|
+
mtimeMs: disk.mtimeMs,
|
|
1459
|
+
size: disk.size,
|
|
1460
|
+
hash: disk.hash,
|
|
1461
|
+
unchanged: true
|
|
1462
|
+
};
|
|
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-WSGEBKT4.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
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
function noteSync(change) {
|
|
1485
|
+
void import("./chunk-JUCAQ6EJ.js").then((mod) => mod.noteLocalChange(change)).catch(() => {
|
|
1486
|
+
console.error("GitHub sync could not record a local change");
|
|
1487
|
+
});
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
export {
|
|
1491
|
+
buildTree,
|
|
1492
|
+
readFile,
|
|
1493
|
+
writeFile
|
|
1494
|
+
};
|