@mitre/hdf-parsers 3.0.0 → 3.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,55 @@
1
+ # License
2
+
3
+ Copyright © 2025 The MITRE Corporation.
4
+
5
+ Approved for Public Release; Distribution Unlimited. Case Number 18-3678.
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
8
+ not use this file except in compliance with the License. You may obtain a
9
+ copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16
+ License for the specific language governing permissions and limitations
17
+ under the License.
18
+
19
+ ## Redistribution Terms
20
+
21
+ Redistribution and use in source and binary forms, with or without
22
+ modification, are permitted provided that the following conditions are
23
+ met:
24
+
25
+ - Redistributions of source code must retain the above copyright/digital
26
+ rights legend, this list of conditions and the following Notice.
27
+ - Redistributions in binary form must reproduce the above
28
+ copyright/digital rights legend, this list of conditions and the
29
+ following Notice in the documentation and/or other materials provided
30
+ with the distribution.
31
+ - Neither the name of The MITRE Corporation nor the names of its contributors
32
+ may be used to endorse or promote products derived from this software
33
+ without specific prior written permission.
34
+
35
+ ## Notice
36
+
37
+ The MITRE Corporation grants permission to reproduce, distribute, modify, and
38
+ otherwise use this software to the extent permitted by the licensed terms
39
+ provided in the LICENSE file included with this project.
40
+
41
+ This software was produced by The MITRE Corporation for the U.S. Government
42
+ under contract. As such the U.S. Government has certain use and data
43
+ rights in this software. No use other than those granted to the U.S.
44
+ Government, or to those acting on behalf of the U.S. Government, under
45
+ these contract arrangements is authorized without the express written
46
+ permission of The MITRE Corporation.
47
+
48
+ Some files in this codebase were generated by generative AI, under the
49
+ direction and review of The MITRE Corporation employees, for the purpose of
50
+ development efficiency. All AI-generated code functionality was validated
51
+ by standard quality and assurance testing.
52
+
53
+ For further information, please contact The MITRE Corporation,
54
+ Contracts Management Office, 7515 Colshire Drive, McLean, VA 22102-7539,
55
+ (703) 983-6000.
package/README.md CHANGED
@@ -90,7 +90,7 @@ import (
90
90
  "fmt"
91
91
  "os"
92
92
 
93
- parsers "github.com/mitre/hdf-parsers/go"
93
+ parsers "github.com/mitre/hdf-libs/hdf-parsers/go"
94
94
  )
95
95
 
