lula2 0.0.5 → 0.0.6

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.
Files changed (108) hide show
  1. package/README.md +291 -8
  2. package/dist/_app/env.js +1 -0
  3. package/dist/_app/immutable/assets/0.DtiRW3lO.css +1 -0
  4. package/dist/_app/immutable/assets/DynamicControlEditor.BkVTzFZ-.css +1 -0
  5. package/dist/_app/immutable/chunks/7x_q-1ab.js +1 -0
  6. package/dist/_app/immutable/chunks/B19gt6-g.js +2 -0
  7. package/dist/_app/immutable/chunks/BR-0Dorr.js +1 -0
  8. package/dist/_app/immutable/chunks/B_3ksxz5.js +2 -0
  9. package/dist/_app/immutable/chunks/Bg_R1qWi.js +3 -0
  10. package/dist/_app/immutable/chunks/D3aNP_lg.js +1 -0
  11. package/dist/_app/immutable/chunks/D4Q_ObIy.js +1 -0
  12. package/dist/_app/immutable/chunks/DsnmJJEf.js +1 -0
  13. package/dist/_app/immutable/chunks/XY2j_owG.js +66 -0
  14. package/dist/_app/immutable/chunks/rzN25oDf.js +1 -0
  15. package/dist/_app/immutable/entry/app.r0uOd9qg.js +2 -0
  16. package/dist/_app/immutable/entry/start.DvoqR0rc.js +1 -0
  17. package/dist/_app/immutable/nodes/0.Ct6FAss_.js +1 -0
  18. package/dist/_app/immutable/nodes/1.DLoKuy8Q.js +1 -0
  19. package/dist/_app/immutable/nodes/2.IRkwSmiB.js +1 -0
  20. package/dist/_app/immutable/nodes/3.BrTg-ZHv.js +1 -0
  21. package/dist/_app/immutable/nodes/4.Blq-4WQS.js +9 -0
  22. package/dist/_app/version.json +1 -0
  23. package/dist/cli/commands/crawl.js +128 -0
  24. package/dist/cli/commands/ui.js +2769 -0
  25. package/dist/cli/commands/version.js +30 -0
  26. package/dist/cli/server/index.js +2713 -0
  27. package/dist/cli/server/server.js +2702 -0
  28. package/dist/cli/server/serverState.js +1199 -0
  29. package/dist/cli/server/spreadsheetRoutes.js +788 -0
  30. package/dist/cli/server/types.js +0 -0
  31. package/dist/cli/server/websocketServer.js +2625 -0
  32. package/dist/cli/utils/debug.js +24 -0
  33. package/dist/favicon.svg +1 -0
  34. package/dist/index.html +38 -0
  35. package/dist/index.js +2924 -37
  36. package/dist/lula.png +0 -0
  37. package/dist/lula2 +2 -0
  38. package/package.json +120 -72
  39. package/src/app.css +192 -0
  40. package/src/app.d.ts +13 -0
  41. package/src/app.html +13 -0
  42. package/src/lib/actions/fadeWhenScrollable.ts +39 -0
  43. package/src/lib/actions/modal.ts +230 -0
  44. package/src/lib/actions/tooltip.ts +82 -0
  45. package/src/lib/components/control-sets/ControlSetInfo.svelte +20 -0
  46. package/src/lib/components/control-sets/ControlSetSelector.svelte +46 -0
  47. package/src/lib/components/control-sets/index.ts +5 -0
  48. package/src/lib/components/controls/ControlDetailsPanel.svelte +235 -0
  49. package/src/lib/components/controls/ControlsList.svelte +608 -0
  50. package/src/lib/components/controls/DynamicControlEditor.svelte +298 -0
  51. package/src/lib/components/controls/MappingCard.svelte +105 -0
  52. package/src/lib/components/controls/MappingForm.svelte +188 -0
  53. package/src/lib/components/controls/index.ts +9 -0
  54. package/src/lib/components/controls/renderers/EditableFieldRenderer.svelte +103 -0
  55. package/src/lib/components/controls/renderers/FieldRenderer.svelte +49 -0
  56. package/src/lib/components/controls/renderers/index.ts +5 -0
  57. package/src/lib/components/controls/tabs/CustomFieldsTab.svelte +130 -0
  58. package/src/lib/components/controls/tabs/ImplementationTab.svelte +127 -0
  59. package/src/lib/components/controls/tabs/MappingsTab.svelte +182 -0
  60. package/src/lib/components/controls/tabs/OverviewTab.svelte +151 -0
  61. package/src/lib/components/controls/tabs/TimelineTab.svelte +41 -0
  62. package/src/lib/components/controls/tabs/index.ts +8 -0
  63. package/src/lib/components/controls/utils/ProcessedTextRenderer.svelte +63 -0
  64. package/src/lib/components/controls/utils/textProcessor.ts +164 -0
  65. package/src/lib/components/forms/DynamicControlForm.svelte +340 -0
  66. package/src/lib/components/forms/DynamicField.svelte +494 -0
  67. package/src/lib/components/forms/FormField.svelte +107 -0
  68. package/src/lib/components/forms/index.ts +6 -0
  69. package/src/lib/components/setup/ExistingControlSets.svelte +284 -0
  70. package/src/lib/components/setup/SpreadsheetImport.svelte +968 -0
  71. package/src/lib/components/setup/index.ts +5 -0
  72. package/src/lib/components/ui/Dropdown.svelte +107 -0
  73. package/src/lib/components/ui/EmptyState.svelte +80 -0
  74. package/src/lib/components/ui/FeatureToggle.svelte +50 -0
  75. package/src/lib/components/ui/SearchBar.svelte +73 -0
  76. package/src/lib/components/ui/StatusBadge.svelte +79 -0
  77. package/src/lib/components/ui/TabNavigation.svelte +48 -0
  78. package/src/lib/components/ui/Tooltip.svelte +120 -0
  79. package/src/lib/components/ui/index.ts +10 -0
  80. package/src/lib/components/version-control/DiffViewer.svelte +292 -0
  81. package/src/lib/components/version-control/TimelineItem.svelte +107 -0
  82. package/src/lib/components/version-control/YamlDiffViewer.svelte +428 -0
  83. package/src/lib/components/version-control/index.ts +6 -0
  84. package/src/lib/form-types.ts +57 -0
  85. package/src/lib/formatUtils.ts +17 -0
  86. package/src/lib/index.ts +5 -0
  87. package/src/lib/types.ts +180 -0
  88. package/src/lib/websocket.ts +359 -0
  89. package/src/routes/+layout.svelte +236 -0
  90. package/src/routes/+page.svelte +38 -0
  91. package/src/routes/control/[id]/+page.svelte +112 -0
  92. package/src/routes/setup/+page.svelte +241 -0
  93. package/src/stores/compliance.ts +95 -0
  94. package/src/styles/highlightjs.css +20 -0
  95. package/src/styles/modal.css +58 -0
  96. package/src/styles/tables.css +111 -0
  97. package/src/styles/tooltip.css +65 -0
  98. package/dist/controls/index.d.ts +0 -18
  99. package/dist/controls/index.d.ts.map +0 -1
  100. package/dist/controls/index.js +0 -18
  101. package/dist/crawl.d.ts +0 -62
  102. package/dist/crawl.d.ts.map +0 -1
  103. package/dist/crawl.js +0 -172
  104. package/dist/index.d.ts +0 -8
  105. package/dist/index.d.ts.map +0 -1
  106. package/src/controls/index.ts +0 -19
  107. package/src/crawl.ts +0 -227
  108. package/src/index.ts +0 -46
