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.
@@ -0,0 +1,492 @@
1
+ import {
2
+ readFile,
3
+ writeFile
4
+ } from "./chunk-I5EOFHBL.js";
5
+ import {
6
+ REPO_ROOT,
7
+ ensureDataRoot,
8
+ httpFail,
9
+ normalizeRelative,
10
+ pathExists,
11
+ resolveAvailablePath,
12
+ resolveSafePath,
13
+ toRelativePath
14
+ } from "./chunk-ULY5YEBR.js";
15
+ import "./chunk-5C6VO4LC.js";
16
+ import {
17
+ applyDiagramPatch,
18
+ diagramConfigKey,
19
+ parseDiagram
20
+ } from "./chunk-AFGGIQ22.js";
21
+
22
+ // server/src/templates.ts
23
+ import fs from "node:fs/promises";
24
+ import path from "node:path";
25
+ var ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,80}$/;
26
+ var FILE_PATTERN = /^[a-z0-9][a-z0-9-]{0,80}\.mmd$/;
27
+ var TEMPLATE_CATEGORIES = [
28
+ "Network",
29
+ "Software",
30
+ "Internet & Cloud",
31
+ "Security",
32
+ "OT & Industrial",
33
+ "Data Center",
34
+ "Operations & Planning",
35
+ "User created"
36
+ ];
37
+ var USER_TEMPLATE_CATEGORY = "User created";
38
+ var PREFERRED_ORDER = [
39
+ "network-topology",
40
+ "home-lab",
41
+ "flowchart-starter",
42
+ "sequence-starter",
43
+ "process-flow",
44
+ "api-request-sequence",
45
+ "class-model",
46
+ "order-state",
47
+ "database-er",
48
+ "cicd-pipeline",
49
+ "git-branching",
50
+ "wan-topology",
51
+ "internet-edge",
52
+ "cloud-vpc",
53
+ "hybrid-cloud",
54
+ "site-to-site-vpn",
55
+ "firewall-policy",
56
+ "zero-trust-access",
57
+ "incident-response",
58
+ "network-segmentation",
59
+ "purdue-model",
60
+ "scada-communications",
61
+ "remote-site-cellular",
62
+ "rack-elevation",
63
+ "spine-leaf",
64
+ "server-storage-rack",
65
+ "power-cooling",
66
+ "change-window",
67
+ "migration-plan",
68
+ "change-request",
69
+ "team-task-board",
70
+ "brainstorm"
71
+ ];
72
+ var TYPE_LABELS = {
73
+ flowchart: "Flowchart",
74
+ sequence: "Sequence",
75
+ class: "Class",
76
+ state: "State",
77
+ er: "ER",
78
+ gantt: "Gantt",
79
+ journey: "Journey",
80
+ pie: "Pie",
81
+ mindmap: "Mindmap",
82
+ timeline: "Timeline",
83
+ gitGraph: "Git graph",
84
+ c4: "C4",
85
+ quadrantChart: "Quadrant",
86
+ requirement: "Requirement",
87
+ xyChart: "XY chart",
88
+ block: "Block",
89
+ sankey: "Sankey",
90
+ packet: "Packet",
91
+ kanban: "Kanban",
92
+ architecture: "Architecture"
93
+ };
94
+ function getTemplatesRoot() {
95
+ return path.join(REPO_ROOT, "templates");
96
+ }
97
+ function getUserTemplatesRoot() {
98
+ return path.join(ensureDataRoot(), ".templates");
99
+ }
100
+ function diagramTypeLabel(body) {
101
+ const key = diagramConfigKey(body);
102
+ if (!key) return "Diagram";
103
+ return TYPE_LABELS[key] ?? "Diagram";
104
+ }
105
+ function assertId(id) {
106
+ const trimmed = id.trim();
107
+ if (!ID_PATTERN.test(trimmed)) {
108
+ throw httpFail(400, "Invalid template id", "invalid");
109
+ }
110
+ return trimmed;
111
+ }
112
+ function safeDataPath(relativePath) {
113
+ try {
114
+ return resolveSafePath(relativePath);
115
+ } catch (err) {
116
+ const message = err instanceof Error ? err.message : "Invalid path";
117
+ throw httpFail(400, message, "invalid");
118
+ }
119
+ }
120
+ function isHttpError(err) {
121
+ return err instanceof Error && typeof err.status === "number";
122
+ }
123
+ function errorStatus(err) {
124
+ if (!err || typeof err !== "object" || !("status" in err)) return null;
125
+ const status = err.status;
126
+ return typeof status === "number" ? status : null;
127
+ }
128
+ function errorCode(err) {
129
+ if (!err || typeof err !== "object" || !("code" in err)) return "";
130
+ const code = err.code;
131
+ return typeof code === "string" ? code : "";
132
+ }
133
+ async function resolveTemplatesRoot(root) {
134
+ let stat;
135
+ try {
136
+ stat = await fs.stat(root);
137
+ } catch (err) {
138
+ const code = err.code;
139
+ if (code === "ENOENT") throw httpFail(404, "Template not found", "not_found");
140
+ throw err;
141
+ }
142
+ if (!stat.isDirectory()) throw httpFail(404, "Template not found", "not_found");
143
+ return fs.realpath(root);
144
+ }
145
+ async function readTemplateFile(root, id) {
146
+ const safeId = assertId(id);
147
+ const rootReal = await resolveTemplatesRoot(root);
148
+ const absolute = path.resolve(rootReal, `${safeId}.mmd`);
149
+ const lexical = path.relative(rootReal, absolute);
150
+ if (lexical.startsWith("..") || path.isAbsolute(lexical)) {
151
+ throw httpFail(400, "Invalid template id", "invalid");
152
+ }
153
+ let fileReal;
154
+ try {
155
+ fileReal = await fs.realpath(absolute);
156
+ } catch (err) {
157
+ const code = err.code;
158
+ if (code === "ENOENT") throw httpFail(404, "Template not found", "not_found");
159
+ throw err;
160
+ }
161
+ const fromRoot = path.relative(rootReal, fileReal);
162
+ const parts = fromRoot.split(/[/\\]/).filter((part) => part.length > 0);
163
+ if (fromRoot.startsWith("..") || path.isAbsolute(fromRoot) || parts.length !== 1 || parts[0] !== `${safeId}.mmd`) {
164
+ throw httpFail(400, "Invalid template id", "invalid");
165
+ }
166
+ const stat = await fs.stat(fileReal);
167
+ if (!stat.isFile()) throw httpFail(404, "Template not found", "not_found");
168
+ return fs.readFile(fileReal, "utf8");
169
+ }
170
+ function toRecord(id, source, origin) {
171
+ const parsed = parseDiagram(source);
172
+ const title = parsed.title?.trim() || id;
173
+ const category = origin === "user" ? USER_TEMPLATE_CATEGORY : parsed.category;
174
+ return {
175
+ id,
176
+ title,
177
+ description: parsed.description,
178
+ tags: parsed.tags,
179
+ category,
180
+ theme: parsed.theme,
181
+ diagramType: diagramTypeLabel(parsed.body),
182
+ cacheKey: parsed.cacheKey,
183
+ malformed: parsed.malformed,
184
+ error: parsed.error,
185
+ source,
186
+ origin
187
+ };
188
+ }
189
+ function sortTemplates(records) {
190
+ const categoryRank = new Map(TEMPLATE_CATEGORIES.map((name, index) => [name.toLowerCase(), index]));
191
+ const rank = new Map(PREFERRED_ORDER.map((id, index) => [id, index]));
192
+ return [...records].sort((a, b) => {
193
+ const leftCategory = categoryRank.get(a.category.trim().toLowerCase()) ?? 500;
194
+ const rightCategory = categoryRank.get(b.category.trim().toLowerCase()) ?? 500;
195
+ if (leftCategory !== rightCategory) return leftCategory - rightCategory;
196
+ const left = rank.get(a.id) ?? 1e3;
197
+ const right = rank.get(b.id) ?? 1e3;
198
+ if (left !== right) return left - right;
199
+ const byTitle = a.title.localeCompare(b.title, void 0, { sensitivity: "base" });
200
+ if (byTitle !== 0) return byTitle;
201
+ return a.id.localeCompare(b.id);
202
+ });
203
+ }
204
+ async function listTemplates(root = getTemplatesRoot()) {
205
+ let rootReal;
206
+ try {
207
+ rootReal = await resolveTemplatesRoot(root);
208
+ } catch (err) {
209
+ if (errorStatus(err) === 404) return [];
210
+ throw err;
211
+ }
212
+ const names = await fs.readdir(rootReal);
213
+ const records = [];
214
+ for (const name of names) {
215
+ if (!FILE_PATTERN.test(name)) continue;
216
+ const id = name.slice(0, -".mmd".length);
217
+ try {
218
+ const source = await readTemplateFile(rootReal, id);
219
+ records.push(toRecord(id, source, "builtin"));
220
+ } catch (err) {
221
+ if (isHttpError(err) && err.status === 400) continue;
222
+ throw err;
223
+ }
224
+ }
225
+ return sortTemplates(records);
226
+ }
227
+ async function readTemplate(id, root = getTemplatesRoot()) {
228
+ const safeId = assertId(id);
229
+ if (path.resolve(root) === path.resolve(getTemplatesRoot())) {
230
+ try {
231
+ const source2 = await readTemplateFile(root, safeId);
232
+ return toRecord(safeId, source2, "builtin");
233
+ } catch (err) {
234
+ if (errorStatus(err) !== 404) throw err;
235
+ return readUserTemplateRecord(safeId);
236
+ }
237
+ }
238
+ const source = await readTemplateFile(root, safeId);
239
+ return toRecord(safeId, source, "builtin");
240
+ }
241
+ async function listAllTemplates() {
242
+ const [builtin, user] = await Promise.all([listTemplates(), listUserTemplates()]);
243
+ return sortTemplates([...builtin, ...user]);
244
+ }
245
+ function fileNameFrom(requested) {
246
+ if (/[\\/\0]/.test(requested)) {
247
+ throw httpFail(400, "Diagram name cannot include a path", "invalid");
248
+ }
249
+ if (requested.startsWith(".")) {
250
+ throw httpFail(400, "Invalid path", "invalid");
251
+ }
252
+ const fileName = requested.toLowerCase().endsWith(".mmd") ? requested : `${requested}.mmd`;
253
+ const stem = fileName.slice(0, -".mmd".length).trim();
254
+ if (!stem || stem.startsWith(".")) {
255
+ throw httpFail(400, "Invalid path", "invalid");
256
+ }
257
+ if (fileName.length > 120) {
258
+ throw httpFail(400, "Diagram name is too long", "invalid");
259
+ }
260
+ return fileName;
261
+ }
262
+ async function assertExistingFolder(folder) {
263
+ if (folder == null || folder === "") return "";
264
+ if (typeof folder !== "string") throw httpFail(400, "folder must be a string", "invalid");
265
+ const normalized = normalizeRelative(folder);
266
+ if (normalized === "" || normalized === ".") return "";
267
+ const absolute = safeDataPath(normalized);
268
+ try {
269
+ const stat = await fs.stat(absolute);
270
+ if (!stat.isDirectory()) throw httpFail(400, "That folder does not exist", "invalid");
271
+ } catch (err) {
272
+ if (isHttpError(err)) throw err;
273
+ const code = err.code;
274
+ if (code === "ENOENT") throw httpFail(400, "That folder does not exist", "invalid");
275
+ throw err;
276
+ }
277
+ return toRelativePath(absolute);
278
+ }
279
+ async function createDiagramFromTemplate(id, input, root = getTemplatesRoot()) {
280
+ if (input.name != null && typeof input.name !== "string") {
281
+ throw httpFail(400, "name must be a string", "invalid");
282
+ }
283
+ const template = await readTemplate(id, root);
284
+ const folder = await assertExistingFolder(input.folder);
285
+ const requested = typeof input.name === "string" ? input.name.trim() : "";
286
+ const fileName = fileNameFrom(requested || template.title || template.id);
287
+ const desired = folder ? `${folder}/${fileName}` : fileName;
288
+ safeDataPath(desired);
289
+ let candidate = desired;
290
+ for (let attempt = 0; attempt < 8; attempt += 1) {
291
+ candidate = await resolveAvailablePath(candidate, (item) => pathExists(safeDataPath(item)));
292
+ try {
293
+ const written = await writeFile(candidate, template.source);
294
+ return {
295
+ path: written.path,
296
+ mtimeMs: written.mtimeMs,
297
+ size: written.size,
298
+ hash: written.hash,
299
+ templateId: template.id
300
+ };
301
+ } catch (err) {
302
+ if (errorCode(err) !== "exists") throw err;
303
+ }
304
+ }
305
+ throw httpFail(409, "No free path is available", "collision", { path: desired });
306
+ }
307
+ var BUILTIN_READONLY = "Built-in templates cannot be changed";
308
+ function asRecord(input) {
309
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
310
+ throw httpFail(400, "JSON object required", "invalid");
311
+ }
312
+ return input;
313
+ }
314
+ function slugFromName(name) {
315
+ const slug = name.trim().toLowerCase().replace(/\.mmd$/i, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
316
+ if (!ID_PATTERN.test(slug)) throw httpFail(400, "Template name needs a letter or number", "invalid");
317
+ return slug;
318
+ }
319
+ function readTags(value, fallback) {
320
+ if (value == null) return fallback;
321
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
322
+ throw httpFail(400, "tags must be an array of strings", "invalid");
323
+ }
324
+ return value.map((item) => item.trim()).filter((item, index, all) => item && all.indexOf(item) === index);
325
+ }
326
+ async function builtinExists(id) {
327
+ try {
328
+ await readTemplateFile(getTemplatesRoot(), id);
329
+ return true;
330
+ } catch (err) {
331
+ const status = errorStatus(err);
332
+ if (status === 404 || status === 400) return false;
333
+ throw err;
334
+ }
335
+ }
336
+ async function refuseBuiltin(id) {
337
+ if (await builtinExists(id)) throw httpFail(403, BUILTIN_READONLY, "forbidden");
338
+ }
339
+ function userFilePath(id) {
340
+ return path.join(getUserTemplatesRoot(), `${assertId(id)}.mmd`);
341
+ }
342
+ async function listUserTemplates() {
343
+ const root = getUserTemplatesRoot();
344
+ let names;
345
+ try {
346
+ names = await fs.readdir(root);
347
+ } catch (err) {
348
+ if (err.code === "ENOENT") return [];
349
+ throw err;
350
+ }
351
+ const records = [];
352
+ for (const name of names) {
353
+ if (!FILE_PATTERN.test(name)) continue;
354
+ const id = name.slice(0, -".mmd".length);
355
+ try {
356
+ records.push(await readUserTemplateRecord(id));
357
+ } catch (err) {
358
+ if (isHttpError(err) && (err.status === 400 || err.status === 404)) continue;
359
+ throw err;
360
+ }
361
+ }
362
+ return records;
363
+ }
364
+ async function readUserTemplateRecord(id) {
365
+ const safeId = assertId(id);
366
+ const absolute = userFilePath(safeId);
367
+ let text;
368
+ try {
369
+ const stat = await fs.stat(absolute);
370
+ if (!stat.isFile()) throw httpFail(404, "Template not found", "not_found");
371
+ text = await fs.readFile(absolute, "utf8");
372
+ } catch (err) {
373
+ if (isHttpError(err)) throw err;
374
+ if (err.code === "ENOENT") throw httpFail(404, "Template not found", "not_found");
375
+ throw err;
376
+ }
377
+ return toRecord(safeId, text, "user");
378
+ }
379
+ async function writeUserFile(id, source) {
380
+ const absolute = userFilePath(id);
381
+ await fs.mkdir(path.dirname(absolute), { recursive: true });
382
+ const temporary = `${absolute}.${process.pid}.tmp`;
383
+ await fs.writeFile(temporary, source, "utf8");
384
+ await fs.rename(temporary, absolute);
385
+ }
386
+ function stampUserTemplate(content, meta) {
387
+ const patch = {
388
+ category: USER_TEMPLATE_CATEGORY
389
+ };
390
+ if (meta.title != null) patch.title = meta.title;
391
+ if (meta.description != null) patch.description = meta.description;
392
+ if (meta.tags != null) patch.tags = meta.tags;
393
+ const applied = applyDiagramPatch(content, patch);
394
+ if (!applied.ok) throw httpFail(400, applied.error, "invalid");
395
+ const parsed = parseDiagram(applied.source);
396
+ if (parsed.category !== USER_TEMPLATE_CATEGORY) {
397
+ throw httpFail(400, "User templates stay in User created", "invalid");
398
+ }
399
+ return applied.source;
400
+ }
401
+ async function contentFromBody(body) {
402
+ if (typeof body.content === "string") {
403
+ if (!body.content.trim()) throw httpFail(400, "content is empty", "invalid");
404
+ return body.content;
405
+ }
406
+ if (typeof body.path === "string" && body.path.trim()) {
407
+ const file = await readFile(body.path);
408
+ return file.content;
409
+ }
410
+ throw httpFail(400, "content or path is required", "invalid");
411
+ }
412
+ async function createUserTemplate(input) {
413
+ const body = asRecord(input);
414
+ const content = await contentFromBody(body);
415
+ const parsed = parseDiagram(content);
416
+ const name = typeof body.name === "string" && body.name.trim() ? body.name.trim() : parsed.title?.trim() || "template";
417
+ const description = typeof body.description === "string" ? body.description : parsed.description;
418
+ const tags = readTags(body.tags, parsed.tags);
419
+ const id = typeof body.id === "string" && body.id.trim() ? assertId(body.id.trim().toLowerCase()) : slugFromName(name);
420
+ await refuseBuiltin(id);
421
+ const absolute = userFilePath(id);
422
+ let exists = false;
423
+ try {
424
+ const stat = await fs.stat(absolute);
425
+ exists = stat.isFile();
426
+ } catch (err) {
427
+ if (err.code !== "ENOENT") throw err;
428
+ }
429
+ if (exists && body.replace !== true) {
430
+ throw httpFail(409, "A user template with that name already exists", "exists", { id, title: name });
431
+ }
432
+ const stamped = stampUserTemplate(content, { title: name, description, tags });
433
+ await writeUserFile(id, stamped);
434
+ return toRecord(id, stamped, "user");
435
+ }
436
+ async function saveUserTemplate(id, input) {
437
+ const safeId = assertId(id);
438
+ await refuseBuiltin(safeId);
439
+ await readUserTemplateRecord(safeId);
440
+ const body = asRecord(input);
441
+ if (typeof body.content !== "string" || !body.content.trim()) {
442
+ throw httpFail(400, "content is required", "invalid");
443
+ }
444
+ const stamped = stampUserTemplate(body.content, {});
445
+ await writeUserFile(safeId, stamped);
446
+ return toRecord(safeId, stamped, "user");
447
+ }
448
+ async function renameUserTemplate(id, input) {
449
+ const safeId = assertId(id);
450
+ await refuseBuiltin(safeId);
451
+ const current = await readUserTemplateRecord(safeId);
452
+ const body = asRecord(input);
453
+ const requested = typeof body.name === "string" ? body.name : typeof body.id === "string" ? body.id : "";
454
+ if (!requested.trim()) throw httpFail(400, "name is required", "invalid");
455
+ const nextId = typeof body.id === "string" && body.id.trim() ? assertId(body.id.trim().toLowerCase()) : slugFromName(requested);
456
+ await refuseBuiltin(nextId);
457
+ if (nextId !== safeId) {
458
+ try {
459
+ const stat = await fs.stat(userFilePath(nextId));
460
+ if (stat.isFile()) throw httpFail(409, "A user template with that name already exists", "exists", { id: nextId });
461
+ } catch (err) {
462
+ if (isHttpError(err)) throw err;
463
+ if (err.code !== "ENOENT") throw err;
464
+ }
465
+ }
466
+ const title = typeof body.name === "string" && body.name.trim() ? body.name.trim() : current.title;
467
+ const stamped = stampUserTemplate(current.source, { title });
468
+ await writeUserFile(nextId, stamped);
469
+ if (nextId !== safeId) await fs.rm(userFilePath(safeId), { force: true });
470
+ return toRecord(nextId, stamped, "user");
471
+ }
472
+ async function deleteUserTemplate(id) {
473
+ const safeId = assertId(id);
474
+ await refuseBuiltin(safeId);
475
+ await readUserTemplateRecord(safeId);
476
+ await fs.rm(userFilePath(safeId), { force: true });
477
+ }
478
+ export {
479
+ TEMPLATE_CATEGORIES,
480
+ USER_TEMPLATE_CATEGORY,
481
+ createDiagramFromTemplate,
482
+ createUserTemplate,
483
+ deleteUserTemplate,
484
+ diagramTypeLabel,
485
+ getTemplatesRoot,
486
+ getUserTemplatesRoot,
487
+ listAllTemplates,
488
+ listTemplates,
489
+ readTemplate,
490
+ renameUserTemplate,
491
+ saveUserTemplate
492
+ };