96
96
  func main() {
package/dist/index.d.ts CHANGED
@@ -1,31 +1,64 @@
1
- import type { HdfResults, HdfBaseline } from '@mitre/hdf-schema';
2
- export { flattenOverlays } from './flatten.js';
3
- export type { FlattenResult, FlattenMetadata, BaselineMerge } from './flatten.js';
1
+ import { HdfBaseline, HdfResults } from "@mitre/hdf-schema";
2
+
3
+ //#region typescript/flatten.d.ts
4
+ interface FlattenResult {
5
+ results: HdfResults;
6
+ metadata: FlattenMetadata;
7
+ }
8
+ interface FlattenMetadata {
9
+ originalBaselineCount: number;
10
+ flattenedBaselineCount: number;
11
+ merges: BaselineMerge[];
12
+ warnings: string[];
13
+ }
14
+ interface BaselineMerge {
15
+ rootBaseline: string;
16
+ absorbedBaselines: string[];
17
+ controlsBefore: number;
18
+ controlsAfter: number;
19
+ pattern: 'deep' | 'wide' | 'hybrid';
20
+ }
21
+ /**
22
+ * Flatten overlay/wrapper baselines in an HDF Results document.
23
+ *
24
+ * Handles:
25
+ * - Deep nesting (overlay chains with shared control IDs via parentBaseline)
26
+ * - Wide nesting (wrapper profiles aggregating independent bases)
27
+ * - Hybrid (both patterns in one document)
28
+ *
29
+ * @param results - Parsed HDF Results (from parseResults() or equivalent)
30
+ * @returns FlattenResult with flattened data and merge metadata
31
+ */
32
+ declare function flattenOverlays(results: HdfResults): FlattenResult;
33
+ //#endregion
34
+ //#region typescript/index.d.ts
4
35
  /**
5
36
  * Result of parsing operation
6
37
  */
7
- export interface ParseResult<T> {
8
- success: boolean;
9
- data?: T;
10
- error?: string;
11
- type?: 'results' | 'baseline';
38
+ interface ParseResult<T> {
39
+ success: boolean;
40
+ data?: T;
41
+ error?: string;
42
+ type?: 'results' | 'baseline';
12
43
  }
13
44
  /**
14
45
  * Parse HDF Results document from string or bytes
15
46
  * @param input - JSON string or Uint8Array to parse
16
47
  * @returns ParseResult with parsed data or error
17
48
  */
18
- export declare function parseResults(input: string | Uint8Array): ParseResult<HdfResults>;
49
+ declare function parseResults(input: string | Uint8Array): ParseResult<HdfResults>;
19
50
  /**
20
51
  * Parse HDF Baseline document from string or bytes
21
52
  * @param input - JSON string or Uint8Array to parse
22
53
  * @returns ParseResult with parsed data or error
23
54
  */
24
- export declare function parseBaseline(input: string | Uint8Array): ParseResult<HdfBaseline>;
55
+ declare function parseBaseline(input: string | Uint8Array): ParseResult<HdfBaseline>;
25
56
  /**
26
57
  * Parse HDF document with auto-detection of type
27
58
  * @param input - JSON string or Uint8Array to parse
28
59
  * @returns ParseResult with parsed data, type indicator, or error
29
60
  */
30
- export declare function parse(input: string | Uint8Array): ParseResult<HdfResults | HdfBaseline>;
61
+ declare function parse(input: string | Uint8Array): ParseResult<HdfResults | HdfBaseline>;
62
+ //#endregion
63
+ export { type BaselineMerge, type FlattenMetadata, type FlattenResult, ParseResult, flattenOverlays, parse, parseBaseline, parseResults };
31
64
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../typescript/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAGlF;;GAEG;AACH,MAAM,WAAW,WAAW,CAAC,CAAC;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,CAAC,EAAE,CAAC,CAAC;IACT,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,SAAS,GAAG,UAAU,CAAC;CAC/B;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,GAAG,WAAW,CAAC,UAAU,CAAC,CA+ChF;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,GAAG,WAAW,CAAC,WAAW,CAAC,CA8ClF;AAED;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,GAAG,WAAW,CAAC,UAAU,GAAG,WAAW,CAAC,CAqEvF"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../typescript/flatten.ts","../typescript/index.ts"],"mappings":";;;UAIiB,aAAA;EACf,OAAA,EAAS,UAAA;EACT,QAAA,EAAU,eAAA;AAAA;AAAA,UAGK,eAAA;EACf,qBAAA;EACA,sBAAA;EACA,MAAA,EAAQ,aAAA;EACR,QAAA;AAAA;AAAA,UAGe,aAAA;EACf,YAAA;EACA,iBAAA;EACA,cAAA;EACA,aAAA;EACA,OAAA;AAAA;;;;;;;AALF;;;;;iBAgIgB,eAAA,CAAgB,OAAA,EAAS,UAAA,GAAa,aAAA;;;AA5ItD;;;AAAA,UCIiB,WAAA;EACf,OAAA;EACA,IAAA,GAAO,CAAA;EACP,KAAA;EACA,IAAA;AAAA;;ADHF;;;;iBCWgB,YAAA,CAAa,KAAA,WAAgB,UAAA,GAAa,WAAA,CAAY,UAAA;;;;;;iBAsDtD,aAAA,CAAc,KAAA,WAAgB,UAAA,GAAa,WAAA,CAAY,WAAA;AD1DvE;;;;;AAAA,iBC+GgB,KAAA,CAAM,KAAA,WAAgB,UAAA,GAAa,WAAA,CAAY,UAAA,GAAa,WAAA"}
package/dist/index.js CHANGED
@@ -1,177 +1,303 @@
1
- export { flattenOverlays } from './flatten.js';
2
- import { validateResults, validateBaseline, validate as autoValidate } from '@mitre/hdf-validators';
1
+ import { validate, validateBaseline, validateResults } from "@mitre/hdf-validators";
2
+ //#region typescript/flatten.ts
3
+ /** BFS from root, returns names in top-down order. Cycle-safe. */
4
+ function collectTree(root, childrenMap) {
5
+ const order = [];
6
+ const seen = /* @__PURE__ */ new Set();
7
+ const queue = [root];
8
+ while (queue.length > 0) {
9
+ const name = queue.shift();
10
+ if (seen.has(name)) continue;
11
+ seen.add(name);
12
+ order.push(name);
13
+ for (const child of childrenMap.get(name) || []) queue.push(child);
14
+ }
15
+ return order;
16
+ }
17
+ /** Classify merge pattern based on tree shape */
18
+ function detectPattern(root, childrenMap) {
19
+ const rootChildren = childrenMap.get(root) || [];
20
+ if (rootChildren.length <= 1) return "deep";
21
+ for (const child of rootChildren) if ((childrenMap.get(child) || []).length > 0) return "hybrid";
22
+ return "wide";
23
+ }
24
+ /** Merge incoming requirement fields onto existing */
25
+ function mergeRequirement(existing, incoming) {
26
+ const result = { ...existing };
27
+ result.impact = incoming.impact;
28
+ if (incoming.results && incoming.results.length > 0) result.results = incoming.results;
29
+ if (incoming.code && incoming.code.trim() !== "") result.code = incoming.code;
30
+ if (incoming.tags) result.tags = {
31
+ ...existing.tags,
32
+ ...incoming.tags
33
+ };
34
+ if (incoming.severity !== void 0) result.severity = incoming.severity;
35
+ if (incoming.effectiveStatus !== void 0 && incoming.results && incoming.results.length > 0) result.effectiveStatus = incoming.effectiveStatus;
36
+ if (incoming.descriptions && incoming.descriptions.length > 0) {
37
+ const descMap = new Map((existing.descriptions || []).map((d) => [d.label, d]));
38
+ for (const d of incoming.descriptions) descMap.set(d.label, d);
39
+ result.descriptions = [...descMap.values()];
40
+ }
41
+ return result;
42
+ }
43
+ /**
44
+ * Resolve parentBaseline for a baseline.
45
+ * InSpec parent_profile can use depends-name aliases (e.g., 'k8s' instead of
46
+ * 'k8s-node-stig-baseline'). When the value isn't a direct profile name,
47
+ * find who depends on this baseline — that's the actual parent.
48
+ */
49
+ function resolveParentBaseline(b, byName, allBaselines) {
50
+ if (!b.parentBaseline) return void 0;
51
+ if (byName.has(b.parentBaseline)) return b.parentBaseline;
52
+ for (const candidate of allBaselines) if (candidate.depends?.some((d) => d.name === b.name)) return candidate.name;
53
+ }
54
+ /**
55
+ * Flatten overlay/wrapper baselines in an HDF Results document.
56
+ *
57
+ * Handles:
58
+ * - Deep nesting (overlay chains with shared control IDs via parentBaseline)
59
+ * - Wide nesting (wrapper profiles aggregating independent bases)
60
+ * - Hybrid (both patterns in one document)
61
+ *
62
+ * @param results - Parsed HDF Results (from parseResults() or equivalent)
63
+ * @returns FlattenResult with flattened data and merge metadata
64
+ */
65
+ function flattenOverlays(results) {
66
+ const { baselines } = results;
67
+ const warnings = [];
68
+ const merges = [];
69
+ if (!baselines || baselines.length === 0) return {
70
+ results: {
71
+ ...results,
72
+ baselines: []
73
+ },
74
+ metadata: {
75
+ originalBaselineCount: 0,
76
+ flattenedBaselineCount: 0,
77
+ merges: [],
78
+ warnings: []
79
+ }
80
+ };
81
+ const byName = /* @__PURE__ */ new Map();
82
+ for (const b of baselines) {
83
+ if (byName.has(b.name)) warnings.push(`Duplicate baseline name "${b.name}" — later entry overwrites earlier`);
84
+ byName.set(b.name, b);
85
+ }
86
+ const resolvedParent = /* @__PURE__ */ new Map();
87
+ for (const b of baselines) {
88
+ const parent = resolveParentBaseline(b, byName, baselines);
89
+ resolvedParent.set(b.name, parent);
90
+ if (b.parentBaseline && !parent) warnings.push(`Baseline "${b.name}" references nonexistent parent "${b.parentBaseline}"`);
91
+ }
92
+ const childrenMap = /* @__PURE__ */ new Map();
93
+ for (const b of baselines) {
94
+ const parent = resolvedParent.get(b.name);
95
+ if (parent) {
96
+ const list = childrenMap.get(parent) || [];
97
+ list.push(b.name);
98
+ childrenMap.set(parent, list);
99
+ }
100
+ }
101
+ const roots = [];
102
+ const visited = /* @__PURE__ */ new Set();
103
+ for (const b of baselines) if (!resolvedParent.get(b.name)) roots.push(b.name);
104
+ function markReachable(start) {
105
+ const stack = [start];
106
+ while (stack.length > 0) {
107
+ const name = stack.pop();
108
+ if (visited.has(name)) continue;
109
+ visited.add(name);
110
+ const children = childrenMap.get(name);
111
+ if (children) for (const child of children) stack.push(child);
112
+ }
113
+ }
114
+ for (const r of roots) markReachable(r);
115
+ for (const b of baselines) if (!visited.has(b.name)) {
116
+ warnings.push(`Circular parentBaseline detected involving "${b.name}"`);
117
+ roots.push(b.name);
118
+ markReachable(b.name);
119
+ }
120
+ const flatBaselines = [];
121
+ for (const rootName of roots) {
122
+ const root = byName.get(rootName);
123
+ const treeNames = collectTree(rootName, childrenMap);
124
+ if (treeNames.length === 1) {
125
+ flatBaselines.push(root);
126
+ continue;
127
+ }
128
+ const bottomUp = [...treeNames].reverse();
129
+ const merged = /* @__PURE__ */ new Map();
130
+ let controlsBefore = 0;
131
+ const absorbed = [];
132
+ for (const name of bottomUp) {
133
+ const b = byName.get(name);
134
+ controlsBefore += b.requirements.length;
135
+ if (name !== rootName) absorbed.push(name);
136
+ for (const req of b.requirements) if (merged.has(req.id)) merged.set(req.id, mergeRequirement(merged.get(req.id), req));
137
+ else merged.set(req.id, { ...req });
138
+ }
139
+ const mergedReqs = [...merged.values()];
140
+ const pattern = detectPattern(rootName, childrenMap);
141
+ merges.push({
142
+ rootBaseline: rootName,
143
+ absorbedBaselines: absorbed,
144
+ controlsBefore,
145
+ controlsAfter: mergedReqs.length,
146
+ pattern
147
+ });
148
+ const out = {
149
+ ...root,
150
+ requirements: mergedReqs
151
+ };
152
+ delete out.parentBaseline;
153
+ delete out.depends;
154
+ flatBaselines.push(out);
155
+ }
156
+ return {
157
+ results: {
158
+ ...results,
159
+ baselines: flatBaselines
160
+ },
161
+ metadata: {
162
+ originalBaselineCount: baselines.length,
163
+ flattenedBaselineCount: flatBaselines.length,
164
+ merges,
165
+ warnings
166
+ }
167
+ };
168
+ }
169
+ //#endregion
170
+ //#region typescript/index.ts
3
171
  /**
4
- * Parse HDF Results document from string or bytes
5
- * @param input - JSON string or Uint8Array to parse
6
- * @returns ParseResult with parsed data or error
7
- */
8
- export function parseResults(input) {
9
- // Convert Uint8Array to string if needed
10
- const jsonStr = typeof input === 'string' ? input : new TextDecoder().decode(input);
11
- // Check for empty input
12
- if (jsonStr.trim().length === 0) {
13
- return {
14
- success: false,
15
- error: 'Input is empty'
16
- };
17
- }
18
- // Parse JSON
19
- let data;
20
- try {
21
- data = JSON.parse(jsonStr);
22
- }
23
- catch (err) {
24
- return {
25
- success: false,
26
- error: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`
27
- };
28
- }
29
- // Check for trailing garbage by re-serializing and comparing length
30
- // This catches cases like: {"valid":"json"}garbage
31
- const serialized = JSON.stringify(data);
32
- const trimmedInput = jsonStr.trim();
33
- if (serialized.length !== trimmedInput.length && !isWhitespaceEquivalent(serialized, trimmedInput)) {
34
- return {
35
- success: false,
36
- error: 'Invalid JSON: unexpected trailing data after end of object'
37
- };
38
- }
39
- // Validate against schema
40
- const validationResult = validateResults(data);
41
- if (!validationResult.valid) {
42
- return {
43
- success: false,
44
- error: `Schema validation failed: ${validationResult.getErrorMessage()}`
45
- };
46
- }
47
- return {
48
- success: true,
49
- data: data
50
- };
172
+ * Parse HDF Results document from string or bytes
173
+ * @param input - JSON string or Uint8Array to parse
174
+ * @returns ParseResult with parsed data or error
175
+ */
176
+ function parseResults(input) {
177
+ const jsonStr = typeof input === "string" ? input : new TextDecoder().decode(input);
178
+ if (jsonStr.trim().length === 0) return {
179
+ success: false,
180
+ error: "Input is empty"
181
+ };
182
+ let data;
183
+ try {
184
+ data = JSON.parse(jsonStr);
185
+ } catch (err) {
186
+ return {
187
+ success: false,
188
+ error: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`
189
+ };
190
+ }
191
+ const serialized = JSON.stringify(data);
192
+ const trimmedInput = jsonStr.trim();
193
+ if (serialized.length !== trimmedInput.length && !isWhitespaceEquivalent(serialized, trimmedInput)) return {
194
+ success: false,
195
+ error: "Invalid JSON: unexpected trailing data after end of object"
196
+ };
197
+ const validationResult = validateResults(data);
198
+ if (!validationResult.valid) return {
199
+ success: false,
200
+ error: `Schema validation failed: ${validationResult.getErrorMessage()}`
201
+ };
202
+ return {
203
+ success: true,
204
+ data
205
+ };
51
206
  }