@@ -0,0 +1,2713 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // cli/utils/debug.ts
12
+ function debug(...args) {
13
+ if (debugEnabled) {
14
+ console.log("[DEBUG]", ...args);
15
+ }
16
+ }
17
+ var debugEnabled;
18
+ var init_debug = __esm({
19
+ "cli/utils/debug.ts"() {
20
+ "use strict";
21
+ debugEnabled = false;
22
+ }
23
+ });
24
+
25
+ // cli/server/infrastructure/controlHelpers.ts
26
+ import { existsSync, readFileSync } from "fs";
27
+ import { join } from "path";
28
+ import * as yaml from "js-yaml";
29
+ function loadControlSetMetadata(baseDir) {
30
+ const path = join(baseDir, "lula.yaml");
31
+ if (metadataPath !== path || !controlSetMetadata) {
32
+ if (existsSync(path)) {
33
+ try {
34
+ const content = readFileSync(path, "utf8");
35
+ controlSetMetadata = yaml.load(content);
36
+ metadataPath = path;
37
+ } catch (error) {
38
+ console.error(`Failed to parse lula.yaml at ${path}:`, error);
39
+ controlSetMetadata = {};
40
+ metadataPath = path;
41
+ }
42
+ } else {
43
+ controlSetMetadata = {};
44
+ metadataPath = path;
45
+ }
46
+ }
47
+ return controlSetMetadata;
48
+ }
49
+ function getControlIdField(baseDir) {
50
+ if (baseDir) {
51
+ loadControlSetMetadata(baseDir);
52
+ }
53
+ return controlSetMetadata?.control_id_field || "id";
54
+ }
55
+ function getControlId(control, baseDir) {
56
+ if (!control || typeof control !== "object") {
57
+ throw new Error("Invalid control object provided");
58
+ }
59
+ const idField = getControlIdField(baseDir);
60
+ const configuredId = control[idField];
61
+ if (configuredId && typeof configuredId === "string") {
62
+ return configuredId;
63
+ }
64
+ if (idField !== "id" && control.id) {
65
+ return control.id;
66
+ }
67
+ const possibleIdFields = [
68
+ "ap-acronym",
69
+ "control-id",
70
+ "control_id",
71
+ "controlId"
72
+ ];
73
+ for (const field of possibleIdFields) {
74
+ const value = control[field];
75
+ if (value && typeof value === "string") {
76
+ return value;
77
+ }
78
+ }
79
+ const availableFields = Object.keys(control).filter(
80
+ (key) => control[key] !== void 0
81
+ );
82
+ throw new Error(
83
+ `No control ID found in control object. Available fields: ${availableFields.join(", ")}`
84
+ );
85
+ }
86
+ var controlSetMetadata, metadataPath;
87
+ var init_controlHelpers = __esm({
88
+ "cli/server/infrastructure/controlHelpers.ts"() {
89
+ "use strict";
90
+ controlSetMetadata = null;
91
+ metadataPath = null;
92
+ }
93
+ });
94
+
95
+ // cli/server/infrastructure/fileStore.ts
96
+ var fileStore_exports = {};
97
+ __export(fileStore_exports, {
98
+ FileStore: () => FileStore
99
+ });
100
+ import {
101
+ existsSync as existsSync2,
102
+ promises as fs,
103
+ mkdirSync,
104
+ readdirSync,
105
+ readFileSync as readFileSync2,
106
+ statSync,
107
+ unlinkSync,
108
+ writeFileSync
109
+ } from "fs";
110
+ import * as yaml2 from "js-yaml";
111
+ import { join as join2 } from "path";
112
+ var FileStore;
113
+ var init_fileStore = __esm({
114
+ "cli/server/infrastructure/fileStore.ts"() {
115
+ "use strict";
116
+ init_controlHelpers();
117
+ FileStore = class {
118
+ baseDir;
119
+ controlsDir;
120
+ mappingsDir;
121
+ // Simple cache - just control ID to filename mapping
122
+ controlMetadataCache = /* @__PURE__ */ new Map();
123
+ constructor(options) {
124
+ this.baseDir = options.baseDir;
125
+ this.controlsDir = join2(this.baseDir, "controls");
126
+ this.mappingsDir = join2(this.baseDir, "mappings");
127
+ if (existsSync2(this.controlsDir)) {
128
+ this.refreshControlsCache();
129
+ }
130
+ }
131
+ /**
132
+ * Get simple filename from control ID
133
+ */
134
+ getControlFilename(controlId) {
135
+ const sanitized = controlId.replace(/[^\w\-]/g, "_");
136
+ return `${sanitized}.yaml`;
137
+ }
138
+ /**
139
+ * Get family name from control ID
140
+ */
141
+ getControlFamily(controlId) {
142
+ return controlId.split("-")[0];
143
+ }
144
+ /**
145
+ * Ensure required directories exist
146
+ */
147
+ ensureDirectories() {
148
+ if (!this.baseDir || this.baseDir === "." || this.baseDir === process.cwd()) {
149
+ return;
150
+ }
151
+ const lulaConfigPath = join2(this.baseDir, "lula.yaml");
152
+ if (!existsSync2(lulaConfigPath)) {
153
+ return;
154
+ }
155
+ if (!existsSync2(this.controlsDir)) {
156
+ mkdirSync(this.controlsDir, { recursive: true });
157
+ }
158
+ if (!existsSync2(this.mappingsDir)) {
159
+ mkdirSync(this.mappingsDir, { recursive: true });
160
+ }
161
+ }
162
+ /**
163
+ * Get control metadata by ID
164
+ */
165
+ getControlMetadata(controlId) {
166
+ return this.controlMetadataCache.get(controlId);
167
+ }
168
+ /**
169
+ * Load a control by ID
170
+ */
171
+ async loadControl(controlId) {
172
+ const sanitizedId = controlId.replace(/[^\w\-]/g, "_");
173
+ const possibleFlatPaths = [
174
+ join2(this.controlsDir, `${controlId}.yaml`),
175
+ join2(this.controlsDir, `${sanitizedId}.yaml`)
176
+ ];
177
+ for (const flatFilePath of possibleFlatPaths) {
178
+ if (existsSync2(flatFilePath)) {
179
+ try {
180
+ const content = readFileSync2(flatFilePath, "utf8");
181
+ const parsed = yaml2.load(content);
182
+ if (!parsed.id) {
183
+ parsed.id = controlId.replace(/_(\d)/g, ".$1");
184
+ }
185
+ return parsed;
186
+ } catch (error) {
187
+ console.error(`Failed to load control ${controlId} from flat structure:`, error);
188
+ throw new Error(
189
+ `Failed to load control ${controlId}: ${error instanceof Error ? error.message : String(error)}`
190
+ );
191
+ }
192
+ }
193
+ }
194
+ const family = this.getControlFamily(controlId);
195
+ const familyDir = join2(this.controlsDir, family);
196
+ const possibleFamilyPaths = [
197
+ join2(familyDir, `${controlId}.yaml`),
198
+ join2(familyDir, `${sanitizedId}.yaml`)
199
+ ];
200
+ for (const filePath of possibleFamilyPaths) {
201
+ if (existsSync2(filePath)) {
202
+ try {
203
+ const content = readFileSync2(filePath, "utf8");
204
+ const parsed = yaml2.load(content);
205
+ if (!parsed.id) {
206
+ parsed.id = controlId.replace(/_(\d)/g, ".$1");
207
+ }
208
+ return parsed;
209
+ } catch (error) {
210
+ console.error(`Failed to load control ${controlId}:`, error);
211
+ throw new Error(
212
+ `Failed to load control ${controlId}: ${error instanceof Error ? error.message : String(error)}`
213
+ );
214
+ }
215
+ }
216
+ }
217
+ return null;
218
+ }
219
+ /**
220
+ * Save a control
221
+ */
222
+ async saveControl(control) {
223
+ this.ensureDirectories();
224
+ const controlId = getControlId(control, this.baseDir);
225
+ const family = this.getControlFamily(controlId);
226
+ const filename = this.getControlFilename(controlId);
227
+ const familyDir = join2(this.controlsDir, family);
228
+ const filePath = join2(familyDir, filename);
229
+ if (!existsSync2(familyDir)) {
230
+ mkdirSync(familyDir, { recursive: true });
231
+ }
232
+ try {
233
+ let yamlContent;
234
+ if (existsSync2(filePath)) {
235
+ const existingContent = readFileSync2(filePath, "utf8");
236
+ const existingControl = yaml2.load(existingContent);
237
+ const fieldsToUpdate = {};
238
+ for (const key in control) {
239
+ if (key === "timeline" || key === "unifiedHistory" || key === "_metadata" || key === "id") {
240
+ continue;
241
+ }
242
+ if (JSON.stringify(control[key]) !== JSON.stringify(existingControl[key])) {
243
+ fieldsToUpdate[key] = control[key];
244
+ }
245
+ }
246
+ if (Object.keys(fieldsToUpdate).length > 0) {
247
+ const updatedControl = { ...existingControl, ...fieldsToUpdate };
248
+ yamlContent = yaml2.dump(updatedControl, {
249
+ indent: 2,
250
+ lineWidth: 80,
251
+ noRefs: true,
252
+ sortKeys: false
253
+ });
254
+ } else {
255
+ yamlContent = existingContent;
256
+ }
257
+ } else {
258
+ const controlToSave = { ...control };
259
+ delete controlToSave.timeline;
260
+ delete controlToSave.unifiedHistory;
261
+ delete controlToSave._metadata;
262
+ delete controlToSave.id;
263
+ yamlContent = yaml2.dump(controlToSave, {
264
+ indent: 2,
265
+ lineWidth: 80,
266
+ noRefs: true,
267
+ sortKeys: false
268
+ });
269
+ }
270
+ writeFileSync(filePath, yamlContent, "utf8");
271
+ this.controlMetadataCache.set(controlId, {
272
+ controlId,
273
+ filename,
274
+ family
275
+ });
276
+ } catch (error) {
277
+ throw new Error(
278
+ `Failed to save control ${controlId}: ${error instanceof Error ? error.message : String(error)}`
279
+ );
280
+ }
281
+ }
282
+ /**
283
+ * Delete a control
284
+ */
285
+ async deleteControl(controlId) {
286
+ const family = this.getControlFamily(controlId);
287
+ const filename = this.getControlFilename(controlId);
288
+ const familyDir = join2(this.controlsDir, family);
289
+ const filePath = join2(familyDir, filename);
290
+ if (existsSync2(filePath)) {
291
+ unlinkSync(filePath);
292
+ this.controlMetadataCache.delete(controlId);
293
+ }
294
+ }
295
+ /**
296
+ * Load all controls
297
+ */
298
+ async loadAllControls() {
299
+ if (!existsSync2(this.controlsDir)) {
300
+ return [];
301
+ }
302
+ const entries = readdirSync(this.controlsDir);
303
+ const yamlFiles = entries.filter((file) => file.endsWith(".yaml"));
304
+ if (yamlFiles.length > 0) {
305
+ const promises = yamlFiles.map(async (file) => {
306
+ try {
307
+ const filePath = join2(this.controlsDir, file);
308
+ const content = await fs.readFile(filePath, "utf8");
309
+ const parsed = yaml2.load(content);
310
+ if (!parsed.id) {
311
+ parsed.id = getControlId(parsed, this.baseDir);
312
+ }
313
+ return parsed;
314
+ } catch (error) {
315
+ console.error(`Failed to load control from file ${file}:`, error);
316
+ return null;
317
+ }
318
+ });
319
+ const results2 = await Promise.all(promises);
320
+ return results2.filter((c) => c !== null);
321
+ }
322
+ const families = entries.filter((name) => {
323
+ const familyPath = join2(this.controlsDir, name);
324
+ return statSync(familyPath).isDirectory();
325
+ });
326
+ const allPromises = [];
327
+ for (const family of families) {
328
+ const familyPath = join2(this.controlsDir, family);
329
+ const files = readdirSync(familyPath).filter((file) => file.endsWith(".yaml"));
330
+ const familyPromises = files.map(async (file) => {
331
+ try {
332
+ const controlId = file.replace(".yaml", "");
333
+ const control = await this.loadControl(controlId);
334
+ return control;
335
+ } catch (error) {
336
+ console.error(`Failed to load control from file ${file}:`, error);
337
+ return null;
338
+ }
339
+ });
340
+ allPromises.push(...familyPromises);
341
+ }
342
+ const results = await Promise.all(allPromises);
343
+ return results.filter((c) => c !== null);
344
+ }
345
+ /**
346
+ * Load mappings from mappings directory
347
+ */
348
+ async loadMappings() {
349
+ const mappings = [];
350
+ if (!existsSync2(this.mappingsDir)) {
351
+ return mappings;
352
+ }
353
+ const families = readdirSync(this.mappingsDir).filter((name) => {
354
+ const familyPath = join2(this.mappingsDir, name);
355
+ return statSync(familyPath).isDirectory();
356
+ });
357
+ for (const family of families) {
358
+ const familyPath = join2(this.mappingsDir, family);
359
+ const files = readdirSync(familyPath).filter((file) => file.endsWith("-mappings.yaml"));
360
+ for (const file of files) {
361
+ const mappingFile = join2(familyPath, file);
362
+ try {
363
+ const content = readFileSync2(mappingFile, "utf8");
364
+ const parsed = yaml2.load(content);
365
+ if (Array.isArray(parsed)) {
366
+ mappings.push(...parsed);
367
+ }
368
+ } catch (error) {
369
+ console.error(`Failed to load mappings from ${family}/${file}:`, error);
370
+ }
371
+ }
372
+ }
373
+ return mappings;
374
+ }
375
+ /**
376
+ * Save a single mapping
377
+ */
378
+ async saveMapping(mapping) {
379
+ this.ensureDirectories();
380
+ const controlId = mapping.control_id;
381
+ const family = this.getControlFamily(controlId);
382
+ const familyDir = join2(this.mappingsDir, family);
383
+ const mappingFile = join2(familyDir, `${controlId}-mappings.yaml`);
384
+ if (!existsSync2(familyDir)) {
385
+ mkdirSync(familyDir, { recursive: true });
386
+ }
387
+ let existingMappings = [];
388
+ if (existsSync2(mappingFile)) {
389
+ try {
390
+ const content = readFileSync2(mappingFile, "utf8");
391
+ existingMappings = yaml2.load(content) || [];
392
+ } catch (error) {
393
+ console.error(`Failed to parse existing mappings file: ${mappingFile}`, error);
394
+ existingMappings = [];
395
+ }
396
+ }
397
+ const existingIndex = existingMappings.findIndex((m) => m.uuid === mapping.uuid);
398
+ if (existingIndex >= 0) {
399
+ existingMappings[existingIndex] = mapping;
400
+ } else {
401
+ existingMappings.push(mapping);
402
+ }
403
+ try {
404
+ const yamlContent = yaml2.dump(existingMappings, {
405
+ indent: 2,
406
+ lineWidth: -1,
407
+ noRefs: true
408
+ });
409
+ writeFileSync(mappingFile, yamlContent, "utf8");
410
+ } catch (error) {
411
+ throw new Error(
412
+ `Failed to save mapping for control ${controlId}: ${error instanceof Error ? error.message : String(error)}`
413
+ );
414
+ }
415
+ }
416
+ /**
417
+ * Delete a single mapping
418
+ */
419
+ async deleteMapping(uuid) {
420
+ const mappingFiles = this.getAllMappingFiles();
421
+ for (const file of mappingFiles) {
422
+ try {
423
+ const content = readFileSync2(file, "utf8");
424
+ let mappings = yaml2.load(content) || [];
425
+ const originalLength = mappings.length;
426
+ mappings = mappings.filter((m) => m.uuid !== uuid);
427
+ if (mappings.length < originalLength) {
428
+ if (mappings.length === 0) {
429
+ unlinkSync(file);
430
+ } else {
431
+ const yamlContent = yaml2.dump(mappings, {
432
+ indent: 2,
433
+ lineWidth: -1,
434
+ noRefs: true
435
+ });
436
+ writeFileSync(file, yamlContent, "utf8");
437
+ }
438
+ return;
439
+ }
440
+ } catch (error) {
441
+ console.error(`Error processing mapping file ${file}:`, error);
442
+ }
443
+ }
444
+ }
445
+ /**
446
+ * Get all mapping files
447
+ */
448
+ getAllMappingFiles() {
449
+ const files = [];
450
+ if (!existsSync2(this.mappingsDir)) {
451
+ return files;
452
+ }
453
+ const flatFiles = readdirSync(this.mappingsDir).filter((file) => file.endsWith("-mappings.yaml")).map((file) => join2(this.mappingsDir, file));
454
+ files.push(...flatFiles);
455
+ const entries = readdirSync(this.mappingsDir, { withFileTypes: true });
456
+ for (const entry of entries) {
457
+ if (entry.isDirectory()) {
458
+ const familyDir = join2(this.mappingsDir, entry.name);
459
+ const familyFiles = readdirSync(familyDir).filter((file) => file.endsWith("-mappings.yaml")).map((file) => join2(familyDir, file));
460
+ files.push(...familyFiles);
461
+ }
462
+ }
463
+ return files;
464
+ }
465
+ /**
466
+ * Save mappings to per-control files
467
+ */
468
+ async saveMappings(mappings) {
469
+ this.ensureDirectories();
470
+ const mappingsByControl = /* @__PURE__ */ new Map();
471
+ for (const mapping of mappings) {
472
+ const controlId = mapping.control_id;
473
+ if (!mappingsByControl.has(controlId)) {
474
+ mappingsByControl.set(controlId, []);
475
+ }
476
+ mappingsByControl.get(controlId).push(mapping);
477
+ }
478
+ for (const [controlId, controlMappings] of mappingsByControl) {
479
+ const family = this.getControlFamily(controlId);
480
+ const familyDir = join2(this.mappingsDir, family);
481
+ const mappingFile = join2(familyDir, `${controlId}-mappings.yaml`);
482
+ if (!existsSync2(familyDir)) {
483
+ mkdirSync(familyDir, { recursive: true });
484
+ }
485
+ try {
486
+ const yamlContent = yaml2.dump(controlMappings, {
487
+ indent: 2,
488
+ lineWidth: -1,
489
+ noRefs: true
490
+ });
491
+ writeFileSync(mappingFile, yamlContent, "utf8");
492
+ } catch (error) {
493
+ throw new Error(
494
+ `Failed to save mappings for control ${controlId}: ${error instanceof Error ? error.message : String(error)}`
495
+ );
496
+ }
497
+ }
498
+ }
499
+ /**
500
+ * Refresh controls cache
501
+ */
502
+ refreshControlsCache() {
503
+ this.controlMetadataCache.clear();
504
+ if (!existsSync2(this.controlsDir)) {
505
+ return;
506
+ }
507
+ const entries = readdirSync(this.controlsDir);
508
+ const yamlFiles = entries.filter((file) => file.endsWith(".yaml"));
509
+ if (yamlFiles.length > 0) {
510
+ for (const filename of yamlFiles) {
511
+ const controlId = filename.replace(".yaml", "");
512
+ const family = this.getControlFamily(controlId);
513
+ this.controlMetadataCache.set(controlId, {
514
+ controlId,
515
+ filename,
516
+ family
517
+ });
518
+ }
519
+ return;
520
+ }
521
+ const families = entries.filter((name) => {
522
+ const familyPath = join2(this.controlsDir, name);
523
+ return statSync(familyPath).isDirectory();
524
+ });
525
+ for (const family of families) {
526
+ const familyPath = join2(this.controlsDir, family);
527
+ const files = readdirSync(familyPath).filter((file) => file.endsWith(".yaml"));
528
+ for (const filename of files) {
529
+ try {
530
+ const filePath = join2(familyPath, filename);
531
+ const content = readFileSync2(filePath, "utf8");
532
+ const parsed = yaml2.load(content);
533
+ const controlId = getControlId(parsed, this.baseDir);
534
+ this.controlMetadataCache.set(controlId, {
535
+ controlId,
536
+ filename,
537
+ family
538
+ });
539
+ } catch (error) {
540
+ console.error(`Failed to read control metadata from ${family}/${filename}:`, error);
541
+ const controlId = filename.replace(".yaml", "").replace(/_/g, "/");
542
+ this.controlMetadataCache.set(controlId, {
543
+ controlId,
544
+ filename,
545
+ family
546
+ });
547
+ }
548
+ }
549
+ }
550
+ }
551
+ /**
552
+ * Get file store statistics
553
+ */
554
+ getStats() {
555
+ const controlCount = this.controlMetadataCache.size;
556
+ let mappingCount = 0;
557
+ if (existsSync2(this.mappingsDir)) {
558
+ const families = readdirSync(this.mappingsDir).filter((name) => {
559
+ const familyPath = join2(this.mappingsDir, name);
560
+ return statSync(familyPath).isDirectory();
561
+ });
562
+ mappingCount = families.length;
563
+ }
564
+ const familyCount = new Set(
565
+ Array.from(this.controlMetadataCache.values()).map((meta) => meta.family)
566
+ ).size;
567
+ return {
568
+ controlCount,
569
+ mappingCount,
570
+ familyCount
571
+ };
572
+ }
573
+ /**
574
+ * Clear all caches
575
+ */
576
+ clearCache() {
577
+ this.controlMetadataCache.clear();
578
+ this.refreshControlsCache();
579
+ }
580
+ };
581
+ }
582
+ });
583
+
584
+ // cli/server/infrastructure/yamlDiff.ts
585
+ import * as yaml3 from "js-yaml";
586
+ function createYamlDiff(oldYaml, newYaml, isArrayFile = false) {
587
+ try {
588
+ const emptyDefault = isArrayFile ? "[]" : "{}";
589
+ const oldData = yaml3.load(oldYaml || emptyDefault);
590
+ const newData = yaml3.load(newYaml || emptyDefault);
591
+ const changes = compareValues(oldData, newData, "");
592
+ return {
593
+ hasChanges: changes.length > 0,
594
+ changes,
595
+ summary: generateSummary(changes)
596
+ };
597
+ } catch (error) {
598
+ console.error("Error parsing YAML for diff:", error);
599
+ return {
600
+ hasChanges: false,
601
+ changes: [],
602
+ summary: "Error parsing YAML content"
603
+ };
604
+ }
605
+ }
606
+ function compareValues(oldValue, newValue, basePath) {
607
+ const changes = [];
608
+ if (oldValue === null || oldValue === void 0) {
609
+ if (newValue !== null && newValue !== void 0) {
610
+ changes.push({
611
+ type: "added",
612
+ path: basePath || "root",
613
+ newValue,
614
+ description: `Added ${basePath || "content"}`
615
+ });
616
+ }
617
+ return changes;
618
+ }
619
+ if (newValue === null || newValue === void 0) {
620
+ changes.push({
621
+ type: "removed",
622
+ path: basePath || "root",
623
+ oldValue,
624
+ description: `Removed ${basePath || "content"}`
625
+ });
626
+ return changes;
627
+ }
628
+ if (Array.isArray(oldValue) || Array.isArray(newValue)) {
629
+ return compareArrays(oldValue, newValue, basePath);
630
+ }
631
+ if (typeof oldValue === "object" && typeof newValue === "object") {
632
+ return compareObjects(oldValue, newValue, basePath);
633
+ }
634
+ if (oldValue !== newValue) {
635
+ changes.push({
636
+ type: "modified",
637
+ path: basePath || "root",
638
+ oldValue,
639
+ newValue,
640
+ description: `Changed ${basePath || "value"}`
641
+ });
642
+ }
643
+ return changes;
644
+ }
645
+ function compareObjects(oldObj, newObj, basePath) {
646
+ const changes = [];
647
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(oldObj), ...Object.keys(newObj)]);
648
+ for (const key of allKeys) {
649
+ const currentPath = basePath ? `${basePath}.${key}` : key;
650
+ const oldValue = oldObj[key];
651
+ const newValue = newObj[key];
652
+ if (!(key in oldObj)) {
653
+ changes.push({
654
+ type: "added",
655
+ path: currentPath,
656
+ newValue,
657
+ description: `Added ${key}`
658
+ });
659
+ } else if (!(key in newObj)) {
660
+ changes.push({
661
+ type: "removed",
662
+ path: currentPath,
663
+ oldValue,
664
+ description: `Removed ${key}`
665
+ });
666
+ } else if (!deepEqual(oldValue, newValue)) {
667
+ if (typeof oldValue === "object" && typeof newValue === "object") {
668
+ changes.push(...compareValues(oldValue, newValue, currentPath));
669
+ } else {
670
+ changes.push({
671
+ type: "modified",
672
+ path: currentPath,
673
+ oldValue,
674
+ newValue,
675
+ description: `Changed ${key}`
676
+ });
677
+ }
678
+ }
679
+ }
680
+ return changes;
681
+ }
682
+ function compareArrays(oldArr, newArr, basePath) {
683
+ const changes = [];
684
+ if (!Array.isArray(oldArr) && Array.isArray(newArr)) {
685
+ changes.push({
686
+ type: "modified",
687
+ path: basePath || "root",
688
+ oldValue: oldArr,
689
+ newValue: newArr,
690
+ description: `Changed ${basePath || "value"} from non-array to array`
691
+ });
692
+ return changes;
693
+ }
694
+ if (Array.isArray(oldArr) && !Array.isArray(newArr)) {
695
+ changes.push({
696
+ type: "modified",
697
+ path: basePath || "root",
698
+ oldValue: oldArr,
699
+ newValue: newArr,
700
+ description: `Changed ${basePath || "value"} from array to non-array`
701
+ });
702
+ return changes;
703
+ }
704
+ const oldArray = oldArr;
705
+ const newArray = newArr;
706
+ if (isMappingArray(oldArray) || isMappingArray(newArray)) {
707
+ return compareMappingArrays(oldArray, newArray, basePath);
708
+ }
709
+ if (oldArray.length !== newArray.length) {
710
+ changes.push({
711
+ type: "modified",
712
+ path: basePath || "root",
713
+ oldValue: oldArray,
714
+ newValue: newArray,
715
+ description: `Array ${basePath || "items"} changed from ${oldArray.length} to ${newArray.length} items`
716
+ });
717
+ } else {
718
+ for (let i = 0; i < oldArray.length; i++) {
719
+ const elementPath = `${basePath}[${i}]`;
720
+ if (!deepEqual(oldArray[i], newArray[i])) {
721
+ changes.push(...compareValues(oldArray[i], newArray[i], elementPath));
722
+ }
723
+ }
724
+ }
725
+ return changes;
726
+ }
727
+ function isMappingArray(arr) {
728
+ if (!Array.isArray(arr) || arr.length === 0) return false;
729
+ const firstItem = arr[0];
730
+ return typeof firstItem === "object" && firstItem !== null && "control_id" in firstItem && "uuid" in firstItem;
731
+ }
732
+ function compareMappingArrays(oldArr, newArr, basePath) {
733
+ const changes = [];
734
+ const oldMappings = /* @__PURE__ */ new Map();
735
+ const newMappings = /* @__PURE__ */ new Map();
736
+ for (const item of oldArr) {
737
+ if (typeof item === "object" && item !== null && "uuid" in item) {
738
+ oldMappings.set(item.uuid, item);
739
+ }
740
+ }
741
+ for (const item of newArr) {
742
+ if (typeof item === "object" && item !== null && "uuid" in item) {
743
+ newMappings.set(item.uuid, item);
744
+ }
745
+ }
746
+ for (const [uuid, mapping] of newMappings) {
747
+ if (!oldMappings.has(uuid)) {
748
+ changes.push({
749
+ type: "added",
750
+ path: `mapping`,
751
+ newValue: mapping,
752
+ description: `Added mapping`
753
+ });
754
+ }
755
+ }
756
+ for (const [uuid, mapping] of oldMappings) {
757
+ if (!newMappings.has(uuid)) {
758
+ changes.push({
759
+ type: "removed",
760
+ path: `mapping`,
761
+ oldValue: mapping,
762
+ description: `Removed mapping`
763
+ });
764
+ }
765
+ }
766
+ for (const [uuid, oldMapping] of oldMappings) {
767
+ if (newMappings.has(uuid)) {
768
+ const newMapping = newMappings.get(uuid);
769
+ if (!deepEqual(oldMapping, newMapping)) {
770
+ changes.push({
771
+ type: "modified",
772
+ path: `mapping`,
773
+ oldValue: oldMapping,
774
+ newValue: newMapping,
775
+ description: `Modified mapping`
776
+ });
777
+ }
778
+ }
779
+ }
780
+ if (changes.length === 0 && oldArr.length !== newArr.length) {
781
+ changes.push({
782
+ type: "modified",
783
+ path: basePath || "mappings",
784
+ oldValue: oldArr,
785
+ newValue: newArr,
786
+ description: `Mappings changed from ${oldArr.length} to ${newArr.length} items`
787
+ });
788
+ }
789
+ return changes;
790
+ }
791
+ function deepEqual(a, b) {
792
+ if (a === b) return true;
793
+ if (a === null || b === null) return false;
794
+ if (typeof a !== typeof b) return false;
795
+ if (Array.isArray(a) && Array.isArray(b)) {
796
+ if (a.length !== b.length) return false;
797
+ for (let i = 0; i < a.length; i++) {
798
+ if (!deepEqual(a[i], b[i])) return false;
799
+ }
800
+ return true;
801
+ }
802
+ if (typeof a === "object" && typeof b === "object") {
803
+ const aObj = a;
804
+ const bObj = b;
805
+ const aKeys = Object.keys(aObj);
806
+ const bKeys = Object.keys(bObj);
807
+ if (aKeys.length !== bKeys.length) return false;
808
+ for (const key of aKeys) {
809
+ if (!bKeys.includes(key)) return false;
810
+ if (!deepEqual(aObj[key], bObj[key])) return false;
811
+ }
812
+ return true;
813
+ }
814
+ return false;
815
+ }
816
+ function generateSummary(changes) {
817
+ if (changes.length === 0) {
818
+ return "No changes detected";
819
+ }
820
+ const added = changes.filter((c) => c.type === "added").length;
821
+ const removed = changes.filter((c) => c.type === "removed").length;
822
+ const modified = changes.filter((c) => c.type === "modified").length;
823
+ const parts = [];
824
+ if (added > 0) parts.push(`${added} added`);
825
+ if (removed > 0) parts.push(`${removed} removed`);
826
+ if (modified > 0) parts.push(`${modified} modified`);
827
+ return parts.join(", ");
828
+ }
829
+ var init_yamlDiff = __esm({
830
+ "cli/server/infrastructure/yamlDiff.ts"() {
831
+ "use strict";
832
+ }
833
+ });
834
+
835
+ // cli/server/infrastructure/gitHistory.ts
836
+ var gitHistory_exports = {};
837
+ __export(gitHistory_exports, {
838
+ GitHistoryUtil: () => GitHistoryUtil
839
+ });
840
+ import * as fs2 from "fs";
841
+ import * as git from "isomorphic-git";
842
+ import { relative } from "path";
843
+ var GitHistoryUtil;
844
+ var init_gitHistory = __esm({
845
+ "cli/server/infrastructure/gitHistory.ts"() {
846
+ "use strict";
847
+ init_yamlDiff();
848
+ GitHistoryUtil = class {
849
+ baseDir;
850
+ constructor(baseDir) {
851
+ this.baseDir = baseDir;
852
+ }
853
+ /**
854
+ * Check if the directory is a git repository
855
+ */
856
+ async isGitRepository() {
857
+ try {
858
+ const gitDir = await git.findRoot({ fs: fs2, filepath: process.cwd() });
859
+ return !!gitDir;
860
+ } catch {
861
+ return false;
862
+ }
863
+ }
864
+ /**
865
+ * Get git history for a specific file
866
+ */
867
+ async getFileHistory(filePath, limit = 50) {
868
+ const isGitRepo = await this.isGitRepository();
869
+ if (!isGitRepo) {
870
+ return {
871
+ filePath,
872
+ commits: [],
873
+ totalCommits: 0,
874
+ firstCommit: null,
875
+ lastCommit: null
876
+ };
877
+ }
878
+ try {
879
+ const gitRoot = await git.findRoot({ fs: fs2, filepath: process.cwd() });
880
+ const relativePath = relative(gitRoot, filePath);
881
+ const commits = await git.log({
882
+ fs: fs2,
883
+ dir: gitRoot,
884
+ filepath: relativePath,
885
+ depth: limit
886
+ });
887
+ if (!commits || commits.length === 0) {
888
+ return {
889
+ filePath,
890
+ commits: [],
891
+ totalCommits: 0,
892
+ firstCommit: null,
893
+ lastCommit: null
894
+ };
895
+ }
896
+ const gitCommits = await this.convertIsomorphicCommits(commits, relativePath, gitRoot);
897
+ return {
898
+ filePath,
899
+ commits: gitCommits,
900
+ totalCommits: gitCommits.length,
901
+ firstCommit: gitCommits[gitCommits.length - 1] || null,
902
+ lastCommit: gitCommits[0] || null
903
+ };
904
+ } catch (error) {
905
+ const err = error;
906
+ if (err?.code === "NotFoundError" || err?.message?.includes("Could not find file")) {
907
+ return {
908
+ filePath,
909
+ commits: [],
910
+ totalCommits: 0,
911
+ firstCommit: null,
912
+ lastCommit: null
913
+ };
914
+ }
915
+ console.error(`Unexpected error getting git history for ${filePath}:`, error);
916
+ return {
917
+ filePath,
918
+ commits: [],
919
+ totalCommits: 0,
920
+ firstCommit: null,
921
+ lastCommit: null
922
+ };
923
+ }
924
+ }
925
+ /**
926
+ * Get the total number of commits for a file
927
+ */
928
+ async getFileCommitCount(filePath) {
929
+ const isGitRepo = await this.isGitRepository();
930
+ if (!isGitRepo) {
931
+ return 0;
932
+ }
933
+ try {
934
+ const gitRoot = await git.findRoot({ fs: fs2, filepath: process.cwd() });
935
+ const relativePath = relative(gitRoot, filePath);
936
+ const commits = await git.log({
937
+ fs: fs2,
938
+ dir: gitRoot,
939
+ filepath: relativePath
940
+ });
941
+ return commits.length;
942
+ } catch {
943
+ return 0;
944
+ }
945
+ }
946
+ /**
947
+ * Get the latest commit info for a file
948
+ */
949
+ async getLatestCommit(filePath) {
950
+ const history = await this.getFileHistory(filePath, 1);
951
+ return history.lastCommit;
952
+ }
953
+ /**
954
+ * Get file content at a specific commit (public method)
955
+ */
956
+ async getFileContentAtCommit(filePath, commitHash) {
957
+ const isGitRepo = await this.isGitRepository();
958
+ if (!isGitRepo) {
959
+ return null;
960
+ }
961
+ try {
962
+ const gitRoot = await git.findRoot({ fs: fs2, filepath: process.cwd() });
963
+ const relativePath = relative(gitRoot, filePath);
964
+ return await this.getFileAtCommit(commitHash, relativePath, gitRoot);
965
+ } catch (error) {
966
+ console.error(`Error getting file content at commit ${commitHash}:`, error);
967
+ return null;
968
+ }
969
+ }
970
+ /**
971
+ * Convert isomorphic-git commits to our GitCommit format
972
+ */
973
+ async convertIsomorphicCommits(commits, relativePath, gitRoot) {
974
+ const gitCommits = [];
975
+ for (let i = 0; i < commits.length; i++) {
976
+ const commit = commits[i];
977
+ const includeDiff = i < 5;
978
+ let changes = { insertions: 0, deletions: 0, files: 1 };
979
+ let diff;
980
+ let yamlDiff;
981
+ if (includeDiff) {
982
+ try {
983
+ const diffResult = await this.getCommitDiff(commit.oid, relativePath, gitRoot);
984
+ changes = diffResult.changes;
985
+ diff = diffResult.diff;
986
+ yamlDiff = diffResult.yamlDiff;
987
+ } catch (error) {
988
+ }
989
+ }
990
+ gitCommits.push({
991
+ hash: commit.oid,
992
+ shortHash: commit.oid.substring(0, 7),
993
+ author: commit.commit.author.name,
994
+ authorEmail: commit.commit.author.email,
995
+ date: new Date(commit.commit.author.timestamp * 1e3).toISOString(),
996
+ message: commit.commit.message,
997
+ changes,
998
+ ...diff && { diff },
999
+ ...yamlDiff && { yamlDiff }
1000
+ });
1001
+ }
1002
+ return gitCommits;
1003
+ }
1004
+ /**
1005
+ * Get diff for a specific commit and file
1006
+ */
1007
+ async getCommitDiff(commitOid, relativePath, gitRoot) {
1008
+ try {
1009
+ const commit = await git.readCommit({ fs: fs2, dir: gitRoot, oid: commitOid });
1010
+ const parentOid = commit.commit.parent.length > 0 ? commit.commit.parent[0] : null;
1011
+ if (!parentOid) {
1012
+ const currentContent2 = await this.getFileAtCommit(commitOid, relativePath, gitRoot);
1013
+ if (currentContent2) {
1014
+ const lines = currentContent2.split("\n");
1015
+ const isMappingFile2 = relativePath.includes("-mappings.yaml");
1016
+ const yamlDiff2 = createYamlDiff("", currentContent2, isMappingFile2);
1017
+ return {
1018
+ changes: { insertions: lines.length, deletions: 0, files: 1 },
1019
+ diff: `--- /dev/null
1020
+ +++ b/${relativePath}
1021
+ @@ -0,0 +1,${lines.length} @@
1022
+ ` + lines.map((line) => "+" + line).join("\n"),
1023
+ yamlDiff: yamlDiff2
1024
+ };
1025
+ }
1026
+ return { changes: { insertions: 0, deletions: 0, files: 1 } };
1027
+ }
1028
+ const currentContent = await this.getFileAtCommit(commitOid, relativePath, gitRoot);
1029
+ const parentContent = await this.getFileAtCommit(parentOid, relativePath, gitRoot);
1030
+ if (!currentContent && !parentContent) {
1031
+ return { changes: { insertions: 0, deletions: 0, files: 1 } };
1032
+ }
1033
+ const currentLines = currentContent ? currentContent.split("\n") : [];
1034
+ const parentLines = parentContent ? parentContent.split("\n") : [];
1035
+ const diff = this.createSimpleDiff(parentLines, currentLines, relativePath);
1036
+ const { insertions, deletions } = this.countChanges(parentLines, currentLines);
1037
+ const isMappingFile = relativePath.includes("-mappings.yaml");
1038
+ const yamlDiff = createYamlDiff(parentContent || "", currentContent || "", isMappingFile);
1039
+ return {
1040
+ changes: { insertions, deletions, files: 1 },
1041
+ diff,
1042
+ yamlDiff
1043
+ };
1044
+ } catch (error) {
1045
+ return { changes: { insertions: 0, deletions: 0, files: 1 } };
1046
+ }
1047
+ }
1048
+ /**
1049
+ * Get file content at a specific commit
1050
+ */
1051
+ async getFileAtCommit(commitOid, filepath, gitRoot) {
1052
+ try {
1053
+ const { blob } = await git.readBlob({
1054
+ fs: fs2,
1055
+ dir: gitRoot,
1056
+ oid: commitOid,
1057
+ filepath
1058
+ });
1059
+ return new TextDecoder().decode(blob);
1060
+ } catch (_error) {
1061
+ return null;
1062
+ }
1063
+ }
1064
+ /**
1065
+ * Create a simple unified diff between two file versions
1066
+ */
1067
+ createSimpleDiff(oldLines, newLines, filepath) {
1068
+ const diffLines = [];
1069
+ diffLines.push(`--- a/${filepath}`);
1070
+ diffLines.push(`+++ b/${filepath}`);
1071
+ const oldCount = oldLines.length;
1072
+ const newCount = newLines.length;
1073
+ diffLines.push(`@@ -1,${oldCount} +1,${newCount} @@`);
1074
+ let i = 0, j = 0;
1075
+ while (i < oldLines.length || j < newLines.length) {
1076
+ if (i < oldLines.length && j < newLines.length && oldLines[i] === newLines[j]) {
1077
+ diffLines.push(` ${oldLines[i]}`);
1078
+ i++;
1079
+ j++;
1080
+ } else if (i < oldLines.length && (j >= newLines.length || oldLines[i] !== newLines[j])) {
1081
+ diffLines.push(`-${oldLines[i]}`);
1082
+ i++;
1083
+ } else if (j < newLines.length) {
1084
+ diffLines.push(`+${newLines[j]}`);
1085
+ j++;
1086
+ }
1087
+ }
1088
+ return diffLines.join("\n");
1089
+ }
1090
+ /**
1091
+ * Count insertions and deletions between two file versions
1092
+ */
1093
+ countChanges(oldLines, newLines) {
1094
+ let insertions = 0;
1095
+ let deletions = 0;
1096
+ const maxLines = Math.max(oldLines.length, newLines.length);
1097
+ for (let i = 0; i < maxLines; i++) {
1098
+ const oldLine = i < oldLines.length ? oldLines[i] : null;
1099
+ const newLine = i < newLines.length ? newLines[i] : null;
1100
+ if (oldLine === null) {
1101
+ insertions++;
1102
+ } else if (newLine === null) {
1103
+ deletions++;
1104
+ } else if (oldLine !== newLine) {
1105
+ insertions++;
1106
+ deletions++;
1107
+ }
1108
+ }
1109
+ return { insertions, deletions };
1110
+ }
1111
+ /**
1112
+ * Get git stats for the entire repository
1113
+ */
1114
+ async getRepositoryStats() {
1115
+ const isGitRepo = await this.isGitRepository();
1116
+ if (!isGitRepo) {
1117
+ return {
1118
+ totalCommits: 0,
1119
+ contributors: 0,
1120
+ lastCommitDate: null,
1121
+ firstCommitDate: null
1122
+ };
1123
+ }
1124
+ try {
1125
+ const gitRoot = await git.findRoot({ fs: fs2, filepath: process.cwd() });
1126
+ const commits = await git.log({ fs: fs2, dir: gitRoot });
1127
+ const contributorEmails = /* @__PURE__ */ new Set();
1128
+ commits.forEach((commit) => {
1129
+ contributorEmails.add(commit.commit.author.email);
1130
+ });
1131
+ const firstCommit = commits[commits.length - 1];
1132
+ const lastCommit = commits[0];
1133
+ return {
1134
+ totalCommits: commits.length,
1135
+ contributors: contributorEmails.size,
1136
+ lastCommitDate: lastCommit ? new Date(lastCommit.commit.author.timestamp * 1e3).toISOString() : null,
1137
+ firstCommitDate: firstCommit ? new Date(firstCommit.commit.author.timestamp * 1e3).toISOString() : null
1138
+ };
1139
+ } catch (error) {
1140
+ console.error("Error getting repository stats:", error);
1141
+ return {
1142
+ totalCommits: 0,
1143
+ contributors: 0,
1144
+ lastCommitDate: null,
1145
+ firstCommitDate: null
1146
+ };
1147
+ }
1148
+ }
1149
+ };
1150
+ }
1151
+ });
1152
+
1153
+ // cli/server/serverState.ts
1154
+ var serverState_exports = {};
1155
+ __export(serverState_exports, {
1156
+ addControlToIndexes: () => addControlToIndexes,
1157
+ addMappingToIndexes: () => addMappingToIndexes,
1158
+ getCurrentControlSetPath: () => getCurrentControlSetPath,
1159
+ getServerState: () => getServerState,
1160
+ initializeServerState: () => initializeServerState,
1161
+ loadAllData: () => loadAllData,
1162
+ saveMappingsToFile: () => saveMappingsToFile
1163
+ });
1164
+ import { join as join3 } from "path";
1165
+ function initializeServerState(controlSetDir, subdir = ".") {
1166
+ const fullPath = subdir === "." ? controlSetDir : join3(controlSetDir, subdir);
1167
+ serverState = {
1168
+ CONTROL_SET_DIR: controlSetDir,
1169
+ currentSubdir: subdir,
1170
+ fileStore: new FileStore({ baseDir: fullPath }),
1171
+ gitHistory: new GitHistoryUtil(fullPath),
1172
+ controlsCache: /* @__PURE__ */ new Map(),
1173
+ mappingsCache: /* @__PURE__ */ new Map(),
1174
+ controlsByFamily: /* @__PURE__ */ new Map(),
1175
+ mappingsByFamily: /* @__PURE__ */ new Map(),
1176
+ mappingsByControl: /* @__PURE__ */ new Map()
1177
+ };
1178
+ return serverState;
1179
+ }
1180
+ function getServerState() {
1181
+ if (!serverState) {
1182
+ throw new Error("Server state not initialized. Call initializeServerState() first.");
1183
+ }
1184
+ return serverState;
1185
+ }
1186
+ function getCurrentControlSetPath() {
1187
+ const state = getServerState();
1188
+ return state.currentSubdir === "." ? state.CONTROL_SET_DIR : join3(state.CONTROL_SET_DIR, state.currentSubdir);
1189
+ }
1190
+ function addControlToIndexes(control) {
1191
+ const state = getServerState();
1192
+ const family = control.family;
1193
+ if (!family) {
1194
+ return;
1195
+ }
1196
+ if (!state.controlsByFamily.has(family)) {
1197
+ state.controlsByFamily.set(family, /* @__PURE__ */ new Set());
1198
+ }
1199
+ state.controlsByFamily.get(family).add(control.id);
1200
+ }
1201
+ function addMappingToIndexes(mapping) {
1202
+ const state = getServerState();
1203
+ const family = mapping.control_id.split("-")[0];
1204
+ if (!state.mappingsByFamily.has(family)) {
1205
+ state.mappingsByFamily.set(family, /* @__PURE__ */ new Set());
1206
+ }
1207
+ state.mappingsByFamily.get(family).add(mapping.uuid);
1208
+ if (!state.mappingsByControl.has(mapping.control_id)) {
1209
+ state.mappingsByControl.set(mapping.control_id, /* @__PURE__ */ new Set());
1210
+ }
1211
+ state.mappingsByControl.get(mapping.control_id).add(mapping.uuid);
1212
+ }
1213
+ async function loadAllData() {
1214
+ const state = getServerState();
1215
+ debug("Loading data into memory...");
1216
+ try {
1217
+ const controls = await state.fileStore.loadAllControls();
1218
+ for (const control of controls) {
1219
+ state.controlsCache.set(control.id, control);
1220
+ addControlToIndexes(control);
1221
+ }
1222
+ debug(`Loaded ${controls.length} controls from individual files`);
1223
+ const mappings = await state.fileStore.loadMappings();
1224
+ for (const mapping of mappings) {
1225
+ state.mappingsCache.set(mapping.uuid, mapping);
1226
+ addMappingToIndexes(mapping);
1227
+ }
1228
+ debug(`Loaded ${mappings.length} mappings`);
1229
+ } catch (error) {
1230
+ console.error("Error loading data:", error);
1231
+ }
1232
+ }
1233
+ async function saveMappingsToFile() {
1234
+ const state = getServerState();
1235
+ try {
1236
+ const allMappings = Array.from(state.mappingsCache.values());
1237
+ await state.fileStore.saveMappings(allMappings);
1238
+ debug(`Saved ${allMappings.length} mappings`);
1239
+ } catch (error) {
1240
+ console.error("Error saving mappings:", error);
1241
+ }
1242
+ }
1243
+ var serverState;
1244
+ var init_serverState = __esm({
1245
+ "cli/server/serverState.ts"() {
1246
+ "use strict";
1247
+ init_debug();
1248
+ init_fileStore();
1249
+ init_gitHistory();
1250
+ serverState = void 0;
1251
+ }
1252
+ });
1253
+
1254
+ // cli/server/spreadsheetRoutes.ts
1255
+ var spreadsheetRoutes_exports = {};
1256
+ __export(spreadsheetRoutes_exports, {
1257
+ default: () => spreadsheetRoutes_default,
1258
+ scanControlSets: () => scanControlSets
1259
+ });
1260
+ import { parse as parseCSVSync } from "csv-parse/sync";
1261
+ import ExcelJS from "exceljs";
1262
+ import express from "express";
1263
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
1264
+ import { glob } from "glob";
1265
+ import * as yaml4 from "js-yaml";
1266
+ import multer from "multer";
1267
+ import { dirname, join as join4, relative as relative2 } from "path";
1268
+ async function scanControlSets() {
1269
+ const state = getServerState();
1270
+ const baseDir = state.CONTROL_SET_DIR;
1271
+ const pattern = "**/lula.yaml";
1272
+ const files = await glob(pattern, {
1273
+ cwd: baseDir,
1274
+ ignore: ["node_modules/**", "dist/**", "build/**"],
1275
+ maxDepth: 5
1276
+ });
1277
+ const controlSets = files.map((file) => {
1278
+ const fullPath = join4(baseDir, file);
1279
+ const dirPath = dirname(fullPath);
1280
+ const relativePath = relative2(baseDir, dirPath) || ".";
1281
+ try {
1282
+ const content = readFileSync3(fullPath, "utf8");
1283
+ const data = yaml4.load(content);
1284
+ if (data.id === "default") {
1285
+ return null;
1286
+ }
1287
+ return {
1288
+ path: relativePath,
1289
+ name: data.name || "Unnamed Control Set",
1290
+ description: data.description || "",
1291
+ controlCount: data.controlCount || 0,
1292
+ file
1293
+ };
1294
+ } catch (_err) {
1295
+ return {
1296
+ path: relativePath,
1297
+ name: "Invalid lula.yaml",
1298
+ description: "Could not parse file",
1299
+ controlCount: 0,
1300
+ file
1301
+ };
1302
+ }
1303
+ }).filter((cs) => cs !== null);
1304
+ return { controlSets };
1305
+ }
1306
+ function applyNamingConvention(fieldName, convention) {
1307
+ if (!fieldName) return fieldName;
1308
+ const cleanedName = fieldName.trim();
1309
+ switch (convention) {
1310
+ case "camelCase":
1311
+ return toCamelCase(cleanedName);
1312
+ case "snake_case":
1313
+ return toSnakeCase(cleanedName);
1314
+ case "kebab-case":
1315
+ return toKebabCase(cleanedName);
1316
+ case "lowercase":
1317
+ return cleanedName.replace(/\W+/g, "").toLowerCase();
1318
+ case "original":
1319
+ return cleanedName;
1320
+ default:
1321
+ return toCamelCase(cleanedName);
1322
+ }
1323
+ }
1324
+ function toCamelCase(str) {
1325
+ return str.replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) => {
1326
+ return index === 0 ? word.toLowerCase() : word.toUpperCase();
1327
+ }).replace(/\s+/g, "");
1328
+ }
1329
+ function toSnakeCase(str) {
1330
+ return str.replace(/\W+/g, " ").split(/ |\s/).map((word) => word.toLowerCase()).join("_");
1331
+ }
1332
+ function toKebabCase(str) {
1333
+ return str.replace(/\W+/g, " ").split(/ |\s/).map((word) => word.toLowerCase()).join("-");
1334
+ }
1335
+ function detectValueType(value) {
1336
+ if (typeof value === "boolean") return "boolean";
1337
+ if (typeof value === "number") return "number";
1338
+ if (typeof value === "string") {
1339
+ const lowerValue = value.toLowerCase().trim();
1340
+ if (lowerValue === "true" || lowerValue === "false" || lowerValue === "yes" || lowerValue === "no" || lowerValue === "y" || lowerValue === "n") {
1341
+ return "boolean";
1342
+ }
1343
+ if (!isNaN(Number(value)) && value.trim() !== "") {
1344
+ return "number";
1345
+ }
1346
+ const datePatterns = [
1347
+ /^\d{4}-\d{2}-\d{2}$/,
1348
+ // YYYY-MM-DD
1349
+ /^\d{2}\/\d{2}\/\d{4}$/,
1350
+ // MM/DD/YYYY
1351
+ /^\d{1,2}\/\d{1,2}\/\d{2,4}$/
1352
+ // M/D/YY or MM/DD/YYYY
1353
+ ];
1354
+ if (datePatterns.some((pattern) => pattern.test(value))) {
1355
+ return "date";
1356
+ }
1357
+ }
1358
+ return "string";
1359
+ }
1360
+ function parseCSV(content) {
1361
+ try {
1362
+ const records = parseCSVSync(content, {
1363
+ // Don't treat first row as headers - we'll handle that ourselves
1364
+ columns: false,
1365
+ // Skip empty lines
1366
+ skip_empty_lines: true,
1367
+ // Handle different line endings
1368
+ relax_column_count: true,
1369
+ // Trim whitespace from fields
1370
+ trim: true,
1371
+ // Handle quoted fields properly
1372
+ quote: '"',
1373
+ // Standard escape character
1374
+ escape: '"',
1375
+ // Auto-detect delimiter (usually comma)
1376
+ delimiter: ","
1377
+ });
1378
+ return records;
1379
+ } catch (error) {
1380
+ console.error("CSV parsing error:", error);
1381
+ return content.split(/\r?\n/).map((line) => line.split(","));
1382
+ }
1383
+ }
1384
+ function extractFamilyFromControlId(controlId) {
1385
+ if (!controlId) return "UNKNOWN";
1386
+ controlId = controlId.trim();
1387
+ const match = controlId.match(/^([A-Za-z]+)[-._ ]?\d/);
1388
+ if (match) {
1389
+ return match[1].toUpperCase();
1390
+ }
1391
+ const letterMatch = controlId.match(/^([A-Za-z]+)/);
1392
+ if (letterMatch) {
1393
+ return letterMatch[1].toUpperCase();
1394
+ }
1395
+ return controlId.substring(0, 2).toUpperCase();
1396
+ }
1397
+ function exportAsCSV(controls, metadata, res) {
1398
+ const fieldSchema = metadata?.fieldSchema?.fields || {};
1399
+ const controlIdField = metadata?.control_id_field || "id";
1400
+ const allFields = /* @__PURE__ */ new Set();
1401
+ controls.forEach((control) => {
1402
+ Object.keys(control).forEach((key) => allFields.add(key));
1403
+ });
1404
+ const fieldMapping = [];
1405
+ if (allFields.has(controlIdField)) {
1406
+ const idSchema = fieldSchema[controlIdField];
1407
+ fieldMapping.push({
1408
+ fieldName: controlIdField,
1409
+ displayName: idSchema?.original_name || "Control ID"
1410
+ });
1411
+ allFields.delete(controlIdField);
1412
+ } else if (allFields.has("id")) {
1413
+ fieldMapping.push({
1414
+ fieldName: "id",
1415
+ displayName: "Control ID"
1416
+ });
1417
+ allFields.delete("id");
1418
+ }
1419
+ if (allFields.has("family")) {
1420
+ const familySchema = fieldSchema["family"];
1421
+ fieldMapping.push({
1422
+ fieldName: "family",
1423
+ displayName: familySchema?.original_name || "Family"
1424
+ });
1425
+ allFields.delete("family");
1426
+ }
1427
+ Array.from(allFields).filter((field) => field !== "mappings" && field !== "mappings_count").sort().forEach((field) => {
1428
+ const schema = fieldSchema[field];
1429
+ const displayName = schema?.original_name || field.replace(/-/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
1430
+ fieldMapping.push({ fieldName: field, displayName });
1431
+ });
1432
+ if (allFields.has("mappings_count")) {
1433
+ fieldMapping.push({ fieldName: "mappings_count", displayName: "Mappings Count" });
1434
+ }
1435
+ if (allFields.has("mappings")) {
1436
+ fieldMapping.push({ fieldName: "mappings", displayName: "Mappings" });
1437
+ }
1438
+ const csvRows = [];
1439
+ csvRows.push(fieldMapping.map((field) => `"${field.displayName}"`).join(","));
1440
+ controls.forEach((control) => {
1441
+ const row = fieldMapping.map(({ fieldName }) => {
1442
+ const value = control[fieldName];
1443
+ if (value === void 0 || value === null) return '""';
1444
+ if (fieldName === "mappings" && Array.isArray(value)) {
1445
+ const mappingsStr = value.map(
1446
+ (m) => `${m.status}: ${m.description.substring(0, 50)}${m.description.length > 50 ? "..." : ""}`
1447
+ ).join("; ");
1448
+ return `"${mappingsStr.replace(/"/g, '""')}"`;
1449
+ }
1450
+ if (Array.isArray(value)) return `"${value.join("; ").replace(/"/g, '""')}"`;
1451
+ if (typeof value === "object") return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
1452
+ return `"${String(value).replace(/"/g, '""')}"`;
1453
+ });
1454
+ csvRows.push(row.join(","));
1455
+ });
1456
+ const csvContent = csvRows.join("\n");
1457
+ const fileName = `${metadata?.name || "controls"}_export_${Date.now()}.csv`;
1458
+ res.setHeader("Content-Type", "text/csv");
1459
+ res.setHeader("Content-Disposition", `attachment; filename="${fileName}"`);
1460
+ res.send(csvContent);
1461
+ }
1462
+ async function exportAsExcel(controls, metadata, res) {
1463
+ const fieldSchema = metadata?.fieldSchema?.fields || {};
1464
+ const controlIdField = metadata?.control_id_field || "id";
1465
+ const worksheetData = controls.map((control) => {
1466
+ const exportControl = {};
1467
+ if (control[controlIdField]) {
1468
+ const idSchema = fieldSchema[controlIdField];
1469
+ const idDisplayName = idSchema?.original_name || "Control ID";
1470
+ exportControl[idDisplayName] = control[controlIdField];
1471
+ } else if (control.id) {
1472
+ exportControl["Control ID"] = control.id;
1473
+ }
1474
+ if (control.family) {
1475
+ const familySchema = fieldSchema["family"];
1476
+ const familyDisplayName = familySchema?.original_name || "Family";
1477
+ exportControl[familyDisplayName] = control.family;
1478
+ }
1479
+ Object.keys(control).forEach((key) => {
1480
+ if (key === controlIdField || key === "id" || key === "family") return;
1481
+ const schema = fieldSchema[key];
1482
+ const displayName = schema?.original_name || (key === "mappings_count" ? "Mappings Count" : key === "mappings" ? "Mappings" : key.replace(/-/g, " ").replace(/\b\w/g, (l) => l.toUpperCase()));
1483
+ const value = control[key];
1484
+ if (key === "mappings" && Array.isArray(value)) {
1485
+ exportControl[displayName] = value.map(
1486
+ (m) => `${m.status}: ${m.description.substring(0, 100)}${m.description.length > 100 ? "..." : ""}`
1487
+ ).join("\n");
1488
+ } else if (Array.isArray(value)) {
1489
+ exportControl[displayName] = value.join("; ");
1490
+ } else if (typeof value === "object" && value !== null) {
1491
+ exportControl[displayName] = JSON.stringify(value);
1492
+ } else {
1493
+ exportControl[displayName] = value;
1494
+ }
1495
+ });
1496
+ return exportControl;
1497
+ });
1498
+ const wb = new ExcelJS.Workbook();
1499
+ const ws = wb.addWorksheet("Controls");
1500
+ const headers = Object.keys(worksheetData[0] || {});
1501
+ ws.columns = headers.map((header) => ({
1502
+ header,
1503
+ key: header,
1504
+ width: Math.min(
1505
+ Math.max(
1506
+ header.length,
1507
+ ...worksheetData.map((row) => String(row[header] || "").length)
1508
+ ) + 2,
1509
+ 50
1510
+ )
1511
+ // Auto-size with max width of 50
1512
+ }));
1513
+ worksheetData.forEach((row) => {
1514
+ ws.addRow(row);
1515
+ });
1516
+ ws.getRow(1).font = { bold: true };
1517
+ ws.getRow(1).fill = {
1518
+ type: "pattern",
1519
+ pattern: "solid",
1520
+ fgColor: { argb: "FFE0E0E0" }
1521
+ };
1522
+ if (metadata) {
1523
+ const metaSheet = wb.addWorksheet("Metadata");
1524
+ const cleanMetadata = { ...metadata };
1525
+ delete cleanMetadata.fieldSchema;
1526
+ metaSheet.columns = [
1527
+ { header: "Property", key: "property", width: 30 },
1528
+ { header: "Value", key: "value", width: 50 }
1529
+ ];
1530
+ Object.entries(cleanMetadata).forEach(([key, value]) => {
1531
+ metaSheet.addRow({ property: key, value: String(value) });
1532
+ });
1533
+ }
1534
+ const buffer = await wb.xlsx.writeBuffer();
1535
+ const fileName = `${metadata?.name || "controls"}_export_${Date.now()}.xlsx`;
1536
+ res.setHeader(
1537
+ "Content-Type",
1538
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
1539
+ );
1540
+ res.setHeader("Content-Disposition", `attachment; filename="${fileName}"`);
1541
+ res.send(buffer);
1542
+ }
1543
+ function exportAsJSON(controls, metadata, res) {
1544
+ const exportData = {
1545
+ metadata: metadata || {},
1546
+ controlCount: controls.length,
1547
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1548
+ controls
1549
+ };
1550
+ const fileName = `${metadata?.name || "controls"}_export_${Date.now()}.json`;
1551
+ res.setHeader("Content-Type", "application/json");
1552
+ res.setHeader("Content-Disposition", `attachment; filename="${fileName}"`);
1553
+ res.json(exportData);
1554
+ }
1555
+ var router, upload, spreadsheetRoutes_default;
1556
+ var init_spreadsheetRoutes = __esm({
1557
+ "cli/server/spreadsheetRoutes.ts"() {
1558
+ "use strict";
1559
+ init_debug();
1560
+ init_serverState();
1561
+ router = express.Router();
1562
+ upload = multer({
1563
+ storage: multer.memoryStorage(),
1564
+ limits: { fileSize: 50 * 1024 * 1024 }
1565
+ // 50MB limit
1566
+ });
1567
+ router.post("/import-spreadsheet", upload.single("file"), async (req, res) => {
1568
+ try {
1569
+ if (!req.file) {
1570
+ return res.status(400).json({ error: "No file uploaded" });
1571
+ }
1572
+ const {
1573
+ controlIdField = "Control ID",
1574
+ startRow = "1",
1575
+ controlSetName = "Imported Control Set",
1576
+ controlSetDescription = "Imported from spreadsheet"
1577
+ } = req.body;
1578
+ debug("Import parameters received:", {
1579
+ controlIdField,
1580
+ startRow,
1581
+ controlSetName,
1582
+ controlSetDescription
1583
+ });
1584
+ const namingConvention = "kebab-case";
1585
+ const skipEmpty = true;
1586
+ const skipEmptyRows = true;
1587
+ const fileName = req.file.originalname || "";
1588
+ const isCSV = fileName.toLowerCase().endsWith(".csv");
1589
+ let rawData = [];
1590
+ if (isCSV) {
1591
+ const csvContent = req.file.buffer.toString("utf-8");
1592
+ rawData = parseCSV(csvContent);
1593
+ } else {
1594
+ const workbook = new ExcelJS.Workbook();
1595
+ const buffer = Buffer.from(req.file.buffer);
1596
+ await workbook.xlsx.load(buffer);
1597
+ const worksheet = workbook.worksheets[0];
1598
+ if (!worksheet) {
1599
+ return res.status(400).json({ error: "No worksheet found in file" });
1600
+ }
1601
+ worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => {
1602
+ const rowData = [];
1603
+ row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
1604
+ rowData[colNumber - 1] = cell.value;
1605
+ });
1606
+ rawData[rowNumber - 1] = rowData;
1607
+ });
1608
+ }
1609
+ const startRowIndex = parseInt(startRow) - 1;
1610
+ if (rawData.length <= startRowIndex) {
1611
+ return res.status(400).json({ error: "Start row exceeds sheet data" });
1612
+ }
1613
+ const headers = rawData[startRowIndex];
1614
+ if (!headers || headers.length === 0) {
1615
+ return res.status(400).json({ error: "No headers found at specified row" });
1616
+ }
1617
+ debug("Headers found:", headers);
1618
+ debug(
1619
+ "After conversion, looking for control ID field:",
1620
+ applyNamingConvention(controlIdField, namingConvention)
1621
+ );
1622
+ const controls = [];
1623
+ const families = /* @__PURE__ */ new Map();
1624
+ const fieldMetadata = /* @__PURE__ */ new Map();
1625
+ headers.forEach((header) => {
1626
+ if (header) {
1627
+ const cleanName = applyNamingConvention(header, namingConvention);
1628
+ fieldMetadata.set(cleanName, {
1629
+ originalName: header,
1630
+ cleanName,
1631
+ type: "string",
1632
+ maxLength: 0,
1633
+ hasMultipleLines: false,
1634
+ uniqueValues: /* @__PURE__ */ new Set(),
1635
+ emptyCount: 0,
1636
+ totalCount: 0,
1637
+ examples: []
1638
+ });
1639
+ }
1640
+ });
1641
+ for (let i = startRowIndex + 1; i < rawData.length; i++) {
1642
+ const row = rawData[i];
1643
+ if (!row || row.length === 0) continue;
1644
+ const control = {};
1645
+ let hasData = false;
1646
+ headers.forEach((header, index) => {
1647
+ if (header && row[index] !== void 0 && row[index] !== null) {
1648
+ const value = typeof row[index] === "string" ? row[index].trim() : row[index];
1649
+ const fieldName = applyNamingConvention(header, namingConvention);
1650
+ const metadata = fieldMetadata.get(fieldName);
1651
+ metadata.totalCount++;
1652
+ if (value === "" || value === null || value === void 0) {
1653
+ metadata.emptyCount++;
1654
+ if (skipEmpty) return;
1655
+ } else {
1656
+ const normalizedValue = typeof value === "string" ? value.trim() : value;
1657
+ if (normalizedValue !== "") {
1658
+ metadata.uniqueValues.add(normalizedValue);
1659
+ }
1660
+ const valueType = detectValueType(value);
1661
+ if (metadata.type === "string" || metadata.totalCount === 1) {
1662
+ metadata.type = valueType;
1663
+ } else if (metadata.type !== valueType) {
1664
+ metadata.type = "mixed";
1665
+ }
1666
+ if (typeof value === "string") {
1667
+ const length = value.length;
1668
+ if (length > metadata.maxLength) {
1669
+ metadata.maxLength = length;
1670
+ }
1671
+ if (value.includes("\n") || length > 100) {
1672
+ metadata.hasMultipleLines = true;
1673
+ }
1674
+ }
1675
+ if (metadata.examples.length < 3 && normalizedValue !== "") {
1676
+ metadata.examples.push(normalizedValue);
1677
+ }
1678
+ }
1679
+ control[fieldName] = value;
1680
+ hasData = true;
1681
+ }
1682
+ });
1683
+ if (hasData && (!skipEmptyRows || Object.keys(control).length > 0)) {
1684
+ const controlIdFieldName = applyNamingConvention(controlIdField, namingConvention);
1685
+ const controlId = control[controlIdFieldName];
1686
+ if (!controlId) {
1687
+ continue;
1688
+ }
1689
+ const family = extractFamilyFromControlId(controlId);
1690
+ control.family = family;
1691
+ controls.push(control);
1692
+ if (!families.has(family)) {
1693
+ families.set(family, []);
1694
+ }
1695
+ families.get(family).push(control);
1696
+ }
1697
+ }
1698
+ const state = getServerState();
1699
+ const folderName = toKebabCase(controlSetName || "imported-controls");
1700
+ const baseDir = join4(state.CONTROL_SET_DIR || process.cwd(), folderName);
1701
+ if (!existsSync3(baseDir)) {
1702
+ mkdirSync2(baseDir, { recursive: true });
1703
+ }
1704
+ const uniqueFamilies = Array.from(families.keys()).filter((f) => f && f !== "UNKNOWN");
1705
+ let frontendFieldSchema = null;
1706
+ if (req.body.fieldSchema) {
1707
+ try {
1708
+ frontendFieldSchema = JSON.parse(req.body.fieldSchema);
1709
+ } catch (e) {
1710
+ }
1711
+ }
1712
+ const fields = {};
1713
+ let displayOrder = 1;
1714
+ const controlIdFieldNameClean = applyNamingConvention(controlIdField, namingConvention);
1715
+ const familyOptions = Array.from(families.keys()).filter((f) => f && f !== "UNKNOWN").sort();
1716
+ fields["family"] = {
1717
+ type: "string",
1718
+ ui_type: familyOptions.length <= 50 ? "select" : "short_text",
1719
+ // Make select if reasonable number of families
1720
+ is_array: false,
1721
+ max_length: 10,
1722
+ usage_count: controls.length,
1723
+ usage_percentage: 100,
1724
+ required: true,
1725
+ visible: true,
1726
+ show_in_table: true,
1727
+ editable: false,
1728
+ display_order: displayOrder++,
1729
+ category: "core",
1730
+ tab: "overview"
1731
+ };
1732
+ if (familyOptions.length <= 50) {
1733
+ fields["family"].options = familyOptions;
1734
+ }
1735
+ fieldMetadata.forEach((metadata, fieldName) => {
1736
+ if (fieldName === "family" || fieldName === "id" && controlIdFieldNameClean !== "id") {
1737
+ return;
1738
+ }
1739
+ const frontendConfig = frontendFieldSchema?.find((f) => f.fieldName === fieldName);
1740
+ if (frontendFieldSchema && !frontendConfig) {
1741
+ return;
1742
+ }
1743
+ const usageCount = metadata.totalCount - metadata.emptyCount;
1744
+ const usagePercentage = metadata.totalCount > 0 ? Math.round(usageCount / metadata.totalCount * 100) : 0;
1745
+ let uiType = "short_text";
1746
+ const nonEmptyCount = metadata.totalCount - metadata.emptyCount;
1747
+ const isDropdownCandidate = metadata.uniqueValues.size > 0 && metadata.uniqueValues.size <= 20 && // Max 20 unique values for dropdown
1748
+ nonEmptyCount >= 10 && // At least 10 non-empty values to be meaningful
1749
+ metadata.maxLength <= 100 && // Reasonably short values only
1750
+ metadata.uniqueValues.size / nonEmptyCount <= 0.3;
1751
+ if (metadata.hasMultipleLines || metadata.maxLength > 500) {
1752
+ uiType = "textarea";
1753
+ } else if (isDropdownCandidate) {
1754
+ uiType = "select";
1755
+ } else if (metadata.type === "boolean") {
1756
+ uiType = "checkbox";
1757
+ } else if (metadata.type === "number") {
1758
+ uiType = "number";
1759
+ } else if (metadata.type === "date") {
1760
+ uiType = "date";
1761
+ } else if (metadata.maxLength <= 50) {
1762
+ uiType = "short_text";
1763
+ } else if (metadata.maxLength <= 200) {
1764
+ uiType = "medium_text";
1765
+ } else {
1766
+ uiType = "long_text";
1767
+ }
1768
+ let category = frontendConfig?.category || "custom";
1769
+ if (!frontendConfig) {
1770
+ if (fieldName.includes("status") || fieldName.includes("state")) {
1771
+ category = "compliance";
1772
+ } else if (fieldName.includes("title") || fieldName.includes("name") || fieldName.includes("description")) {
1773
+ category = "core";
1774
+ } else if (fieldName.includes("note") || fieldName.includes("comment")) {
1775
+ category = "notes";
1776
+ }
1777
+ }
1778
+ const isControlIdField = fieldName === controlIdFieldNameClean;
1779
+ const fieldDef = {
1780
+ type: metadata.type,
1781
+ ui_type: uiType,
1782
+ is_array: false,
1783
+ max_length: metadata.maxLength,
1784
+ usage_count: usageCount,
1785
+ usage_percentage: usagePercentage,
1786
+ required: isControlIdField ? true : frontendConfig?.required ?? usagePercentage > 95,
1787
+ // Control ID is always required
1788
+ visible: frontendConfig?.tab !== "hidden",
1789
+ show_in_table: isControlIdField ? true : metadata.maxLength <= 100 && usagePercentage > 30,
1790
+ // Always show control ID in table
1791
+ editable: isControlIdField ? false : true,
1792
+ // Control ID is not editable
1793
+ display_order: isControlIdField ? 1 : frontendConfig?.displayOrder ?? displayOrder++,
1794
+ // Control ID is always first
1795
+ category: isControlIdField ? "core" : category,
1796
+ // Control ID is always core
1797
+ tab: isControlIdField ? "overview" : frontendConfig?.tab || void 0
1798
+ // Control ID is always in overview
1799
+ };
1800
+ if (uiType === "select") {
1801
+ fieldDef.options = Array.from(metadata.uniqueValues).sort();
1802
+ }
1803
+ if (frontendConfig?.originalName || metadata.originalName) {
1804
+ fieldDef.original_name = frontendConfig?.originalName || metadata.originalName;
1805
+ }
1806
+ fields[fieldName] = fieldDef;
1807
+ });
1808
+ const fieldSchema = {
1809
+ fields,
1810
+ total_controls: controls.length,
1811
+ analyzed_at: (/* @__PURE__ */ new Date()).toISOString()
1812
+ };
1813
+ const controlSetData = {
1814
+ name: controlSetName,
1815
+ description: controlSetDescription,
1816
+ version: "1.0.0",
1817
+ control_id_field: controlIdFieldNameClean,
1818
+ // Add this to indicate which field is the control ID
1819
+ controlCount: controls.length,
1820
+ families: uniqueFamilies,
1821
+ fieldSchema
1822
+ };
1823
+ writeFileSync2(join4(baseDir, "lula.yaml"), yaml4.dump(controlSetData));
1824
+ const controlsDir = join4(baseDir, "controls");
1825
+ families.forEach((familyControls, family) => {
1826
+ const familyDir = join4(controlsDir, family);
1827
+ if (!existsSync3(familyDir)) {
1828
+ mkdirSync2(familyDir, { recursive: true });
1829
+ }
1830
+ familyControls.forEach((control) => {
1831
+ const controlId = control[controlIdFieldNameClean];
1832
+ if (!controlId) {
1833
+ console.error("Missing control ID for control:", control);
1834
+ return;
1835
+ }
1836
+ const controlIdStr = String(controlId).slice(0, 50);
1837
+ const fileName2 = `${controlIdStr.replace(/[^a-zA-Z0-9-]/g, "_")}.yaml`;
1838
+ const filePath = join4(familyDir, fileName2);
1839
+ const filteredControl = {};
1840
+ if (control.family !== void 0) {
1841
+ filteredControl.family = control.family;
1842
+ }
1843
+ Object.keys(control).forEach((fieldName) => {
1844
+ if (fieldName === "family") return;
1845
+ const isInFrontendSchema = frontendFieldSchema?.some((f) => f.fieldName === fieldName);
1846
+ const isInFieldsMetadata = fields.hasOwnProperty(fieldName);
1847
+ if (isInFrontendSchema || isInFieldsMetadata) {
1848
+ filteredControl[fieldName] = control[fieldName];
1849
+ }
1850
+ });
1851
+ writeFileSync2(filePath, yaml4.dump(filteredControl));
1852
+ });
1853
+ });
1854
+ res.json({
1855
+ success: true,
1856
+ controlCount: controls.length,
1857
+ families: Array.from(families.keys()),
1858
+ outputDir: folderName
1859
+ // Return just the folder name, not full path
1860
+ });
1861
+ } catch (error) {
1862
+ console.error("Error processing spreadsheet:", error);
1863
+ res.status(500).json({ error: "Failed to process spreadsheet" });
1864
+ }
1865
+ });
1866
+ router.get("/export-controls", async (req, res) => {
1867
+ try {
1868
+ const format = req.query.format || "csv";
1869
+ const state = getServerState();
1870
+ const fileStore = state.fileStore;
1871
+ if (!fileStore) {
1872
+ return res.status(500).json({ error: "No control set loaded" });
1873
+ }
1874
+ const controls = await fileStore.loadAllControls();
1875
+ const mappings = await fileStore.loadMappings();
1876
+ let metadata = {};
1877
+ try {
1878
+ const metadataPath2 = join4(state.CONTROL_SET_DIR, "lula.yaml");
1879
+ if (existsSync3(metadataPath2)) {
1880
+ const metadataContent = readFileSync3(metadataPath2, "utf8");
1881
+ metadata = yaml4.load(metadataContent);
1882
+ }
1883
+ } catch (err) {
1884
+ debug("Could not load metadata:", err);
1885
+ }
1886
+ if (!controls || controls.length === 0) {
1887
+ return res.status(404).json({ error: "No controls found" });
1888
+ }
1889
+ const controlsWithMappings = controls.map((control) => {
1890
+ const controlIdField = metadata?.control_id_field || "id";
1891
+ const controlId = control[controlIdField] || control.id;
1892
+ const controlMappings = mappings.filter((m) => m.control_id === controlId);
1893
+ return {
1894
+ ...control,
1895
+ mappings_count: controlMappings.length,
1896
+ mappings: controlMappings.map((m) => ({
1897
+ uuid: m.uuid,
1898
+ status: m.status,
1899
+ description: m.justification || ""
1900
+ }))
1901
+ };
1902
+ });
1903
+ debug(`Exporting ${controlsWithMappings.length} controls as ${format}`);
1904
+ switch (format.toLowerCase()) {
1905
+ case "csv":
1906
+ return exportAsCSV(controlsWithMappings, metadata, res);
1907
+ case "excel":
1908
+ case "xlsx":
1909
+ return await exportAsExcel(controlsWithMappings, metadata, res);
1910
+ case "json":
1911
+ return exportAsJSON(controlsWithMappings, metadata, res);
1912
+ default:
1913
+ return res.status(400).json({ error: `Unsupported format: ${format}` });
1914
+ }
1915
+ } catch (error) {
1916
+ console.error("Export error:", error);
1917
+ res.status(500).json({ error: error.message });
1918
+ }
1919
+ });
1920
+ router.post("/parse-excel", upload.single("file"), async (req, res) => {
1921
+ try {
1922
+ if (!req.file) {
1923
+ return res.status(400).json({ error: "No file uploaded" });
1924
+ }
1925
+ const fileName = req.file.originalname || "";
1926
+ const isCSV = fileName.toLowerCase().endsWith(".csv");
1927
+ let sheets = [];
1928
+ let rows = [];
1929
+ if (isCSV) {
1930
+ const csvContent = req.file.buffer.toString("utf-8");
1931
+ rows = parseCSV(csvContent);
1932
+ sheets = ["Sheet1"];
1933
+ } else {
1934
+ const workbook = new ExcelJS.Workbook();
1935
+ const buffer = Buffer.from(req.file.buffer);
1936
+ await workbook.xlsx.load(buffer);
1937
+ sheets = workbook.worksheets.map((ws) => ws.name);
1938
+ const worksheet = workbook.worksheets[0];
1939
+ if (!worksheet) {
1940
+ return res.status(400).json({ error: "No worksheet found in file" });
1941
+ }
1942
+ worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
1943
+ const rowData = [];
1944
+ row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
1945
+ rowData[colNumber - 1] = cell.value;
1946
+ });
1947
+ rows.push(rowData);
1948
+ });
1949
+ }
1950
+ const headerCandidates = rows.slice(0, 5).map((row, index) => ({
1951
+ row: index + 1,
1952
+ preview: row.slice(0, 4).filter((v) => v != null).join(", ") + (row.length > 4 ? ", ..." : "")
1953
+ }));
1954
+ res.json({
1955
+ sheets,
1956
+ selectedSheet: sheets[0],
1957
+ rowPreviews: headerCandidates,
1958
+ totalRows: rows.length,
1959
+ sampleData: rows.slice(0, 10)
1960
+ // First 10 rows for preview
1961
+ });
1962
+ } catch (error) {
1963
+ console.error("Error parsing Excel file:", error);
1964
+ res.status(500).json({ error: "Failed to parse Excel file" });
1965
+ }
1966
+ });
1967
+ router.post("/parse-excel-sheet", upload.single("file"), async (req, res) => {
1968
+ try {
1969
+ const { sheetName, headerRow } = req.body;
1970
+ if (!req.file) {
1971
+ return res.status(400).json({ error: "No file uploaded" });
1972
+ }
1973
+ const fileName = req.file.originalname || "";
1974
+ const isCSV = fileName.toLowerCase().endsWith(".csv");
1975
+ let rows = [];
1976
+ if (isCSV) {
1977
+ const csvContent = req.file.buffer.toString("utf-8");
1978
+ rows = parseCSV(csvContent);
1979
+ } else {
1980
+ const workbook = new ExcelJS.Workbook();
1981
+ const buffer = Buffer.from(req.file.buffer);
1982
+ await workbook.xlsx.load(buffer);
1983
+ const worksheet = workbook.getWorksheet(sheetName);
1984
+ if (!worksheet) {
1985
+ return res.status(400).json({ error: `Sheet "${sheetName}" not found` });
1986
+ }
1987
+ worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
1988
+ const rowData = [];
1989
+ row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
1990
+ rowData[colNumber - 1] = cell.value;
1991
+ });
1992
+ rows.push(rowData);
1993
+ });
1994
+ }
1995
+ const headerRowIndex = parseInt(headerRow) - 1;
1996
+ const headers = rows[headerRowIndex] || [];
1997
+ const fields = headers.filter((h) => h && typeof h === "string");
1998
+ const sampleData = rows.slice(headerRowIndex + 1, headerRowIndex + 4).map((row) => {
1999
+ const obj = {};
2000
+ headers.forEach((header, index) => {
2001
+ if (header) {
2002
+ obj[header] = row[index];
2003
+ }
2004
+ });
2005
+ return obj;
2006
+ });
2007
+ res.json({
2008
+ fields,
2009
+ sampleData,
2010
+ controlCount: rows.length - headerRowIndex - 1
2011
+ });
2012
+ } catch (error) {
2013
+ console.error("Error parsing Excel sheet:", error);
2014
+ res.status(500).json({ error: "Failed to parse Excel sheet" });
2015
+ }
2016
+ });
2017
+ spreadsheetRoutes_default = router;
2018
+ }
2019
+ });
2020
+
2021
+ // cli/server/server.ts
2022
+ init_serverState();
2023
+ init_spreadsheetRoutes();
2024
+ import cors from "cors";
2025
+ import express2 from "express";
2026
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3 } from "fs";
2027
+ import { createServer as createHttpServer } from "http";
2028
+ import { dirname as dirname2, join as join6 } from "path";
2029
+ import { fileURLToPath } from "url";
2030
+
2031
+ // cli/server/websocketServer.ts
2032
+ import { readFileSync as readFileSync4 } from "fs";
2033
+ init_debug();
2034
+ init_controlHelpers();
2035
+ init_serverState();
2036
+ import * as yaml5 from "js-yaml";
2037
+ import { join as join5 } from "path";
2038
+ import { WebSocket, WebSocketServer } from "ws";
2039
+ var WebSocketManager = class {
2040
+ wss = null;
2041
+ clients = /* @__PURE__ */ new Set();
2042
+ /**
2043
+ * Handle incoming commands from WebSocket clients
2044
+ * @param message - The command message from the client
2045
+ * @param ws - The WebSocket connection that sent the message
2046
+ */
2047
+ async handleCommand(message, ws) {
2048
+ const { type, payload } = message;
2049
+ try {
2050
+ switch (type) {
2051
+ case "update-control": {
2052
+ const state = getServerState();
2053
+ if (payload && payload.id) {
2054
+ const existingControl = state.controlsCache.get(payload.id);
2055
+ if (!existingControl) {
2056
+ console.error("Control not found:", payload.id);
2057
+ return;
2058
+ }
2059
+ const updatedControl = { ...existingControl, ...payload };
2060
+ await state.fileStore.saveControl(updatedControl);
2061
+ state.controlsCache.set(updatedControl.id, updatedControl);
2062
+ const family = updatedControl.family || updatedControl.id.split("-")[0];
2063
+ if (!state.controlsByFamily.has(family)) {
2064
+ state.controlsByFamily.set(family, /* @__PURE__ */ new Set());
2065
+ }
2066
+ const familyControlIds = state.controlsByFamily.get(family);
2067
+ if (familyControlIds) {
2068
+ familyControlIds.add(updatedControl.id);
2069
+ }
2070
+ ws.send(
2071
+ JSON.stringify({
2072
+ type: "control-updated",
2073
+ payload: { id: payload.id, success: true }
2074
+ })
2075
+ );
2076
+ }
2077
+ break;
2078
+ }
2079
+ case "refresh-controls": {
2080
+ const state = getServerState();
2081
+ state.controlsCache.clear();
2082
+ state.controlsByFamily.clear();
2083
+ const { loadAllData: loadAllData2 } = await Promise.resolve().then(() => (init_serverState(), serverState_exports));
2084
+ await loadAllData2();
2085
+ this.broadcastState();
2086
+ break;
2087
+ }
2088
+ case "switch-control-set": {
2089
+ if (payload && payload.path) {
2090
+ const { initializeServerState: initializeServerState2, loadAllData: loadAllData2 } = await Promise.resolve().then(() => (init_serverState(), serverState_exports));
2091
+ const currentState = getServerState();
2092
+ initializeServerState2(currentState.CONTROL_SET_DIR, payload.path);
2093
+ await loadAllData2();
2094
+ this.broadcastState();
2095
+ }
2096
+ break;
2097
+ }
2098
+ case "create-mapping": {
2099
+ const state = getServerState();
2100
+ if (payload && payload.control_id) {
2101
+ const mapping = payload;
2102
+ if (!mapping.uuid) {
2103
+ const crypto = await import("crypto");
2104
+ mapping.uuid = crypto.randomUUID();
2105
+ }
2106
+ await state.fileStore.saveMapping(mapping);
2107
+ state.mappingsCache.set(mapping.uuid, mapping);
2108
+ const family = mapping.control_id.split("-")[0];
2109
+ if (!state.mappingsByFamily.has(family)) {
2110
+ state.mappingsByFamily.set(family, /* @__PURE__ */ new Set());
2111
+ }
2112
+ state.mappingsByFamily.get(family)?.add(mapping.uuid);
2113
+ if (!state.mappingsByControl.has(mapping.control_id)) {
2114
+ state.mappingsByControl.set(mapping.control_id, /* @__PURE__ */ new Set());
2115
+ }
2116
+ state.mappingsByControl.get(mapping.control_id)?.add(mapping.uuid);
2117
+ ws.send(
2118
+ JSON.stringify({
2119
+ type: "mapping-created",
2120
+ payload: { uuid: mapping.uuid, success: true }
2121
+ })
2122
+ );
2123
+ this.broadcastState();
2124
+ }
2125
+ break;
2126
+ }
2127
+ case "update-mapping": {
2128
+ const state = getServerState();
2129
+ if (payload && payload.uuid) {
2130
+ const mapping = payload;
2131
+ await state.fileStore.saveMapping(mapping);
2132
+ state.mappingsCache.set(mapping.uuid, mapping);
2133
+ ws.send(
2134
+ JSON.stringify({
2135
+ type: "mapping-updated",
2136
+ payload: { uuid: mapping.uuid, success: true }
2137
+ })
2138
+ );
2139
+ this.broadcastState();
2140
+ }
2141
+ break;
2142
+ }
2143
+ case "delete-mapping": {
2144
+ const state = getServerState();
2145
+ if (payload && payload.uuid) {
2146
+ const uuid = payload.uuid;
2147
+ const mapping = state.mappingsCache.get(uuid);
2148
+ if (mapping) {
2149
+ await state.fileStore.deleteMapping(uuid);
2150
+ state.mappingsCache.delete(uuid);
2151
+ const family = mapping.control_id.split("-")[0];
2152
+ state.mappingsByFamily.get(family)?.delete(uuid);
2153
+ state.mappingsByControl.get(mapping.control_id)?.delete(uuid);
2154
+ ws.send(
2155
+ JSON.stringify({
2156
+ type: "mapping-deleted",
2157
+ payload: { uuid, success: true }
2158
+ })
2159
+ );
2160
+ this.broadcastState();
2161
+ }
2162
+ }
2163
+ break;
2164
+ }
2165
+ case "scan-control-sets": {
2166
+ const { scanControlSets: scanControlSets2 } = await Promise.resolve().then(() => (init_spreadsheetRoutes(), spreadsheetRoutes_exports));
2167
+ try {
2168
+ const controlSets = await scanControlSets2();
2169
+ ws.send(
2170
+ JSON.stringify({
2171
+ type: "control-sets-list",
2172
+ payload: controlSets
2173
+ })
2174
+ );
2175
+ } catch (error) {
2176
+ console.error("Error scanning control sets:", error);
2177
+ ws.send(
2178
+ JSON.stringify({
2179
+ type: "error",
2180
+ payload: { message: `Failed to scan control sets: ${error.message}` }
2181
+ })
2182
+ );
2183
+ }
2184
+ break;
2185
+ }
2186
+ case "get-control": {
2187
+ if (payload && payload.id) {
2188
+ const { FileStore: FileStore2 } = await Promise.resolve().then(() => (init_fileStore(), fileStore_exports));
2189
+ const currentPath = getCurrentControlSetPath();
2190
+ const fileStore = new FileStore2({ baseDir: currentPath });
2191
+ const controlId = payload.id;
2192
+ const control = await fileStore.loadControl(controlId);
2193
+ if (control) {
2194
+ if (!control.id) {
2195
+ control.id = controlId;
2196
+ }
2197
+ const { GitHistoryUtil: GitHistoryUtil2 } = await Promise.resolve().then(() => (init_gitHistory(), gitHistory_exports));
2198
+ const { execSync } = await import("child_process");
2199
+ let timeline = null;
2200
+ try {
2201
+ const currentPath2 = getCurrentControlSetPath();
2202
+ const { existsSync: existsSync5 } = await import("fs");
2203
+ const family = control.family || control.id.split("-")[0];
2204
+ const familyDir = join5(currentPath2, "controls", family);
2205
+ const possibleFilenames = [
2206
+ `${control.id}.yaml`,
2207
+ `${control.id.replace(/\./g, "_")}.yaml`,
2208
+ // AC-1.1 -> AC-1_1.yaml
2209
+ `${control.id.replace(/[^\w\-]/g, "_")}.yaml`
2210
+ // General sanitization
2211
+ ];
2212
+ let controlPath = "";
2213
+ for (const filename of possibleFilenames) {
2214
+ const testPath = join5(familyDir, filename);
2215
+ if (existsSync5(testPath)) {
2216
+ controlPath = testPath;
2217
+ break;
2218
+ }
2219
+ }
2220
+ if (!controlPath) {
2221
+ for (const filename of possibleFilenames) {
2222
+ const testPath = join5(currentPath2, "controls", filename);
2223
+ if (existsSync5(testPath)) {
2224
+ controlPath = testPath;
2225
+ break;
2226
+ }
2227
+ }
2228
+ }
2229
+ debug(`Getting timeline for control ${control.id}:`);
2230
+ debug(` Current path: ${currentPath2}`);
2231
+ debug(` Control path found: ${controlPath}`);
2232
+ debug(` File exists: ${existsSync5(controlPath)}`);
2233
+ if (!controlPath) {
2234
+ console.error(`Could not find file for control ${control.id}`);
2235
+ timeline = null;
2236
+ } else {
2237
+ const gitUtil = new GitHistoryUtil2(currentPath2);
2238
+ const controlHistory = await gitUtil.getFileHistory(controlPath);
2239
+ debug(`Git history for ${control.id}:`, {
2240
+ path: controlPath,
2241
+ totalCommits: controlHistory.totalCommits,
2242
+ commits: controlHistory.commits?.length || 0
2243
+ });
2244
+ const mappingFilename = `${control.id}-mappings.yaml`;
2245
+ const mappingPath = join5(currentPath2, "mappings", family, mappingFilename);
2246
+ let mappingHistory = { commits: [], totalCommits: 0 };
2247
+ if (existsSync5(mappingPath)) {
2248
+ mappingHistory = await gitUtil.getFileHistory(mappingPath);
2249
+ debug(`Mapping history for ${control.id}:`, {
2250
+ path: mappingPath,
2251
+ totalCommits: mappingHistory.totalCommits,
2252
+ commits: mappingHistory.commits?.length || 0
2253
+ });
2254
+ }
2255
+ let hasPendingChanges = false;
2256
+ try {
2257
+ try {
2258
+ execSync(`git ls-files --error-unmatch "${controlPath}"`, {
2259
+ encoding: "utf8",
2260
+ cwd: process.cwd(),
2261
+ stdio: "pipe"
2262
+ });
2263
+ const gitStatus = execSync(`git status --porcelain "${controlPath}"`, {
2264
+ encoding: "utf8",
2265
+ cwd: process.cwd()
2266
+ }).trim();
2267
+ hasPendingChanges = gitStatus.length > 0;
2268
+ if (hasPendingChanges) {
2269
+ debug(
2270
+ `Control ${payload.id} has pending changes: ${gitStatus.substring(0, 2)}`
2271
+ );
2272
+ }
2273
+ } catch {
2274
+ hasPendingChanges = true;
2275
+ debug(`Control ${payload.id} is untracked (new file)`);
2276
+ }
2277
+ } catch {
2278
+ }
2279
+ if (existsSync5(mappingPath)) {
2280
+ try {
2281
+ try {
2282
+ execSync(`git ls-files --error-unmatch "${mappingPath}"`, {
2283
+ encoding: "utf8",
2284
+ cwd: process.cwd(),
2285
+ stdio: "pipe"
2286
+ });
2287
+ const gitStatus = execSync(`git status --porcelain "${mappingPath}"`, {
2288
+ encoding: "utf8",
2289
+ cwd: process.cwd()
2290
+ }).trim();
2291
+ if (gitStatus.length > 0) {
2292
+ hasPendingChanges = true;
2293
+ debug(`Mapping file has pending changes: ${gitStatus.substring(0, 2)}`);
2294
+ }
2295
+ } catch {
2296
+ hasPendingChanges = true;
2297
+ debug(`Mapping file is untracked`);
2298
+ }
2299
+ } catch {
2300
+ }
2301
+ }
2302
+ const allCommits = [
2303
+ ...(controlHistory.commits || []).map((c) => ({
2304
+ ...c,
2305
+ source: "control"
2306
+ })),
2307
+ ...(mappingHistory.commits || []).map((c) => ({ ...c, source: "mapping" }))
2308
+ ];
2309
+ allCommits.sort(
2310
+ (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
2311
+ );
2312
+ timeline = {
2313
+ commits: allCommits,
2314
+ totalCommits: controlHistory.totalCommits + mappingHistory.totalCommits,
2315
+ controlCommits: controlHistory.totalCommits || 0,
2316
+ mappingCommits: mappingHistory.totalCommits || 0,
2317
+ hasPendingChanges
2318
+ };
2319
+ if (timeline.totalCommits === 0 && hasPendingChanges) {
2320
+ debug(`No git history for control ${payload.id} - showing as pending`);
2321
+ timeline.commits = [
2322
+ {
2323
+ hash: "pending",
2324
+ shortHash: "pending",
2325
+ author: "Current User",
2326
+ authorEmail: "",
2327
+ date: (/* @__PURE__ */ new Date()).toISOString(),
2328
+ message: "Pending changes (uncommitted)",
2329
+ isPending: true,
2330
+ changes: {
2331
+ insertions: 0,
2332
+ deletions: 0,
2333
+ files: 1
2334
+ },
2335
+ source: "control"
2336
+ }
2337
+ ];
2338
+ timeline.totalCommits = 1;
2339
+ } else if (hasPendingChanges && timeline.totalCommits > 0) {
2340
+ timeline.commits.unshift({
2341
+ hash: "pending",
2342
+ shortHash: "pending",
2343
+ author: "Current User",
2344
+ authorEmail: "",
2345
+ date: (/* @__PURE__ */ new Date()).toISOString(),
2346
+ message: "Pending changes (uncommitted)",
2347
+ isPending: true,
2348
+ changes: {
2349
+ insertions: 0,
2350
+ deletions: 0,
2351
+ files: 1
2352
+ },
2353
+ source: "control"
2354
+ });
2355
+ timeline.totalCommits += 1;
2356
+ }
2357
+ debug(`Final timeline for ${control.id}:`, {
2358
+ totalCommits: timeline.totalCommits,
2359
+ commits: timeline.commits?.length || 0,
2360
+ hasPending: timeline.hasPendingChanges
2361
+ });
2362
+ }
2363
+ } catch (error) {
2364
+ console.error("Error fetching timeline:", error);
2365
+ timeline = null;
2366
+ }
2367
+ ws.send(
2368
+ JSON.stringify({
2369
+ type: "control-details",
2370
+ payload: { ...control, timeline }
2371
+ })
2372
+ );
2373
+ } else {
2374
+ ws.send(
2375
+ JSON.stringify({
2376
+ type: "error",
2377
+ payload: { message: `Control not found: ${payload.id}` }
2378
+ })
2379
+ );
2380
+ }
2381
+ }
2382
+ break;
2383
+ }
2384
+ default:
2385
+ console.warn("Unknown command type:", type);
2386
+ ws.send(
2387
+ JSON.stringify({
2388
+ type: "error",
2389
+ payload: { message: `Unknown command: ${type}` }
2390
+ })
2391
+ );
2392
+ }
2393
+ } catch (error) {
2394
+ console.error("Error handling command:", error);
2395
+ ws.send(
2396
+ JSON.stringify({
2397
+ type: "error",
2398
+ payload: { message: error.message }
2399
+ })
2400
+ );
2401
+ }
2402
+ }
2403
+ /**
2404
+ * Get the complete application state for broadcasting
2405
+ * @returns The complete state object or null if error
2406
+ */
2407
+ getCompleteState() {
2408
+ try {
2409
+ const state = getServerState();
2410
+ const currentPath = getCurrentControlSetPath();
2411
+ let controlSetData = {};
2412
+ try {
2413
+ const controlSetFile = join5(currentPath, "lula.yaml");
2414
+ const content = readFileSync4(controlSetFile, "utf8");
2415
+ controlSetData = yaml5.load(content);
2416
+ } catch {
2417
+ controlSetData = {
2418
+ id: "unknown",
2419
+ name: "Unknown Control Set"
2420
+ };
2421
+ }
2422
+ const controlsMetadata = Array.from(state.controlsCache.values()).map((control) => {
2423
+ if (!control.id) {
2424
+ control.id = getControlId(control, currentPath);
2425
+ }
2426
+ const metadata = {
2427
+ id: control.id,
2428
+ family: control.family
2429
+ };
2430
+ const fieldSchema = controlSetData.fieldSchema?.fields || {};
2431
+ for (const [fieldName, fieldConfig] of Object.entries(fieldSchema)) {
2432
+ if (fieldConfig.tab === "overview" && control[fieldName] !== void 0) {
2433
+ metadata[fieldName] = control[fieldName];
2434
+ }
2435
+ }
2436
+ if (control.title !== void 0) metadata.title = control.title;
2437
+ if (control.implementation_status !== void 0)
2438
+ metadata.implementation_status = control.implementation_status;
2439
+ if (control.compliance_status !== void 0)
2440
+ metadata.compliance_status = control.compliance_status;
2441
+ return metadata;
2442
+ });
2443
+ return {
2444
+ ...controlSetData,
2445
+ // Spread control set properties at root level
2446
+ currentPath,
2447
+ controls: controlsMetadata,
2448
+ // Send lightweight metadata instead of full controls
2449
+ mappings: Array.from(state.mappingsCache.values()),
2450
+ families: Array.from(state.controlsByFamily.keys()).sort(),
2451
+ totalControls: state.controlsCache.size,
2452
+ totalMappings: state.mappingsCache.size
2453
+ };
2454
+ } catch (error) {
2455
+ console.error("Error getting complete state:", error);
2456
+ return null;
2457
+ }
2458
+ }
2459
+ /**
2460
+ * Send state updates to client in chunks for better performance
2461
+ * @param ws - The WebSocket connection to send to
2462
+ * @param fullData - Whether to send full data or summaries
2463
+ */
2464
+ sendStateInChunks(ws, fullData = false) {
2465
+ try {
2466
+ const state = getServerState();
2467
+ const currentPath = getCurrentControlSetPath();
2468
+ let controlSetData = {};
2469
+ try {
2470
+ const controlSetFile = join5(currentPath, "lula.yaml");
2471
+ const content = readFileSync4(controlSetFile, "utf8");
2472
+ controlSetData = yaml5.load(content);
2473
+ } catch {
2474
+ controlSetData = {
2475
+ id: "unknown",
2476
+ name: "Unknown Control Set"
2477
+ };
2478
+ }
2479
+ ws.send(
2480
+ JSON.stringify({
2481
+ type: "metadata-update",
2482
+ payload: {
2483
+ ...controlSetData,
2484
+ currentPath,
2485
+ families: Array.from(state.controlsByFamily.keys()).sort(),
2486
+ totalControls: state.controlsCache.size,
2487
+ totalMappings: state.mappingsCache.size
2488
+ }
2489
+ })
2490
+ );
2491
+ const controlSummaries = Array.from(state.controlsCache.values()).map((control) => {
2492
+ const controlId = control.id || getControlId(control, currentPath);
2493
+ const summary = {
2494
+ id: controlId,
2495
+ family: control.family || control["control-acronym"]?.toString().split("-")[0] || ""
2496
+ };
2497
+ if (controlSetData.field_schema?.fields) {
2498
+ for (const [fieldName] of Object.entries(controlSetData.field_schema.fields)) {
2499
+ if (control[fieldName] !== void 0) {
2500
+ summary[fieldName] = control[fieldName];
2501
+ }
2502
+ }
2503
+ } else {
2504
+ Object.assign(summary, control);
2505
+ }
2506
+ return summary;
2507
+ });
2508
+ setTimeout(() => {
2509
+ ws.send(
2510
+ JSON.stringify({
2511
+ type: "controls-update",
2512
+ payload: fullData ? Array.from(state.controlsCache.values()) : controlSummaries
2513
+ })
2514
+ );
2515
+ }, 10);
2516
+ setTimeout(() => {
2517
+ ws.send(
2518
+ JSON.stringify({
2519
+ type: "mappings-update",
2520
+ payload: Array.from(state.mappingsCache.values())
2521
+ })
2522
+ );
2523
+ }, 20);
2524
+ } catch (error) {
2525
+ console.error("Error sending state in chunks:", error);
2526
+ }
2527
+ }
2528
+ /**
2529
+ * Initialize the WebSocket server
2530
+ * @param server - The HTTP server to attach to
2531
+ */
2532
+ initialize(server) {
2533
+ this.wss = new WebSocketServer({ server, path: "/ws" });
2534
+ this.wss.on("connection", (ws) => {
2535
+ debug("New WebSocket client connected");
2536
+ this.clients.add(ws);
2537
+ const initialState = this.getCompleteState();
2538
+ if (initialState) {
2539
+ ws.send(
2540
+ JSON.stringify({
2541
+ type: "state-update",
2542
+ payload: initialState
2543
+ })
2544
+ );
2545
+ }
2546
+ ws.on("message", async (message) => {
2547
+ try {
2548
+ const data = JSON.parse(message.toString());
2549
+ debug("Received WebSocket message:", data);
2550
+ await this.handleCommand(data, ws);
2551
+ } catch (error) {
2552
+ console.error("Invalid WebSocket message:", error);
2553
+ ws.send(
2554
+ JSON.stringify({
2555
+ type: "error",
2556
+ payload: { message: "Invalid message format" }
2557
+ })
2558
+ );
2559
+ }
2560
+ });
2561
+ ws.on("close", () => {
2562
+ debug("WebSocket client disconnected");
2563
+ this.clients.delete(ws);
2564
+ });
2565
+ ws.on("error", (error) => {
2566
+ console.error("WebSocket error:", error);
2567
+ this.clients.delete(ws);
2568
+ });
2569
+ ws.send(JSON.stringify({ type: "connected" }));
2570
+ this.sendStateInChunks(ws);
2571
+ });
2572
+ }
2573
+ /**
2574
+ * Broadcast a message to all connected clients
2575
+ * @param message - The message to broadcast
2576
+ */
2577
+ broadcast(message) {
2578
+ const data = JSON.stringify(message);
2579
+ this.clients.forEach((client) => {
2580
+ if (client.readyState === WebSocket.OPEN) {
2581
+ client.send(data);
2582
+ }
2583
+ });
2584
+ }
2585
+ /**
2586
+ * Broadcast the complete state to all connected clients
2587
+ */
2588
+ broadcastState() {
2589
+ const completeState = this.getCompleteState();
2590
+ if (completeState) {
2591
+ this.broadcast({
2592
+ type: "state-update",
2593
+ payload: completeState
2594
+ });
2595
+ }
2596
+ }
2597
+ /**
2598
+ * Notify all clients that a control was updated
2599
+ * @param _controlId - The ID of the updated control (unused but kept for API compatibility)
2600
+ */
2601
+ notifyControlUpdate(_controlId) {
2602
+ this.broadcastState();
2603
+ }
2604
+ /**
2605
+ * Notify all clients that a mapping was created
2606
+ * @param _mapping - The created mapping (unused but kept for API compatibility)
2607
+ */
2608
+ notifyMappingCreated(_mapping) {
2609
+ this.broadcastState();
2610
+ }
2611
+ /**
2612
+ * Notify all clients that a mapping was updated
2613
+ * @param _mapping - The updated mapping (unused but kept for API compatibility)
2614
+ */
2615
+ notifyMappingUpdated(_mapping) {
2616
+ this.broadcastState();
2617
+ }
2618
+ /**
2619
+ * Notify all clients that a mapping was deleted
2620
+ * @param _uuid - The UUID of the deleted mapping (unused but kept for API compatibility)
2621
+ */
2622
+ notifyMappingDeleted(_uuid) {
2623
+ this.broadcastState();
2624
+ }
2625
+ /**
2626
+ * Notify all clients to refresh their data
2627
+ */
2628
+ notifyDataRefresh() {
2629
+ this.broadcastState();
2630
+ }
2631
+ };
2632
+ var wsManager = new WebSocketManager();
2633
+
2634
+ // cli/server/server.ts
2635
+ var __filename = fileURLToPath(import.meta.url);
2636
+ var __dirname = dirname2(__filename);
2637
+ async function createServer(options) {
2638
+ const { controlSetDir, port } = options;
2639
+ if (!existsSync4(controlSetDir)) {
2640
+ mkdirSync3(controlSetDir, { recursive: true });
2641
+ }
2642
+ initializeServerState(controlSetDir);
2643
+ await loadAllData();
2644
+ const app = express2();
2645
+ app.use(cors());
2646
+ app.use(express2.json({ limit: "50mb" }));
2647
+ const distPath = join6(__dirname, "../dist");
2648
+ app.use(express2.static(distPath));
2649
+ app.use("/api", spreadsheetRoutes_default);
2650
+ app.get("*", (req, res) => {
2651
+ res.sendFile(join6(distPath, "index.html"));
2652
+ });
2653
+ const httpServer = createHttpServer(app);
2654
+ wsManager.initialize(httpServer);
2655
+ return {
2656
+ app,
2657
+ start: () => {
2658
+ return new Promise((resolve) => {
2659
+ httpServer.listen(port, () => {
2660
+ console.log(`
2661
+ \u2728 Lula is running at http://localhost:${port}`);
2662
+ resolve();
2663
+ });
2664
+ });
2665
+ }
2666
+ };
2667
+ }
2668
+ async function startServer(options) {
2669
+ const server = await createServer(options);
2670
+ await server.start();
2671
+ if (process.stdin.isTTY) {
2672
+ process.stdin.setRawMode(true);
2673
+ process.stdin.resume();
2674
+ process.stdin.setEncoding("utf8");
2675
+ console.log("\nPress ESC to close the app\n");
2676
+ process.stdin.on("data", async (key) => {
2677
+ const keyStr = key.toString();
2678
+ if (keyStr === "\x1B" || keyStr === "") {
2679
+ console.log("\n\nShutting down server...");
2680
+ try {
2681
+ await saveMappingsToFile();
2682
+ console.log("Changes saved successfully");
2683
+ } catch (error) {
2684
+ console.error("Error saving changes:", error);
2685
+ }
2686
+ process.exit(0);
2687
+ }
2688
+ });
2689
+ }
2690
+ process.on("SIGINT", async () => {
2691
+ try {
2692
+ await saveMappingsToFile();
2693
+ } catch (error) {
2694
+ console.error("Error saving changes:", error);
2695
+ }
2696
+ process.exit(0);
2697
+ });
2698
+ }
2699
+
2700
+ // cli/server/index.ts
2701
+ init_serverState();
2702
+ init_fileStore();
2703
+ init_gitHistory();
2704
+ export {
2705
+ FileStore,
2706
+ GitHistoryUtil,
2707
+ createServer,
2708
+ getServerState,
2709
+ initializeServerState,
2710
+ loadAllData,
2711
+ saveMappingsToFile,
2712
+ startServer
2713
+ };