@jini-ai/devops 0.3.3 → 0.5.0

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 (104) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/README.md +65 -5
  3. package/dist/agent-jobs/entry.d.ts +4 -0
  4. package/dist/agent-jobs/entry.js +4 -0
  5. package/dist/agent-jobs/jobs.d.ts +25 -0
  6. package/dist/agent-jobs/jobs.js +115 -0
  7. package/dist/agent-jobs/node.d.ts +12 -0
  8. package/dist/agent-jobs/node.js +53 -0
  9. package/dist/agent-jobs/ports.d.ts +69 -0
  10. package/dist/agent-jobs/ports.js +2 -0
  11. package/dist/checks/coverage/diff.d.ts +57 -0
  12. package/dist/checks/coverage/diff.js +48 -0
  13. package/dist/checks/coverage/disk.d.ts +65 -0
  14. package/dist/checks/coverage/disk.js +136 -0
  15. package/dist/checks/coverage/floors.d.ts +31 -0
  16. package/dist/checks/coverage/floors.js +24 -0
  17. package/dist/checks/coverage/index.d.ts +7 -0
  18. package/dist/checks/coverage/index.js +6 -0
  19. package/dist/checks/coverage/integrity.d.ts +79 -0
  20. package/dist/checks/coverage/integrity.js +140 -0
  21. package/dist/checks/coverage/lcov.d.ts +65 -0
  22. package/dist/checks/coverage/lcov.js +64 -0
  23. package/dist/checks/node.d.ts +19 -0
  24. package/dist/checks/node.js +40 -0
  25. package/dist/checks/ports.d.ts +67 -0
  26. package/dist/checks/ports.js +2 -0
  27. package/dist/checks/published-types/index.d.ts +77 -0
  28. package/dist/checks/published-types/index.js +186 -0
  29. package/dist/deploy/host-kit.d.ts +27 -10
  30. package/dist/deploy/index.d.ts +0 -4
  31. package/dist/deploy/index.js +0 -4
  32. package/dist/deploy/naming.d.ts +9 -6
  33. package/dist/deploy/naming.js +5 -7
  34. package/dist/deploy/node.d.ts +18 -0
  35. package/dist/deploy/node.js +57 -0
  36. package/dist/deploy/reachability.d.ts +47 -18
  37. package/dist/deploy/reachability.js +77 -71
  38. package/dist/deploy/redirect-guard.d.ts +15 -11
  39. package/dist/deploy/redirect-guard.js +11 -12
  40. package/dist/deploy/tokens.d.ts +17 -14
  41. package/dist/deploy/tokens.js +16 -16
  42. package/dist/deploy/tool.d.ts +12 -8
  43. package/dist/deploy/tool.js +9 -10
  44. package/dist/deploy/types.d.ts +27 -15
  45. package/dist/deploy/types.js +3 -3
  46. package/dist/index.d.ts +2 -1
  47. package/dist/index.js +2 -1
  48. package/dist/local-dev/index.d.ts +34 -0
  49. package/dist/local-dev/index.js +37 -0
  50. package/dist/packaging/electron/archive.d.ts +41 -0
  51. package/dist/packaging/electron/archive.js +77 -0
  52. package/dist/packaging/electron/asar-adapter.d.ts +13 -0
  53. package/dist/packaging/electron/asar-adapter.js +5 -0
  54. package/dist/packaging/electron/entry.d.ts +9 -0
  55. package/dist/packaging/electron/entry.js +9 -0
  56. package/dist/packaging/electron/imports.d.ts +13 -0
  57. package/dist/packaging/electron/imports.js +44 -0
  58. package/dist/packaging/electron/node.d.ts +8 -0
  59. package/dist/packaging/electron/node.js +51 -0
  60. package/dist/packaging/electron/policies.d.ts +64 -0
  61. package/dist/packaging/electron/policies.js +63 -0
  62. package/dist/packaging/electron/ports.d.ts +113 -0
  63. package/dist/packaging/electron/ports.js +2 -0
  64. package/dist/packaging/electron/stability.d.ts +9 -0
  65. package/dist/packaging/electron/stability.js +12 -0
  66. package/dist/packaging/electron/staging.d.ts +108 -0
  67. package/dist/packaging/electron/staging.js +249 -0
  68. package/dist/packaging/electron/typescript.d.ts +7 -0
  69. package/dist/packaging/electron/typescript.js +18 -0
  70. package/dist/source-control/commit.d.ts +11 -0
  71. package/dist/source-control/commit.js +71 -0
  72. package/dist/source-control/contracts.d.ts +327 -0
  73. package/dist/source-control/contracts.js +2 -0
  74. package/dist/source-control/entry.d.ts +6 -0
  75. package/dist/source-control/entry.js +6 -0
  76. package/dist/source-control/kit.d.ts +15 -0
  77. package/dist/source-control/kit.js +17 -0
  78. package/dist/source-control/registry.d.ts +100 -0
  79. package/dist/source-control/registry.js +174 -0
  80. package/dist/source-control/repository-target.d.ts +13 -0
  81. package/dist/source-control/repository-target.js +28 -0
  82. package/dist/static-export/contracts.d.ts +138 -0
  83. package/dist/static-export/contracts.js +5 -0
  84. package/dist/static-export/entry.d.ts +6 -0
  85. package/dist/static-export/entry.js +6 -0
  86. package/dist/static-export/failure-summary.d.ts +12 -0
  87. package/dist/static-export/failure-summary.js +12 -0
  88. package/dist/static-export/fetch-adapter.d.ts +6 -0
  89. package/dist/static-export/fetch-adapter.js +5 -0
  90. package/dist/static-export/node-adapters.d.ts +11 -0
  91. package/dist/static-export/node-adapters.js +111 -0
  92. package/dist/static-export/runner.d.ts +6 -0
  93. package/dist/static-export/runner.js +135 -0
  94. package/dist/static-export/transforms.d.ts +53 -0
  95. package/dist/static-export/transforms.js +154 -0
  96. package/package.json +82 -5
  97. package/dist/deploy/cloudflare-pages.d.ts +0 -105
  98. package/dist/deploy/cloudflare-pages.js +0 -943
  99. package/dist/deploy/github-pages.d.ts +0 -62
  100. package/dist/deploy/github-pages.js +0 -373
  101. package/dist/deploy/netlify.d.ts +0 -40
  102. package/dist/deploy/netlify.js +0 -299
  103. package/dist/deploy/vercel.d.ts +0 -56
  104. package/dist/deploy/vercel.js +0 -258