52
207
  /**
53
- * Parse HDF Baseline document from string or bytes
54
- * @param input - JSON string or Uint8Array to parse
55
- * @returns ParseResult with parsed data or error
56
- */
57
- export function parseBaseline(input) {
58
- // Convert Uint8Array to string if needed
59
- const jsonStr = typeof input === 'string' ? input : new TextDecoder().decode(input);
60
- // Check for empty input
61
- if (jsonStr.trim().length === 0) {
62
- return {
63
- success: false,
64
- error: 'Input is empty'
65
- };
66
- }
67
- // Parse JSON
68
- let data;
69
- try {
70
- data = JSON.parse(jsonStr);
71
- }
72
- catch (err) {
73
- return {
74
- success: false,
75
- error: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`
76
- };
77
- }
78
- // Check for trailing garbage
79
- const serialized = JSON.stringify(data);
80
- const trimmedInput = jsonStr.trim();
81
- if (serialized.length !== trimmedInput.length && !isWhitespaceEquivalent(serialized, trimmedInput)) {
82
- return {
83
- success: false,
84
- error: 'Invalid JSON: unexpected trailing data after end of object'
85
- };
86
- }
87
- // Validate against schema
88
- const validationResult = validateBaseline(data);
89
- if (!validationResult.valid) {
90
- return {
91
- success: false,
92
- error: `Schema validation failed: ${validationResult.getErrorMessage()}`
93
- };
94
- }
95
- return {
96
- success: true,
97
- data: data
98
- };
208
+ * Parse HDF Baseline document from string or bytes
209
+ * @param input - JSON string or Uint8Array to parse
210
+ * @returns ParseResult with parsed data or error
211
+ */
212
+ function parseBaseline(input) {
213
+ const jsonStr = typeof input === "string" ? input : new TextDecoder().decode(input);
214
+ if (jsonStr.trim().length === 0) return {
215
+ success: false,
216
+ error: "Input is empty"
217
+ };
218
+ let data;
219
+ try {
220
+ data = JSON.parse(jsonStr);
221
+ } catch (err) {
222
+ return {
223
+ success: false,
224
+ error: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`
225
+ };
226
+ }
227
+ const serialized = JSON.stringify(data);
228
+ const trimmedInput = jsonStr.trim();
229
+ if (serialized.length !== trimmedInput.length && !isWhitespaceEquivalent(serialized, trimmedInput)) return {
230
+ success: false,
231
+ error: "Invalid JSON: unexpected trailing data after end of object"
232
+ };
233
+ const validationResult = validateBaseline(data);
234
+ if (!validationResult.valid) return {
235
+ success: false,
236
+ error: `Schema validation failed: ${validationResult.getErrorMessage()}`
237
+ };
238
+ return {
239
+ success: true,
240
+ data
241
+ };
99
242
  }
100
243
  /**
101
- * Parse HDF document with auto-detection of type
102
- * @param input - JSON string or Uint8Array to parse
103
- * @returns ParseResult with parsed data, type indicator, or error
104
- */
105
- export function parse(input) {
106
- // Convert Uint8Array to string if needed
107
- const jsonStr = typeof input === 'string' ? input : new TextDecoder().decode(input);
108
- // Check for empty input
109
- if (jsonStr.trim().length === 0) {
110
- return {
111
- success: false,
112
- error: 'Input is empty'
113
- };
114
- }
115
- // Parse JSON
116
- let data;
117
- try {
118
- data = JSON.parse(jsonStr);
119
- }
120
- catch (err) {
121
- return {
122
- success: false,
123
- error: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`
124
- };
125
- }
126
- // Check for trailing garbage
127
- const serialized = JSON.stringify(data);
128
- const trimmedInput = jsonStr.trim();
129
- if (serialized.length !== trimmedInput.length && !isWhitespaceEquivalent(serialized, trimmedInput)) {
130
- return {
131
- success: false,
132
- error: 'Invalid JSON: unexpected trailing data after end of object'
133
- };
134
- }
135
- // Auto-validate and detect type
136
- const validationResult = autoValidate(data);
137
- if (!validationResult.valid) {
138
- return {
139
- success: false,
140
- error: `Schema validation failed: ${validationResult.getErrorMessage()}`
141
- };
142
- }
143
- // Determine type based on structure
144
- if (typeof data === 'object' && data !== null) {
145
- const obj = data;
146
- // HDF Results has 'baselines' array at root
147
- if ('baselines' in obj) {
148
- return {
149
- success: true,
150
- data: data,
151
- type: 'results'
152
- };
153
- }
154
- // HDF Baseline has 'name' and 'requirements' at root
155
- if ('name' in obj && 'requirements' in obj) {
156
- return {
157
- success: true,
158
- data: data,
159
- type: 'baseline'
160
- };
161
- }
162
- }
163
- return {
164
- success: false,
165
- error: 'Unable to determine HDF document type'
166
- };
244
+ * Parse HDF document with auto-detection of type
245
+ * @param input - JSON string or Uint8Array to parse
246
+ * @returns ParseResult with parsed data, type indicator, or error
247
+ */
248
+ function parse(input) {
249
+ const jsonStr = typeof input === "string" ? input : new TextDecoder().decode(input);
250
+ if (jsonStr.trim().length === 0) return {
251
+ success: false,
252
+ error: "Input is empty"
253
+ };
254
+ let data;
255
+ try {
256
+ data = JSON.parse(jsonStr);
257
+ } catch (err) {
258
+ return {
259
+ success: false,
260
+ error: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`
261
+ };
262
+ }
263
+ const serialized = JSON.stringify(data);
264
+ const trimmedInput = jsonStr.trim();
265
+ if (serialized.length !== trimmedInput.length && !isWhitespaceEquivalent(serialized, trimmedInput)) return {
266
+ success: false,
267
+ error: "Invalid JSON: unexpected trailing data after end of object"
268
+ };
269
+ const validationResult = validate(data);
270
+ if (!validationResult.valid) return {
271
+ success: false,
272
+ error: `Schema validation failed: ${validationResult.getErrorMessage()}`
273
+ };
274
+ if (typeof data === "object" && data !== null) {
275
+ const obj = data;
276
+ if ("baselines" in obj) return {
277
+ success: true,
278
+ data,
279
+ type: "results"
280
+ };
281
+ if ("name" in obj && "requirements" in obj) return {
282
+ success: true,
283
+ data,
284
+ type: "baseline"
285
+ };
286
+ }
287
+ return {
288
+ success: false,
289
+ error: "Unable to determine HDF document type"
290
+ };
167
291
  }
168
292
  /**
169
- * Check if two JSON strings are equivalent modulo whitespace
170
- * This is a simple heuristic - we check if one is just whitespace-padded version of other
171
- */
293
+ * Check if two JSON strings are equivalent modulo whitespace
294
+ * This is a simple heuristic - we check if one is just whitespace-padded version of other
295
+ */
172
296
  function isWhitespaceEquivalent(a, b) {
173
- // Remove all whitespace and compare
174
- const normalizeWhitespace = (s) => s.replace(/\s+/g, '');
175
- return normalizeWhitespace(a) === normalizeWhitespace(b);
297
+ const normalizeWhitespace = (s) => s.replace(/\s+/g, "");
298
+ return normalizeWhitespace(a) === normalizeWhitespace(b);
176
299
  }