@@ -0,0 +1,65 @@
1
+ export interface LcovCounters {
2
+ lf: number;
3
+ lh: number;
4
+ brf: number;
5
+ brh: number;
6
+ fnf: number;
7
+ fnh: number;
8
+ }
9
+ export type CoverageAxis = "line" | "branch" | "funcs";
10
+ export interface CoverageArea {
11
+ id: string;
12
+ dirs?: readonly string[];
13
+ excludeDirs?: readonly string[];
14
+ extensions?: readonly string[];
15
+ floors?: Partial<Record<CoverageAxis, number>>;
16
+ knownUnmeasured?: readonly string[];
17
+ minFilesOnDisk?: number;
18
+ }
19
+ export interface RunnerGlobs {
20
+ nodeArgs: readonly string[];
21
+ globs: readonly string[];
22
+ }
23
+ export interface TestPass extends RunnerGlobs {
24
+ id: string;
25
+ }
26
+ export interface DiskAreaResult {
27
+ id: string;
28
+ actual: Record<CoverageAxis, number>;
29
+ measuredCount: number;
30
+ onDiskCount: number;
31
+ unmeasured: string[];
32
+ newlyUnmeasured: string[];
33
+ recovered: string[];
34
+ failures: string[];
35
+ }
36
+ /** Exclude test and declaration filenames from a production-source inventory. */
37
+ export declare function isMeasurableSource({ file: relPath }: {
38
+ file: string;
39
+ }): boolean;
40
+ /** Match excluded directories on segment boundaries. */
41
+ export declare function isInExcludedDir({ file: relPath, excludeDirs }: {
42
+ file: string;
43
+ excludeDirs: readonly string[];
44
+ }): boolean;
45
+ /** Read a chain of node test commands into runner/glob records; reject other commands. */
46
+ export declare function parseNodeTestScript({ script }: {
47
+ script: string;
48
+ }): RunnerGlobs[];
49
+ /** Report every runner/glob mismatch between two explicitly supplied inventories. */
50
+ export declare function runnerSplitDrift({ passes, scriptPasses }: {
51
+ passes: readonly RunnerGlobs[];
52
+ scriptPasses: readonly RunnerGlobs[];
53
+ }): string[];
54
+ /** Evaluate floors against an independently supplied source inventory and declared gaps. */
55
+ export declare function evaluateDiskArea({ area, onDisk, coverage }: {
56
+ area: CoverageArea;
57
+ onDisk: readonly string[];
58
+ coverage: ReadonlyMap<string, LcovCounters>;
59
+ }): DiskAreaResult;
60
+ /** Render floors and every measured/unmeasured source path in an area. */
61
+ export declare function formatDiskArea({ result, area }: {
62
+ result: DiskAreaResult;
63
+ area: CoverageArea;
64
+ }): string;
65
+ //# sourceMappingURL=disk.d.ts.map
@@ -0,0 +1,136 @@
1
+ import { pct } from './lcov.js';
2
+ /** Exclude test and declaration filenames from a production-source inventory. */
3
+ export function isMeasurableSource({ file: relPath }) {
4
+ if (/\.(test|spec)\.(js|cjs|mjs|ts|tsx|mts)$/.test(relPath))
5
+ return false;
6
+ if (relPath.endsWith(".d.ts"))
7
+ return false;
8
+ return true;
9
+ }
10
+ /** Match excluded directories on segment boundaries. */
11
+ export function isInExcludedDir({ file: relPath, excludeDirs }) {
12
+ return excludeDirs.some((dir) => {
13
+ const base = dir.replace(/\/+$/, "");
14
+ return relPath === base || relPath.startsWith(`${base}/`);
15
+ });
16
+ }
17
+ /** Read a chain of node test commands into runner/glob records; reject other commands. */
18
+ export function parseNodeTestScript({ script }) {
19
+ return script.split("&&").map((command) => {
20
+ const tokens = [...command.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2]);
21
+ const testAt = tokens.indexOf("--test");
22
+ if (tokens[0] !== "node" || testAt < 0) {
23
+ throw new Error(`not a "node [args] --test <globs>" command: ${command.trim()}`);
24
+ }
25
+ return { nodeArgs: tokens.slice(1, testAt), globs: tokens.slice(testAt + 1) };
26
+ });
27
+ }
28
+ function globsByRunner(passes) {
29
+ const byRunner = new Map();
30
+ for (const pass of passes) {
31
+ const runner = ["node", ...pass.nodeArgs].join(" ");
32
+ const globs = byRunner.get(runner) ?? new Set();
33
+ for (const glob of pass.globs)
34
+ globs.add(glob);
35
+ byRunner.set(runner, globs);
36
+ }
37
+ return byRunner;
38
+ }
39
+ function unmatchedGlobs(side, other) {
40
+ const unmatched = [];
41
+ for (const [runner, globs] of side) {
42
+ for (const glob of globs)
43
+ if (!other.get(runner)?.has(glob))
44
+ unmatched.push({ runner, glob });
45
+ }
46
+ return unmatched;
47
+ }
48
+ /** Report every runner/glob mismatch between two explicitly supplied inventories. */
49
+ export function runnerSplitDrift({ passes, scriptPasses }) {
50
+ const inPasses = globsByRunner(passes);
51
+ const inScript = globsByRunner(scriptPasses);
52
+ return [
53
+ ...unmatchedGlobs(inScript, inPasses).map(({ runner, glob }) => `package.json runs ${glob} under "${runner}"; TEST_PASSES does not`),
54
+ ...unmatchedGlobs(inPasses, inScript).map(({ runner, glob }) => `TEST_PASSES runs ${glob} under "${runner}"; package.json does not`),
55
+ ];
56
+ }
57
+ function total(records) {
58
+ const sum = { lf: 0, lh: 0, brf: 0, brh: 0, fnf: 0, fnh: 0 };
59
+ for (const r of records) {
60
+ sum.lf += r.lf;
61
+ sum.lh += r.lh;
62
+ sum.brf += r.brf;
63
+ sum.brh += r.brh;
64
+ sum.fnf += r.fnf;
65
+ sum.fnh += r.fnh;
66
+ }
67
+ return sum;
68
+ }
69
+ function floorFailures(area, measured) {
70
+ const actual = {
71
+ line: pct({ hit: measured.lh, found: measured.lf }),
72
+ branch: pct({ hit: measured.brh, found: measured.brf }),
73
+ funcs: pct({ hit: measured.fnh, found: measured.fnf }),
74
+ };
75
+ const failures = [];
76
+ for (const axis of ["line", "branch", "funcs"]) {
77
+ const floor = area.floors?.[axis];
78
+ if (typeof floor === "number" && actual[axis] < floor) {
79
+ failures.push(`${axis} ${actual[axis].toFixed(2)}% < floor ${floor}%`);
80
+ }
81
+ }
82
+ return { actual, failures };
83
+ }
84
+ /** Evaluate floors against an independently supplied source inventory and declared gaps. */
85
+ export function evaluateDiskArea({ area, onDisk, coverage }) {
86
+ const diskPaths = [...new Set(onDisk)];
87
+ const known = new Set(area.knownUnmeasured ?? []);
88
+ const measuredPaths = diskPaths.filter((p) => coverage.has(p));
89
+ const unmeasured = diskPaths.filter((p) => !coverage.has(p));
90
+ const measured = total(measuredPaths.map((p) => coverage.get(p)));
91
+ const { actual, failures } = floorFailures(area, measured);
92
+ const newlyUnmeasured = unmeasured.filter((p) => !known.has(p));
93
+ if (newlyUnmeasured.length > 0) {
94
+ failures.push(`${newlyUnmeasured.length} file(s) have NO coverage record and are not in knownUnmeasured: ` +
95
+ `${newlyUnmeasured.join(", ")}. Add a test, or grandfather them explicitly with a reason.`);
96
+ }
97
+ const minOnDisk = area.minFilesOnDisk ?? 1;
98
+ if (diskPaths.length < minOnDisk) {
99
+ failures.push(`only ${diskPaths.length} file(s) found on disk, expected at least ${minOnDisk}. ` +
100
+ `The glob is stale (directory renamed?) or the scan is broken — this is NOT a pass.`);
101
+ }
102
+ const recovered = [...known].filter((p) => coverage.has(p));
103
+ return {
104
+ id: area.id,
105
+ actual,
106
+ measuredCount: measuredPaths.length,
107
+ onDiskCount: diskPaths.length,
108
+ unmeasured,
109
+ newlyUnmeasured,
110
+ recovered,
111
+ failures,
112
+ };
113
+ }
114
+ /** Render floors and every measured/unmeasured source path in an area. */
115
+ export function formatDiskArea({ result, area }) {
116
+ const lines = [` ${result.failures.length === 0 ? "OK " : "FAIL"} ${result.id}`];
117
+ const floors = area.floors ?? {};
118
+ for (const axis of ["line", "branch", "funcs"]) {
119
+ const floor = floors[axis];
120
+ const shown = `${result.actual[axis].toFixed(2)}%`;
121
+ lines.push(` ${axis.padEnd(6)} ${shown.padStart(7)} ${typeof floor === "number" ? `(floor ${floor}%)` : "(no floor configured)"}`);
122
+ }
123
+ lines.push(` files: ${result.measuredCount} measured of ${result.onDiskCount} on disk`);
124
+ if (result.unmeasured.length > 0) {
125
+ lines.push(` UNMEASURED (${result.unmeasured.length}, known gap — no test loads these):`);
126
+ for (const p of result.unmeasured)
127
+ lines.push(` - ${p}`);
128
+ }
129
+ if (result.recovered.length > 0) {
130
+ lines.push(` NOW COVERED, remove from knownUnmeasured: ${result.recovered.join(", ")}`);
131
+ }
132
+ for (const f of result.failures)
133
+ lines.push(` ! ${f}`);
134
+ return lines.join("\n");
135
+ }
136
+ //# sourceMappingURL=disk.js.map
@@ -0,0 +1,31 @@
1
+ import type { FileCoverage, SourceClassifier } from './lcov.js';
2
+ export interface CoverageFloor {
3
+ line: number;
4
+ branch: number;
5
+ funcs: number;
6
+ }
7
+ export interface AreaFloor extends CoverageFloor {
8
+ prefix: string;
9
+ }
10
+ export interface FloorResult {
11
+ count: number;
12
+ line: number;
13
+ branch: number;
14
+ funcs: number;
15
+ failures: readonly string[];
16
+ }
17
+ export interface AreaFloorResult extends FloorResult {
18
+ area: AreaFloor;
19
+ }
20
+ /** Aggregate counters before comparing percentages; an empty measurable scope always fails. */
21
+ export declare function evaluateFloor({ files, floors }: {
22
+ files: readonly FileCoverage[];
23
+ floors: CoverageFloor;
24
+ }): FloorResult;
25
+ /** Evaluate one declared area with a host classifier; the prefix must match whole directories. */
26
+ export declare function evaluateArea({ area, all, isMeasurable }: {
27
+ area: AreaFloor;
28
+ all: readonly FileCoverage[];
29
+ isMeasurable: SourceClassifier;
30
+ }): AreaFloorResult;
31
+ //# sourceMappingURL=floors.d.ts.map
@@ -0,0 +1,24 @@
1
+ import { pct } from './lcov.js';
2
+ /** Aggregate counters before comparing percentages; an empty measurable scope always fails. */
3
+ export function evaluateFloor({ files, floors }) {
4
+ for (const value of Object.values(floors))
5
+ if (!Number.isFinite(value) || value < 0 || value > 100)
6
+ throw new RangeError('coverage floors must be percentages from 0 to 100');
7
+ const totals = files.reduce((sum, record) => ({ lf: sum.lf + record.lf, lh: sum.lh + record.lh, brf: sum.brf + record.brf, brh: sum.brh + record.brh, fnf: sum.fnf + record.fnf, fnh: sum.fnh + record.fnh }), { lf: 0, lh: 0, brf: 0, brh: 0, fnf: 0, fnh: 0 });
8
+ const actual = { line: pct({ hit: totals.lh, found: totals.lf }), branch: pct({ hit: totals.brh, found: totals.brf }), funcs: pct({ hit: totals.fnh, found: totals.fnf }) };
9
+ const failures = [];
10
+ if (files.length === 0)
11
+ failures.push('0 measurable files');
12
+ else
13
+ for (const axis of ['line', 'branch', 'funcs'])
14
+ if (actual[axis] < floors[axis])
15
+ failures.push(`${axis} ${actual[axis].toFixed(2)}% < floor ${floors[axis]}%`);
16
+ return { count: files.length, ...actual, failures };
17
+ }
18
+ /** Evaluate one declared area with a host classifier; the prefix must match whole directories. */
19
+ export function evaluateArea({ area, all, isMeasurable }) {
20
+ const prefix = `${area.prefix.replace(/\/+$/, '')}/`;
21
+ const files = all.filter((record) => record.file.startsWith(prefix) && isMeasurable({ file: record.file }));
22
+ return { area, ...evaluateFloor({ files, floors: { line: area.line, branch: area.branch, funcs: area.funcs } }) };
23
+ }
24
+ //# sourceMappingURL=floors.js.map
@@ -0,0 +1,7 @@
1
+ export * from './lcov.js';
2
+ export * from './floors.js';
3
+ export * from './diff.js';
4
+ export * from './integrity.js';
5
+ export * from './disk.js';
6
+ export type { SourceReaderPort } from '../ports.js';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,6 @@
1
+ export * from './lcov.js';
2
+ export * from './floors.js';
3
+ export * from './diff.js';
4
+ export * from './integrity.js';
5
+ export * from './disk.js';
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,79 @@
1
+ import type { SourceClassifier } from './lcov.js';
2
+ export interface LcovBlock {
3
+ readonly file: string;
4
+ readonly fnda: ReadonlyArray<{
5
+ readonly name: string;
6
+ readonly hits: number;
7
+ }>;
8
+ readonly da: ReadonlyArray<number>;
9
+ readonly fnf?: number | undefined;
10
+ readonly fnh?: number | undefined;
11
+ }
12
+ export type BlockStatus = "contaminated" | "ok" | "skip";
13
+ export interface BlockVerdict {
14
+ readonly file: string;
15
+ readonly status: BlockStatus;
16
+ readonly severe: boolean;
17
+ readonly reason: string;
18
+ }
19
+ export interface IntegrityReport {
20
+ readonly contaminated: readonly BlockVerdict[];
21
+ readonly evaluated: number;
22
+ readonly skipped: number;
23
+ }
24
+ export interface GatedVerdict extends BlockVerdict {
25
+ readonly baselined: boolean;
26
+ readonly fails: boolean;
27
+ }
28
+ /** Apply path-based debt: severe contamination can never be suppressed. */
29
+ export declare function applyBaseline({ contaminated, baselineSet }: {
30
+ contaminated: readonly BlockVerdict[];
31
+ baselineSet: ReadonlySet<string>;
32
+ }): readonly GatedVerdict[];
33
+ /** Read the caller-provided baseline JSON; an absent ledger is empty. */
34
+ export declare function parseBaseline({ baselineJson }: {
35
+ baselineJson: string;
36
+ }): ReadonlySet<string>;
37
+ export declare const DEFAULT_BASELINE_COMMENT: readonly string[];
38
+ /** Serialize deduplicated, sorted debt paths for reviewable changes. */
39
+ export declare function serializeBaseline({ paths }: {
40
+ paths: readonly string[];
41
+ }, { comment }?: {
42
+ comment?: readonly string[] | undefined;
43
+ }): string;
44
+ export interface ParsedArgs {
45
+ readonly lcovArg?: string | undefined;
46
+ readonly baselinePath?: string | undefined;
47
+ readonly updateBaseline: boolean;
48
+ }
49
+ /** Parse coverage artifact and baseline CLI arguments without process globals. */
50
+ export declare function parseArgs({ argv }: {
51
+ argv: readonly string[];
52
+ }): ParsedArgs;
53
+ /** Parse function and line hit records, preserving summaries when present. */
54
+ export declare function parseLcovBlocks({ lcovText }: {
55
+ lcovText: string;
56
+ }): LcovBlock[];
57
+ /** Recognize plain re-export barrels using the inherited source-text heuristic. */
58
+ export declare function isPureReExportBarrelSource({ sourceText }: {
59
+ sourceText: string;
60
+ }): boolean;
61
+ /** Classify esbuild interop contamination using the host source classifier. */
62
+ export declare function classifyBlock({ block, repoRoot, isFirstParty }: {
63
+ block: LcovBlock;
64
+ repoRoot: string;
65
+ isFirstParty: SourceClassifier;
66
+ }, { sourceText }?: {
67
+ sourceText?: string | undefined;
68
+ }): BlockVerdict;
69
+ /** Evaluate supplied LCOV text and an optional host source reader, without disk I/O. */
70
+ export declare function checkCoverageIntegrity({ lcovText, repoRoot, isFirstParty }: {
71
+ lcovText: string;
72
+ repoRoot: string;
73
+ isFirstParty: SourceClassifier;
74
+ }, { readSource }?: {
75
+ readSource?: ((args: {
76
+ file: string;
77
+ }) => string | undefined) | undefined;
78
+ }): IntegrityReport;
79
+ //# sourceMappingURL=integrity.d.ts.map
@@ -0,0 +1,140 @@
1
+ import { toRepoRelative } from './lcov.js';
2
+ const WRAPPER_HELPER_NAMES = new Set(["__toCommonJS", "__copyProps", "__toESM", "__export"]);
3
+ const MIN_DA_RECORDS_FOR_SEVERE_HEURISTIC = 30;
4
+ /** Apply path-based debt: severe contamination can never be suppressed. */
5
+ export function applyBaseline({ contaminated, baselineSet }) {
6
+ return contaminated.map((v) => {
7
+ const baselined = baselineSet.has(v.file);
8
+ return { ...v, baselined, fails: v.severe || !baselined };
9
+ });
10
+ }
11
+ /** Read the caller-provided baseline JSON; an absent ledger is empty. */
12
+ export function parseBaseline({ baselineJson }) {
13
+ const parsed = JSON.parse(baselineJson);
14
+ return new Set(parsed.knownContaminated ?? []);
15
+ }
16
+ export const DEFAULT_BASELINE_COMMENT = [
17
+ 'Known, reviewed coverage-contamination debt, recorded by path.',
18
+ 'Severe findings always fail regardless of baseline membership.',
19
+ ];
20
+ /** Serialize deduplicated, sorted debt paths for reviewable changes. */
21
+ export function serializeBaseline({ paths }, { comment = DEFAULT_BASELINE_COMMENT } = {}) {
22
+ const knownContaminated = [...new Set(paths)].sort((a, b) => a.localeCompare(b));
23
+ return `${JSON.stringify({ _comment: comment, knownContaminated }, null, 2)}\n`;
24
+ }
25
+ /** Parse coverage artifact and baseline CLI arguments without process globals. */
26
+ export function parseArgs({ argv }) {
27
+ let lcovArg;
28
+ let baselinePath;
29
+ let updateBaseline = false;
30
+ for (let i = 0; i < argv.length; i++) {
31
+ const arg = argv[i];
32
+ if (arg === "--update-baseline") {
33
+ updateBaseline = true;
34
+ }
35
+ else if (arg === "--baseline") {
36
+ baselinePath = argv[i + 1];
37
+ i++; // consume the flag's value too
38
+ }
39
+ else if (!arg.startsWith("--") && lcovArg === undefined) {
40
+ lcovArg = arg;
41
+ }
42
+ }
43
+ return { lcovArg, baselinePath, updateBaseline };
44
+ }
45
+ /** Parse function and line hit records, preserving summaries when present. */
46
+ export function parseLcovBlocks({ lcovText }) {
47
+ const records = lcovText.replace(/\r\n/g, '\n').split(/^end_of_record$/m);
48
+ const blocks = [];
49
+ for (const record of records) {
50
+ const sfMatch = record.match(/^SF:(.+)$/m);
51
+ if (!sfMatch)
52
+ continue;
53
+ const fnda = [...record.matchAll(/^FNDA:(\d+),(.+)$/gm)].map((m) => ({
54
+ hits: Number(m[1]),
55
+ name: m[2],
56
+ }));
57
+ const da = [...record.matchAll(/^DA:\d+,(\d+)$/gm)].map((m) => Number(m[1]));
58
+ const fnfMatch = record.match(/^FNF:(\d+)$/m);
59
+ const fnhMatch = record.match(/^FNH:(\d+)$/m);
60
+ blocks.push({
61
+ file: sfMatch[1].trim(),
62
+ fnda,
63
+ da,
64
+ fnf: fnfMatch ? Number(fnfMatch[1]) : undefined,
65
+ fnh: fnhMatch ? Number(fnhMatch[1]) : undefined,
66
+ });
67
+ }
68
+ return blocks;
69
+ }
70
+ const EXPORT_FROM_STATEMENT = /export\s+(?:type\s+)?(?:\{[^{}]*\}|\*(?:\s+as\s+[A-Za-z_$][\w$]*)?)\s+from\s+["'][^"']+["']\s*;?/g;
71
+ /** Recognize plain re-export barrels using the inherited source-text heuristic. */
72
+ export function isPureReExportBarrelSource({ sourceText }) {
73
+ const withoutComments = sourceText.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "");
74
+ const matches = [...withoutComments.matchAll(EXPORT_FROM_STATEMENT)];
75
+ if (matches.length === 0)
76
+ return false;
77
+ const remaining = withoutComments.replace(EXPORT_FROM_STATEMENT, "").trim();
78
+ return remaining.length === 0;
79
+ }
80
+ /** Classify esbuild interop contamination using the host source classifier. */
81
+ export function classifyBlock({ block, repoRoot, isFirstParty }, { sourceText } = {}) {
82
+ const file = toRepoRelative({ sourceFile: block.file, repoRoot });
83
+ if (!isFirstParty({ file }))
84
+ return { file, status: 'skip', severe: false, reason: 'not a first-party source path' };
85
+ if (sourceText !== undefined && isPureReExportBarrelSource({ sourceText })) {
86
+ return {
87
+ file, status: 'skip', severe: false,
88
+ reason: 'pure re-export barrel (source is entirely `export ... from "...";` statements) -- its only ' +
89
+ "instrumented \"functions\" are esbuild's own CJS-interop wrapper helpers plus one lazy getter " +
90
+ 'per re-exported name, not a second merged coverage image; wrapper-name presence here is ' +
91
+ 'structurally guaranteed for any barrel, with or without Route A, so it carries no ' +
92
+ "contamination signal -- see this file's header",
93
+ };
94
+ }
95
+ const wrapperNamesFound = new Set();
96
+ const wrapperValues = new Set();
97
+ for (const { name, hits } of block.fnda) {
98
+ if (WRAPPER_HELPER_NAMES.has(name)) {
99
+ wrapperNamesFound.add(name);
100
+ wrapperValues.add(hits);
101
+ }
102
+ }
103
+ if (wrapperNamesFound.size === 0)
104
+ return { file, status: 'ok', severe: false, reason: 'no esbuild CJS-wrapper FNDA records in this block' };
105
+ const fnSummary = block.fnf !== undefined && block.fnh !== undefined ? ` FNF:${block.fnf} FNH:${block.fnh}` : '';
106
+ const contaminatedReason = `${wrapperNamesFound.size} esbuild CJS-wrapper helper record(s) [${[...wrapperNamesFound].sort().join(', ')}] ` +
107
+ `present in this block's FNDA records -- two coverage images (real ESM + CJS wrapper) were merged ` +
108
+ `here.${fnSummary} function coverage for this run is untrustworthy`;
109
+ // A tiny barrel can share hit counts by coincidence. Escalation requires enough DA records
110
+ // and a nonzero overlap with the wrapper's own counts; all-zero runs carry no merge signal.
111
+ if (block.da.length >= MIN_DA_RECORDS_FOR_SEVERE_HEURISTIC) {
112
+ const comparisonSet = new Set(wrapperValues);
113
+ comparisonSet.add(0);
114
+ const distinctDa = [...new Set(block.da)].sort((a, b) => a - b);
115
+ const extra = distinctDa.filter((value) => !comparisonSet.has(value));
116
+ const overlapHasRealSignal = distinctDa.some((value) => value !== 0 && comparisonSet.has(value));
117
+ if (extra.length === 0 && overlapHasRealSignal) {
118
+ const wrapperValuesSorted = [...wrapperValues].sort((a, b) => a - b);
119
+ return {
120
+ file, status: 'contaminated', severe: true,
121
+ reason: `${contaminatedReason}. SEVERE: additionally, every one of this block's ${distinctDa.length} ` +
122
+ `distinct DA hit-count value(s) [${distinctDa.join(', ')}] matches a wrapper helper's own FNDA ` +
123
+ `hit-count [${wrapperValuesSorted.join(', ')}] (or 0) -- the wrapper image also won the line-hit ` +
124
+ `merge, so line coverage for this run is untrustworthy too, regardless of what LH:/LF: report`,
125
+ };
126
+ }
127
+ }
128
+ return { file, status: 'contaminated', severe: false, reason: `${contaminatedReason}.` };
129
+ }
130
+ /** Evaluate supplied LCOV text and an optional host source reader, without disk I/O. */
131
+ export function checkCoverageIntegrity({ lcovText, repoRoot, isFirstParty }, { readSource } = {}) {
132
+ const verdicts = parseLcovBlocks({ lcovText }).map((block) => {
133
+ const file = toRepoRelative({ sourceFile: block.file, repoRoot });
134
+ return classifyBlock({ block, repoRoot, isFirstParty }, { sourceText: readSource?.({ file }) });
135
+ });
136
+ const contaminated = verdicts.filter((v) => v.status === "contaminated");
137
+ const skipped = verdicts.filter((v) => v.status === "skip").length;
138
+ return { contaminated, evaluated: verdicts.length - skipped, skipped };
139
+ }
140
+ //# sourceMappingURL=integrity.js.map
@@ -0,0 +1,65 @@
1
+ import type { SourceReaderPort } from '../ports.js';
2
+ export interface FileCoverage {
3
+ file: string;
4
+ lf: number;
5
+ lh: number;
6
+ brf: number;
7
+ brh: number;
8
+ fnf: number;
9
+ fnh: number;
10
+ }
11
+ export interface SourceClassificationRules {
12
+ prefixes: readonly string[];
13
+ sourceExtensions: readonly string[];
14
+ excludedDirectories: readonly string[];
15
+ excludedBasenames: readonly string[];
16
+ testPattern: RegExp;
17
+ }
18
+ export type SourceClassifier = (args: {
19
+ file: string;
20
+ }) => boolean;
21
+ /** LCOV's empty denominator is vacuously 100%; area checks separately reject empty scopes. */
22
+ export declare function pct({ hit, found }: {
23
+ hit: number;
24
+ found: number;
25
+ }): number;
26
+ /** Normalize paths with a directory boundary check, including Windows paths on non-Windows hosts. */
27
+ export declare function toRepoRelative({ sourceFile, repoRoot }: {
28
+ sourceFile: string;
29
+ repoRoot: string;
30
+ }): string;
31
+ /** Match caller-supplied integration suffixes and directory segments. */
32
+ export declare function isIntegrationTestFile({ file, suffixes, directories }: {
33
+ file: string;
34
+ suffixes: readonly string[];
35
+ directories: readonly string[];
36
+ }): boolean;
37
+ /** Match source roots on directory boundaries and apply host-defined exclusions. */
38
+ export declare function isMeasurableSourceFile({ file, rules }: {
39
+ file: string;
40
+ rules: SourceClassificationRules;
41
+ }): boolean;
42
+ /** Parse LCOV summaries without filtering source or accessing a filesystem. */
43
+ export declare function parseLcov({ text, repoRoot }: {
44
+ text: string;
45
+ repoRoot: string;
46
+ }): FileCoverage[];
47
+ /** Read the exact supplied artifact; missing/unreadable artifacts propagate the reader's error. */
48
+ export declare function loadLcov({ lcovPath, repoRoot, reader }: {
49
+ lcovPath: string;
50
+ repoRoot: string;
51
+ reader: SourceReaderPort;
52
+ }): FileCoverage[];
53
+ /** Load and classify coverage without repository-specific route knowledge. */
54
+ export declare function loadRouteCoverage({ lcovPath, repoRoot, reader, isMeasurable }: {
55
+ lcovPath: string;
56
+ repoRoot: string;
57
+ reader: SourceReaderPort;
58
+ isMeasurable: SourceClassifier;
59
+ }): FileCoverage[];
60
+ /** Merge separate coverage images without adding incomparable counters; higher line-hit image wins. */
61
+ export declare function mergeCoverage({ reports, isMeasurable }: {
62
+ reports: readonly (readonly FileCoverage[])[];
63
+ isMeasurable: SourceClassifier;
64
+ }): ReadonlyMap<string, FileCoverage>;
65
+ //# sourceMappingURL=lcov.d.ts.map
@@ -0,0 +1,64 @@
1
+ /** LCOV's empty denominator is vacuously 100%; area checks separately reject empty scopes. */
2
+ export function pct({ hit, found }) { return found === 0 ? 100 : 100 * hit / found; }
3
+ /** Normalize paths with a directory boundary check, including Windows paths on non-Windows hosts. */
4
+ export function toRepoRelative({ sourceFile, repoRoot }) {
5
+ const file = sourceFile.trim().replace(/\\/g, '/');
6
+ const root = repoRoot.replace(/\\/g, '/').replace(/\/+$/, '');
7
+ if (file === root)
8
+ return '';
9
+ if (file.startsWith(`${root}/`))
10
+ return file.slice(root.length + 1);
11
+ return file;
12
+ }
13
+ /** Match caller-supplied integration suffixes and directory segments. */
14
+ export function isIntegrationTestFile({ file, suffixes, directories }) {
15
+ const normalized = file.replace(/\\/g, '/');
16
+ return suffixes.some((suffix) => normalized.endsWith(suffix)) || directories.some((dir) => `/${normalized}`.includes(`/${dir.replace(/^\/+|\/+$/g, '')}/`));
17
+ }
18
+ /** Match source roots on directory boundaries and apply host-defined exclusions. */
19
+ export function isMeasurableSourceFile({ file, rules }) {
20
+ const normalized = file.replace(/\\/g, '/');
21
+ if (!rules.prefixes.some((prefix) => normalized.startsWith(`${prefix.replace(/\/+$/, '')}/`)))
22
+ return false;
23
+ if (!rules.sourceExtensions.some((extension) => normalized.endsWith(extension)))
24
+ return false;
25
+ const parts = normalized.split('/');
26
+ if (parts.some((part) => rules.excludedDirectories.includes(part)))
27
+ return false;
28
+ if (rules.excludedBasenames.includes(parts.at(-1) ?? ''))
29
+ return false;
30
+ // Do not mutate a host's global/sticky regex or inherit its lastIndex.
31
+ return !new RegExp(rules.testPattern.source, rules.testPattern.flags.replace(/[gy]/g, '')).test(normalized);
32
+ }
33
+ function field(record, name) { return Number(record.match(new RegExp(`^${name}:(\\d+)$`, 'm'))?.[1] ?? 0); }
34
+ /** Parse LCOV summaries without filtering source or accessing a filesystem. */
35
+ export function parseLcov({ text, repoRoot }) {
36
+ const out = [];
37
+ for (const record of text.replace(/\r\n/g, '\n').split(/^end_of_record$/m)) {
38
+ const source = record.match(/^SF:(.+)$/m)?.[1];
39
+ if (!source)
40
+ continue;
41
+ out.push({ file: toRepoRelative({ sourceFile: source, repoRoot }), lf: field(record, 'LF'), lh: field(record, 'LH'), brf: field(record, 'BRF'), brh: field(record, 'BRH'), fnf: field(record, 'FNF'), fnh: field(record, 'FNH') });
42
+ }
43
+ return out;
44
+ }
45
+ /** Read the exact supplied artifact; missing/unreadable artifacts propagate the reader's error. */
46
+ export function loadLcov({ lcovPath, repoRoot, reader }) {
47
+ return parseLcov({ text: reader.readText({ path: lcovPath }), repoRoot });
48
+ }
49
+ /** Load and classify coverage without repository-specific route knowledge. */
50
+ export function loadRouteCoverage({ lcovPath, repoRoot, reader, isMeasurable }) { return loadLcov({ lcovPath, repoRoot, reader }).filter((record) => isMeasurable({ file: record.file })); }
51
+ /** Merge separate coverage images without adding incomparable counters; higher line-hit image wins. */
52
+ export function mergeCoverage({ reports, isMeasurable }) {
53
+ const byFile = new Map();
54
+ for (const report of reports)
55
+ for (const record of report) {
56
+ if (!isMeasurable({ file: record.file }))
57
+ continue;
58
+ const previous = byFile.get(record.file);
59
+ if (!previous || record.lh > previous.lh)
60
+ byFile.set(record.file, { ...record });
61
+ }
62
+ return byFile;
63
+ }
64
+ //# sourceMappingURL=lcov.js.map
@@ -0,0 +1,19 @@
1
+ import type { EnvLoaderPort } from '../local-dev/index.js';
2
+ import type { FilesystemPort, PackageInstallerPort, ProcessRunnerPort } from './ports.js';
3
+ /** Explicit Node filesystem adapter. Temporary parents must already exist. */
4
+ export declare function createNodeFilesystem(_args: Record<string, never>): FilesystemPort;
5
+ /** Uses Node's environment precedence: exported variables win over file values. Requires Node 20.12+. */
6
+ export declare function createNodeEnvLoader(_args: Record<string, never>): EnvLoaderPort;
7
+ /** Shell-free runner; captures compiler output and reports signals/spawn failures as null exits. */
8
+ export declare function createNodeProcessRunner(_args: Record<string, never>, { maxBuffer, timeoutMs }?: {
9
+ maxBuffer?: number;
10
+ timeoutMs?: number;
11
+ }): ProcessRunnerPort;
12
+ /** Optional npm executable adapter. The caller explicitly selects the executable and runner. */
13
+ export declare function createNpmInstaller({ runner, command }: {
14
+ runner: ProcessRunnerPort;
15
+ command: string;
16
+ }, { args }?: {
17
+ args?: readonly string[];
18
+ }): PackageInstallerPort;
19
+ //# sourceMappingURL=node.d.ts.map