300
+ //#endregion
301
+ export { flattenOverlays, parse, parseBaseline, parseResults };
302
+
177
303
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../typescript/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/C,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,QAAQ,IAAI,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAYpG;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,KAA0B;IACrD,yCAAyC;IACzC,MAAM,OAAO,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAEpF,wBAAwB;IACxB,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAChC,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,gBAAgB;SACxB,CAAC;IACJ,CAAC;IAED,aAAa;IACb,IAAI,IAAa,CAAC;IAClB,IAAI,CAAC;QACH,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,iBAAiB,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE;SAC3E,CAAC;IACJ,CAAC;IAED,oEAAoE;IACpE,mDAAmD;IACnD,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IACxC,MAAM,YA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EAAE,UAAU;aACjB,CAAC;QACJ,CAAC;IACH,CAAC;IAED,OAAO;QACL,OAAO,EAAE,KAAK;QACd,KAAK,EAAE,uCAAuC;KAC/C,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,SAAS,sBAAsB,CAAC,CAAS,EAAE,CAAS;IAClD,oCAAoC;IACpC,MAAM,mBAAmB,GAAG,CAAC,CAAS,EAAU,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IACzE,OAAO,mBAAmB,CAAC,CAAC,CAAC,KAAK,mBAAmB,CAAC,CAAC,CAAC,CAAC;AAC3D,CAAC"}
1
+ {"version":3,"file":"index.js","names":["autoValidate"],"sources":["../typescript/flatten.ts","../typescript/index.ts"],"sourcesContent":["import type { HdfResults, EvaluatedBaseline, EvaluatedRequirement } from '@mitre/hdf-schema';\n\n// ── Public Types ────────────────────────────────────────────\n\nexport interface FlattenResult {\n results: HdfResults;\n metadata: FlattenMetadata;\n}\n\nexport interface FlattenMetadata {\n originalBaselineCount: number;\n flattenedBaselineCount: number;\n merges: BaselineMerge[];\n warnings: string[];\n}\n\nexport interface BaselineMerge {\n rootBaseline: string;\n absorbedBaselines: string[];\n controlsBefore: number;\n controlsAfter: number;\n pattern: 'deep' | 'wide' | 'hybrid';\n}\n\n// ── Internal Helpers ───────────────────────────────────────\n\n/** BFS from root, returns names in top-down order. Cycle-safe. */\nfunction collectTree(root: string, childrenMap: Map<string, string[]>): string[] {\n const order: string[] = [];\n const seen = new Set<string>();\n const queue = [root];\n while (queue.length > 0) {\n const name = queue.shift()!;\n if (seen.has(name)) continue;\n seen.add(name);\n order.push(name);\n for (const child of (childrenMap.get(name) || [])) {\n queue.push(child);\n }\n }\n return order;\n}\n\n/** Classify merge pattern based on tree shape */\nfunction detectPattern(root: string, childrenMap: Map<string, string[]>): 'deep' | 'wide' | 'hybrid' {\n const rootChildren = childrenMap.get(root) || [];\n if (rootChildren.length <= 1) {\n return 'deep';\n }\n for (const child of rootChildren) {\n if ((childrenMap.get(child) || []).length > 0) {\n return 'hybrid';\n }\n }\n return 'wide';\n}\n\n/** Merge incoming requirement fields onto existing */\nfunction mergeRequirement(\n existing: EvaluatedRequirement,\n incoming: EvaluatedRequirement\n): EvaluatedRequirement {\n const result: EvaluatedRequirement = { ...existing };\n\n // Impact: incoming always wins (required field, always present)\n result.impact = incoming.impact;\n\n // Results: keep whichever is non-empty (base has them, overlay doesn't)\n if (incoming.results && incoming.results.length > 0) {\n result.results = incoming.results;\n }\n\n // Code: incoming wins if non-empty\n if (incoming.code && incoming.code.trim() !== '') {\n result.code = incoming.code;\n }\n\n // Tags: shallow merge (incoming keys override)\n if (incoming.tags) {\n result.tags = { ...existing.tags, ...incoming.tags };\n }\n\n // Severity: incoming wins if present, else keep existing\n if (incoming.severity !== undefined) {\n result.severity = incoming.severity;\n }\n\n // EffectiveStatus: incoming wins only if it has results (otherwise its\n // effectiveStatus is a computed artifact from empty results, not intentional).\n // Overlays typically have empty results — the base has the real test results.\n if (incoming.effectiveStatus !== undefined && incoming.results && incoming.results.length > 0) {\n result.effectiveStatus = incoming.effectiveStatus;\n }\n\n // Descriptions: merge by label (incoming overrides same label)\n if (incoming.descriptions && incoming.descriptions.length > 0) {\n const descMap = new Map(\n (existing.descriptions || []).map(d => [d.label, d])\n );\n for (const d of incoming.descriptions) {\n descMap.set(d.label, d);\n }\n result.descriptions = [...descMap.values()];\n }\n\n return result;\n}\n\n/**\n * Resolve parentBaseline for a baseline.\n * InSpec parent_profile can use depends-name aliases (e.g., 'k8s' instead of\n * 'k8s-node-stig-baseline'). When the value isn't a direct profile name,\n * find who depends on this baseline — that's the actual parent.\n */\nfunction resolveParentBaseline(\n b: EvaluatedBaseline,\n byName: Map<string, EvaluatedBaseline>,\n allBaselines: EvaluatedBaseline[]\n): string | undefined {\n if (!b.parentBaseline) return undefined;\n if (byName.has(b.parentBaseline)) return b.parentBaseline;\n\n // Alias resolution: find the profile whose depends array includes this baseline\n for (const candidate of allBaselines) {\n if (candidate.depends?.some((d) => d.name === b.name)) {\n return candidate.name;\n }\n }\n return undefined; // orphan\n}\n\n// ── Public API ──────────────────────────────────────────────\n\n/**\n * Flatten overlay/wrapper baselines in an HDF Results document.\n *\n * Handles:\n * - Deep nesting (overlay chains with shared control IDs via parentBaseline)\n * - Wide nesting (wrapper profiles aggregating independent bases)\n * - Hybrid (both patterns in one document)\n *\n * @param results - Parsed HDF Results (from parseResults() or equivalent)\n * @returns FlattenResult with flattened data and merge metadata\n */\nexport function flattenOverlays(results: HdfResults): FlattenResult {\n const { baselines } = results;\n const warnings: string[] = [];\n const merges: BaselineMerge[] = [];\n\n if (!baselines || baselines.length === 0) {\n return {\n results: { ...results, baselines: [] },\n metadata: {\n originalBaselineCount: 0,\n flattenedBaselineCount: 0,\n merges: [],\n warnings: [],\n },\n };\n }\n\n // Index baselines by name\n const byName = new Map<string, EvaluatedBaseline>();\n for (const b of baselines) {\n if (byName.has(b.name)) {\n warnings.push(`Duplicate baseline name \"${b.name}\" — later entry overwrites earlier`);\n }\n byName.set(b.name, b);\n }\n\n // Resolve parentBaseline aliases and build parent map\n const resolvedParent = new Map<string, string | undefined>();\n for (const b of baselines) {\n const parent = resolveParentBaseline(b, byName, baselines);\n resolvedParent.set(b.name, parent);\n if (b.parentBaseline && !parent) {\n warnings.push(\n `Baseline \"${b.name}\" references nonexistent parent \"${b.parentBaseline}\"`\n );\n }\n }\n\n // Build parent → children adjacency using resolved parents\n const childrenMap = new Map<string, string[]>();\n for (const b of baselines) {\n const parent = resolvedParent.get(b.name);\n if (parent) {\n const list = childrenMap.get(parent) || [];\n list.push(b.name);\n childrenMap.set(parent, list);\n }\n }\n\n // Find roots: no resolved parent\n const roots: string[] = [];\n const visited = new Set<string>();\n\n for (const b of baselines) {\n if (!resolvedParent.get(b.name)) {\n roots.push(b.name);\n }\n }\n\n // Mark reachable from roots (iterative DFS to avoid stack overflow on deep trees)\n function markReachable(start: string): void {\n const stack = [start];\n while (stack.length > 0) {\n const name = stack.pop()!;\n if (visited.has(name)) continue;\n visited.add(name);\n const children = childrenMap.get(name);\n if (children) {\n for (const child of children) {\n stack.push(child);\n }\n }\n }\n }\n for (const r of roots) {\n markReachable(r);\n }\n\n // Detect cycles: unvisited baselines are in cycles\n for (const b of baselines) {\n if (!visited.has(b.name)) {\n warnings.push(`Circular parentBaseline detected involving \"${b.name}\"`);\n roots.push(b.name);\n markReachable(b.name);\n }\n }\n\n // Process each root tree\n const flatBaselines: EvaluatedBaseline[] = [];\n\n for (const rootName of roots) {\n const root = byName.get(rootName)!;\n const treeNames = collectTree(rootName, childrenMap);\n\n if (treeNames.length === 1) {\n // Standalone baseline — pass through unchanged (preserve depends)\n flatBaselines.push(root);\n continue;\n }\n\n // Bottom-up order: reverse top-down BFS\n const bottomUp = [...treeNames].reverse();\n\n // Merge requirements across the tree\n const merged = new Map<string, EvaluatedRequirement>();\n let controlsBefore = 0;\n const absorbed: string[] = [];\n\n for (const name of bottomUp) {\n const b = byName.get(name)!;\n controlsBefore += b.requirements.length;\n if (name !== rootName) {\n absorbed.push(name);\n }\n for (const req of b.requirements) {\n if (merged.has(req.id)) {\n merged.set(req.id, mergeRequirement(merged.get(req.id)!, req));\n } else {\n merged.set(req.id, { ...req });\n }\n }\n }\n\n const mergedReqs = [...merged.values()];\n const pattern = detectPattern(rootName, childrenMap);\n\n merges.push({\n rootBaseline: rootName,\n absorbedBaselines: absorbed,\n controlsBefore,\n controlsAfter: mergedReqs.length,\n pattern,\n });\n\n const out: EvaluatedBaseline = {\n ...root,\n requirements: mergedReqs,\n };\n delete out.parentBaseline;\n delete out.depends;\n flatBaselines.push(out);\n }\n\n return {\n results: { ...results, baselines: flatBaselines },\n metadata: {\n originalBaselineCount: baselines.length,\n flattenedBaselineCount: flatBaselines.length,\n merges,\n warnings,\n },\n };\n}\n","import type { HdfResults, HdfBaseline } from '@mitre/hdf-schema';\nexport { flattenOverlays } from './flatten.js';\nexport type { FlattenResult, FlattenMetadata, BaselineMerge } from './flatten.js';\nimport { validateResults, validateBaseline, validate as autoValidate } from '@mitre/hdf-validators';\n\n/**\n * Result of parsing operation\n */\nexport interface ParseResult<T> {\n success: boolean;\n data?: T;\n error?: string;\n type?: 'results' | 'baseline';\n}\n\n/**\n * Parse HDF Results document from string or bytes\n * @param input - JSON string or Uint8Array to parse\n * @returns ParseResult with parsed data or error\n */\nexport function parseResults(input: string | Uint8Array): ParseResult<HdfResults> {\n // Convert Uint8Array to string if needed\n const jsonStr = typeof input === 'string' ? input : new TextDecoder().decode(input);\n\n // Check for empty input\n if (jsonStr.trim().length === 0) {\n return {\n success: false,\n error: 'Input is empty'\n };\n }\n\n // Parse JSON\n let data: unknown;\n try {\n data = JSON.parse(jsonStr);\n } catch (err) {\n return {\n success: false,\n error: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`\n };\n }\n\n // Check for trailing garbage by re-serializing and comparing length\n // This catches cases like: {\"valid\":\"json\"}garbage\n const serialized = JSON.stringify(data);\n const trimmedInput = jsonStr.trim();\n if (serialized.length !== trimmedInput.length && !isWhitespaceEquivalent(serialized, trimmedInput)) {\n return {\n success: false,\n error: 'Invalid JSON: unexpected trailing data after end of object'\n };\n }\n\n // Validate against schema\n const validationResult = validateResults(data);\n if (!validationResult.valid) {\n return {\n success: false,\n error: `Schema validation failed: ${validationResult.getErrorMessage()}`\n };\n }\n\n return {\n success: true,\n data: data as HdfResults\n };\n}\n\n/**\n * Parse HDF Baseline document from string or bytes\n * @param input - JSON string or Uint8Array to parse\n * @returns ParseResult with parsed data or error\n */\nexport function parseBaseline(input: string | Uint8Array): ParseResult<HdfBaseline> {\n // Convert Uint8Array to string if needed\n const jsonStr = typeof input === 'string' ? input : new TextDecoder().decode(input);\n\n // Check for empty input\n if (jsonStr.trim().length === 0) {\n return {\n success: false,\n error: 'Input is empty'\n };\n }\n\n // Parse JSON\n let data: unknown;\n try {\n data = JSON.parse(jsonStr);\n } catch (err) {\n return {\n success: false,\n error: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`\n };\n }\n\n // Check for trailing garbage\n const serialized = JSON.stringify(data);\n const trimmedInput = jsonStr.trim();\n if (serialized.length !== trimmedInput.length && !isWhitespaceEquivalent(serialized, trimmedInput)) {\n return {\n success: false,\n error: 'Invalid JSON: unexpected trailing data after end of object'\n };\n }\n\n // Validate against schema\n const validationResult = validateBaseline(data);\n if (!validationResult.valid) {\n return {\n success: false,\n error: `Schema validation failed: ${validationResult.getErrorMessage()}`\n };\n }\n\n return {\n success: true,\n data: data as HdfBaseline\n };\n}\n\n/**\n * Parse HDF document with auto-detection of type\n * @param input - JSON string or Uint8Array to parse\n * @returns ParseResult with parsed data, type indicator, or error\n */\nexport function parse(input: string | Uint8Array): ParseResult<HdfResults | HdfBaseline> {\n // Convert Uint8Array to string if needed\n const jsonStr = typeof input === 'string' ? input : new TextDecoder().decode(input);\n\n // Check for empty input\n if (jsonStr.trim().length === 0) {\n return {\n success: false,\n error: 'Input is empty'\n };\n }\n\n // Parse JSON\n let data: unknown;\n try {\n data = JSON.parse(jsonStr);\n } catch (err) {\n return {\n success: false,\n error: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`\n };\n }\n\n // Check for trailing garbage\n const serialized = JSON.stringify(data);\n const trimmedInput = jsonStr.trim();\n if (serialized.length !== trimmedInput.length && !isWhitespaceEquivalent(serialized, trimmedInput)) {\n return {\n success: false,\n error: 'Invalid JSON: unexpected trailing data after end of object'\n };\n }\n\n // Auto-validate and detect type\n const validationResult = autoValidate(data);\n if (!validationResult.valid) {\n return {\n success: false,\n error: `Schema validation failed: ${validationResult.getErrorMessage()}`\n };\n }\n\n // Determine type based on structure\n if (typeof data === 'object' && data !== null) {\n const obj = data as Record<string, unknown>;\n\n // HDF Results has 'baselines' array at root\n if ('baselines' in obj) {\n return {\n success: true,\n data: data as HdfResults,\n type: 'results'\n };\n }\n\n // HDF Baseline has 'name' and 'requirements' at root\n if ('name' in obj && 'requirements' in obj) {\n return {\n success: true,\n data: data as HdfBaseline,\n type: 'baseline'\n };\n }\n }\n\n return {\n success: false,\n error: 'Unable to determine HDF document type'\n };\n}\n\n/**\n * Check if two JSON strings are equivalent modulo whitespace\n * This is a simple heuristic - we check if one is just whitespace-padded version of other\n */\nfunction isWhitespaceEquivalent(a: string, b: string): boolean {\n // Remove all whitespace and compare\n const normalizeWhitespace = (s: string): string => s.replace(/\\s+/g, '');\n return normalizeWhitespace(a) === normalizeWhitespace(b);\n}\n"],"mappings":";;;AA2BA,SAAS,YAAY,MAAc,aAA8C;CAC/E,MAAM,QAAkB,EAAE;CAC1B,MAAM,uBAAO,IAAI,KAAa;CAC9B,MAAM,QAAQ,CAAC,KAAK;AACpB,QAAO,MAAM,SAAS,GAAG;EACvB,MAAM,OAAO,MAAM,OAAO;AAC1B,MAAI,KAAK,IAAI,KAAK,CAAE;AACpB,OAAK,IAAI,KAAK;AACd,QAAM,KAAK,KAAK;AAChB,OAAK,MAAM,SAAU,YAAY,IAAI,KAAK,IAAI,EAAE,CAC9C,OAAM,KAAK,MAAM;;AAGrB,QAAO;;;AAIT,SAAS,cAAc,MAAc,aAAgE;CACnG,MAAM,eAAe,YAAY,IAAI,KAAK,IAAI,EAAE;AAChD,KAAI,aAAa,UAAU,EACzB,QAAO;AAET,MAAK,MAAM,SAAS,aAClB,MAAK,YAAY,IAAI,MAAM,IAAI,EAAE,EAAE,SAAS,EAC1C,QAAO;AAGX,QAAO;;;AAIT,SAAS,iBACP,UACA,UACsB;CACtB,MAAM,SAA+B,EAAE,GAAG,UAAU;AAGpD,QAAO,SAAS,SAAS;AAGzB,KAAI,SAAS,WAAW,SAAS,QAAQ,SAAS,EAChD,QAAO,UAAU,SAAS;AAI5B,KAAI,SAAS,QAAQ,SAAS,KAAK,MAAM,KAAK,GAC5C,QAAO,OAAO,SAAS;AAIzB,KAAI,SAAS,KACX,QAAO,OAAO;EAAE,GAAG,SAAS;EAAM,GAAG,SAAS;EAAM;AAItD,KAAI,SAAS,aAAa,KAAA,EACxB,QAA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AACZ,SAAO;GACL,SAAS;GACT,OAAO,iBAAiB,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;GACzE;;CAIH,MAAM,aAAa,KAAK,UAAU,KAAK;CACvC,MAAM,eAAe,QAAQ,MAAM;AACnC,KAAI,WAAW,WAAW,aAAa,UAAU,CAAC,uBAAuB,YAAY,aAAa,CAChG,QAAO;EACL,SAAS;EACT,OAAO;EACR;CAIH,MAAM,mBAAmBA,SAAa,KAAK;AAC3C,KAAI,CAAC,iBAAiB,MACpB,QAAO;EACL,SAAS;EACT,OAAO,6BAA6B,iBAAiB,iBAAiB;EACvE;AAIH,KAAI,OAAO,SAAS,YAAY,SAAS,MAAM;EAC7C,MAAM,MAAM;AAGZ,MAAI,eAAe,IACjB,QAAO;GACL,SAAS;GACH;GACN,MAAM;GACP;AAIH,MAAI,UAAU,OAAO,kBAAkB,IACrC,QAAO;GACL,SAAS;GACH;GACN,MAAM;GACP;;AAIL,QAAO;EACL,SAAS;EACT,OAAO;EACR;;;;;;AAOH,SAAS,uBAAuB,GAAW,GAAoB;CAE7D,MAAM,uBAAuB,MAAsB,EAAE,QAAQ,QAAQ,GAAG;AACxE,QAAO,oBAAoB,EAAE,KAAK,oBAAoB,EAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitre/hdf-parsers",
3
- "version": "3.0.0",
3
+ "version": "3.1.0-rc.1",
4
4
  "description": "Parse and load HDF documents with validation",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -10,25 +10,13 @@
10
10
  "types": "./dist/index.d.ts",
11
11
  "exports": {
12
12
  ".": {
13
- "import": "./dist/index.js",
14
- "types": "./dist/index.d.ts"
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
15
  }
16
16
  },
17
17
  "files": [
18
18
  "dist"
19
19
  ],
20
- "scripts": {
21
- "build": "pnpm clean && tsc",
22
- "clean": "rimraf dist",
23
- "test": "pnpm run test:ts && pnpm run test:go",
24
- "test:ts": "vitest run",
25
- "test:go": "cd go && go test ./...",
26
- "test:watch": "vitest",
27
- "test:coverage": "vitest run --coverage",
28
- "type-check": "tsc --noEmit",
29
- "lint": "eslint typescript",
30
- "lint:fix": "eslint typescript --fix"
31
- },
32
20
  "repository": {
33
21
  "type": "git",
34
22
  "url": "https://github.com/mitre/hdf-libs.git",
@@ -37,11 +25,11 @@
37
25
  "author": "MITRE Corporation",
38
26
  "license": "Apache-2.0",
39
27
  "dependencies": {
40
- "@mitre/hdf-schema": "workspace:*",
41
- "@mitre/hdf-validators": "workspace:*"
28
+ "@mitre/hdf-schema": "^3.1.0-rc.1",
29
+ "@mitre/hdf-validators": "^3.1.0-rc.1"
42
30
  },
43
31
  "engines": {
44
- "node": ">=20.0.0"
32
+ "node": ">=22.0.0"
45
33
  },
46
34
  "keywords": [
47
35
  "hdf",
@@ -52,5 +40,17 @@
52
40
  "devDependencies": {
53
41
  "@stryker-mutator/core": "^9.5.1",
54
42
  "@stryker-mutator/vitest-runner": "^9.5.1"
43
+ },
44
+ "scripts": {
45
+ "build": "tsdown",
46
+ "clean": "rimraf dist",
47
+ "test": "pnpm run test:ts && pnpm run test:go",
48
+ "test:ts": "vitest run",
49
+ "test:go": "cd go && go test ./...",
50
+ "test:watch": "vitest",
51
+ "test:coverage": "vitest run --coverage",
52
+ "type-check": "tsc --noEmit",
53
+ "lint": "eslint typescript",
54
+ "lint:fix": "eslint typescript --fix"
55
55
  }
56
- }
56
+ }
package/dist/flatten.d.ts DELETED
@@ -1,31 +0,0 @@
1
- import type { HdfResults } from '@mitre/hdf-schema';
2
- export interface FlattenResult {
3
- results: HdfResults;
4
- metadata: FlattenMetadata;
5
- }
6
- export interface FlattenMetadata {
7
- originalBaselineCount: number;
8
- flattenedBaselineCount: number;
9
- merges: BaselineMerge[];
10
- warnings: string[];
11
- }
12
- export interface BaselineMerge {
13
- rootBaseline: string;
14
- absorbedBaselines: string[];
15
- controlsBefore: number;
16
- controlsAfter: number;
17
- pattern: 'deep' | 'wide' | 'hybrid';
18
- }
19
- /**
20
- * Flatten overlay/wrapper baselines in an HDF Results document.
21
- *
22
- * Handles:
23
- * - Deep nesting (overlay chains with shared control IDs via parentBaseline)
24
- * - Wide nesting (wrapper profiles aggregating independent bases)
25
- * - Hybrid (both patterns in one document)
26
- *
27
- * @param results - Parsed HDF Results (from parseResults() or equivalent)
28
- * @returns FlattenResult with flattened data and merge metadata
29
- */
30
- export declare function flattenOverlays(results: HdfResults): FlattenResult;
31
- //# sourceMappingURL=flatten.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"flatten.d.ts","sourceRoot":"","sources":["../typescript/flatten.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAA2C,MAAM,mBAAmB,CAAC;AAI7F,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,UAAU,CAAC;IACpB,QAAQ,EAAE,eAAe,CAAC;CAC3B;AAED,MAAM,WAAW,eAAe;IAC9B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,sBAAsB,EAAE,MAAM,CAAC;IAC/B,MAAM,EAAE,aAAa,EAAE,CAAC;IACxB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAED,MAAM,WAAW,aAAa;IAC5B,YAAY,EAAE,MAAM,CAAC;IACrB,iBAAiB,EAAE,MAAM,EAAE,CAAC;IAC5B,cAAc,EAAE,MAAM,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,QAAQ,CAAC;CACrC;AA+GD;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,UAAU,GAAG,aAAa,CAwJlE"}
package/dist/flatten.js DELETED
@@ -1,235 +0,0 @@
1
- // ── Internal Helpers ───────────────────────────────────────
2
- /** BFS from root, returns names in top-down order. Cycle-safe. */
3
- function collectTree(root, childrenMap) {
4
- const order = [];
5
- const seen = new Set();
6
- const queue = [root];
7
- while (queue.length > 0) {
8
- const name = queue.shift();
9
- if (seen.has(name))
10
- continue;
11
- seen.add(name);
12
- order.push(name);
13
- for (const child of (childrenMap.get(name) || [])) {
14
- queue.push(child);
15
- }
16
- }
17
- return order;
18
- }
19
- /** Classify merge pattern based on tree shape */
20
- function detectPattern(root, childrenMap) {
21
- const rootChildren = childrenMap.get(root) || [];
22
- if (rootChildren.length <= 1) {
23
- return 'deep';
24
- }
25
- for (const child of rootChildren) {
26
- if ((childrenMap.get(child) || []).length > 0) {
27
- return 'hybrid';
28
- }
29
- }
30
- return 'wide';
31
- }
32
- /** Merge incoming requirement fields onto existing */
33
- function mergeRequirement(existing, incoming) {
34
- const result = { ...existing };
35
- // Impact: incoming always wins (required field, always present)
36
- result.impact = incoming.impact;
37
- // Results: keep whichever is non-empty (base has them, overlay doesn't)
38
- if (incoming.results && incoming.results.length > 0) {
39
- result.results = incoming.results;
40
- }
41
- // Code: incoming wins if non-empty
42
- if (incoming.code && incoming.code.trim() !== '') {
43
- result.code = incoming.code;
44
- }
45
- // Tags: shallow merge (incoming keys override)
46
- if (incoming.tags) {
47
- result.tags = { ...existing.tags, ...incoming.tags };
48
- }
49
- // Severity: incoming wins if present, else keep existing
50
- if (incoming.severity !== undefined) {
51
- result.severity = incoming.severity;
52
- }
53
- // EffectiveStatus: incoming wins only if it has results (otherwise its
54
- // effectiveStatus is a computed artifact from empty results, not intentional).
55
- // Overlays typically have empty results — the base has the real test results.
56
- if (incoming.effectiveStatus !== undefined && incoming.results && incoming.results.length > 0) {
57
- result.effectiveStatus = incoming.effectiveStatus;
58
- }
59
- // Descriptions: merge by label (incoming overrides same label)
60
- if (incoming.descriptions && incoming.descriptions.length > 0) {
61
- const descMap = new Map((existing.descriptions || []).map(d => [d.label, d]));
62
- for (const d of incoming.descriptions) {
63
- descMap.set(d.label, d);
64
- }
65
- result.descriptions = [...descMap.values()];
66
- }
67
- return result;
68
- }
69
- /**
70
- * Resolve parentBaseline for a baseline.
71
- * InSpec parent_profile can use depends-name aliases (e.g., 'k8s' instead of
72
- * 'k8s-node-stig-baseline'). When the value isn't a direct profile name,
73
- * find who depends on this baseline — that's the actual parent.
74
- */
75
- function resolveParentBaseline(b, byName, allBaselines) {
76
- if (!b.parentBaseline)
77
- return undefined;
78
- if (byName.has(b.parentBaseline))
79
- return b.parentBaseline;
80
- // Alias resolution: find the profile whose depends array includes this baseline
81
- for (const candidate of allBaselines) {
82
- if (candidate.depends?.some((d) => d.name === b.name)) {
83
- return candidate.name;
84
- }
85
- }
86
- return undefined; // orphan
87
- }
88
- // ── Public API ──────────────────────────────────────────────
89
- /**
90
- * Flatten overlay/wrapper baselines in an HDF Results document.
91
- *
92
- * Handles:
93
- * - Deep nesting (overlay chains with shared control IDs via parentBaseline)
94
- * - Wide nesting (wrapper profiles aggregating independent bases)
95
- * - Hybrid (both patterns in one document)
96
- *
97
- * @param results - Parsed HDF Results (from parseResults() or equivalent)
98
- * @returns FlattenResult with flattened data and merge metadata
99
- */
100
- export function flattenOverlays(results) {
101
- const { baselines } = results;
102
- const warnings = [];
103
- const merges = [];
104
- if (!baselines || baselines.length === 0) {
105
- return {
106
- results: { ...results, baselines: [] },
107
- metadata: {
108
- originalBaselineCount: 0,
109
- flattenedBaselineCount: 0,
110
- merges: [],
111
- warnings: [],
112
- },
113
- };
114
- }
115
- // Index baselines by name
116
- const byName = new Map();
117
- for (const b of baselines) {
118
- if (byName.has(b.name)) {
119
- warnings.push(`Duplicate baseline name "${b.name}" — later entry overwrites earlier`);
120
- }
121
- byName.set(b.name, b);
122
- }
123
- // Resolve parentBaseline aliases and build parent map
124
- const resolvedParent = new Map();
125
- for (const b of baselines) {
126
- const parent = resolveParentBaseline(b, byName, baselines);
127
- resolvedParent.set(b.name, parent);
128
- if (b.parentBaseline && !parent) {
129
- warnings.push(`Baseline "${b.name}" references nonexistent parent "${b.parentBaseline}"`);
130
- }
131
- }
132
- // Build parent → children adjacency using resolved parents
133
- const childrenMap = new Map();
134
- for (const b of baselines) {
135
- const parent = resolvedParent.get(b.name);
136
- if (parent) {
137
- const list = childrenMap.get(parent) || [];
138
- list.push(b.name);
139
- childrenMap.set(parent, list);
140
- }
141
- }
142
- // Find roots: no resolved parent
143
- const roots = [];
144
- const visited = new Set();
145
- for (const b of baselines) {
146
- if (!resolvedParent.get(b.name)) {
147
- roots.push(b.name);
148
- }
149
- }
150
- // Mark reachable from roots (iterative DFS to avoid stack overflow on deep trees)
151
- function markReachable(start) {
152
- const stack = [start];
153
- while (stack.length > 0) {
154
- const name = stack.pop();
155
- if (visited.has(name))
156
- continue;
157
- visited.add(name);
158
- const children = childrenMap.get(name);
159
- if (children) {
160
- for (const child of children) {
161
- stack.push(child);
162
- }
163
- }
164
- }
165
- }
166
- for (const r of roots) {
167
- markReachable(r);
168
- }
169
- // Detect cycles: unvisited baselines are in cycles
170
- for (const b of baselines) {
171
- if (!visited.has(b.name)) {
172
- warnings.push(`Circular parentBaseline detected involving "${b.name}"`);
173
- roots.push(b.name);
174
- markReachable(b.name);
175
- }
176
- }
177
- // Process each root tree
178
- const flatBaselines = [];
179
- for (const rootName of roots) {
180
- const root = byName.get(rootName);
181
- const treeNames = collectTree(rootName, childrenMap);
182
- if (treeNames.length === 1) {
183
- // Standalone baseline — pass through unchanged (preserve depends)
184
- flatBaselines.push(root);
185
- continue;
186
- }
187
- // Bottom-up order: reverse top-down BFS
188
- const bottomUp = [...treeNames].reverse();
189
- // Merge requirements across the tree
190
- const merged = new Map();
191
- let controlsBefore = 0;
192
- const absorbed = [];
193
- for (const name of bottomUp) {
194
- const b = byName.get(name);
195
- controlsBefore += b.requirements.length;
196
- if (name !== rootName) {
197
- absorbed.push(name);
198
- }
199
- for (const req of b.requirements) {
200
- if (merged.has(req.id)) {
201
- merged.set(req.id, mergeRequirement(merged.get(req.id), req));
202
- }
203
- else {
204
- merged.set(req.id, { ...req });
205
- }
206
- }
207
- }
208
- const mergedReqs = [...merged.values()];
209
- const pattern = detectPattern(rootName, childrenMap);
210
- merges.push({
211
- rootBaseline: rootName,
212
- absorbedBaselines: absorbed,
213
- controlsBefore,
214
- controlsAfter: mergedReqs.length,
215
- pattern,
216
- });
217
- const out = {
218
- ...root,
219
- requirements: mergedReqs,
220
- };
221
- delete out.parentBaseline;
222
- delete out.depends;
223
- flatBaselines.push(out);
224
- }
225
- return {
226
- results: { ...results, baselines: flatBaselines },
227
- metadata: {
228
- originalBaselineCount: baselines.length,
229
- flattenedBaselineCount: flatBaselines.length,
230
- merges,
231
- warnings,
232
- },
233
- };
234
- }
235
- //# sourceMappingURL=flatten.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"flatten.js","sourceRoot":"","sources":["../typescript/flatten.ts"],"names":[],"mappings":"AAwBA,8DAA8D;AAE9D,kEAAkE;AAClE,SAAS,WAAW,CAAC,IAAY,EAAE,WAAkC;IACnE,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,MAAM,KAAK,GAAG,CAAC,IAAI,CAAC,CAAC;IACrB,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACxB,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,EAAG,CAAC;QAC5B,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;YAAE,SAAS;QAC7B,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACf,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjB,KAAK,MAAM,KAAK,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;YAClD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACpB,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,iDAAiD;AACjD,SAAS,aAAa,CAAC,IAAY,EAAE,WAAkC;IACrE,MAAM,YAAY,GAAG,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,C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