codebase-snapshot 0.9.16 → 0.9.17
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/CHANGELOG.md +64 -0
- package/README.md +1 -1
- package/SECURITY.md +18 -6
- package/dist/bin.js +2019 -619
- package/dist/{chunk-6TRFLA7N.js → chunk-IIP43I7C.js} +1755 -443
- package/dist/{chunk-WIL536QD.js → chunk-S4367K5X.js} +97 -24
- package/dist/cli.cjs +2001 -605
- package/dist/cli.d.cts +1 -11
- package/dist/cli.d.ts +1 -11
- package/dist/cli.js +16 -5
- package/dist/index.cjs +1748 -437
- package/dist/index.d.cts +97 -8
- package/dist/index.d.ts +97 -8
- package/dist/index.js +1 -1
- package/dist/mcp.cjs +1760 -340
- package/dist/mcp.d.cts +7 -0
- package/dist/mcp.d.ts +7 -0
- package/dist/mcp.js +2 -2
- package/dist/{types-DIX6zWSt.d.cts → types-KbJvBjmV.d.cts} +46 -1
- package/dist/{types-DIX6zWSt.d.ts → types-KbJvBjmV.d.ts} +46 -1
- package/docs/cli.md +14 -9
- package/docs/configuration.md +16 -1
- package/docs/mcp.md +17 -7
- package/docs/output.md +3 -3
- package/docs/vs-gitingest.md +6 -2
- package/package.json +3 -2
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import * as crypto2 from 'crypto';
|
|
2
2
|
import { createHash } from 'crypto';
|
|
3
|
+
import { Worker } from 'worker_threads';
|
|
3
4
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
4
|
-
import * as
|
|
5
|
+
import * as fs15 from 'fs';
|
|
5
6
|
import * as os from 'os';
|
|
6
7
|
import * as path16 from 'path';
|
|
7
8
|
import ts from 'typescript';
|
|
@@ -12,7 +13,6 @@ import { execFileSync } from 'child_process';
|
|
|
12
13
|
import * as http from 'http';
|
|
13
14
|
import * as https from 'https';
|
|
14
15
|
import * as readline from 'readline';
|
|
15
|
-
import { Worker } from 'worker_threads';
|
|
16
16
|
|
|
17
17
|
// src/index.ts
|
|
18
18
|
var hookStdoutScope = new AsyncLocalStorage();
|
|
@@ -620,9 +620,9 @@ var rubyProfile = {
|
|
|
620
620
|
eachLine(content, (line) => {
|
|
621
621
|
const trimmed = line.trim();
|
|
622
622
|
if (!trimmed || trimmed.startsWith("#")) return;
|
|
623
|
-
const
|
|
624
|
-
if (
|
|
625
|
-
summary.imports.push(`./${
|
|
623
|
+
const relative10 = REQUIRE_RELATIVE.exec(trimmed);
|
|
624
|
+
if (relative10) {
|
|
625
|
+
summary.imports.push(`./${relative10[1]}`);
|
|
626
626
|
return;
|
|
627
627
|
}
|
|
628
628
|
const required = REQUIRE.exec(trimmed);
|
|
@@ -722,6 +722,16 @@ var ROUTE_HANDLER_NAMES = /* @__PURE__ */ new Set([
|
|
|
722
722
|
"HEAD",
|
|
723
723
|
"OPTIONS"
|
|
724
724
|
]);
|
|
725
|
+
var ROUTE_RECEIVERS = /* @__PURE__ */ new Set(["app", "router", "server", "fastify", "api", "route"]);
|
|
726
|
+
var ROUTE_REGISTRATION_VERBS = /* @__PURE__ */ new Set([
|
|
727
|
+
"get",
|
|
728
|
+
"post",
|
|
729
|
+
"put",
|
|
730
|
+
"delete",
|
|
731
|
+
"patch",
|
|
732
|
+
"head",
|
|
733
|
+
"options"
|
|
734
|
+
]);
|
|
725
735
|
function bindingNames(name, into) {
|
|
726
736
|
if (ts.isIdentifier(name)) {
|
|
727
737
|
into.push(name.text);
|
|
@@ -732,6 +742,53 @@ function bindingNames(name, into) {
|
|
|
732
742
|
bindingNames(element.name, into);
|
|
733
743
|
}
|
|
734
744
|
}
|
|
745
|
+
function objectLiteralNames(node) {
|
|
746
|
+
const names = [];
|
|
747
|
+
for (const property of node.properties) {
|
|
748
|
+
if (ts.isShorthandPropertyAssignment(property)) {
|
|
749
|
+
names.push(property.name.text);
|
|
750
|
+
continue;
|
|
751
|
+
}
|
|
752
|
+
if (!ts.isPropertyAssignment(property)) continue;
|
|
753
|
+
const name = property.name;
|
|
754
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {
|
|
755
|
+
names.push(name.text);
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
return names;
|
|
759
|
+
}
|
|
760
|
+
function cjsExportedNames(expression) {
|
|
761
|
+
const left = expression.left;
|
|
762
|
+
if (!ts.isPropertyAccessExpression(left)) return null;
|
|
763
|
+
const isModuleExports = left.name.text === "exports" && ts.isIdentifier(left.expression) && left.expression.text === "module";
|
|
764
|
+
if (isModuleExports) {
|
|
765
|
+
const right = expression.right;
|
|
766
|
+
if (ts.isObjectLiteralExpression(right)) return objectLiteralNames(right);
|
|
767
|
+
if (ts.isIdentifier(right)) return [right.text];
|
|
768
|
+
return [];
|
|
769
|
+
}
|
|
770
|
+
if (ts.isIdentifier(left.expression) && left.expression.text === "exports") {
|
|
771
|
+
return [left.name.text];
|
|
772
|
+
}
|
|
773
|
+
const parent = left.expression;
|
|
774
|
+
if (ts.isPropertyAccessExpression(parent) && parent.name.text === "exports" && ts.isIdentifier(parent.expression) && parent.expression.text === "module") {
|
|
775
|
+
return [left.name.text];
|
|
776
|
+
}
|
|
777
|
+
return null;
|
|
778
|
+
}
|
|
779
|
+
function countSyntacticErrors(fileName, content) {
|
|
780
|
+
const result = ts.transpileModule(content, {
|
|
781
|
+
fileName,
|
|
782
|
+
compilerOptions: {
|
|
783
|
+
target: ts.ScriptTarget.Latest,
|
|
784
|
+
module: ts.ModuleKind.ESNext
|
|
785
|
+
},
|
|
786
|
+
reportDiagnostics: true
|
|
787
|
+
});
|
|
788
|
+
return (result.diagnostics ?? []).filter(
|
|
789
|
+
(diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error
|
|
790
|
+
).length;
|
|
791
|
+
}
|
|
735
792
|
function summarizeTypeScriptSource(relativePath, content) {
|
|
736
793
|
const summary = {
|
|
737
794
|
directives: [],
|
|
@@ -749,16 +806,17 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
749
806
|
routeHandlers: []
|
|
750
807
|
};
|
|
751
808
|
const lowerPath = relativePath.toLowerCase();
|
|
752
|
-
const
|
|
809
|
+
const scriptKind = /.tsx$/.test(lowerPath) ? ts.ScriptKind.TSX : /.jsx$/.test(lowerPath) ? ts.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts.ScriptKind.JS : ts.ScriptKind.TS;
|
|
753
810
|
const sourceFile = ts.createSourceFile(
|
|
754
811
|
relativePath,
|
|
755
812
|
content,
|
|
756
813
|
ts.ScriptTarget.Latest,
|
|
757
814
|
/* setParentNodes */
|
|
758
815
|
false,
|
|
759
|
-
|
|
816
|
+
scriptKind
|
|
760
817
|
);
|
|
761
|
-
const
|
|
818
|
+
const parsedDiagnostics = sourceFile.parseDiagnostics;
|
|
819
|
+
const parseErrors = Array.isArray(parsedDiagnostics) ? parsedDiagnostics.filter((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error).length : countSyntacticErrors(relativePath, content);
|
|
762
820
|
if (parseErrors > 0) summary.parseErrors = parseErrors;
|
|
763
821
|
for (const statement of sourceFile.statements) {
|
|
764
822
|
if (ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)) {
|
|
@@ -815,6 +873,7 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
815
873
|
if (/^use[A-Z0-9]/.test(name)) summary.hooks.push(name);
|
|
816
874
|
if (/^[A-Z]/.test(name) && rendersJsx(node)) summary.reactComponents.push(name);
|
|
817
875
|
};
|
|
876
|
+
const cjsExports = [];
|
|
818
877
|
const stack = [sourceFile];
|
|
819
878
|
while (stack.length > 0) {
|
|
820
879
|
const node = stack.pop();
|
|
@@ -831,6 +890,10 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
831
890
|
const isRequire = ts.isIdentifier(node.expression) && node.expression.text === "require";
|
|
832
891
|
if (isDynamicImport || isRequire) summary.imports.push(firstArgument.text);
|
|
833
892
|
}
|
|
893
|
+
const callee = node.expression;
|
|
894
|
+
if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && ROUTE_RECEIVERS.has(callee.expression.text) && ROUTE_REGISTRATION_VERBS.has(callee.name.text.toLowerCase()) && firstArgument !== void 0 && ts.isStringLiteral(firstArgument)) {
|
|
895
|
+
summary.routeHandlers.push(callee.name.text.toUpperCase());
|
|
896
|
+
}
|
|
834
897
|
}
|
|
835
898
|
if (ts.isExportDeclaration(node)) {
|
|
836
899
|
if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
|
|
@@ -848,6 +911,10 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
848
911
|
}
|
|
849
912
|
}
|
|
850
913
|
}
|
|
914
|
+
if (ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
|
|
915
|
+
const cjsNames = cjsExportedNames(node.expression);
|
|
916
|
+
if (cjsNames !== null) cjsExports.push(...cjsNames);
|
|
917
|
+
}
|
|
851
918
|
if (ts.isExportAssignment(node)) {
|
|
852
919
|
summary.exports.push("default");
|
|
853
920
|
if (rendersJsx(node.expression)) summary.reactComponents.push("default");
|
|
@@ -911,6 +978,10 @@ function summarizeTypeScriptSource(relativePath, content) {
|
|
|
911
978
|
stack.push(children[index]);
|
|
912
979
|
}
|
|
913
980
|
}
|
|
981
|
+
if (cjsExports.length > 0) {
|
|
982
|
+
summary.exportsKind = summary.exports.length > 0 ? "mixed" : "cjs";
|
|
983
|
+
summary.exports.push(...cjsExports);
|
|
984
|
+
}
|
|
914
985
|
const dedupeSorted2 = (values) => Array.from(new Set(values)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
915
986
|
summary.directives = dedupeSorted2(summary.directives);
|
|
916
987
|
summary.imports = dedupeSorted2(summary.imports);
|
|
@@ -1366,13 +1437,13 @@ function isBinaryFile(absolutePath) {
|
|
|
1366
1437
|
if (isBinaryExtension(absolutePath)) return true;
|
|
1367
1438
|
let fd;
|
|
1368
1439
|
try {
|
|
1369
|
-
fd =
|
|
1440
|
+
fd = fs15.openSync(absolutePath, "r");
|
|
1370
1441
|
const buffer = Buffer.alloc(CHUNK);
|
|
1371
1442
|
let sample;
|
|
1372
1443
|
let position = 0;
|
|
1373
1444
|
while (position < BINARY_SCAN_BYTES) {
|
|
1374
1445
|
const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
|
|
1375
|
-
const bytesRead =
|
|
1446
|
+
const bytesRead = fs15.readSync(fd, buffer, 0, wanted, position);
|
|
1376
1447
|
if (bytesRead === 0) return false;
|
|
1377
1448
|
const chunk = buffer.subarray(0, bytesRead);
|
|
1378
1449
|
if (sample === void 0) {
|
|
@@ -1390,7 +1461,7 @@ function isBinaryFile(absolutePath) {
|
|
|
1390
1461
|
} finally {
|
|
1391
1462
|
if (fd !== void 0) {
|
|
1392
1463
|
try {
|
|
1393
|
-
|
|
1464
|
+
fs15.closeSync(fd);
|
|
1394
1465
|
} catch {
|
|
1395
1466
|
}
|
|
1396
1467
|
}
|
|
@@ -1412,9 +1483,9 @@ function importsOfText(relativePath, text2) {
|
|
|
1412
1483
|
function importsOfFile(relativePath, absolutePath) {
|
|
1413
1484
|
let buffer;
|
|
1414
1485
|
try {
|
|
1415
|
-
const stats =
|
|
1486
|
+
const stats = fs15.statSync(absolutePath);
|
|
1416
1487
|
if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
|
|
1417
|
-
buffer =
|
|
1488
|
+
buffer = fs15.readFileSync(absolutePath);
|
|
1418
1489
|
} catch {
|
|
1419
1490
|
return [];
|
|
1420
1491
|
}
|
|
@@ -1706,9 +1777,9 @@ var SKIPPED_WALK_DIRS = /* @__PURE__ */ new Set([
|
|
|
1706
1777
|
]);
|
|
1707
1778
|
function readSmallFile(fullPath) {
|
|
1708
1779
|
try {
|
|
1709
|
-
const stats =
|
|
1780
|
+
const stats = fs15.statSync(fullPath);
|
|
1710
1781
|
if (!stats.isFile() || stats.size > MANIFEST_MAX_BYTES) return null;
|
|
1711
|
-
return
|
|
1782
|
+
return fs15.readFileSync(fullPath, "utf8");
|
|
1712
1783
|
} catch {
|
|
1713
1784
|
return null;
|
|
1714
1785
|
}
|
|
@@ -1774,7 +1845,7 @@ function pnpmWorkspacePatterns(raw) {
|
|
|
1774
1845
|
function childDirectories(cwd, parent) {
|
|
1775
1846
|
let entries;
|
|
1776
1847
|
try {
|
|
1777
|
-
entries =
|
|
1848
|
+
entries = fs15.readdirSync(path16.join(cwd, parent), { withFileTypes: true });
|
|
1778
1849
|
} catch {
|
|
1779
1850
|
return [];
|
|
1780
1851
|
}
|
|
@@ -1809,10 +1880,10 @@ function workspacePackageDirs(cwd, patterns) {
|
|
|
1809
1880
|
function scanWorkspacePackages(cwd, patterns) {
|
|
1810
1881
|
const files = /* @__PURE__ */ new Set();
|
|
1811
1882
|
const dependencies = /* @__PURE__ */ new Set();
|
|
1812
|
-
for (const
|
|
1813
|
-
const full = path16.join(cwd,
|
|
1883
|
+
for (const relative10 of workspacePackageDirs(cwd, patterns)) {
|
|
1884
|
+
const full = path16.join(cwd, relative10);
|
|
1814
1885
|
try {
|
|
1815
|
-
for (const entry of
|
|
1886
|
+
for (const entry of fs15.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
|
|
1816
1887
|
} catch {
|
|
1817
1888
|
}
|
|
1818
1889
|
const raw = readSmallFile(path16.join(full, "package.json"));
|
|
@@ -1825,7 +1896,7 @@ function scanWorkspacePackages(cwd, patterns) {
|
|
|
1825
1896
|
var SNAPSHOT_MARKER = ".codebase-snapshot";
|
|
1826
1897
|
function isToolOwnedDirectory(dir) {
|
|
1827
1898
|
try {
|
|
1828
|
-
return
|
|
1899
|
+
return fs15.statSync(dir).isDirectory() && fs15.existsSync(path16.join(dir, SNAPSHOT_MARKER));
|
|
1829
1900
|
} catch {
|
|
1830
1901
|
return false;
|
|
1831
1902
|
}
|
|
@@ -1840,7 +1911,7 @@ function countMarkdownFiles(cwd) {
|
|
|
1840
1911
|
directoriesSeen += 1;
|
|
1841
1912
|
let entries;
|
|
1842
1913
|
try {
|
|
1843
|
-
entries =
|
|
1914
|
+
entries = fs15.readdirSync(current.dir, { withFileTypes: true });
|
|
1844
1915
|
} catch {
|
|
1845
1916
|
continue;
|
|
1846
1917
|
}
|
|
@@ -1862,7 +1933,7 @@ function buildPresetContext(cwd) {
|
|
|
1862
1933
|
const files = /* @__PURE__ */ new Set();
|
|
1863
1934
|
const dirs = /* @__PURE__ */ new Set();
|
|
1864
1935
|
try {
|
|
1865
|
-
for (const entry of
|
|
1936
|
+
for (const entry of fs15.readdirSync(cwd, { withFileTypes: true })) {
|
|
1866
1937
|
if (entry.isDirectory()) dirs.add(entry.name);
|
|
1867
1938
|
else if (entry.isFile()) files.add(entry.name);
|
|
1868
1939
|
}
|
|
@@ -2737,7 +2808,10 @@ var ASSIGN = String.raw`(?<![=!<>])[:=](?!=)`;
|
|
|
2737
2808
|
var NOT_AFTER_QUOTE = String.raw`(?<!["'])`;
|
|
2738
2809
|
var NOT_A_NAMESPACED_IDENTIFIER = String.raw`(?![a-z][a-z0-9]*(?:\.[a-z][a-z0-9-]*)+/)`;
|
|
2739
2810
|
var QUOTED_CREDENTIAL_KEY = `["'](?!id[-_]token["'])[A-Za-z0-9_$-]{0,64}${STRONG_CREDENTIAL_NAME}["']`;
|
|
2740
|
-
|
|
2811
|
+
function quotedValueFor(delimiterGroup) {
|
|
2812
|
+
return "((?:(?!\\" + delimiterGroup + String.raw`)[^\\\n]|\\\\["'](?=[A-Za-z0-9_])|\\.){1,512})`;
|
|
2813
|
+
}
|
|
2814
|
+
var QUOTED_VALUE = quotedValueFor(1);
|
|
2741
2815
|
var UNQUOTED_STRONG_NAME = `(?<!id[-_])${STRONG_CREDENTIAL_NAME}`;
|
|
2742
2816
|
var CREDENTIAL_KEY_TAIL = new RegExp(`(?:${STRONG_CREDENTIAL_NAME})$`, "i");
|
|
2743
2817
|
var DEFAULT_SECRET_PATTERNS = [
|
|
@@ -2891,7 +2965,7 @@ var DEFAULT_SECRET_PATTERNS = [
|
|
|
2891
2965
|
// consumes the flag so the match is the credential alone.
|
|
2892
2966
|
// - An Azure SAS link authenticates with `?sig=`; the signature *is* the credential.
|
|
2893
2967
|
rule: "uri-credentials",
|
|
2894
|
-
pattern: /\/\/[^\s:/@"'`;()<>,]{0,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}|(?<=(?:^|[\s;|&(])--?u(?:ser)?[ \t=]{1,8})["']?[
|
|
2968
|
+
pattern: /\/\/[^\s:/@"'`;()<>,]{0,128}:[^\s:/@"'`;()<>,]{1,256}@[^\s/"'`;()<>,]{1,256}|(?<=(?:^|[\s;|&(])--?u(?:ser)?[ \t=]{1,8})["']?[A-Za-z0-9._~-][A-Za-z0-9._~-]{0,127}:[^\s"'%$()+]{1,256}["']?|(?<=[?&])sig=[A-Za-z0-9%._=~-]{20,300}(?![A-Za-z0-9%._=~-])/
|
|
2895
2969
|
},
|
|
2896
2970
|
{
|
|
2897
2971
|
// The host tail stops at quotes, `;`, `)`, `<`, `>` and `,`: an unbounded
|
|
@@ -3003,7 +3077,7 @@ var DEFAULT_SECRET_PATTERNS = [
|
|
|
3003
3077
|
// rendering of textual userinfo mixes cases, while the prose the earlier rules were
|
|
3004
3078
|
// protecting (`Bearer authentication`) is a lowercase word.
|
|
3005
3079
|
rule: "authorization-header",
|
|
3006
|
-
pattern: /(?<=
|
|
3080
|
+
pattern: /(?<=[Aa]uthorization["']?\s*[:=]\s*["']?[A-Za-z][A-Za-z0-9._~+/-]{0,31}\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
|
|
3007
3081
|
},
|
|
3008
3082
|
{
|
|
3009
3083
|
// Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
|
|
@@ -3030,7 +3104,9 @@ var DEFAULT_SECRET_PATTERNS = [
|
|
|
3030
3104
|
// between the braces to mask, and `isTemplateInterpolation` keeps such a value readable.
|
|
3031
3105
|
rule: "interpolation-fallback-secret",
|
|
3032
3106
|
pattern: new RegExp(
|
|
3033
|
-
|
|
3107
|
+
// The operator set deliberately omits `?`: `${VAR:?message}` is an error message in shell
|
|
3108
|
+
// and Compose, not a fallback value, and masking it hid the sentence a user is meant to read.
|
|
3109
|
+
`(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}["'\`]?\\$\\{[A-Za-z_][A-Za-z0-9_]*:?[-=+]([^}"'\`\\r\\n]{2,512})\\}["'\`]?`,
|
|
3034
3110
|
"i"
|
|
3035
3111
|
),
|
|
3036
3112
|
valueGroup: 1
|
|
@@ -3079,19 +3155,15 @@ function compilePattern(rule, pattern, valueGroup) {
|
|
|
3079
3155
|
if (pattern instanceof RegExp) {
|
|
3080
3156
|
const flags = new Set(pattern.flags.replace(/[gy]/g, "").split(""));
|
|
3081
3157
|
if (valueGroup !== void 0) flags.add("d");
|
|
3082
|
-
return
|
|
3083
|
-
rule,
|
|
3084
|
-
pattern: new RegExp(pattern.source, [...flags].join("")),
|
|
3085
|
-
...valueGroup === void 0 ? {} : { valueGroup }
|
|
3086
|
-
};
|
|
3158
|
+
return checkedPattern(rule, new RegExp(pattern.source, [...flags].join("")), valueGroup);
|
|
3087
3159
|
}
|
|
3088
3160
|
if (typeof pattern === "string") {
|
|
3089
3161
|
try {
|
|
3090
|
-
return
|
|
3162
|
+
return checkedPattern(
|
|
3091
3163
|
rule,
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
|
|
3164
|
+
new RegExp(pattern, valueGroup === void 0 ? "i" : "id"),
|
|
3165
|
+
valueGroup
|
|
3166
|
+
);
|
|
3095
3167
|
} catch (err) {
|
|
3096
3168
|
throw new Error(
|
|
3097
3169
|
`Invalid regular expression for secret rule "${rule}": ${err.message}`
|
|
@@ -3102,6 +3174,19 @@ function compilePattern(rule, pattern, valueGroup) {
|
|
|
3102
3174
|
`Secret rule "${rule}" has a pattern that is neither a RegExp nor a string (received ${describeValue(pattern)}).`
|
|
3103
3175
|
);
|
|
3104
3176
|
}
|
|
3177
|
+
function checkedPattern(rule, compiled, valueGroup) {
|
|
3178
|
+
const stateless = new RegExp(compiled.source, compiled.flags.replace(/[gy]/g, ""));
|
|
3179
|
+
if (stateless.test("")) {
|
|
3180
|
+
throw new Error(
|
|
3181
|
+
`Secret rule "${rule}" can match the empty string. Every alternative must require at least one character, or the scan cannot advance past a match.`
|
|
3182
|
+
);
|
|
3183
|
+
}
|
|
3184
|
+
return {
|
|
3185
|
+
rule,
|
|
3186
|
+
pattern: compiled,
|
|
3187
|
+
...valueGroup === void 0 ? {} : { valueGroup }
|
|
3188
|
+
};
|
|
3189
|
+
}
|
|
3105
3190
|
function compileSecretRules(rules) {
|
|
3106
3191
|
if (!Array.isArray(rules)) {
|
|
3107
3192
|
throw new Error(
|
|
@@ -3158,6 +3243,193 @@ function toGlobal(rule) {
|
|
|
3158
3243
|
}
|
|
3159
3244
|
var LINE_BREAK = /(\r\n|\n|\r)/;
|
|
3160
3245
|
var LINE_TERMINATOR = /\r\n|\n|\r/g;
|
|
3246
|
+
function isOpeningQuote(line, index) {
|
|
3247
|
+
const code = line.charCodeAt(index);
|
|
3248
|
+
if (code === 96) return true;
|
|
3249
|
+
if (code !== 34 && code !== 39) return false;
|
|
3250
|
+
return index === 0 || !/[A-Za-z0-9]/.test(line[index - 1]);
|
|
3251
|
+
}
|
|
3252
|
+
function quoteStates(line) {
|
|
3253
|
+
const states = new Uint8Array(line.length + 1);
|
|
3254
|
+
let quote = 0;
|
|
3255
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3256
|
+
states[index] = quote;
|
|
3257
|
+
const code = line.charCodeAt(index);
|
|
3258
|
+
if (quote === 0) {
|
|
3259
|
+
if (isOpeningQuote(line, index)) quote = code;
|
|
3260
|
+
} else if (code === 92) {
|
|
3261
|
+
if (index + 1 < line.length) {
|
|
3262
|
+
index += 1;
|
|
3263
|
+
states[index] = quote;
|
|
3264
|
+
}
|
|
3265
|
+
} else if (code === quote) {
|
|
3266
|
+
quote = 0;
|
|
3267
|
+
}
|
|
3268
|
+
}
|
|
3269
|
+
states[line.length] = quote;
|
|
3270
|
+
return states;
|
|
3271
|
+
}
|
|
3272
|
+
function quoteStateFor(line, context) {
|
|
3273
|
+
if (context.quoteAt === void 0) context.quoteAt = quoteStates(line);
|
|
3274
|
+
return context.quoteAt;
|
|
3275
|
+
}
|
|
3276
|
+
function quoteStateAfter(text2, quote, end = text2.length) {
|
|
3277
|
+
for (let index = 0; index < end; index += 1) {
|
|
3278
|
+
const code = text2.charCodeAt(index);
|
|
3279
|
+
if (quote === 0) {
|
|
3280
|
+
if (isOpeningQuote(text2, index)) quote = code;
|
|
3281
|
+
} else if (code === 92) {
|
|
3282
|
+
index += 1;
|
|
3283
|
+
} else if (code === quote) {
|
|
3284
|
+
quote = 0;
|
|
3285
|
+
}
|
|
3286
|
+
}
|
|
3287
|
+
return quote;
|
|
3288
|
+
}
|
|
3289
|
+
function commentStartFor(line, context) {
|
|
3290
|
+
if (context.commentStart !== void 0) return context.commentStart;
|
|
3291
|
+
const quotes = quoteStateFor(line, context);
|
|
3292
|
+
let start = line.length;
|
|
3293
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3294
|
+
if (line.charCodeAt(index) !== 35 || quotes[index] !== 0) continue;
|
|
3295
|
+
if (index === 0 || /\s/.test(line[index - 1])) {
|
|
3296
|
+
start = index;
|
|
3297
|
+
break;
|
|
3298
|
+
}
|
|
3299
|
+
}
|
|
3300
|
+
context.commentStart = start;
|
|
3301
|
+
return start;
|
|
3302
|
+
}
|
|
3303
|
+
function commandSeparatorsFor(line, context) {
|
|
3304
|
+
if (context.commandSeparators !== void 0) return context.commandSeparators;
|
|
3305
|
+
const quotes = quoteStateFor(line, context);
|
|
3306
|
+
const separators = [];
|
|
3307
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3308
|
+
if (quotes[index] !== 0) continue;
|
|
3309
|
+
const ch = line[index];
|
|
3310
|
+
const spaced = index > 0 && /\s/.test(line[index - 1]) || index + 1 < line.length && /\s/.test(line[index + 1]);
|
|
3311
|
+
if (ch === "&" || ch === "|") {
|
|
3312
|
+
if (line[index + 1] === ch) {
|
|
3313
|
+
const after = index + 2;
|
|
3314
|
+
const doubleSpaced = spaced || after >= line.length || /\s/.test(line[after]);
|
|
3315
|
+
if (doubleSpaced) separators.push(index);
|
|
3316
|
+
index += 1;
|
|
3317
|
+
} else if (spaced) {
|
|
3318
|
+
separators.push(index);
|
|
3319
|
+
}
|
|
3320
|
+
} else if ((ch === ";" || ch === ">" || ch === "<") && spaced) {
|
|
3321
|
+
separators.push(index);
|
|
3322
|
+
}
|
|
3323
|
+
}
|
|
3324
|
+
context.commandSeparators = separators;
|
|
3325
|
+
return separators;
|
|
3326
|
+
}
|
|
3327
|
+
function lineValueEnd(line, start, context) {
|
|
3328
|
+
const comment = commentStartFor(line, context);
|
|
3329
|
+
let end = comment > start ? comment : line.length;
|
|
3330
|
+
for (const separator of commandSeparatorsFor(line, context)) {
|
|
3331
|
+
if (separator > start && separator < end) {
|
|
3332
|
+
end = separator;
|
|
3333
|
+
break;
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
while (end > start && /\s/.test(line[end - 1])) end -= 1;
|
|
3337
|
+
return end;
|
|
3338
|
+
}
|
|
3339
|
+
function hasStructuralQuote(line) {
|
|
3340
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3341
|
+
const ch = line[index];
|
|
3342
|
+
if (ch !== '"' && ch !== "'" && ch !== "`") continue;
|
|
3343
|
+
if (ch === "'" && index > 0 && /[A-Za-z0-9]/.test(line[index - 1])) continue;
|
|
3344
|
+
let backslashes = 0;
|
|
3345
|
+
for (let before2 = index - 1; before2 >= 0 && line[before2] === "\\"; before2 -= 1) backslashes += 1;
|
|
3346
|
+
if (backslashes % 2 === 1) continue;
|
|
3347
|
+
let before = index - 1;
|
|
3348
|
+
while (before >= 0 && (line[before] === " " || line[before] === " ")) before -= 1;
|
|
3349
|
+
if (before < 0 || "+,=:([{".includes(line[before])) return true;
|
|
3350
|
+
}
|
|
3351
|
+
return false;
|
|
3352
|
+
}
|
|
3353
|
+
function maskRawPemLine(line) {
|
|
3354
|
+
if (line.trim() === "") return line;
|
|
3355
|
+
const leading = /^[ \t]*(?:#|\/\/|;)?[ \t]*/.exec(line)?.[0] ?? "";
|
|
3356
|
+
let rest = line.slice(leading.length);
|
|
3357
|
+
const trailing = /[ \t]*(?:[,;\\+])?[ \t]*$/.exec(rest)?.[0] ?? "";
|
|
3358
|
+
rest = rest.slice(0, rest.length - trailing.length);
|
|
3359
|
+
return leading + (rest.length > 0 ? PEM_REDACTION_MARKER : "") + trailing;
|
|
3360
|
+
}
|
|
3361
|
+
function skeletonisePemLine(line, initialQuote) {
|
|
3362
|
+
const hasQuote = line.includes('"') || line.includes("'") || line.includes("`");
|
|
3363
|
+
const structural = initialQuote !== 0 || hasQuote && (hasStructuralQuote(line) || /-----BEGIN|-----END/.test(line));
|
|
3364
|
+
if (!structural) return { text: maskRawPemLine(line), quote: initialQuote };
|
|
3365
|
+
let out = "";
|
|
3366
|
+
let quote = initialQuote;
|
|
3367
|
+
let masking = false;
|
|
3368
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
3369
|
+
const code = line.charCodeAt(index);
|
|
3370
|
+
if (quote === 0) {
|
|
3371
|
+
if (isOpeningQuote(line, index)) {
|
|
3372
|
+
quote = code;
|
|
3373
|
+
masking = false;
|
|
3374
|
+
}
|
|
3375
|
+
out += line[index];
|
|
3376
|
+
continue;
|
|
3377
|
+
}
|
|
3378
|
+
if (code === 92) {
|
|
3379
|
+
masking = false;
|
|
3380
|
+
out += line[index];
|
|
3381
|
+
if (index + 1 < line.length) {
|
|
3382
|
+
out += line[index + 1];
|
|
3383
|
+
index += 1;
|
|
3384
|
+
}
|
|
3385
|
+
continue;
|
|
3386
|
+
}
|
|
3387
|
+
if (code === quote) {
|
|
3388
|
+
masking = false;
|
|
3389
|
+
quote = 0;
|
|
3390
|
+
out += line[index];
|
|
3391
|
+
continue;
|
|
3392
|
+
}
|
|
3393
|
+
if (!masking) {
|
|
3394
|
+
out += PEM_REDACTION_MARKER;
|
|
3395
|
+
masking = true;
|
|
3396
|
+
}
|
|
3397
|
+
}
|
|
3398
|
+
return { text: out, quote };
|
|
3399
|
+
}
|
|
3400
|
+
function lineSpanAt(text2, start, end) {
|
|
3401
|
+
let lineStart = start;
|
|
3402
|
+
while (lineStart > 0 && text2[lineStart - 1] !== "\n" && text2[lineStart - 1] !== "\r") {
|
|
3403
|
+
lineStart -= 1;
|
|
3404
|
+
}
|
|
3405
|
+
let lineEnd = end;
|
|
3406
|
+
while (lineEnd < text2.length && text2[lineEnd] !== "\n" && text2[lineEnd] !== "\r") lineEnd += 1;
|
|
3407
|
+
if (lineEnd < text2.length) {
|
|
3408
|
+
lineEnd += text2[lineEnd] === "\r" && text2[lineEnd + 1] === "\n" ? 2 : 1;
|
|
3409
|
+
}
|
|
3410
|
+
return { start: lineStart, end: lineEnd };
|
|
3411
|
+
}
|
|
3412
|
+
function redactPemSpan(text2, matchStart, matchEnd) {
|
|
3413
|
+
const span = lineSpanAt(text2, matchStart, matchEnd);
|
|
3414
|
+
const segments = text2.slice(span.start, span.end).split(LINE_BREAK);
|
|
3415
|
+
let quote = quoteStateAfter(text2, 0, matchStart);
|
|
3416
|
+
let cursor = span.start;
|
|
3417
|
+
for (let index = 0; index < segments.length; index += 2) {
|
|
3418
|
+
const line = segments[index];
|
|
3419
|
+
const lineStart = cursor;
|
|
3420
|
+
const lineEnd = lineStart + line.length;
|
|
3421
|
+
cursor = lineEnd + (index + 1 < segments.length ? segments[index + 1].length : 0);
|
|
3422
|
+
const from = Math.max(lineStart, matchStart);
|
|
3423
|
+
const to = Math.min(lineEnd, matchEnd);
|
|
3424
|
+
if (from >= to) continue;
|
|
3425
|
+
const localFrom = from - lineStart;
|
|
3426
|
+
const localTo = to - lineStart;
|
|
3427
|
+
const result = skeletonisePemLine(line.slice(localFrom, localTo), quote);
|
|
3428
|
+
segments[index] = line.slice(0, localFrom) + result.text + line.slice(localTo);
|
|
3429
|
+
quote = result.quote;
|
|
3430
|
+
}
|
|
3431
|
+
return { replacement: segments.join(""), start: span.start, end: span.end };
|
|
3432
|
+
}
|
|
3161
3433
|
var COMPILED_RULES = /* @__PURE__ */ new WeakMap();
|
|
3162
3434
|
function compiledRuleFor(rule) {
|
|
3163
3435
|
let compiled = COMPILED_RULES.get(rule);
|
|
@@ -3172,22 +3444,30 @@ function compiledRuleFor(rule) {
|
|
|
3172
3444
|
return compiled;
|
|
3173
3445
|
}
|
|
3174
3446
|
function scanAndRedactSecrets(content, rules, filePath) {
|
|
3175
|
-
const
|
|
3447
|
+
const findingsByLine = /* @__PURE__ */ new Map();
|
|
3448
|
+
const recordFinding = (line, rulesForLine) => {
|
|
3449
|
+
let entry = findingsByLine.get(line);
|
|
3450
|
+
if (entry === void 0) {
|
|
3451
|
+
entry = /* @__PURE__ */ new Set();
|
|
3452
|
+
findingsByLine.set(line, entry);
|
|
3453
|
+
}
|
|
3454
|
+
for (const rule of rulesForLine) entry.add(rule);
|
|
3455
|
+
};
|
|
3176
3456
|
let redacted = content;
|
|
3177
3457
|
for (const blockPattern of [PEM_BLOCK_PATTERN, PEM_UNTERMINATED_PATTERN]) {
|
|
3178
3458
|
blockPattern.lastIndex = 0;
|
|
3179
3459
|
let match;
|
|
3180
3460
|
while ((match = blockPattern.exec(redacted)) !== null) {
|
|
3181
3461
|
if (match[0].length === 0) {
|
|
3182
|
-
blockPattern.lastIndex
|
|
3462
|
+
blockPattern.lastIndex = advanceStringIndex(redacted, match.index, blockPattern.unicode);
|
|
3183
3463
|
continue;
|
|
3184
3464
|
}
|
|
3185
|
-
const
|
|
3186
|
-
const line = (
|
|
3187
|
-
const
|
|
3188
|
-
|
|
3189
|
-
redacted =
|
|
3190
|
-
blockPattern.lastIndex =
|
|
3465
|
+
const matchEnd = match.index + match[0].length;
|
|
3466
|
+
const line = (redacted.slice(0, match.index).match(LINE_TERMINATOR) ?? []).length + 1;
|
|
3467
|
+
const span = redactPemSpan(redacted, match.index, matchEnd);
|
|
3468
|
+
recordFinding(line, ["private-key-block"]);
|
|
3469
|
+
redacted = redacted.slice(0, span.start) + span.replacement + redacted.slice(span.end);
|
|
3470
|
+
blockPattern.lastIndex = span.start + span.replacement.length;
|
|
3191
3471
|
}
|
|
3192
3472
|
}
|
|
3193
3473
|
const compiled = rules.map(compiledRuleFor);
|
|
@@ -3198,17 +3478,38 @@ function scanAndRedactSecrets(content, rules, filePath) {
|
|
|
3198
3478
|
if (line.length > 0) {
|
|
3199
3479
|
const spans = [];
|
|
3200
3480
|
const matchedRules = /* @__PURE__ */ new Set();
|
|
3481
|
+
const context = {};
|
|
3201
3482
|
for (const { rule, pattern, valueGroup } of compiled) {
|
|
3202
3483
|
pattern.lastIndex = 0;
|
|
3203
3484
|
let match;
|
|
3204
3485
|
while ((match = pattern.exec(line)) !== null) {
|
|
3205
3486
|
if (match[0].length === 0) {
|
|
3206
|
-
pattern.lastIndex
|
|
3487
|
+
pattern.lastIndex = advanceStringIndex(line, match.index, pattern.unicode);
|
|
3207
3488
|
continue;
|
|
3208
3489
|
}
|
|
3209
3490
|
const group = valueGroup === void 0 ? void 0 : match.indices?.[valueGroup];
|
|
3491
|
+
const candidate = group ? line.slice(group[0], group[1]) : line.slice(match.index, match.index + match[0].length);
|
|
3492
|
+
if (isPlaceholderValue(candidate)) continue;
|
|
3493
|
+
if (group && isUnquotedValue(line, group[0]) && isSourceCodeFile(filePath) && (quoteStateFor(line, context)[match.index] ?? 0) === 0) {
|
|
3494
|
+
continue;
|
|
3495
|
+
}
|
|
3496
|
+
if (group && /^\$[({A-Za-z_]/.test(line.slice(group[0], group[1])) && (isAssignmentFile(filePath) || isUnquotedValue(line, group[0]))) {
|
|
3497
|
+
continue;
|
|
3498
|
+
}
|
|
3499
|
+
if (rule === "credential-assignment-weak" && group) {
|
|
3500
|
+
let before = match.index - 1;
|
|
3501
|
+
while (before >= 0 && (line[before] === " " || line[before] === " ")) before -= 1;
|
|
3502
|
+
if (before >= 0 && (line[before] === "?" || line[before] === ":")) continue;
|
|
3503
|
+
const keyText = line.slice(match.index, group[0]).replace(/["'\s:=]+/g, " ").trim();
|
|
3504
|
+
if (/^(?:PASS|FAIL)$/i.test(keyText) && /^[A-Z]{2,}$/.test(line.slice(group[0], group[1]))) {
|
|
3505
|
+
continue;
|
|
3506
|
+
}
|
|
3507
|
+
}
|
|
3210
3508
|
if (group && isSelfNamingConstant(line, group[0], group[1])) continue;
|
|
3211
|
-
if (
|
|
3509
|
+
if (group && !isUnquotedValue(line, group[0]) && /["'`]\s*\+\s*|\s*\+\s*["'`]/.test(line.slice(group[0], group[1]))) {
|
|
3510
|
+
continue;
|
|
3511
|
+
}
|
|
3512
|
+
if (valueGroup !== void 0 && startsInsideStringLiteral(line, match.index, group?.[0], context, filePath)) {
|
|
3212
3513
|
continue;
|
|
3213
3514
|
}
|
|
3214
3515
|
if (group && isUnquotedValue(line, group[0]) && isDeclaredBinding(line, match.index, filePath)) {
|
|
@@ -3234,7 +3535,12 @@ function scanAndRedactSecrets(content, rules, filePath) {
|
|
|
3234
3535
|
if (wholeValue) {
|
|
3235
3536
|
spans.push({
|
|
3236
3537
|
start: group[0],
|
|
3237
|
-
|
|
3538
|
+
// A passphrase contains spaces: `DB_PASSWORD=correct horse battery staple` used to
|
|
3539
|
+
// stop at the first one and emit the rest beside the marker. Stop at the end of
|
|
3540
|
+
// the value, a trailing comment, or a shell operator instead. The rule's own end
|
|
3541
|
+
// is not used: the colon form's value pattern includes the spaces before a
|
|
3542
|
+
// trailing `# comment`, and masking them welds the comment to the marker.
|
|
3543
|
+
end: lineValueEnd(line, group[0], context),
|
|
3238
3544
|
rule
|
|
3239
3545
|
});
|
|
3240
3546
|
matchedRules.add(rule);
|
|
@@ -3247,14 +3553,153 @@ function scanAndRedactSecrets(content, rules, filePath) {
|
|
|
3247
3553
|
matchedRules.add(rule);
|
|
3248
3554
|
}
|
|
3249
3555
|
}
|
|
3556
|
+
for (const span of concatenatedCredentialSpans(line)) {
|
|
3557
|
+
spans.push(span);
|
|
3558
|
+
matchedRules.add(span.rule);
|
|
3559
|
+
}
|
|
3250
3560
|
if (spans.length > 0) {
|
|
3251
|
-
|
|
3252
|
-
|
|
3561
|
+
const maskedLine = applySpans(line, spans);
|
|
3562
|
+
if (!quotesAreBalanced(line) || quotesAreBalanced(maskedLine)) {
|
|
3563
|
+
recordFinding(lineNumber, matchedRules);
|
|
3564
|
+
segments[index] = maskedLine;
|
|
3565
|
+
}
|
|
3253
3566
|
}
|
|
3254
3567
|
}
|
|
3255
3568
|
if (index + 1 < segments.length) lineNumber += 1;
|
|
3256
3569
|
}
|
|
3257
|
-
|
|
3570
|
+
let finalText = segments.join("");
|
|
3571
|
+
finalText = redactStructuredValues(finalText, filePath, recordFinding);
|
|
3572
|
+
finalText = redactDockerfileEnv(finalText, filePath, recordFinding);
|
|
3573
|
+
const findings = [...findingsByLine.entries()].sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
|
|
3574
|
+
rules: [...rulesForLine],
|
|
3575
|
+
line,
|
|
3576
|
+
path: filePath
|
|
3577
|
+
}));
|
|
3578
|
+
return { redacted: finalText, findings };
|
|
3579
|
+
}
|
|
3580
|
+
function advanceStringIndex(text2, index, unicode) {
|
|
3581
|
+
if (!unicode) return index + 1;
|
|
3582
|
+
const first = text2.charCodeAt(index);
|
|
3583
|
+
if (first >= 55296 && first <= 56319) {
|
|
3584
|
+
const second = text2.charCodeAt(index + 1);
|
|
3585
|
+
if (second >= 56320 && second <= 57343) return index + 2;
|
|
3586
|
+
}
|
|
3587
|
+
return index + 1;
|
|
3588
|
+
}
|
|
3589
|
+
var STRUCTURED_FILE = /\.(?:json|jsonc|json5|ya?ml|toml|ini|conf|cfg|properties|env|tf|tfvars)$/i;
|
|
3590
|
+
var STRUCTURED_BASENAME = /^(?:\.env(?:\.[^/]*)?|docker-compose(?:\.[^/]*)?|compose(?:\.[^/]*)?)$/i;
|
|
3591
|
+
function isStructuredFile(filePath) {
|
|
3592
|
+
if (filePath === void 0) return false;
|
|
3593
|
+
const normalised = filePath.replace(/\\/g, "/");
|
|
3594
|
+
if (STRUCTURED_FILE.test(normalised)) return true;
|
|
3595
|
+
return STRUCTURED_BASENAME.test(normalised.slice(normalised.lastIndexOf("/") + 1));
|
|
3596
|
+
}
|
|
3597
|
+
function isDockerfile(filePath) {
|
|
3598
|
+
if (filePath === void 0) return false;
|
|
3599
|
+
const normalised = filePath.replace(/\\/g, "/");
|
|
3600
|
+
return /^(?:Dockerfile|[^/]*\.dockerfile)$/i.test(
|
|
3601
|
+
normalised.slice(normalised.lastIndexOf("/") + 1)
|
|
3602
|
+
);
|
|
3603
|
+
}
|
|
3604
|
+
function maskLineContent(line) {
|
|
3605
|
+
if (line.trim() === "") return line;
|
|
3606
|
+
const indent = /^[ \t]*/.exec(line)?.[0] ?? "";
|
|
3607
|
+
return `${indent}${REDACTION_MARKER}`;
|
|
3608
|
+
}
|
|
3609
|
+
function maskValueLine(line) {
|
|
3610
|
+
if (line.trim() === "") return line;
|
|
3611
|
+
const indent = /^[ \t]*/.exec(line)?.[0] ?? "";
|
|
3612
|
+
const content = line.slice(indent.length);
|
|
3613
|
+
const quoted = /^(["'`])(.*)\1([,;]?[ \t]*)$/.exec(content);
|
|
3614
|
+
if (quoted !== null) {
|
|
3615
|
+
return `${indent}${quoted[1]}${REDACTION_MARKER}${quoted[1]}${quoted[3] ?? ""}`;
|
|
3616
|
+
}
|
|
3617
|
+
return `${indent}${REDACTION_MARKER}`;
|
|
3618
|
+
}
|
|
3619
|
+
var STRUCTURED_KEY = /^([ \t]*)["']?([A-Za-z0-9_$.-]{1,128})["']?[ \t]*([:=])[ \t]*(.*)$/;
|
|
3620
|
+
var BLOCK_SCALAR = /^[|>][+-]?\d*[ \t]*(?:#.*)?$/;
|
|
3621
|
+
function redactStructuredValues(text2, filePath, recordFinding) {
|
|
3622
|
+
if (!isStructuredFile(filePath)) return text2;
|
|
3623
|
+
const segments = text2.split(LINE_BREAK);
|
|
3624
|
+
for (let index = 0; index < segments.length; index += 2) {
|
|
3625
|
+
const line = segments[index];
|
|
3626
|
+
if (line === void 0 || line.length === 0) continue;
|
|
3627
|
+
const match = STRUCTURED_KEY.exec(line);
|
|
3628
|
+
if (match === null) continue;
|
|
3629
|
+
const key = match[2] ?? "";
|
|
3630
|
+
if (!CREDENTIAL_KEY_TAIL.test(key)) continue;
|
|
3631
|
+
const baseIndent = (match[1] ?? "").length;
|
|
3632
|
+
const rest = (match[4] ?? "").trim();
|
|
3633
|
+
if (BLOCK_SCALAR.test(rest)) {
|
|
3634
|
+
let cursor2 = index + 2;
|
|
3635
|
+
let masked2 = false;
|
|
3636
|
+
while (cursor2 < segments.length) {
|
|
3637
|
+
const body = segments[cursor2] ?? "";
|
|
3638
|
+
if (body.trim() !== "") {
|
|
3639
|
+
const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
|
|
3640
|
+
if (indent <= baseIndent) break;
|
|
3641
|
+
segments[cursor2] = maskLineContent(body);
|
|
3642
|
+
masked2 = true;
|
|
3643
|
+
}
|
|
3644
|
+
cursor2 += 2;
|
|
3645
|
+
}
|
|
3646
|
+
if (masked2) recordFinding(index / 2 + 1, ["credential-block-scalar"]);
|
|
3647
|
+
continue;
|
|
3648
|
+
}
|
|
3649
|
+
if (rest !== "") continue;
|
|
3650
|
+
let cursor = index + 2;
|
|
3651
|
+
while (cursor < segments.length && (segments[cursor] ?? "").trim() === "") cursor += 2;
|
|
3652
|
+
const firstValue = segments[cursor];
|
|
3653
|
+
if (firstValue === void 0) continue;
|
|
3654
|
+
const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
|
|
3655
|
+
if (valueIndent <= baseIndent) continue;
|
|
3656
|
+
let masked = false;
|
|
3657
|
+
while (cursor < segments.length) {
|
|
3658
|
+
const body = segments[cursor] ?? "";
|
|
3659
|
+
if (body.trim() !== "") {
|
|
3660
|
+
const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
|
|
3661
|
+
if (indent < valueIndent) break;
|
|
3662
|
+
segments[cursor] = maskValueLine(body);
|
|
3663
|
+
masked = true;
|
|
3664
|
+
}
|
|
3665
|
+
cursor += 2;
|
|
3666
|
+
}
|
|
3667
|
+
if (masked) recordFinding(index / 2 + 1, ["credential-multiline-value"]);
|
|
3668
|
+
}
|
|
3669
|
+
return segments.join("");
|
|
3670
|
+
}
|
|
3671
|
+
var DOCKERFILE_ENV = /^([ \t]*ENV[ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/;
|
|
3672
|
+
function redactDockerfileEnv(text2, filePath, recordFinding) {
|
|
3673
|
+
if (!isDockerfile(filePath)) return text2;
|
|
3674
|
+
const segments = text2.split(LINE_BREAK);
|
|
3675
|
+
for (let index = 0; index < segments.length; index += 2) {
|
|
3676
|
+
const line = segments[index];
|
|
3677
|
+
if (line === void 0) continue;
|
|
3678
|
+
const match = DOCKERFILE_ENV.exec(line);
|
|
3679
|
+
if (match === null) continue;
|
|
3680
|
+
if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
|
|
3681
|
+
const value = match[4] ?? "";
|
|
3682
|
+
if (value.startsWith("=")) continue;
|
|
3683
|
+
segments[index] = `${match[1]}${match[2]}${match[3]}${REDACTION_MARKER}`;
|
|
3684
|
+
recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
|
|
3685
|
+
}
|
|
3686
|
+
return segments.join("");
|
|
3687
|
+
}
|
|
3688
|
+
var CONCATENATED_CREDENTIAL = new RegExp(
|
|
3689
|
+
"([A-Za-z0-9_$.-]{0,64}(?:password|passwd|passphrase|pwd|api[_-]?key|api[_-]?secret|access[_-]?key|secret[_-]?access[_-]?key|secret[_-]?key|client[_-]?secret[_-]?key|client[_-]?secret|private[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|session[_-]?token|session[_-]?key|secret|token))\\s*=\\s*(?<=[=:]\\s{0,8})([\"'`])\\s*\\+\\s*([\"'`])((?:(?!\\3)[^\\\\\\n]|\\\\.){1,512})\\3",
|
|
3690
|
+
"gid"
|
|
3691
|
+
);
|
|
3692
|
+
function concatenatedCredentialSpans(line) {
|
|
3693
|
+
const spans = [];
|
|
3694
|
+
CONCATENATED_CREDENTIAL.lastIndex = 0;
|
|
3695
|
+
let match;
|
|
3696
|
+
while ((match = CONCATENATED_CREDENTIAL.exec(line)) !== null) {
|
|
3697
|
+
const group = match.indices?.[4];
|
|
3698
|
+
if (group !== void 0) {
|
|
3699
|
+
spans.push({ start: group[0], end: group[1], rule: "credential-concatenation" });
|
|
3700
|
+
}
|
|
3701
|
+
}
|
|
3702
|
+
return spans;
|
|
3258
3703
|
}
|
|
3259
3704
|
var TOKEN_CHARS_LEFT = /[A-Za-z0-9_+/-]/;
|
|
3260
3705
|
var TOKEN_CHARS_RIGHT = /[A-Za-z0-9_+/=-]/;
|
|
@@ -3272,13 +3717,20 @@ function expandOverToken(line, start, end) {
|
|
|
3272
3717
|
while (right < line.length && TOKEN_CHARS_RIGHT.test(line[right])) right += 1;
|
|
3273
3718
|
return { start: left, end: right };
|
|
3274
3719
|
}
|
|
3275
|
-
function startsInsideStringLiteral(line, matchIndex, valueStart) {
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
if (before !== '"' && before !== "'" && before !== "`") return false;
|
|
3720
|
+
function startsInsideStringLiteral(line, matchIndex, valueStart, context, filePath) {
|
|
3721
|
+
const quote = quoteStateFor(line, context)[matchIndex] ?? 0;
|
|
3722
|
+
if (quote === 0) return false;
|
|
3723
|
+
if (quote === 96 && /\.(?:md|mdx)$/i.test(filePath ?? "")) return true;
|
|
3280
3724
|
if (valueStart === void 0) return true;
|
|
3281
|
-
|
|
3725
|
+
for (let index = matchIndex; index < valueStart; index += 1) {
|
|
3726
|
+
const code = line.charCodeAt(index);
|
|
3727
|
+
if (code === 92) {
|
|
3728
|
+
index += 1;
|
|
3729
|
+
} else if (code === quote) {
|
|
3730
|
+
return true;
|
|
3731
|
+
}
|
|
3732
|
+
}
|
|
3733
|
+
return false;
|
|
3282
3734
|
}
|
|
3283
3735
|
function isTemplateInterpolation(line, start, end) {
|
|
3284
3736
|
if (line[start] !== "$" || line[start + 1] !== "{" || line[end - 1] !== "}") {
|
|
@@ -3306,6 +3758,40 @@ function isSelfNamingConstant(line, start, end) {
|
|
|
3306
3758
|
}
|
|
3307
3759
|
return line.endsWith(value, index);
|
|
3308
3760
|
}
|
|
3761
|
+
var SOURCE_CODE_FILE = /\.(?:[cm]?[jt]sx?)$/i;
|
|
3762
|
+
function isSourceCodeFile(filePath) {
|
|
3763
|
+
return filePath !== void 0 && SOURCE_CODE_FILE.test(filePath.replace(/\\/g, "/"));
|
|
3764
|
+
}
|
|
3765
|
+
var PLACEHOLDER_PATTERNS = [
|
|
3766
|
+
/^<[^>]*>?$/,
|
|
3767
|
+
/^\.{3,}$/,
|
|
3768
|
+
/^(?:x{4,}|X{4,}|\*{3,})$/,
|
|
3769
|
+
/^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
|
|
3770
|
+
/^your[-_ ].*$/i,
|
|
3771
|
+
/^(?:example|sample)(?:[-_ ].*)?$/i
|
|
3772
|
+
];
|
|
3773
|
+
function isPlaceholderValue(value) {
|
|
3774
|
+
const trimmed = value.trim().replace(/^["'`]+/, "").replace(/["'`]+$/, "");
|
|
3775
|
+
if (trimmed.length === 0) return false;
|
|
3776
|
+
if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
|
|
3777
|
+
return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
|
|
3778
|
+
}
|
|
3779
|
+
function quotesAreBalanced(text2) {
|
|
3780
|
+
let single = 0;
|
|
3781
|
+
let double = 0;
|
|
3782
|
+
let backtick = 0;
|
|
3783
|
+
for (let index = 0; index < text2.length; index += 1) {
|
|
3784
|
+
const char = text2[index];
|
|
3785
|
+
if (char === "\\") {
|
|
3786
|
+
index += 1;
|
|
3787
|
+
continue;
|
|
3788
|
+
}
|
|
3789
|
+
if (char === '"') double += 1;
|
|
3790
|
+
else if (char === "'") single += 1;
|
|
3791
|
+
else if (char === "`") backtick += 1;
|
|
3792
|
+
}
|
|
3793
|
+
return double % 2 === 0 && single % 2 === 0 && backtick % 2 === 0;
|
|
3794
|
+
}
|
|
3309
3795
|
function assignmentAround(line, valueStart) {
|
|
3310
3796
|
let index = valueStart;
|
|
3311
3797
|
while (index > 0 && (line[index - 1] === " " || line[index - 1] === " ")) index -= 1;
|
|
@@ -3375,6 +3861,16 @@ function applySpans(line, spans) {
|
|
|
3375
3861
|
return out;
|
|
3376
3862
|
}
|
|
3377
3863
|
|
|
3864
|
+
// src/version.ts
|
|
3865
|
+
var GENERATOR_NAME = "codebase-snapshot";
|
|
3866
|
+
var GENERATOR_VERSION = "0.9.17";
|
|
3867
|
+
var SCHEMA_VERSION = "3.0.0";
|
|
3868
|
+
var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
|
|
3869
|
+
function isOurGeneratorName(name) {
|
|
3870
|
+
if (typeof name !== "string") return false;
|
|
3871
|
+
return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
|
|
3872
|
+
}
|
|
3873
|
+
|
|
3378
3874
|
// src/scanner/files.ts
|
|
3379
3875
|
function isDiscoveryMode(value) {
|
|
3380
3876
|
return value === "auto" || value === "git" || value === "walk";
|
|
@@ -3384,7 +3880,7 @@ var PRESET_IGNORES = new Set(
|
|
|
3384
3880
|
);
|
|
3385
3881
|
function readLinkTarget(linkPath, fallback) {
|
|
3386
3882
|
try {
|
|
3387
|
-
return
|
|
3883
|
+
return fs15.readlinkSync(linkPath);
|
|
3388
3884
|
} catch {
|
|
3389
3885
|
return fallback;
|
|
3390
3886
|
}
|
|
@@ -3399,8 +3895,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
|
|
|
3399
3895
|
};
|
|
3400
3896
|
}
|
|
3401
3897
|
function isInside(root, candidate) {
|
|
3402
|
-
const
|
|
3403
|
-
return
|
|
3898
|
+
const relative10 = path16.relative(root, candidate);
|
|
3899
|
+
return relative10 === "" || !relative10.startsWith(`..${path16.sep}`) && relative10 !== ".." && !path16.isAbsolute(relative10);
|
|
3404
3900
|
}
|
|
3405
3901
|
var GIT_OUTPUT_LIMIT = 68157440;
|
|
3406
3902
|
function getGitInfo(cwd, fallbackBranch = "main") {
|
|
@@ -3461,10 +3957,10 @@ var DEFAULT_IGNORED_FILES = [
|
|
|
3461
3957
|
"bun.lockb",
|
|
3462
3958
|
"composer.lock"
|
|
3463
3959
|
];
|
|
3464
|
-
var SENSITIVE_BASENAME = /^(?:\.env(?:[._-][A-Za-z0-9_-]*)*|\.env(?:backup|bak|old|orig|copy|save)|\.envrc|\.npmrc(?:\.[A-Za-z0-9_-]+)?|\.yarnrc(?:\.yml)?|\.netrc(?:\.[A-Za-z0-9_-]+)?|\.git-credentials|\.htpasswd|\.pgpass|\.vault-token|vault[-_]agent[-_]token|id_[a-z0-9_]+(?:\.[A-Za-z0-9_-]+)?|credentials(?:\.(?:json|ya?ml|toml))?|service[-_]?account(?:\.[a-z0-9_-]+)*\.json|secrets?\.(?:json|ya?ml|toml)|env|[A-Za-z0-9_-]{1,64}\.env)$/i;
|
|
3465
|
-
var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$/i;
|
|
3960
|
+
var SENSITIVE_BASENAME = /^(?:\.env(?:[._-][A-Za-z0-9_-]*)*|\.env(?:backup|bak|old|orig|copy|save)|\.envrc|\.npmrc(?:\.[A-Za-z0-9_-]+)?|\.yarnrc(?:\.yml)?|\.netrc(?:\.[A-Za-z0-9_-]+)?|\.git-credentials|\.htpasswd|\.pgpass|\.pypirc|\.vault-token|vault[-_]agent[-_]token|\.composer-auth\.json|auth\.json|application_default_credentials\.json|id_[a-z0-9_]+(?:\.[A-Za-z0-9_-]+)?|credentials(?:\.(?:json|ya?ml|toml))?|service[-_]?account(?:\.[a-z0-9_-]+)*\.json|secrets?\.(?:json|ya?ml|toml)|env|[A-Za-z0-9_-]{1,64}\.env)$/i;
|
|
3961
|
+
var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
|
|
3466
3962
|
var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
|
|
3467
|
-
var TEMPLATE_SUFFIX =
|
|
3963
|
+
var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.[A-Za-z0-9_-]+)?$/i;
|
|
3468
3964
|
var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
|
|
3469
3965
|
function normaliseName(name) {
|
|
3470
3966
|
let normalised = name.trim().replace(/[. ]+$/, "");
|
|
@@ -3480,12 +3976,16 @@ function isSensitivePath(relativePath) {
|
|
|
3480
3976
|
const posixPath = relativePath.replace(/\\/g, "/");
|
|
3481
3977
|
const raw = posixPath.split("/").pop() ?? posixPath;
|
|
3482
3978
|
const base = normaliseName(raw);
|
|
3483
|
-
if (
|
|
3484
|
-
const stripped = base.replace(new RegExp(TEMPLATE_SUFFIX.source, "gi"), "");
|
|
3485
|
-
if (matchesSensitiveList(posixPath, stripped)) return false;
|
|
3486
|
-
}
|
|
3979
|
+
if (templateOfCredentialFile(posixPath, base)) return false;
|
|
3487
3980
|
return matchesSensitiveList(posixPath, base);
|
|
3488
3981
|
}
|
|
3982
|
+
function templateOfCredentialFile(posixPath, base) {
|
|
3983
|
+
const match = TEMPLATE_SUFFIX.exec(base);
|
|
3984
|
+
if (match === null) return null;
|
|
3985
|
+
const stripped = `${match[1] ?? ""}${match[2] ?? ""}`;
|
|
3986
|
+
if (SENSITIVE_EXT.test(stripped)) return null;
|
|
3987
|
+
return matchesSensitiveList(posixPath, stripped) ? stripped : null;
|
|
3988
|
+
}
|
|
3489
3989
|
var GLOBAL_PATTERNS = /* @__PURE__ */ new WeakMap();
|
|
3490
3990
|
var GLOB_REGEX_CACHE = /* @__PURE__ */ new Map();
|
|
3491
3991
|
var GITIGNORE_REGEX_CACHE = /* @__PURE__ */ new Map();
|
|
@@ -3517,7 +4017,7 @@ function findSecretInPath(relativePath, extraRules) {
|
|
|
3517
4017
|
let match;
|
|
3518
4018
|
while ((match = scan.exec(posixPath)) !== null) {
|
|
3519
4019
|
if (match[0].length === 0) {
|
|
3520
|
-
scan.lastIndex
|
|
4020
|
+
scan.lastIndex = advanceStringIndex(posixPath, match.index, scan.unicode);
|
|
3521
4021
|
continue;
|
|
3522
4022
|
}
|
|
3523
4023
|
spans.push({ start: match.index, end: match.index + match[0].length });
|
|
@@ -3578,11 +4078,14 @@ function globBodyToRegExp(body, allowBraces) {
|
|
|
3578
4078
|
if (char === "*") {
|
|
3579
4079
|
if (body[i + 1] === "*") {
|
|
3580
4080
|
i += 1;
|
|
3581
|
-
|
|
4081
|
+
const startsSegment = i - 2 < 0 || body[i - 2] === "/";
|
|
4082
|
+
if (startsSegment && body[i + 1] === "/") {
|
|
3582
4083
|
i += 1;
|
|
3583
|
-
out += "(
|
|
3584
|
-
} else {
|
|
4084
|
+
out += "(?:[^/]+/)*";
|
|
4085
|
+
} else if (startsSegment && i + 1 === body.length) {
|
|
3585
4086
|
out += ".*";
|
|
4087
|
+
} else {
|
|
4088
|
+
out += "[^/]*";
|
|
3586
4089
|
}
|
|
3587
4090
|
} else {
|
|
3588
4091
|
out += "[^/]*";
|
|
@@ -3654,7 +4157,7 @@ function readGitignoreRules(dir) {
|
|
|
3654
4157
|
const gitignorePath2 = path16.join(dir, ".gitignore");
|
|
3655
4158
|
let raw;
|
|
3656
4159
|
try {
|
|
3657
|
-
raw =
|
|
4160
|
+
raw = fs15.readFileSync(gitignorePath2, "utf8");
|
|
3658
4161
|
} catch {
|
|
3659
4162
|
return [];
|
|
3660
4163
|
}
|
|
@@ -3827,10 +4330,49 @@ function listIgnoredPaths(cwd) {
|
|
|
3827
4330
|
}
|
|
3828
4331
|
function hasSnapshotMarker(target) {
|
|
3829
4332
|
try {
|
|
3830
|
-
return
|
|
4333
|
+
return fs15.statSync(target).isDirectory() && fs15.existsSync(path16.join(target, ".codebase-snapshot"));
|
|
4334
|
+
} catch {
|
|
4335
|
+
return false;
|
|
4336
|
+
}
|
|
4337
|
+
}
|
|
4338
|
+
var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
|
|
4339
|
+
function isToolOwnedDirectory2(dir) {
|
|
4340
|
+
let raw;
|
|
4341
|
+
try {
|
|
4342
|
+
raw = fs15.readFileSync(path16.join(dir, ".codebase-snapshot"), "utf8");
|
|
4343
|
+
} catch {
|
|
4344
|
+
return false;
|
|
4345
|
+
}
|
|
4346
|
+
let parsed;
|
|
4347
|
+
try {
|
|
4348
|
+
parsed = JSON.parse(raw);
|
|
4349
|
+
} catch {
|
|
4350
|
+
return false;
|
|
4351
|
+
}
|
|
4352
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
|
|
4353
|
+
const marker2 = parsed;
|
|
4354
|
+
if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || typeof marker2.id !== "string" || !Array.isArray(marker2.files)) {
|
|
4355
|
+
return false;
|
|
4356
|
+
}
|
|
4357
|
+
const accounted = /* @__PURE__ */ new Set();
|
|
4358
|
+
for (const item of marker2.files) {
|
|
4359
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) return false;
|
|
4360
|
+
const entry = item.path;
|
|
4361
|
+
if (typeof entry !== "string" || entry.length === 0) return false;
|
|
4362
|
+
const parts = entry.split("/");
|
|
4363
|
+
for (let depth = 1; depth <= parts.length; depth += 1) {
|
|
4364
|
+
accounted.add(parts.slice(0, depth).join("/"));
|
|
4365
|
+
}
|
|
4366
|
+
}
|
|
4367
|
+
let entries;
|
|
4368
|
+
try {
|
|
4369
|
+
entries = fs15.readdirSync(dir);
|
|
3831
4370
|
} catch {
|
|
3832
4371
|
return false;
|
|
3833
4372
|
}
|
|
4373
|
+
return entries.every(
|
|
4374
|
+
(entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || accounted.has(entry)
|
|
4375
|
+
);
|
|
3834
4376
|
}
|
|
3835
4377
|
function makeToolOwnedDecider(cwd, toolOwnedPaths) {
|
|
3836
4378
|
const markers = /* @__PURE__ */ new Map();
|
|
@@ -3841,7 +4383,7 @@ function makeToolOwnedDecider(cwd, toolOwnedPaths) {
|
|
|
3841
4383
|
const prefix = parts.slice(0, depth).join("/");
|
|
3842
4384
|
let hasMarker = markers.get(prefix);
|
|
3843
4385
|
if (hasMarker === void 0) {
|
|
3844
|
-
hasMarker =
|
|
4386
|
+
hasMarker = isToolOwnedDirectory2(path16.join(cwd, prefix));
|
|
3845
4387
|
markers.set(prefix, hasMarker);
|
|
3846
4388
|
}
|
|
3847
4389
|
if (hasMarker) return true;
|
|
@@ -3856,7 +4398,7 @@ function makeLinkProbe() {
|
|
|
3856
4398
|
let known = cache.get(absolutePath);
|
|
3857
4399
|
if (known === void 0) {
|
|
3858
4400
|
try {
|
|
3859
|
-
known =
|
|
4401
|
+
known = fs15.lstatSync(absolutePath).isSymbolicLink();
|
|
3860
4402
|
} catch {
|
|
3861
4403
|
known = false;
|
|
3862
4404
|
}
|
|
@@ -3869,7 +4411,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
|
|
|
3869
4411
|
const isLink = makeLinkProbe();
|
|
3870
4412
|
let rootReal = cwd;
|
|
3871
4413
|
try {
|
|
3872
|
-
rootReal =
|
|
4414
|
+
rootReal = fs15.realpathSync(cwd);
|
|
3873
4415
|
} catch {
|
|
3874
4416
|
}
|
|
3875
4417
|
const reported = /* @__PURE__ */ new Set();
|
|
@@ -3897,7 +4439,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
|
|
|
3897
4439
|
const rawTarget = readLinkTarget(absolute, absolute);
|
|
3898
4440
|
let targetReal = null;
|
|
3899
4441
|
try {
|
|
3900
|
-
targetReal =
|
|
4442
|
+
targetReal = fs15.realpathSync(absolute);
|
|
3901
4443
|
} catch {
|
|
3902
4444
|
targetReal = null;
|
|
3903
4445
|
}
|
|
@@ -3915,7 +4457,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
|
|
|
3915
4457
|
}
|
|
3916
4458
|
let stats = null;
|
|
3917
4459
|
try {
|
|
3918
|
-
stats =
|
|
4460
|
+
stats = fs15.statSync(absolute);
|
|
3919
4461
|
} catch {
|
|
3920
4462
|
stats = null;
|
|
3921
4463
|
}
|
|
@@ -4003,7 +4545,7 @@ function collectFiles(cwd, options = {}) {
|
|
|
4003
4545
|
"Discovery mode is `git`, but git could not list this directory's files. Run inside a working repository, or pass --discovery walk (or auto) to scan the tree directly."
|
|
4004
4546
|
);
|
|
4005
4547
|
}
|
|
4006
|
-
if (
|
|
4548
|
+
if (fs15.existsSync(path16.join(cwd, ".git"))) {
|
|
4007
4549
|
throw new Error(
|
|
4008
4550
|
"This directory is a git repository, but git could not list its files. A plain walk honours .gitignore files, but git also applies .git/info/exclude and your global excludes file, includes files that are tracked although a .gitignore now matches them, and treats a submodule as a single entry. Fix the repository (git status should work), run outside git, or pass --discovery walk to accept those differences."
|
|
4009
4551
|
);
|
|
@@ -4013,6 +4555,15 @@ function collectFiles(cwd, options = {}) {
|
|
|
4013
4555
|
for (const record of walked.skipped) skipped.push(record);
|
|
4014
4556
|
}
|
|
4015
4557
|
}
|
|
4558
|
+
const extraPaths = (options.extraPaths ?? []).map((entry) => entry.replace(/\\/g, "/"));
|
|
4559
|
+
if (extraPaths.length > 0) {
|
|
4560
|
+
const known = new Set(candidates);
|
|
4561
|
+
for (const extra of extraPaths) {
|
|
4562
|
+
if (extra.length === 0 || known.has(extra)) continue;
|
|
4563
|
+
known.add(extra);
|
|
4564
|
+
candidates.push(extra);
|
|
4565
|
+
}
|
|
4566
|
+
}
|
|
4016
4567
|
const files = candidates.filter((file) => {
|
|
4017
4568
|
if (isToolOwned(file)) return false;
|
|
4018
4569
|
const ignored = defaultIgnoreReason(file, toolDirNames);
|
|
@@ -4062,7 +4613,7 @@ function collectFiles(cwd, options = {}) {
|
|
|
4062
4613
|
}
|
|
4063
4614
|
function rootRealFor(root) {
|
|
4064
4615
|
try {
|
|
4065
|
-
return
|
|
4616
|
+
return fs15.realpathSync(root);
|
|
4066
4617
|
} catch {
|
|
4067
4618
|
return root;
|
|
4068
4619
|
}
|
|
@@ -4082,7 +4633,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
|
|
|
4082
4633
|
];
|
|
4083
4634
|
let entries;
|
|
4084
4635
|
try {
|
|
4085
|
-
entries =
|
|
4636
|
+
entries = fs15.readdirSync(current, { withFileTypes: true });
|
|
4086
4637
|
} catch {
|
|
4087
4638
|
results.skipped.push({
|
|
4088
4639
|
path: relativeToBase(current),
|
|
@@ -4138,14 +4689,14 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
|
|
|
4138
4689
|
if (entry.isSymbolicLink()) {
|
|
4139
4690
|
let targetReal;
|
|
4140
4691
|
try {
|
|
4141
|
-
targetReal =
|
|
4692
|
+
targetReal = fs15.realpathSync(fullPath);
|
|
4142
4693
|
} catch {
|
|
4143
4694
|
results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
|
|
4144
4695
|
continue;
|
|
4145
4696
|
}
|
|
4146
4697
|
let stats;
|
|
4147
4698
|
try {
|
|
4148
|
-
stats =
|
|
4699
|
+
stats = fs15.statSync(fullPath);
|
|
4149
4700
|
} catch {
|
|
4150
4701
|
results.skipped.push({ path: relPath, reason: "read-error", detail: "unreadable symlink" });
|
|
4151
4702
|
continue;
|
|
@@ -4175,6 +4726,15 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
|
|
|
4175
4726
|
});
|
|
4176
4727
|
continue;
|
|
4177
4728
|
}
|
|
4729
|
+
const targetRelative = path16.relative(rootReal, targetReal).split(path16.sep).join("/");
|
|
4730
|
+
if (isSensitivePath(targetRelative)) {
|
|
4731
|
+
results.skipped.push({
|
|
4732
|
+
path: relPath,
|
|
4733
|
+
reason: "sensitive-file",
|
|
4734
|
+
detail: "link target is a credential-bearing file; not followed"
|
|
4735
|
+
});
|
|
4736
|
+
continue;
|
|
4737
|
+
}
|
|
4178
4738
|
isDirectory = false;
|
|
4179
4739
|
isFile = true;
|
|
4180
4740
|
}
|
|
@@ -4223,12 +4783,19 @@ var CONFIG_FILENAMES = [
|
|
|
4223
4783
|
function findConfigFile(cwd) {
|
|
4224
4784
|
for (const filename of CONFIG_FILENAMES) {
|
|
4225
4785
|
const fullPath = path16.join(cwd, filename);
|
|
4226
|
-
|
|
4786
|
+
let stats = null;
|
|
4787
|
+
try {
|
|
4788
|
+
stats = fs15.statSync(fullPath);
|
|
4789
|
+
} catch {
|
|
4790
|
+
if (fs15.existsSync(fullPath)) return fullPath;
|
|
4791
|
+
continue;
|
|
4792
|
+
}
|
|
4793
|
+
if (stats.isFile()) return fullPath;
|
|
4227
4794
|
}
|
|
4228
4795
|
const pkgJsonPath = path16.join(cwd, "package.json");
|
|
4229
|
-
if (!
|
|
4796
|
+
if (!fs15.existsSync(pkgJsonPath)) return null;
|
|
4230
4797
|
try {
|
|
4231
|
-
const parsed = JSON.parse(stripJsonComments2(
|
|
4798
|
+
const parsed = JSON.parse(stripJsonComments2(fs15.readFileSync(pkgJsonPath, "utf8")));
|
|
4232
4799
|
const snapshot = parsed?.snapshot;
|
|
4233
4800
|
return typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? pkgJsonPath : null;
|
|
4234
4801
|
} catch {
|
|
@@ -4489,17 +5056,34 @@ function readConfigExport(exported, file) {
|
|
|
4489
5056
|
assertKnownConfigKeys(exported, file);
|
|
4490
5057
|
return exported;
|
|
4491
5058
|
}
|
|
4492
|
-
var
|
|
5059
|
+
var lastModuleConfig = null;
|
|
5060
|
+
function moduleConfigKey(fullPath) {
|
|
5061
|
+
try {
|
|
5062
|
+
return createHash("sha256").update(fs15.readFileSync(fullPath)).digest("hex").slice(0, 24);
|
|
5063
|
+
} catch {
|
|
5064
|
+
try {
|
|
5065
|
+
const stats = fs15.statSync(fullPath);
|
|
5066
|
+
return `stat-${stats.mtimeMs}-${stats.size}`;
|
|
5067
|
+
} catch {
|
|
5068
|
+
return "unreadable";
|
|
5069
|
+
}
|
|
5070
|
+
}
|
|
5071
|
+
}
|
|
4493
5072
|
async function importConfigModule(fullPath) {
|
|
5073
|
+
const key = moduleConfigKey(fullPath);
|
|
5074
|
+
if (lastModuleConfig !== null && lastModuleConfig.path === fullPath && lastModuleConfig.key === key) {
|
|
5075
|
+
return lastModuleConfig.exports;
|
|
5076
|
+
}
|
|
4494
5077
|
try {
|
|
4495
5078
|
const requireFromConfig = createRequire(fullPath);
|
|
4496
5079
|
delete requireFromConfig.cache[requireFromConfig.resolve(fullPath)];
|
|
4497
5080
|
} catch {
|
|
4498
5081
|
}
|
|
4499
5082
|
const url = pathToFileURL(fullPath);
|
|
4500
|
-
|
|
4501
|
-
url.
|
|
4502
|
-
|
|
5083
|
+
url.searchParams.set("codebaseSnapshotLoad", key);
|
|
5084
|
+
const loaded = await import(url.href);
|
|
5085
|
+
lastModuleConfig = { path: fullPath, key, exports: loaded };
|
|
5086
|
+
return loaded;
|
|
4503
5087
|
}
|
|
4504
5088
|
function attachConfigDir(config, filePath) {
|
|
4505
5089
|
if (typeof config === "object" && config !== null) {
|
|
@@ -4511,15 +5095,25 @@ function attachConfigDir(config, filePath) {
|
|
|
4511
5095
|
}
|
|
4512
5096
|
return config;
|
|
4513
5097
|
}
|
|
4514
|
-
async function loadConfigFileDetailed(cwd) {
|
|
5098
|
+
async function loadConfigFileDetailed(cwd, options = {}) {
|
|
4515
5099
|
const warnings = [];
|
|
4516
5100
|
const errors = [];
|
|
5101
|
+
const configDirectories = [];
|
|
4517
5102
|
for (const filename of CONFIG_FILENAMES) {
|
|
4518
5103
|
const fullPath = path16.join(cwd, filename);
|
|
4519
|
-
|
|
5104
|
+
let candidateStats = null;
|
|
5105
|
+
try {
|
|
5106
|
+
candidateStats = fs15.statSync(fullPath);
|
|
5107
|
+
} catch {
|
|
5108
|
+
if (!fs15.existsSync(fullPath)) continue;
|
|
5109
|
+
}
|
|
5110
|
+
if (candidateStats !== null && !candidateStats.isFile()) {
|
|
5111
|
+
configDirectories.push(fullPath);
|
|
5112
|
+
continue;
|
|
5113
|
+
}
|
|
4520
5114
|
if (filename.endsWith(".json") || filename === ".snapshotrc") {
|
|
4521
5115
|
try {
|
|
4522
|
-
const config = parseJsonish(
|
|
5116
|
+
const config = parseJsonish(fs15.readFileSync(fullPath, "utf8"), fullPath);
|
|
4523
5117
|
if (config === null || typeof config !== "object" || Array.isArray(config)) {
|
|
4524
5118
|
throw new Error(
|
|
4525
5119
|
`${fullPath} does not hold a configuration object (received ${describeValue2(config)}).`
|
|
@@ -4535,6 +5129,12 @@ async function loadConfigFileDetailed(cwd) {
|
|
|
4535
5129
|
continue;
|
|
4536
5130
|
}
|
|
4537
5131
|
}
|
|
5132
|
+
if (options.allowExecutableConfig === false) {
|
|
5133
|
+
const message = `${fullPath} was not loaded: it is an executable config, and this server does not run repository code. Export the same settings from snapshot.config.json instead.`;
|
|
5134
|
+
warnings.push(message);
|
|
5135
|
+
errors.push(message);
|
|
5136
|
+
continue;
|
|
5137
|
+
}
|
|
4538
5138
|
if (filename.endsWith(".ts") && !supportsTypeScriptImports()) {
|
|
4539
5139
|
warnings.push(
|
|
4540
5140
|
`${fullPath} was ignored: loading a .ts config needs Node >= 22.6 (running ${process.versions.node}). Use snapshot.config.mjs, .cjs or .json instead.`
|
|
@@ -4554,9 +5154,9 @@ async function loadConfigFileDetailed(cwd) {
|
|
|
4554
5154
|
}
|
|
4555
5155
|
}
|
|
4556
5156
|
const pkgJsonPath = path16.join(cwd, "package.json");
|
|
4557
|
-
if (
|
|
5157
|
+
if (fs15.existsSync(pkgJsonPath)) {
|
|
4558
5158
|
try {
|
|
4559
|
-
const parsed = parseJsonish(
|
|
5159
|
+
const parsed = parseJsonish(fs15.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
|
|
4560
5160
|
const snapshotKey = parsed.snapshot;
|
|
4561
5161
|
if (snapshotKey && typeof snapshotKey === "object" && !Array.isArray(snapshotKey)) {
|
|
4562
5162
|
assertKnownConfigKeys(
|
|
@@ -4582,6 +5182,11 @@ async function loadConfigFileDetailed(cwd) {
|
|
|
4582
5182
|
errors.push(message);
|
|
4583
5183
|
}
|
|
4584
5184
|
}
|
|
5185
|
+
if (configDirectories.length > 0) {
|
|
5186
|
+
warnings.push(
|
|
5187
|
+
`${configDirectories.join(", ")} ${configDirectories.length === 1 ? "is a directory" : "are directories"}, not a configuration file; no configuration was read from ${configDirectories.length === 1 ? "it" : "them"}.`
|
|
5188
|
+
);
|
|
5189
|
+
}
|
|
4585
5190
|
return { config: null, file: null, warnings, errors };
|
|
4586
5191
|
}
|
|
4587
5192
|
async function loadConfigFile(cwd) {
|
|
@@ -4757,11 +5362,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
|
|
|
4757
5362
|
const patterns = [];
|
|
4758
5363
|
for (const dir of [outDir, tmpDir]) {
|
|
4759
5364
|
const absolute = path16.resolve(cwd, dir);
|
|
4760
|
-
const
|
|
4761
|
-
if (!
|
|
5365
|
+
const relative10 = path16.relative(cwd, absolute);
|
|
5366
|
+
if (!relative10 || relative10 === ".." || relative10.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative10)) {
|
|
4762
5367
|
continue;
|
|
4763
5368
|
}
|
|
4764
|
-
patterns.push(`${
|
|
5369
|
+
patterns.push(`${relative10.replace(/\\/g, "/")}/**`);
|
|
4765
5370
|
}
|
|
4766
5371
|
return patterns;
|
|
4767
5372
|
}
|
|
@@ -4892,10 +5497,10 @@ function resolveCandidateCwd(userConfig, cliOptions, baseDir) {
|
|
|
4892
5497
|
}
|
|
4893
5498
|
const candidate = cliOptions?.cwd || userConfig?.cwd || baseDir || process.cwd();
|
|
4894
5499
|
const resolved = path16.resolve(candidate);
|
|
4895
|
-
if (!
|
|
5500
|
+
if (!fs15.existsSync(resolved)) {
|
|
4896
5501
|
throw new Error(`Working directory does not exist: ${resolved}`);
|
|
4897
5502
|
}
|
|
4898
|
-
if (!
|
|
5503
|
+
if (!fs15.statSync(resolved).isDirectory()) {
|
|
4899
5504
|
throw new Error(`Working directory is not a directory: ${resolved}`);
|
|
4900
5505
|
}
|
|
4901
5506
|
return resolved;
|
|
@@ -5145,6 +5750,13 @@ function configDigest(config) {
|
|
|
5145
5750
|
// moving `{ name: "api", match: "src/api/**" }` to `"src/v2/**"` produced the same
|
|
5146
5751
|
// digest, so `validate` reported "valid and up to date" for a snapshot whose files
|
|
5147
5752
|
// had all been reclassified — and per-layer budgets applied to different files.
|
|
5753
|
+
// A function matcher's `String()` is its source, not its closure: two functions with the same
|
|
5754
|
+
// body but different captured values digest identically. That cannot be fixed by hashing, so
|
|
5755
|
+
// the digest records that executable matchers are present and `validate` says the digest does
|
|
5756
|
+
// not cover their closure, instead of claiming a equality it cannot prove.
|
|
5757
|
+
executableMatchers: [...config.layers, ...config.kinds].some(
|
|
5758
|
+
(rule) => typeof rule.match === "function"
|
|
5759
|
+
),
|
|
5148
5760
|
layers: config.layers.map((layer2) => ({ name: layer2.name, match: String(layer2.match) })),
|
|
5149
5761
|
kinds: config.kinds.map((kind) => ({ kind: kind.kind, match: String(kind.match) })),
|
|
5150
5762
|
// How files are enumerated decides what is in the snapshot at all.
|
|
@@ -5201,8 +5813,9 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
|
|
|
5201
5813
|
`**Generated:** ${manifest.generatedAt} `,
|
|
5202
5814
|
`**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
|
|
5203
5815
|
`**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
|
|
5204
|
-
`**
|
|
5205
|
-
`**
|
|
5816
|
+
`**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
|
|
5817
|
+
`**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
|
|
5818
|
+
`**Total Size:** ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MiB `,
|
|
5206
5819
|
// This counts the bytes that were *emitted* after redaction, not the bytes
|
|
5207
5820
|
// that were masked: calling it "redacted bytes" made a repository with zero
|
|
5208
5821
|
// secrets report a non-zero redacted-byte figure directly above "no secrets
|
|
@@ -5242,9 +5855,19 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
|
|
|
5242
5855
|
const parseIssues = manifest.files.filter(
|
|
5243
5856
|
(file) => file.summary !== void 0 && typeof file.summary === "object" && "parseErrors" in file.summary && typeof file.summary.parseErrors === "number" && file.summary.parseErrors > 0
|
|
5244
5857
|
);
|
|
5858
|
+
const unparsedPreviews = manifest.files.filter(
|
|
5859
|
+
(file) => file.summary === void 0 && (file.isPreviewTruncated === true || file.isLarge === true)
|
|
5860
|
+
).length;
|
|
5245
5861
|
lines.push("## 2. Parse & AST Diagnostics", "");
|
|
5246
5862
|
if (parseIssues.length === 0) {
|
|
5247
|
-
|
|
5863
|
+
if (unparsedPreviews > 0) {
|
|
5864
|
+
lines.push(
|
|
5865
|
+
`\u2705 No parse errors among the files that were parsed; ${formatNumber(unparsedPreviews)} file(s) were previewed or too large to parse and produced no structural summary.`,
|
|
5866
|
+
""
|
|
5867
|
+
);
|
|
5868
|
+
} else {
|
|
5869
|
+
lines.push("\u2705 Every parsed file produced a complete structural summary.", "");
|
|
5870
|
+
}
|
|
5248
5871
|
} else {
|
|
5249
5872
|
lines.push(
|
|
5250
5873
|
`${parseIssues.length} file(s) produced an incomplete summary:`,
|
|
@@ -5444,9 +6067,9 @@ function truncateToBytes(content, maxBytes) {
|
|
|
5444
6067
|
if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
|
|
5445
6068
|
const buffer = Buffer.from(content, "utf8");
|
|
5446
6069
|
if (buffer.length <= maxBytes) return { content, isTruncated: false };
|
|
5447
|
-
let
|
|
5448
|
-
while (
|
|
5449
|
-
return { content:
|
|
6070
|
+
let end = maxBytes;
|
|
6071
|
+
while (end > 0 && (buffer[end] & 192) === 128) end -= 1;
|
|
6072
|
+
return { content: buffer.subarray(0, end).toString("utf8"), isTruncated: true };
|
|
5450
6073
|
}
|
|
5451
6074
|
function truncatePreview(content, headLines, tailLines) {
|
|
5452
6075
|
const normalised = normaliseLineEndings(content);
|
|
@@ -5529,19 +6152,19 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
5529
6152
|
for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
|
|
5530
6153
|
}
|
|
5531
6154
|
if (groups.length === 0) return [];
|
|
5532
|
-
const
|
|
6155
|
+
const assemblies = /* @__PURE__ */ new Map();
|
|
5533
6156
|
const widthOf = (total) => Math.max(3, String(total).length);
|
|
5534
|
-
const
|
|
5535
|
-
const cached = measurements.get(group);
|
|
6157
|
+
const assemble = (group, index, total) => {
|
|
5536
6158
|
const width = widthOf(total);
|
|
6159
|
+
const cached = assemblies.get(group);
|
|
5537
6160
|
if (cached !== void 0 && cached.index === index && cached.width === width) {
|
|
5538
|
-
return cached.
|
|
6161
|
+
return cached.value;
|
|
5539
6162
|
}
|
|
5540
|
-
const
|
|
5541
|
-
|
|
5542
|
-
|
|
5543
|
-
return size2;
|
|
6163
|
+
const value = assembleGroup(group, index, total, contentFingerprint);
|
|
6164
|
+
assemblies.set(group, { index, width, value });
|
|
6165
|
+
return value;
|
|
5544
6166
|
};
|
|
6167
|
+
const measure = (group, index, total) => Buffer.byteLength(assemble(group, index, total).content, "utf8");
|
|
5545
6168
|
for (let pass = 0; pass < MAX_SPLIT_PASSES; pass++) {
|
|
5546
6169
|
const total = groups.length;
|
|
5547
6170
|
let oversized = -1;
|
|
@@ -5552,16 +6175,16 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
5552
6175
|
break;
|
|
5553
6176
|
}
|
|
5554
6177
|
}
|
|
5555
|
-
if (oversized === -1) return renderGroups(groups, contentFingerprint);
|
|
6178
|
+
if (oversized === -1) return renderGroups(groups, contentFingerprint, assemble);
|
|
5556
6179
|
const group = groups[oversized];
|
|
5557
6180
|
if (group.sections.length > 1) {
|
|
5558
6181
|
const moved = group.sections.pop();
|
|
5559
6182
|
groups.splice(oversized + 1, 0, { sections: [moved], budget: group.budget });
|
|
5560
|
-
|
|
6183
|
+
assemblies.delete(group);
|
|
5561
6184
|
continue;
|
|
5562
6185
|
}
|
|
5563
6186
|
const [section] = group.sections;
|
|
5564
|
-
if (section === void 0) return renderGroups(groups, contentFingerprint);
|
|
6187
|
+
if (section === void 0) return renderGroups(groups, contentFingerprint, assemble);
|
|
5565
6188
|
const overflow = measure(group, oversized, total) - group.budget;
|
|
5566
6189
|
const currentContent = section.file.content ?? "";
|
|
5567
6190
|
const shrinkTo = Math.max(
|
|
@@ -5578,10 +6201,10 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
5578
6201
|
applyTruncatedContent(section.file, shrunk.content);
|
|
5579
6202
|
section.text = renderFileSection(section.file);
|
|
5580
6203
|
section.byteSize = Buffer.byteLength(section.text, "utf8");
|
|
5581
|
-
|
|
6204
|
+
assemblies.delete(group);
|
|
5582
6205
|
continue;
|
|
5583
6206
|
}
|
|
5584
|
-
const rendered = renderGroups(groups, contentFingerprint);
|
|
6207
|
+
const rendered = renderGroups(groups, contentFingerprint, assemble);
|
|
5585
6208
|
const marker2 = TRUNCATION_MARKER;
|
|
5586
6209
|
assertBudgetHoldsMarker(group.budget);
|
|
5587
6210
|
const target = Math.max(
|
|
@@ -5595,7 +6218,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
|
|
|
5595
6218
|
);
|
|
5596
6219
|
return rendered;
|
|
5597
6220
|
}
|
|
5598
|
-
return renderGroups(groups, contentFingerprint).flatMap(
|
|
6221
|
+
return renderGroups(groups, contentFingerprint, assemble).flatMap(
|
|
5599
6222
|
(part) => enforceBudget([part], part.metadata.budgetBytes)
|
|
5600
6223
|
);
|
|
5601
6224
|
}
|
|
@@ -5633,8 +6256,8 @@ function renumberParts(parts, contentFingerprint) {
|
|
|
5633
6256
|
if (markerIndex === -1) {
|
|
5634
6257
|
throw new Error(`${part.filename} has no "## Contents" section to re-number.`);
|
|
5635
6258
|
}
|
|
5636
|
-
const layerCounts =
|
|
5637
|
-
const kindCounts =
|
|
6259
|
+
const layerCounts = /* @__PURE__ */ Object.create(null);
|
|
6260
|
+
const kindCounts = /* @__PURE__ */ Object.create(null);
|
|
5638
6261
|
for (const file of included) {
|
|
5639
6262
|
layerCounts[file.layer] = (layerCounts[file.layer] || 0) + 1;
|
|
5640
6263
|
kindCounts[file.kind] = (kindCounts[file.kind] || 0) + 1;
|
|
@@ -5831,8 +6454,8 @@ function assembleGroup(group, index, total, contentFingerprint) {
|
|
|
5831
6454
|
for (const section of group.sections) {
|
|
5832
6455
|
section.file.part = filename;
|
|
5833
6456
|
}
|
|
5834
|
-
const layerCounts =
|
|
5835
|
-
const kindCounts =
|
|
6457
|
+
const layerCounts = /* @__PURE__ */ Object.create(null);
|
|
6458
|
+
const kindCounts = /* @__PURE__ */ Object.create(null);
|
|
5836
6459
|
for (const section of group.sections) {
|
|
5837
6460
|
layerCounts[section.file.layer] = (layerCounts[section.file.layer] || 0) + 1;
|
|
5838
6461
|
kindCounts[section.file.kind] = (kindCounts[section.file.kind] || 0) + 1;
|
|
@@ -5867,15 +6490,10 @@ function assembleGroup(group, index, total, contentFingerprint) {
|
|
|
5867
6490
|
const estimatedTokens = estimateTokens(assembled);
|
|
5868
6491
|
return { filename, content: insertTokenLine(assembled, estimatedTokens), estimatedTokens };
|
|
5869
6492
|
}
|
|
5870
|
-
function renderGroups(groups, contentFingerprint) {
|
|
6493
|
+
function renderGroups(groups, contentFingerprint, assemble = (group, index, total) => assembleGroup(group, index, total, contentFingerprint)) {
|
|
5871
6494
|
const total = groups.length;
|
|
5872
6495
|
return groups.map((group, index) => {
|
|
5873
|
-
const { filename, content, estimatedTokens } =
|
|
5874
|
-
group,
|
|
5875
|
-
index,
|
|
5876
|
-
total,
|
|
5877
|
-
contentFingerprint
|
|
5878
|
-
);
|
|
6496
|
+
const { filename, content, estimatedTokens } = assemble(group, index, total);
|
|
5879
6497
|
const byteSize = Buffer.byteLength(content, "utf8");
|
|
5880
6498
|
const sha256 = crypto2.createHash("sha256").update(content).digest("hex");
|
|
5881
6499
|
const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
|
|
@@ -6092,9 +6710,10 @@ function generateReadme(manifest, artifacts) {
|
|
|
6092
6710
|
`- **Schema Version:** \`${manifest.schemaVersion}\``,
|
|
6093
6711
|
`- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
|
|
6094
6712
|
`- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
|
|
6095
|
-
`- **
|
|
6096
|
-
`- **
|
|
6097
|
-
`- **
|
|
6713
|
+
`- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
|
|
6714
|
+
`- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
|
|
6715
|
+
`- **Total Size:** \`${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MiB\``,
|
|
6716
|
+
`- **Emitted Content:** \`${(manifest.totals.totalContentBytes / (1024 * 1024)).toFixed(2)} MiB\``,
|
|
6098
6717
|
`- **Part Count:** \`${manifest.counts.partsCount}\` (budget \`${(manifest.budgets.maxPartBytes / 1024).toFixed(0)} KB\` per part)`,
|
|
6099
6718
|
`- **Generator:** \`${manifest.generator.name}@${manifest.generator.version}\``,
|
|
6100
6719
|
"",
|
|
@@ -6226,7 +6845,18 @@ function gitPaths(cwd, args) {
|
|
|
6226
6845
|
`Could not list changed files (git ${args.join(" ")}): ${reason}. A changed-files snapshot needs a git working tree and a ref that exists; run \`codebase-snapshot generate\` without --changed-since to scan everything.`
|
|
6227
6846
|
);
|
|
6228
6847
|
}
|
|
6229
|
-
return output.split("\0").
|
|
6848
|
+
return output.split("\0").filter((entry) => entry.length > 0);
|
|
6849
|
+
}
|
|
6850
|
+
function readStagedBlob(cwd, relativePath) {
|
|
6851
|
+
try {
|
|
6852
|
+
return execFileSync("git", ["cat-file", "blob", `:${relativePath}`], {
|
|
6853
|
+
cwd,
|
|
6854
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
6855
|
+
maxBuffer: 512 * 1024 * 1024
|
|
6856
|
+
});
|
|
6857
|
+
} catch {
|
|
6858
|
+
return null;
|
|
6859
|
+
}
|
|
6230
6860
|
}
|
|
6231
6861
|
function assertUsableRef(ref) {
|
|
6232
6862
|
if (ref.startsWith("-")) {
|
|
@@ -6237,6 +6867,8 @@ function assertUsableRef(ref) {
|
|
|
6237
6867
|
}
|
|
6238
6868
|
function resolveChangedScope(cwd, request) {
|
|
6239
6869
|
const paths = /* @__PURE__ */ new Set();
|
|
6870
|
+
const stagedPaths = /* @__PURE__ */ new Set();
|
|
6871
|
+
const deletedPaths = /* @__PURE__ */ new Set();
|
|
6240
6872
|
const descriptions = [];
|
|
6241
6873
|
if (request.changedSince !== void 0) {
|
|
6242
6874
|
assertUsableRef(request.changedSince);
|
|
@@ -6245,7 +6877,17 @@ function resolveChangedScope(cwd, request) {
|
|
|
6245
6877
|
"--name-only",
|
|
6246
6878
|
"-z",
|
|
6247
6879
|
"--relative",
|
|
6248
|
-
request.changedSince
|
|
6880
|
+
`${request.changedSince}...HEAD`,
|
|
6881
|
+
"--"
|
|
6882
|
+
])) {
|
|
6883
|
+
paths.add(path17);
|
|
6884
|
+
}
|
|
6885
|
+
for (const path17 of gitPaths(cwd, [
|
|
6886
|
+
"diff",
|
|
6887
|
+
"--name-only",
|
|
6888
|
+
"-z",
|
|
6889
|
+
"--relative",
|
|
6890
|
+
"HEAD",
|
|
6249
6891
|
"--"
|
|
6250
6892
|
])) {
|
|
6251
6893
|
paths.add(path17);
|
|
@@ -6265,10 +6907,22 @@ function resolveChangedScope(cwd, request) {
|
|
|
6265
6907
|
"--"
|
|
6266
6908
|
])) {
|
|
6267
6909
|
paths.add(path17);
|
|
6910
|
+
stagedPaths.add(path17);
|
|
6911
|
+
}
|
|
6912
|
+
for (const path17 of gitPaths(cwd, [
|
|
6913
|
+
"diff",
|
|
6914
|
+
"--cached",
|
|
6915
|
+
"--name-only",
|
|
6916
|
+
"-z",
|
|
6917
|
+
"--relative",
|
|
6918
|
+
"--diff-filter=D",
|
|
6919
|
+
"--"
|
|
6920
|
+
])) {
|
|
6921
|
+
deletedPaths.add(path17);
|
|
6268
6922
|
}
|
|
6269
6923
|
descriptions.push("staged");
|
|
6270
6924
|
}
|
|
6271
|
-
return { paths, detail: descriptions.join(" and ") };
|
|
6925
|
+
return { paths, stagedPaths, deletedPaths, detail: descriptions.join(" and ") };
|
|
6272
6926
|
}
|
|
6273
6927
|
var RELATIVE_SPECIFIER = /^\.{1,2}\//;
|
|
6274
6928
|
var IMPORT_CANDIDATE_SUFFIXES = [
|
|
@@ -6299,34 +6953,88 @@ var PYTHON_EXTENSIONS = /* @__PURE__ */ new Set([".py", ".pyi"]);
|
|
|
6299
6953
|
var RUBY_EXTENSIONS = /* @__PURE__ */ new Set([".rb", ".rake", ".gemspec"]);
|
|
6300
6954
|
var C_EXTENSIONS = /* @__PURE__ */ new Set([".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".m", ".mm"]);
|
|
6301
6955
|
var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
|
|
6302
|
-
|
|
6956
|
+
var CASE_INSENSITIVE_FILESYSTEM = process.platform === "win32" || process.platform === "darwin";
|
|
6957
|
+
var TSCONFIG_CACHE = /* @__PURE__ */ new Map();
|
|
6958
|
+
function tsconfigPathsFor(cwd) {
|
|
6959
|
+
const configPath = path16.join(cwd, "tsconfig.json");
|
|
6960
|
+
let stats;
|
|
6961
|
+
try {
|
|
6962
|
+
stats = fs15.statSync(configPath);
|
|
6963
|
+
} catch (err) {
|
|
6964
|
+
if (err.code === "ENOENT") return null;
|
|
6965
|
+
return null;
|
|
6966
|
+
}
|
|
6967
|
+
const key = `${stats.mtimeMs}:${stats.size}`;
|
|
6968
|
+
const cached = TSCONFIG_CACHE.get(configPath);
|
|
6969
|
+
if (cached !== void 0 && cached.key === key) return cached.value;
|
|
6970
|
+
let value = null;
|
|
6971
|
+
try {
|
|
6972
|
+
const read = ts.readConfigFile(configPath, ts.sys.readFile);
|
|
6973
|
+
if (read.error === void 0) {
|
|
6974
|
+
const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, cwd, void 0, configPath);
|
|
6975
|
+
const options = parsed.options;
|
|
6976
|
+
const baseUrl = typeof options.baseUrl === "string" ? repositoryRelative(cwd, options.baseUrl) : null;
|
|
6977
|
+
const rules = [];
|
|
6978
|
+
if (options.paths !== void 0) {
|
|
6979
|
+
for (const [pattern, targets] of Object.entries(options.paths)) {
|
|
6980
|
+
if (!Array.isArray(targets)) continue;
|
|
6981
|
+
rules.push({
|
|
6982
|
+
pattern,
|
|
6983
|
+
targets: targets.map((target) => String(target).replace(/\\/g, "/"))
|
|
6984
|
+
});
|
|
6985
|
+
}
|
|
6986
|
+
}
|
|
6987
|
+
if (baseUrl !== null || rules.length > 0) value = { baseUrl, paths: rules };
|
|
6988
|
+
}
|
|
6989
|
+
} catch (err) {
|
|
6990
|
+
value = null;
|
|
6991
|
+
}
|
|
6992
|
+
TSCONFIG_CACHE.set(configPath, { key, value });
|
|
6993
|
+
return value;
|
|
6994
|
+
}
|
|
6995
|
+
function repositoryRelative(cwd, target) {
|
|
6996
|
+
const relative10 = path16.relative(cwd, target).replace(/\\/g, "/");
|
|
6997
|
+
return relative10.length === 0 || !relative10.startsWith("..") && !path16.isAbsolute(relative10) ? relative10 : null;
|
|
6998
|
+
}
|
|
6999
|
+
function rememberFirst(map, key, value) {
|
|
7000
|
+
if (!map.has(key)) map.set(key, value);
|
|
7001
|
+
}
|
|
7002
|
+
function buildImportResolver(files, options = {}) {
|
|
6303
7003
|
const byPath = /* @__PURE__ */ new Map();
|
|
6304
7004
|
const byPathFolded = /* @__PURE__ */ new Map();
|
|
6305
7005
|
const byStem = /* @__PURE__ */ new Map();
|
|
6306
7006
|
const byStemFolded = /* @__PURE__ */ new Map();
|
|
6307
|
-
const
|
|
6308
|
-
|
|
6309
|
-
|
|
6310
|
-
|
|
6311
|
-
|
|
6312
|
-
remember(byPath, relativePath, relativePath);
|
|
6313
|
-
remember(byPathFolded, relativePath.toLowerCase(), relativePath);
|
|
7007
|
+
const register = (relativePath) => {
|
|
7008
|
+
rememberFirst(byPath, relativePath, relativePath);
|
|
7009
|
+
if (CASE_INSENSITIVE_FILESYSTEM) {
|
|
7010
|
+
rememberFirst(byPathFolded, relativePath.toLowerCase(), relativePath);
|
|
7011
|
+
}
|
|
6314
7012
|
const extension = path16.posix.extname(relativePath);
|
|
6315
|
-
if (!SOURCE_EXTENSIONS.has(extension))
|
|
7013
|
+
if (!SOURCE_EXTENSIONS.has(extension)) return;
|
|
6316
7014
|
const stem = relativePath.slice(0, -extension.length);
|
|
6317
|
-
|
|
6318
|
-
|
|
7015
|
+
rememberFirst(byStem, stem, relativePath);
|
|
7016
|
+
if (CASE_INSENSITIVE_FILESYSTEM) {
|
|
7017
|
+
rememberFirst(byStemFolded, stem.toLowerCase(), relativePath);
|
|
7018
|
+
}
|
|
6319
7019
|
if (path16.posix.basename(stem) === "index") {
|
|
6320
7020
|
const directory = path16.posix.dirname(stem);
|
|
6321
|
-
|
|
6322
|
-
|
|
7021
|
+
rememberFirst(byStem, directory, relativePath);
|
|
7022
|
+
if (CASE_INSENSITIVE_FILESYSTEM) {
|
|
7023
|
+
rememberFirst(byStemFolded, directory.toLowerCase(), relativePath);
|
|
7024
|
+
}
|
|
7025
|
+
}
|
|
7026
|
+
};
|
|
7027
|
+
for (const file of files) register(file.relativePath);
|
|
7028
|
+
if (options.extraPaths !== void 0) {
|
|
7029
|
+
for (const extra of options.extraPaths) {
|
|
7030
|
+
if (!byPath.has(extra)) register(extra);
|
|
6323
7031
|
}
|
|
6324
7032
|
}
|
|
6325
|
-
return { byPath, byPathFolded, byStem, byStemFolded };
|
|
7033
|
+
return { byPath, byPathFolded, byStem, byStemFolded, tsconfig: options.tsconfig ?? null };
|
|
6326
7034
|
}
|
|
6327
7035
|
function resolveSpecifier(fromFile, specifier, resolver) {
|
|
6328
7036
|
const extension = path16.posix.extname(fromFile).toLowerCase();
|
|
6329
|
-
const exact = (key) => resolver.byPath.get(key) ?? resolver.byPathFolded.get(key.toLowerCase()) ?? null;
|
|
7037
|
+
const exact = (key) => resolver.byPath.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byPathFolded.get(key.toLowerCase()) : void 0) ?? null;
|
|
6330
7038
|
const firstOf = (candidates) => {
|
|
6331
7039
|
for (const candidate of candidates) {
|
|
6332
7040
|
const hit = exact(candidate);
|
|
@@ -6334,6 +7042,17 @@ function resolveSpecifier(fromFile, specifier, resolver) {
|
|
|
6334
7042
|
}
|
|
6335
7043
|
return null;
|
|
6336
7044
|
};
|
|
7045
|
+
const lookupPath = (joined2) => {
|
|
7046
|
+
const direct = exact(joined2);
|
|
7047
|
+
if (direct) return direct;
|
|
7048
|
+
for (const suffix of IMPORT_CANDIDATE_SUFFIXES) {
|
|
7049
|
+
const hit = exact(`${joined2}${suffix}`);
|
|
7050
|
+
if (hit) return hit;
|
|
7051
|
+
}
|
|
7052
|
+
const stem = joined2.replace(/\.(?:js|mjs|cjs|jsx)$/, "");
|
|
7053
|
+
const byStem = (key) => resolver.byStem.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byStemFolded.get(key.toLowerCase()) : void 0) ?? null;
|
|
7054
|
+
return byStem(joined2) ?? byStem(stem);
|
|
7055
|
+
};
|
|
6337
7056
|
if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
|
|
6338
7057
|
const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
|
|
6339
7058
|
const rest = specifier.slice(dots).replace(/\./g, "/");
|
|
@@ -6360,20 +7079,44 @@ function resolveSpecifier(fromFile, specifier, resolver) {
|
|
|
6360
7079
|
);
|
|
6361
7080
|
return firstOf([joined2, `${joined2}.dart`]);
|
|
6362
7081
|
}
|
|
6363
|
-
if (!RELATIVE_SPECIFIER.test(specifier))
|
|
7082
|
+
if (!RELATIVE_SPECIFIER.test(specifier)) {
|
|
7083
|
+
return resolveTsconfigSpecifier(specifier, resolver, lookupPath);
|
|
7084
|
+
}
|
|
6364
7085
|
const joined = path16.posix.normalize(
|
|
6365
7086
|
path16.posix.join(path16.posix.dirname(fromFile), specifier)
|
|
6366
7087
|
);
|
|
6367
|
-
|
|
6368
|
-
|
|
6369
|
-
|
|
6370
|
-
|
|
6371
|
-
|
|
6372
|
-
|
|
6373
|
-
|
|
6374
|
-
|
|
6375
|
-
|
|
6376
|
-
|
|
7088
|
+
return lookupPath(joined);
|
|
7089
|
+
}
|
|
7090
|
+
function resolveTsconfigSpecifier(specifier, resolver, lookupPath) {
|
|
7091
|
+
const config = resolver.tsconfig;
|
|
7092
|
+
if (!config) return null;
|
|
7093
|
+
for (const rule of config.paths) {
|
|
7094
|
+
const star = rule.pattern.indexOf("*");
|
|
7095
|
+
let captured;
|
|
7096
|
+
if (star === -1) {
|
|
7097
|
+
captured = specifier === rule.pattern ? "" : null;
|
|
7098
|
+
} else {
|
|
7099
|
+
const prefix = rule.pattern.slice(0, star);
|
|
7100
|
+
const suffix = rule.pattern.slice(star + 1);
|
|
7101
|
+
if (specifier.length < prefix.length + suffix.length || !specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {
|
|
7102
|
+
captured = null;
|
|
7103
|
+
} else {
|
|
7104
|
+
captured = specifier.slice(prefix.length, specifier.length - suffix.length);
|
|
7105
|
+
}
|
|
7106
|
+
}
|
|
7107
|
+
if (captured === null) continue;
|
|
7108
|
+
for (const target of rule.targets) {
|
|
7109
|
+
const substituted = target.split("*").join(captured);
|
|
7110
|
+
const base = config.baseUrl === null ? substituted : path16.posix.join(config.baseUrl, substituted);
|
|
7111
|
+
const hit = lookupPath(path16.posix.normalize(base));
|
|
7112
|
+
if (hit) return hit;
|
|
7113
|
+
}
|
|
7114
|
+
}
|
|
7115
|
+
if (config.baseUrl !== null) {
|
|
7116
|
+
return lookupPath(path16.posix.normalize(path16.posix.join(config.baseUrl, specifier)));
|
|
7117
|
+
}
|
|
7118
|
+
return null;
|
|
7119
|
+
}
|
|
6377
7120
|
function importsChangedFile(importerPath, imports, changedPaths, resolver) {
|
|
6378
7121
|
for (const specifier of imports) {
|
|
6379
7122
|
const resolved = resolveSpecifier(importerPath, specifier, resolver);
|
|
@@ -6461,7 +7204,7 @@ function findStagingDirectory(config) {
|
|
|
6461
7204
|
const tmpDir = path16.resolve(config.cwd, config.tmpDir);
|
|
6462
7205
|
let entries;
|
|
6463
7206
|
try {
|
|
6464
|
-
entries =
|
|
7207
|
+
entries = fs15.readdirSync(tmpDir);
|
|
6465
7208
|
} catch {
|
|
6466
7209
|
return null;
|
|
6467
7210
|
}
|
|
@@ -6474,8 +7217,8 @@ function describeMissingManifest(config, manifestPath) {
|
|
|
6474
7217
|
const markerPath = path16.join(outDir, ".codebase-snapshot");
|
|
6475
7218
|
let marker2 = null;
|
|
6476
7219
|
try {
|
|
6477
|
-
if (
|
|
6478
|
-
const parsed = JSON.parse(
|
|
7220
|
+
if (fs15.existsSync(markerPath)) {
|
|
7221
|
+
const parsed = JSON.parse(fs15.readFileSync(markerPath, "utf8"));
|
|
6479
7222
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
6480
7223
|
marker2 = parsed;
|
|
6481
7224
|
}
|
|
@@ -6512,11 +7255,11 @@ function sha256Hex(buffer) {
|
|
|
6512
7255
|
function wouldNowBeIncluded(cwd, relativePath) {
|
|
6513
7256
|
const absolutePath = path16.join(cwd, relativePath);
|
|
6514
7257
|
try {
|
|
6515
|
-
const stats =
|
|
7258
|
+
const stats = fs15.statSync(absolutePath);
|
|
6516
7259
|
if (!stats.isFile()) return false;
|
|
6517
7260
|
if (isBinaryExtension(absolutePath)) return false;
|
|
6518
7261
|
if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
|
|
6519
|
-
return !decodeText(
|
|
7262
|
+
return !decodeText(fs15.readFileSync(absolutePath)).binary;
|
|
6520
7263
|
} catch {
|
|
6521
7264
|
return false;
|
|
6522
7265
|
}
|
|
@@ -6547,14 +7290,71 @@ function describeManifestShapeProblem(value) {
|
|
|
6547
7290
|
if (!candidate.totals || typeof candidate.totals !== "object" || Array.isArray(candidate.totals)) {
|
|
6548
7291
|
return 'missing "totals" object';
|
|
6549
7292
|
}
|
|
7293
|
+
const currentSchema = candidate.schemaVersion === SCHEMA_VERSION;
|
|
7294
|
+
if (currentSchema) {
|
|
7295
|
+
const generator = candidate.generator;
|
|
7296
|
+
if (!generator || typeof generator !== "object" || Array.isArray(generator)) {
|
|
7297
|
+
return 'missing "generator" object';
|
|
7298
|
+
}
|
|
7299
|
+
const generatorFields = generator;
|
|
7300
|
+
if (!isOurGeneratorName(generatorFields.name)) {
|
|
7301
|
+
return "`generator.name` is not this generator";
|
|
7302
|
+
}
|
|
7303
|
+
if (typeof generatorFields.version !== "string" || generatorFields.version.trim() === "") {
|
|
7304
|
+
return "`generator.version` must be a non-empty string";
|
|
7305
|
+
}
|
|
7306
|
+
const git = candidate.git;
|
|
7307
|
+
if (!git || typeof git !== "object" || Array.isArray(git)) return 'missing "git" object';
|
|
7308
|
+
const gitFields = git;
|
|
7309
|
+
if (typeof gitFields.branch !== "string") return "`git.branch` must be a string";
|
|
7310
|
+
if (typeof gitFields.commit !== "string") return "`git.commit` must be a string";
|
|
7311
|
+
if (typeof gitFields.isDirty !== "boolean") return "`git.isDirty` must be a boolean";
|
|
7312
|
+
const config = candidate.config;
|
|
7313
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) {
|
|
7314
|
+
return 'missing "config" object';
|
|
7315
|
+
}
|
|
7316
|
+
const budgets = candidate.budgets;
|
|
7317
|
+
if (!budgets || typeof budgets !== "object" || Array.isArray(budgets)) {
|
|
7318
|
+
return 'missing "budgets" object';
|
|
7319
|
+
}
|
|
7320
|
+
for (const key of ["maxPartBytes", "largeFileBytes"]) {
|
|
7321
|
+
const value2 = budgets[key];
|
|
7322
|
+
if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
|
|
7323
|
+
return `\`budgets.${key}\` must be a non-negative integer`;
|
|
7324
|
+
}
|
|
7325
|
+
}
|
|
7326
|
+
if (!candidate.indexes || typeof candidate.indexes !== "object" || Array.isArray(candidate.indexes)) {
|
|
7327
|
+
return 'missing "indexes" object';
|
|
7328
|
+
}
|
|
7329
|
+
if (!candidate.kinds || typeof candidate.kinds !== "object" || Array.isArray(candidate.kinds)) {
|
|
7330
|
+
return 'missing "kinds" object';
|
|
7331
|
+
}
|
|
7332
|
+
}
|
|
6550
7333
|
if (!Array.isArray(candidate.files)) return 'missing "files" array';
|
|
6551
7334
|
for (const entry of candidate.files) {
|
|
6552
7335
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
6553
7336
|
return 'a "files" entry is not an object';
|
|
6554
7337
|
}
|
|
6555
|
-
|
|
7338
|
+
const fields = entry;
|
|
7339
|
+
if (typeof fields.relativePath !== "string") {
|
|
6556
7340
|
return 'a "files" entry has no "relativePath"';
|
|
6557
7341
|
}
|
|
7342
|
+
if (!currentSchema) continue;
|
|
7343
|
+
if (typeof fields.part !== "string" || fields.part.length === 0) {
|
|
7344
|
+
return 'a "files" entry records no "part"';
|
|
7345
|
+
}
|
|
7346
|
+
if (typeof fields.hashSha256 !== "string" || !/^[0-9a-f]{64}$/.test(fields.hashSha256)) {
|
|
7347
|
+
return 'a "files" entry "hashSha256" must be a 64-character lowercase sha256 hex digest';
|
|
7348
|
+
}
|
|
7349
|
+
for (const key of ["sizeBytes", "lines"]) {
|
|
7350
|
+
const value2 = fields[key];
|
|
7351
|
+
if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
|
|
7352
|
+
return `a "files" entry "${key}" must be a non-negative integer`;
|
|
7353
|
+
}
|
|
7354
|
+
}
|
|
7355
|
+
if (!["full", "preview", "signatures"].includes(String(fields.inclusionMode))) {
|
|
7356
|
+
return 'a "files" entry has an unknown "inclusionMode"';
|
|
7357
|
+
}
|
|
6558
7358
|
}
|
|
6559
7359
|
if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
|
|
6560
7360
|
if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
|
|
@@ -6562,13 +7362,28 @@ function describeManifestShapeProblem(value) {
|
|
|
6562
7362
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
6563
7363
|
return 'a "parts" entry is not an object';
|
|
6564
7364
|
}
|
|
6565
|
-
const
|
|
7365
|
+
const fields = entry;
|
|
7366
|
+
const filename = fields.filename;
|
|
6566
7367
|
if (typeof filename !== "string" || filename.trim() === "") {
|
|
6567
7368
|
return 'a "parts" entry has no "filename"';
|
|
6568
7369
|
}
|
|
6569
7370
|
if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path16.isAbsolute(filename)) {
|
|
6570
7371
|
return 'a "parts" entry "filename" must be a bare filename inside parts/';
|
|
6571
7372
|
}
|
|
7373
|
+
if (currentSchema) {
|
|
7374
|
+
if (typeof fields.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(fields.sha256)) {
|
|
7375
|
+
return 'a "parts" entry "sha256" must be a 64-character lowercase sha256 hex digest';
|
|
7376
|
+
}
|
|
7377
|
+
if (typeof fields.byteSize !== "number" || !Number.isSafeInteger(fields.byteSize) || fields.byteSize < 0) {
|
|
7378
|
+
return 'a "parts" entry "byteSize" must be a non-negative integer';
|
|
7379
|
+
}
|
|
7380
|
+
if (typeof fields.index !== "number" || !Number.isSafeInteger(fields.index) || fields.index < 1) {
|
|
7381
|
+
return 'a "parts" entry "index" must be a positive integer';
|
|
7382
|
+
}
|
|
7383
|
+
if (!Array.isArray(fields.includedFiles)) {
|
|
7384
|
+
return 'a "parts" entry has no "includedFiles" array';
|
|
7385
|
+
}
|
|
7386
|
+
}
|
|
6572
7387
|
}
|
|
6573
7388
|
if (!candidate.layers || typeof candidate.layers !== "object" || Array.isArray(candidate.layers)) {
|
|
6574
7389
|
return 'missing "layers" object';
|
|
@@ -6579,7 +7394,7 @@ function validateSnapshot(configInput) {
|
|
|
6579
7394
|
assertUsableConfigInput(configInput);
|
|
6580
7395
|
const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
|
|
6581
7396
|
const manifestPath = path16.resolve(config.cwd, config.outDir, "manifest.json");
|
|
6582
|
-
if (!
|
|
7397
|
+
if (!fs15.existsSync(manifestPath)) {
|
|
6583
7398
|
return {
|
|
6584
7399
|
valid: false,
|
|
6585
7400
|
manifestPresent: false,
|
|
@@ -6590,7 +7405,7 @@ function validateSnapshot(configInput) {
|
|
|
6590
7405
|
}
|
|
6591
7406
|
let manifest;
|
|
6592
7407
|
try {
|
|
6593
|
-
manifest = JSON.parse(
|
|
7408
|
+
manifest = JSON.parse(fs15.readFileSync(manifestPath, "utf8"));
|
|
6594
7409
|
} catch (err) {
|
|
6595
7410
|
return {
|
|
6596
7411
|
valid: false,
|
|
@@ -6613,6 +7428,19 @@ function validateSnapshot(configInput) {
|
|
|
6613
7428
|
const drift = emptyDrift();
|
|
6614
7429
|
const warnings = [];
|
|
6615
7430
|
const snapshotDir = path16.resolve(config.cwd, config.outDir);
|
|
7431
|
+
const unreadableSkips = manifest.skipped.filter(
|
|
7432
|
+
(entry) => entry.reason === "missing" || entry.reason === "read-error"
|
|
7433
|
+
);
|
|
7434
|
+
if (unreadableSkips.length > 0) {
|
|
7435
|
+
warnings.push(
|
|
7436
|
+
`${unreadableSkips.length} path(s) could not be read when this snapshot was generated (see manifest.skipped[] with reason "missing" or "read-error"); they are not in the snapshot.`
|
|
7437
|
+
);
|
|
7438
|
+
}
|
|
7439
|
+
if ([...config.layers, ...config.kinds].some((rule) => typeof rule.match === "function")) {
|
|
7440
|
+
warnings.push(
|
|
7441
|
+
"The configuration uses executable (function) matchers; the recorded digest covers their source text, not the values they capture, so it cannot prove their classification is unchanged."
|
|
7442
|
+
);
|
|
7443
|
+
}
|
|
6616
7444
|
const manifestFileMap = /* @__PURE__ */ new Map();
|
|
6617
7445
|
for (const file of manifest.files) {
|
|
6618
7446
|
if (file && typeof file.relativePath === "string") {
|
|
@@ -6675,7 +7503,7 @@ function validateSnapshot(configInput) {
|
|
|
6675
7503
|
// snapshot was reported as drifting.
|
|
6676
7504
|
toolOwnedPaths: [config.outDir, config.tmpDir].map(
|
|
6677
7505
|
(directory) => path16.relative(config.cwd, path16.resolve(config.cwd, directory)).replace(/\\/g, "/")
|
|
6678
|
-
).filter((
|
|
7506
|
+
).filter((relative10) => relative10.length > 0 && !relative10.startsWith(".."))
|
|
6679
7507
|
});
|
|
6680
7508
|
for (const diskFile of collection.files) {
|
|
6681
7509
|
const snapshotHash = manifestFileMap.get(diskFile);
|
|
@@ -6700,7 +7528,7 @@ function validateSnapshot(configInput) {
|
|
|
6700
7528
|
}
|
|
6701
7529
|
let diskHash;
|
|
6702
7530
|
try {
|
|
6703
|
-
diskHash = sha256Hex(
|
|
7531
|
+
diskHash = sha256Hex(fs15.readFileSync(path16.join(config.cwd, diskFile)));
|
|
6704
7532
|
} catch (err) {
|
|
6705
7533
|
if (err.code === "ENOENT") {
|
|
6706
7534
|
drift.missingOnDisk.push(diskFile);
|
|
@@ -6724,7 +7552,7 @@ function validateSnapshot(configInput) {
|
|
|
6724
7552
|
}
|
|
6725
7553
|
let statFailure = null;
|
|
6726
7554
|
try {
|
|
6727
|
-
|
|
7555
|
+
fs15.statSync(confined);
|
|
6728
7556
|
} catch (err) {
|
|
6729
7557
|
statFailure = err;
|
|
6730
7558
|
}
|
|
@@ -6759,7 +7587,7 @@ function validateSnapshot(configInput) {
|
|
|
6759
7587
|
}
|
|
6760
7588
|
let buffer;
|
|
6761
7589
|
try {
|
|
6762
|
-
buffer =
|
|
7590
|
+
buffer = fs15.readFileSync(partPath);
|
|
6763
7591
|
} catch {
|
|
6764
7592
|
drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
|
|
6765
7593
|
continue;
|
|
@@ -6781,22 +7609,83 @@ function validateSnapshot(configInput) {
|
|
|
6781
7609
|
});
|
|
6782
7610
|
}
|
|
6783
7611
|
}
|
|
6784
|
-
const
|
|
6785
|
-
|
|
6786
|
-
|
|
6787
|
-
)
|
|
6788
|
-
|
|
6789
|
-
|
|
6790
|
-
|
|
6791
|
-
|
|
6792
|
-
|
|
7612
|
+
const maskDriftPath = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
|
|
7613
|
+
const includedByPart = /* @__PURE__ */ new Map();
|
|
7614
|
+
const partIndexes = /* @__PURE__ */ new Set();
|
|
7615
|
+
for (const part of manifest.parts) {
|
|
7616
|
+
if (includedByPart.has(part.filename)) {
|
|
7617
|
+
drift.partIssues.push({
|
|
7618
|
+
part: maskDriftPath(part.filename),
|
|
7619
|
+
issue: "appears more than once in parts[]"
|
|
7620
|
+
});
|
|
7621
|
+
}
|
|
7622
|
+
if (typeof part.index === "number") {
|
|
7623
|
+
if (partIndexes.has(part.index)) {
|
|
7624
|
+
drift.partIssues.push({
|
|
7625
|
+
part: maskDriftPath(part.filename),
|
|
7626
|
+
issue: `reuses part index ${part.index}`
|
|
7627
|
+
});
|
|
7628
|
+
}
|
|
7629
|
+
partIndexes.add(part.index);
|
|
7630
|
+
}
|
|
7631
|
+
const listed = /* @__PURE__ */ new Set();
|
|
7632
|
+
for (const included of part.includedFiles ?? []) {
|
|
7633
|
+
if (typeof included?.relativePath !== "string") continue;
|
|
7634
|
+
if (listed.has(included.relativePath)) {
|
|
7635
|
+
drift.partIssues.push({
|
|
7636
|
+
part: maskDriftPath(part.filename),
|
|
7637
|
+
issue: `lists ${maskDriftPath(included.relativePath)} twice`
|
|
7638
|
+
});
|
|
7639
|
+
}
|
|
7640
|
+
listed.add(included.relativePath);
|
|
7641
|
+
}
|
|
7642
|
+
includedByPart.set(part.filename, listed);
|
|
7643
|
+
if (typeof part.fileCount === "number" && part.fileCount !== listed.size) {
|
|
7644
|
+
drift.partIssues.push({
|
|
7645
|
+
part: maskDriftPath(part.filename),
|
|
7646
|
+
issue: `declares ${part.fileCount} file(s) but lists ${listed.size} in includedFiles`
|
|
7647
|
+
});
|
|
7648
|
+
}
|
|
6793
7649
|
}
|
|
7650
|
+
const filePaths = /* @__PURE__ */ new Set();
|
|
6794
7651
|
for (const file of manifest.files) {
|
|
6795
|
-
if (
|
|
7652
|
+
if (filePaths.has(file.relativePath)) {
|
|
7653
|
+
drift.partIssues.push({
|
|
7654
|
+
part: "(files)",
|
|
7655
|
+
issue: `${maskDriftPath(file.relativePath)} appears more than once in files[]`
|
|
7656
|
+
});
|
|
7657
|
+
continue;
|
|
7658
|
+
}
|
|
7659
|
+
filePaths.add(file.relativePath);
|
|
7660
|
+
if (typeof file.part !== "string" || file.part.length === 0) {
|
|
7661
|
+
drift.partIssues.push({
|
|
7662
|
+
part: "(files)",
|
|
7663
|
+
issue: `${maskDriftPath(file.relativePath)} records no part`
|
|
7664
|
+
});
|
|
7665
|
+
continue;
|
|
7666
|
+
}
|
|
7667
|
+
if (!partNames.has(file.part)) {
|
|
6796
7668
|
drift.partIssues.push({
|
|
6797
|
-
part: file.part,
|
|
6798
|
-
issue: `${file.relativePath} points at a part that is not in the manifest`
|
|
7669
|
+
part: maskDriftPath(file.part),
|
|
7670
|
+
issue: `${maskDriftPath(file.relativePath)} points at a part that is not in the manifest`
|
|
6799
7671
|
});
|
|
7672
|
+
continue;
|
|
7673
|
+
}
|
|
7674
|
+
if (!includedByPart.get(file.part)?.has(file.relativePath)) {
|
|
7675
|
+
drift.partIssues.push({
|
|
7676
|
+
part: maskDriftPath(file.part),
|
|
7677
|
+
issue: `${maskDriftPath(file.relativePath)} is not listed in that part's includedFiles`
|
|
7678
|
+
});
|
|
7679
|
+
}
|
|
7680
|
+
}
|
|
7681
|
+
for (const [partName, listed] of includedByPart) {
|
|
7682
|
+
for (const relativePath of listed) {
|
|
7683
|
+
if (!filePaths.has(relativePath)) {
|
|
7684
|
+
drift.partIssues.push({
|
|
7685
|
+
part: maskDriftPath(partName),
|
|
7686
|
+
issue: `lists ${maskDriftPath(relativePath)}, which the manifest does not`
|
|
7687
|
+
});
|
|
7688
|
+
}
|
|
6800
7689
|
}
|
|
6801
7690
|
}
|
|
6802
7691
|
const maskValue = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
|
|
@@ -6954,6 +7843,13 @@ function validateSnapshot(configInput) {
|
|
|
6954
7843
|
0
|
|
6955
7844
|
);
|
|
6956
7845
|
expectEqual("counts.totalFiles", counts.totalFiles, manifest.files.length);
|
|
7846
|
+
if (manifest.files.every((file) => typeof file?.lines === "number")) {
|
|
7847
|
+
expectEqual(
|
|
7848
|
+
"counts.totalLines",
|
|
7849
|
+
counts.totalLines,
|
|
7850
|
+
manifest.files.reduce((total, file) => total + file.lines, 0)
|
|
7851
|
+
);
|
|
7852
|
+
}
|
|
6957
7853
|
expectEqual("counts.partsCount", counts.partsCount, manifest.parts.length);
|
|
6958
7854
|
expectEqual("counts.skippedCount", counts.skippedCount, manifest.skipped.length);
|
|
6959
7855
|
expectEqual("counts.totalSizeBytes", counts.totalSizeBytes, sumSourceBytes);
|
|
@@ -6977,6 +7873,37 @@ function validateSnapshot(configInput) {
|
|
|
6977
7873
|
`totals.fullFiles + previewFiles (${totals.fullFiles} + ${totals.previewFiles}) != ${manifest.files.length} files`
|
|
6978
7874
|
);
|
|
6979
7875
|
}
|
|
7876
|
+
const recordedSettingsDigest = manifest.config && typeof manifest.config.digest === "string" ? manifest.config.digest : null;
|
|
7877
|
+
if (recordedSettingsDigest !== null && manifest.files.every((file) => typeof file?.hashSha256 === "string")) {
|
|
7878
|
+
const settingsLine = `settings:${recordedSettingsDigest}`;
|
|
7879
|
+
const currentDefinition = sha256Hex(
|
|
7880
|
+
Buffer.from(
|
|
7881
|
+
[
|
|
7882
|
+
...manifest.files.map(
|
|
7883
|
+
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
|
|
7884
|
+
),
|
|
7885
|
+
settingsLine
|
|
7886
|
+
].join("\n"),
|
|
7887
|
+
"utf8"
|
|
7888
|
+
)
|
|
7889
|
+
);
|
|
7890
|
+
const legacyDefinition = sha256Hex(
|
|
7891
|
+
Buffer.from(
|
|
7892
|
+
[
|
|
7893
|
+
...manifest.files.map(
|
|
7894
|
+
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}:${file.inclusionMode}`
|
|
7895
|
+
),
|
|
7896
|
+
settingsLine
|
|
7897
|
+
].join("\n"),
|
|
7898
|
+
"utf8"
|
|
7899
|
+
)
|
|
7900
|
+
);
|
|
7901
|
+
if (manifest.fingerprint !== currentDefinition && manifest.fingerprint !== legacyDefinition) {
|
|
7902
|
+
totalsMismatches.push(
|
|
7903
|
+
"fingerprint: does not match the files and settings recorded in this manifest"
|
|
7904
|
+
);
|
|
7905
|
+
}
|
|
7906
|
+
}
|
|
6980
7907
|
if (manifest.budgets && manifest.budgets.maxPartBytes !== config.maxPartBytes) {
|
|
6981
7908
|
totalsMismatches.push(
|
|
6982
7909
|
`budgets.maxPartBytes: manifest ${manifest.budgets.maxPartBytes} vs current ${config.maxPartBytes}`
|
|
@@ -7004,26 +7931,49 @@ function validateSnapshot(configInput) {
|
|
|
7004
7931
|
drift.configMismatches.push(`manifest declared itself invalid: ${error}`);
|
|
7005
7932
|
}
|
|
7006
7933
|
}
|
|
7007
|
-
|
|
7934
|
+
const declaredArtifacts = [
|
|
7935
|
+
["README.md", manifest.artifacts?.readme],
|
|
7936
|
+
["reports/navigation.md", manifest.artifacts?.navigation],
|
|
7937
|
+
["reports/project-tree.md", manifest.artifacts?.projectTree],
|
|
7938
|
+
["reports/audit.md", manifest.artifacts?.audit],
|
|
7008
7939
|
["full-codebase.json", manifest.artifacts?.fullJson],
|
|
7009
7940
|
["full-codebase.md", manifest.artifacts?.fullMarkdown]
|
|
7010
|
-
]
|
|
7941
|
+
];
|
|
7942
|
+
for (const [key, artifact] of declaredArtifacts) {
|
|
7011
7943
|
if (!artifact) continue;
|
|
7012
|
-
const artifactPath = path16.join(snapshotDir, key);
|
|
7944
|
+
const artifactPath = path16.join(snapshotDir, ...key.split("/"));
|
|
7945
|
+
let buffer;
|
|
7013
7946
|
try {
|
|
7014
|
-
|
|
7015
|
-
|
|
7016
|
-
drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
|
|
7017
|
-
}
|
|
7947
|
+
if (!fs15.statSync(artifactPath).isFile()) throw new Error("not a regular file");
|
|
7948
|
+
buffer = fs15.readFileSync(artifactPath);
|
|
7018
7949
|
} catch {
|
|
7019
7950
|
drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
|
|
7951
|
+
continue;
|
|
7952
|
+
}
|
|
7953
|
+
if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
|
|
7954
|
+
drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
|
|
7955
|
+
continue;
|
|
7956
|
+
}
|
|
7957
|
+
if (key === "reports/navigation.md") {
|
|
7958
|
+
for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
|
|
7959
|
+
const target = match[1].split("#")[0];
|
|
7960
|
+
if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
|
|
7961
|
+
const resolved = path16.resolve(snapshotDir, "reports", target);
|
|
7962
|
+
const relative10 = path16.relative(snapshotDir, resolved);
|
|
7963
|
+
if (relative10.startsWith("..") || path16.isAbsolute(relative10) || !fs15.existsSync(resolved)) {
|
|
7964
|
+
drift.partIssues.push({
|
|
7965
|
+
part: key,
|
|
7966
|
+
issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
|
|
7967
|
+
});
|
|
7968
|
+
}
|
|
7969
|
+
}
|
|
7020
7970
|
}
|
|
7021
7971
|
}
|
|
7022
7972
|
const sarifArtifact = manifest.artifacts?.sarif;
|
|
7023
7973
|
if (sarifArtifact) {
|
|
7024
7974
|
const sarifKey = "reports/audit.sarif";
|
|
7025
7975
|
try {
|
|
7026
|
-
const buffer =
|
|
7976
|
+
const buffer = fs15.readFileSync(path16.join(snapshotDir, "reports", "audit.sarif"));
|
|
7027
7977
|
if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
|
|
7028
7978
|
drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
|
|
7029
7979
|
}
|
|
@@ -7032,8 +7982,11 @@ function validateSnapshot(configInput) {
|
|
|
7032
7982
|
}
|
|
7033
7983
|
}
|
|
7034
7984
|
if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
|
|
7985
|
+
const maskBranch = (value) => findSecretInPath(value, config.secretRules)?.masked ?? value;
|
|
7986
|
+
const generatedOn = maskBranch(manifest.git.branch);
|
|
7987
|
+
const configuredAs = maskBranch(config.branch);
|
|
7035
7988
|
warnings.push(
|
|
7036
|
-
`Snapshot was generated on branch "${
|
|
7989
|
+
`Snapshot was generated on branch "${generatedOn}" but the configured branch is "${configuredAs}".`
|
|
7037
7990
|
);
|
|
7038
7991
|
}
|
|
7039
7992
|
const errors = [];
|
|
@@ -7090,15 +8043,6 @@ function validateSnapshot(configInput) {
|
|
|
7090
8043
|
warnings
|
|
7091
8044
|
};
|
|
7092
8045
|
}
|
|
7093
|
-
|
|
7094
|
-
// src/version.ts
|
|
7095
|
-
var GENERATOR_NAME = "codebase-snapshot";
|
|
7096
|
-
var GENERATOR_VERSION = "0.9.16";
|
|
7097
|
-
var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
|
|
7098
|
-
function isOurGeneratorName(name) {
|
|
7099
|
-
if (typeof name !== "string") return false;
|
|
7100
|
-
return name === GENERATOR_NAME || LEGACY_GENERATOR_NAMES.includes(name);
|
|
7101
|
-
}
|
|
7102
8046
|
var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
|
|
7103
8047
|
var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
7104
8048
|
var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
|
|
@@ -7169,23 +8113,24 @@ function shouldCheck(argv, env) {
|
|
|
7169
8113
|
for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
|
|
7170
8114
|
if (args.includes(skip)) return false;
|
|
7171
8115
|
}
|
|
8116
|
+
let format = null;
|
|
7172
8117
|
for (let index = 0; index < args.length; index += 1) {
|
|
7173
8118
|
const argument = args[index];
|
|
8119
|
+
if (argument === "--") break;
|
|
7174
8120
|
if (argument === "--format") {
|
|
7175
|
-
|
|
7176
|
-
|
|
7177
|
-
|
|
7178
|
-
if (argument.startsWith("--format=")) {
|
|
7179
|
-
if (argument.slice("--format=".length) === "json") return false;
|
|
7180
|
-
break;
|
|
8121
|
+
format = args[index + 1] ?? null;
|
|
8122
|
+
index += 1;
|
|
8123
|
+
continue;
|
|
7181
8124
|
}
|
|
8125
|
+
if (argument.startsWith("--format=")) format = argument.slice("--format=".length);
|
|
7182
8126
|
}
|
|
8127
|
+
if (format === "json") return false;
|
|
7183
8128
|
return true;
|
|
7184
8129
|
}
|
|
7185
8130
|
function readCache(file) {
|
|
7186
8131
|
let raw;
|
|
7187
8132
|
try {
|
|
7188
|
-
raw =
|
|
8133
|
+
raw = fs15.readFileSync(file, "utf8");
|
|
7189
8134
|
} catch {
|
|
7190
8135
|
return null;
|
|
7191
8136
|
}
|
|
@@ -7202,21 +8147,21 @@ function readCache(file) {
|
|
|
7202
8147
|
}
|
|
7203
8148
|
function writeCache(file, entry) {
|
|
7204
8149
|
try {
|
|
7205
|
-
|
|
7206
|
-
|
|
8150
|
+
fs15.mkdirSync(path16.dirname(file), { recursive: true });
|
|
8151
|
+
fs15.writeFileSync(file, `${JSON.stringify(entry)}
|
|
7207
8152
|
`, "utf8");
|
|
7208
8153
|
} catch {
|
|
7209
8154
|
}
|
|
7210
8155
|
}
|
|
7211
8156
|
function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
7212
|
-
return new Promise((
|
|
8157
|
+
return new Promise((resolve7) => {
|
|
7213
8158
|
let settled = false;
|
|
7214
8159
|
let request = null;
|
|
7215
8160
|
const finish = (value) => {
|
|
7216
8161
|
if (settled) return;
|
|
7217
8162
|
settled = true;
|
|
7218
8163
|
clearTimeout(deadline);
|
|
7219
|
-
|
|
8164
|
+
resolve7(value);
|
|
7220
8165
|
};
|
|
7221
8166
|
const deadline = setTimeout(() => {
|
|
7222
8167
|
request?.destroy();
|
|
@@ -7303,23 +8248,23 @@ function describeMatcher(matcher) {
|
|
|
7303
8248
|
function normalizeTarget(cwd, target) {
|
|
7304
8249
|
const resolvedCwd = path16.resolve(cwd);
|
|
7305
8250
|
const absolute = path16.resolve(resolvedCwd, target);
|
|
7306
|
-
const
|
|
7307
|
-
if (
|
|
8251
|
+
const relative10 = path16.relative(resolvedCwd, absolute);
|
|
8252
|
+
if (relative10 === "" || relative10 === ".." || relative10.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative10)) {
|
|
7308
8253
|
return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
|
|
7309
8254
|
}
|
|
7310
|
-
return { relative:
|
|
8255
|
+
return { relative: relative10.split(path16.sep).join("/"), outsideRoot: false };
|
|
7311
8256
|
}
|
|
7312
8257
|
function findRuleMatch(rules, relativePath) {
|
|
7313
8258
|
return rules.find(
|
|
7314
8259
|
(rule) => matchRule(relativePath, rule.match)
|
|
7315
8260
|
);
|
|
7316
8261
|
}
|
|
7317
|
-
function findRecordedAncestor(skipped,
|
|
8262
|
+
function findRecordedAncestor(skipped, relative10, maskedPath2) {
|
|
7318
8263
|
let nearest;
|
|
7319
8264
|
for (const record of skipped) {
|
|
7320
8265
|
const ancestorPath = record.path;
|
|
7321
8266
|
if (ancestorPath.length === 0) continue;
|
|
7322
|
-
const isAncestor =
|
|
8267
|
+
const isAncestor = relative10.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
|
|
7323
8268
|
if (!isAncestor) continue;
|
|
7324
8269
|
if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
|
|
7325
8270
|
}
|
|
@@ -7328,15 +8273,15 @@ function findRecordedAncestor(skipped, relative8, maskedPath2) {
|
|
|
7328
8273
|
function readManifest2(config) {
|
|
7329
8274
|
const manifestPath = path16.resolve(config.cwd, config.outDir, "manifest.json");
|
|
7330
8275
|
try {
|
|
7331
|
-
return JSON.parse(
|
|
8276
|
+
return JSON.parse(fs15.readFileSync(manifestPath, "utf8"));
|
|
7332
8277
|
} catch {
|
|
7333
8278
|
return null;
|
|
7334
8279
|
}
|
|
7335
8280
|
}
|
|
7336
8281
|
function explainPath(config, target) {
|
|
7337
8282
|
const normalized = normalizeTarget(config.cwd, target);
|
|
7338
|
-
const
|
|
7339
|
-
const maskedPath2 = findSecretInPath(
|
|
8283
|
+
const relative10 = normalized.relative;
|
|
8284
|
+
const maskedPath2 = findSecretInPath(relative10, config.secretRules)?.masked ?? relative10;
|
|
7340
8285
|
if (normalized.outsideRoot) {
|
|
7341
8286
|
return {
|
|
7342
8287
|
path: maskedPath2,
|
|
@@ -7346,10 +8291,10 @@ function explainPath(config, target) {
|
|
|
7346
8291
|
detail: "path resolves outside the configured repository root and was not inspected"
|
|
7347
8292
|
};
|
|
7348
8293
|
}
|
|
7349
|
-
const absolute = path16.join(config.cwd,
|
|
8294
|
+
const absolute = path16.join(config.cwd, relative10);
|
|
7350
8295
|
const result = {
|
|
7351
8296
|
path: maskedPath2,
|
|
7352
|
-
exists:
|
|
8297
|
+
exists: fs15.existsSync(absolute),
|
|
7353
8298
|
included: false
|
|
7354
8299
|
};
|
|
7355
8300
|
const collection = collectFiles(config.cwd, {
|
|
@@ -7364,11 +8309,11 @@ function explainPath(config, target) {
|
|
|
7364
8309
|
// that is only missing because the walker dropped the tool's own output directory.
|
|
7365
8310
|
toolOwnedPaths: [config.outDir, config.tmpDir].map(
|
|
7366
8311
|
(directory) => path16.relative(config.cwd, path16.resolve(config.cwd, directory)).replace(/\\/g, "/")
|
|
7367
|
-
).filter((
|
|
8312
|
+
).filter((relative11) => relative11.length > 0 && !relative11.startsWith(".."))
|
|
7368
8313
|
});
|
|
7369
|
-
if (!collection.files.includes(
|
|
8314
|
+
if (!collection.files.includes(relative10)) {
|
|
7370
8315
|
const record = collection.skipped.find(
|
|
7371
|
-
(entry2) => entry2.path ===
|
|
8316
|
+
(entry2) => entry2.path === relative10 || entry2.path === maskedPath2
|
|
7372
8317
|
);
|
|
7373
8318
|
if (record) {
|
|
7374
8319
|
result.reason = record.reason;
|
|
@@ -7377,7 +8322,7 @@ function explainPath(config, target) {
|
|
|
7377
8322
|
result.reason = "missing";
|
|
7378
8323
|
result.detail = "no such file or directory, relative to the configured cwd";
|
|
7379
8324
|
} else {
|
|
7380
|
-
const ancestor = findRecordedAncestor(collection.skipped,
|
|
8325
|
+
const ancestor = findRecordedAncestor(collection.skipped, relative10, maskedPath2);
|
|
7381
8326
|
if (ancestor) {
|
|
7382
8327
|
result.reason = ancestor.reason;
|
|
7383
8328
|
result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
|
|
@@ -7397,11 +8342,11 @@ function explainPath(config, target) {
|
|
|
7397
8342
|
...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
|
|
7398
8343
|
...config.staged === true ? { staged: true } : {}
|
|
7399
8344
|
});
|
|
7400
|
-
inScope = scope.paths.has(
|
|
8345
|
+
inScope = scope.paths.has(relative10);
|
|
7401
8346
|
if (!inScope && config.withDependents === true) {
|
|
7402
8347
|
inScope = importsChangedFile(
|
|
7403
|
-
|
|
7404
|
-
importsOfFile(
|
|
8348
|
+
relative10,
|
|
8349
|
+
importsOfFile(relative10, absolute),
|
|
7405
8350
|
scope.paths,
|
|
7406
8351
|
buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
|
|
7407
8352
|
);
|
|
@@ -7428,7 +8373,7 @@ function explainPath(config, target) {
|
|
|
7428
8373
|
}
|
|
7429
8374
|
let sizeOnDisk = null;
|
|
7430
8375
|
try {
|
|
7431
|
-
sizeOnDisk =
|
|
8376
|
+
sizeOnDisk = fs15.statSync(absolute).size;
|
|
7432
8377
|
} catch {
|
|
7433
8378
|
sizeOnDisk = null;
|
|
7434
8379
|
}
|
|
@@ -7438,8 +8383,16 @@ function explainPath(config, target) {
|
|
|
7438
8383
|
result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
|
|
7439
8384
|
return result;
|
|
7440
8385
|
}
|
|
7441
|
-
if (
|
|
7442
|
-
|
|
8386
|
+
if (fs15.existsSync(absolute) && fs15.statSync(absolute).isFile()) {
|
|
8387
|
+
let buffer;
|
|
8388
|
+
try {
|
|
8389
|
+
buffer = fs15.readFileSync(absolute);
|
|
8390
|
+
} catch (err) {
|
|
8391
|
+
result.included = false;
|
|
8392
|
+
result.reason = "read-error";
|
|
8393
|
+
result.detail = `${err.message} (explain could not read the file; generate records this as a skipped entry)`;
|
|
8394
|
+
return result;
|
|
8395
|
+
}
|
|
7443
8396
|
const decoded = decodeText(buffer);
|
|
7444
8397
|
if (decoded.binary) {
|
|
7445
8398
|
result.included = false;
|
|
@@ -7451,21 +8404,30 @@ function explainPath(config, target) {
|
|
|
7451
8404
|
result.bytes = buffer.length;
|
|
7452
8405
|
result.lines = countLines(text2);
|
|
7453
8406
|
if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
|
|
7454
|
-
const { findings } = scanAndRedactSecrets(text2, config.secretRules,
|
|
8407
|
+
const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative10);
|
|
7455
8408
|
result.secretCount = findings.length;
|
|
7456
8409
|
result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
|
|
8410
|
+
let inclusionMode = "full";
|
|
8411
|
+
if (config.skeleton === true && isSkeletonizable(relative10)) {
|
|
8412
|
+
const skeleton = skeletonizeTypeScript(text2, relative10);
|
|
8413
|
+
if (skeleton.collapsed > 0) inclusionMode = "signatures";
|
|
8414
|
+
}
|
|
8415
|
+
if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
|
|
8416
|
+
const preview = truncatePreview(text2, config.previewHeadLines, config.previewTailLines);
|
|
8417
|
+
inclusionMode = preview.isTruncated ? "preview" : "full";
|
|
8418
|
+
}
|
|
8419
|
+
result.inclusionMode = inclusionMode;
|
|
7457
8420
|
}
|
|
7458
|
-
result.layer = classifyLayer(
|
|
7459
|
-
result.kind = classifyKind(
|
|
7460
|
-
result.language = detectLanguage(
|
|
7461
|
-
const layerRule = findRuleMatch(config.layers,
|
|
8421
|
+
result.layer = classifyLayer(relative10, config.layers);
|
|
8422
|
+
result.kind = classifyKind(relative10, config.kinds);
|
|
8423
|
+
result.language = detectLanguage(relative10);
|
|
8424
|
+
const layerRule = findRuleMatch(config.layers, relative10);
|
|
7462
8425
|
if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
|
|
7463
|
-
const kindRule = findRuleMatch(config.kinds,
|
|
8426
|
+
const kindRule = findRuleMatch(config.kinds, relative10);
|
|
7464
8427
|
if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
|
|
7465
8428
|
const manifest = readManifest2(config);
|
|
7466
|
-
const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath ===
|
|
8429
|
+
const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative10) : void 0;
|
|
7467
8430
|
result.part = entry?.part ?? null;
|
|
7468
|
-
result.inclusionMode = entry?.inclusionMode;
|
|
7469
8431
|
return result;
|
|
7470
8432
|
}
|
|
7471
8433
|
function renderExplainText(result) {
|
|
@@ -7694,14 +8656,14 @@ function compareManifests(before, after) {
|
|
|
7694
8656
|
function loadManifest(target) {
|
|
7695
8657
|
let isDirectory;
|
|
7696
8658
|
try {
|
|
7697
|
-
isDirectory =
|
|
8659
|
+
isDirectory = fs15.statSync(target).isDirectory();
|
|
7698
8660
|
} catch {
|
|
7699
8661
|
throw new Error(`No snapshot found at ${target}: the path does not exist.`);
|
|
7700
8662
|
}
|
|
7701
8663
|
const manifestPath = isDirectory ? path16.join(target, "manifest.json") : target;
|
|
7702
8664
|
let raw;
|
|
7703
8665
|
try {
|
|
7704
|
-
raw =
|
|
8666
|
+
raw = fs15.readFileSync(manifestPath, "utf8");
|
|
7705
8667
|
} catch {
|
|
7706
8668
|
throw new Error(`Could not read a manifest at ${manifestPath}.`);
|
|
7707
8669
|
}
|
|
@@ -7755,18 +8717,70 @@ function renderDiffText(diff) {
|
|
|
7755
8717
|
}
|
|
7756
8718
|
return lines.join("\n");
|
|
7757
8719
|
}
|
|
8720
|
+
function decodeGitignore(buffer) {
|
|
8721
|
+
const startsWith = (...bytes) => buffer.length >= bytes.length && bytes.every((byte, index) => buffer[index] === byte);
|
|
8722
|
+
if (startsWith(239, 187, 191)) {
|
|
8723
|
+
const body = buffer.subarray(3);
|
|
8724
|
+
const text3 = body.toString("utf8");
|
|
8725
|
+
if (!Buffer.from(text3, "utf8").equals(body)) return null;
|
|
8726
|
+
return { text: text3, bom: buffer.subarray(0, 3), encoding: "utf8" };
|
|
8727
|
+
}
|
|
8728
|
+
if (startsWith(255, 254)) {
|
|
8729
|
+
const body = buffer.subarray(2);
|
|
8730
|
+
if (body.length % 2 !== 0) return null;
|
|
8731
|
+
const text3 = body.toString("utf16le");
|
|
8732
|
+
if (!Buffer.from(text3, "utf16le").equals(body)) return null;
|
|
8733
|
+
return { text: text3, bom: buffer.subarray(0, 2), encoding: "utf16le" };
|
|
8734
|
+
}
|
|
8735
|
+
if (startsWith(254, 255)) {
|
|
8736
|
+
const body = buffer.subarray(2);
|
|
8737
|
+
if (body.length % 2 !== 0) return null;
|
|
8738
|
+
const swapped = Buffer.from(body);
|
|
8739
|
+
swapped.swap16();
|
|
8740
|
+
const text3 = swapped.toString("utf16le");
|
|
8741
|
+
if (!Buffer.from(text3, "utf16le").equals(swapped)) return null;
|
|
8742
|
+
return { text: text3, bom: buffer.subarray(0, 2), encoding: "utf16be" };
|
|
8743
|
+
}
|
|
8744
|
+
const text2 = buffer.toString("utf8");
|
|
8745
|
+
if (!Buffer.from(text2, "utf8").equals(buffer)) return null;
|
|
8746
|
+
return { text: text2, bom: Buffer.alloc(0), encoding: "utf8" };
|
|
8747
|
+
}
|
|
8748
|
+
function encodeGitignore(decoded, text2) {
|
|
8749
|
+
if (decoded.encoding === "utf8") {
|
|
8750
|
+
return Buffer.concat([decoded.bom, Buffer.from(text2, "utf8")]);
|
|
8751
|
+
}
|
|
8752
|
+
const littleEndian = Buffer.from(text2, "utf16le");
|
|
8753
|
+
if (decoded.encoding === "utf16le") return Buffer.concat([decoded.bom, littleEndian]);
|
|
8754
|
+
const bigEndian = Buffer.from(littleEndian);
|
|
8755
|
+
bigEndian.swap16();
|
|
8756
|
+
return Buffer.concat([decoded.bom, bigEndian]);
|
|
8757
|
+
}
|
|
8758
|
+
function canonicalIgnorePattern(line) {
|
|
8759
|
+
const trimmed = line.trim();
|
|
8760
|
+
if (trimmed.length === 0 || trimmed.startsWith("#")) return trimmed;
|
|
8761
|
+
const negated = trimmed.startsWith("!");
|
|
8762
|
+
const body = (negated ? trimmed.slice(1) : trimmed).replace(/^\/+/, "").replace(/\/+$/, "");
|
|
8763
|
+
return `${negated ? "!" : ""}${body}`;
|
|
8764
|
+
}
|
|
7758
8765
|
function appendGitignoreEntries(cwd, entries) {
|
|
7759
8766
|
const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
|
|
7760
8767
|
if (wanted.length === 0) return { added: [], note: null };
|
|
7761
8768
|
const ignorePath = path16.join(cwd, ".gitignore");
|
|
7762
8769
|
const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
|
|
7763
|
-
let
|
|
8770
|
+
let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
|
|
7764
8771
|
try {
|
|
7765
|
-
if (
|
|
7766
|
-
if (
|
|
8772
|
+
if (fs15.existsSync(ignorePath)) {
|
|
8773
|
+
if (fs15.statSync(ignorePath).isDirectory()) {
|
|
7767
8774
|
return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
|
|
7768
8775
|
}
|
|
7769
|
-
|
|
8776
|
+
const read = decodeGitignore(fs15.readFileSync(ignorePath));
|
|
8777
|
+
if (read === null) {
|
|
8778
|
+
return {
|
|
8779
|
+
added: [],
|
|
8780
|
+
note: `${ignorePath} is not valid UTF-8, UTF-16LE or UTF-16BE text, so it was not updated. ` + manual
|
|
8781
|
+
};
|
|
8782
|
+
}
|
|
8783
|
+
decoded = read;
|
|
7770
8784
|
}
|
|
7771
8785
|
} catch (err) {
|
|
7772
8786
|
return {
|
|
@@ -7774,13 +8788,17 @@ function appendGitignoreEntries(cwd, entries) {
|
|
|
7774
8788
|
note: `${ignorePath} could not be read (${err.message}). ${manual}`
|
|
7775
8789
|
};
|
|
7776
8790
|
}
|
|
7777
|
-
const
|
|
7778
|
-
const
|
|
8791
|
+
const existing = decoded.text;
|
|
8792
|
+
const present = new Set(existing.split(/\r?\n/).map(canonicalIgnorePattern));
|
|
8793
|
+
const added = wanted.filter((entry) => !present.has(canonicalIgnorePattern(entry)));
|
|
7779
8794
|
if (added.length === 0) return { added: [], note: null };
|
|
7780
|
-
const
|
|
8795
|
+
const newline = existing.includes("\r\n") ? "\r\n" : "\n";
|
|
8796
|
+
const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
|
|
7781
8797
|
try {
|
|
7782
|
-
|
|
7783
|
-
|
|
8798
|
+
fs15.writeFileSync(
|
|
8799
|
+
ignorePath,
|
|
8800
|
+
encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
|
|
8801
|
+
);
|
|
7784
8802
|
} catch (err) {
|
|
7785
8803
|
return { added: [], note: `${err.message}. ${manual}` };
|
|
7786
8804
|
}
|
|
@@ -8098,7 +9116,7 @@ function keyReader(input) {
|
|
|
8098
9116
|
next() {
|
|
8099
9117
|
const queued = queue.shift();
|
|
8100
9118
|
if (queued) return Promise.resolve(queued);
|
|
8101
|
-
return new Promise((
|
|
9119
|
+
return new Promise((resolve7) => waiters.push(resolve7));
|
|
8102
9120
|
},
|
|
8103
9121
|
close() {
|
|
8104
9122
|
input.off("keypress", onKey);
|
|
@@ -8324,7 +9342,7 @@ function parsePackageJson(raw) {
|
|
|
8324
9342
|
}
|
|
8325
9343
|
function readPackageJson(cwd) {
|
|
8326
9344
|
try {
|
|
8327
|
-
return parsePackageJson(
|
|
9345
|
+
return parsePackageJson(fs15.readFileSync(path16.join(cwd, "package.json"), "utf8"));
|
|
8328
9346
|
} catch {
|
|
8329
9347
|
return null;
|
|
8330
9348
|
}
|
|
@@ -8361,7 +9379,7 @@ function artifactAnswers(options) {
|
|
|
8361
9379
|
}
|
|
8362
9380
|
function topLevelDirs(cwd) {
|
|
8363
9381
|
try {
|
|
8364
|
-
return
|
|
9382
|
+
return fs15.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
|
|
8365
9383
|
} catch {
|
|
8366
9384
|
return [];
|
|
8367
9385
|
}
|
|
@@ -8374,10 +9392,38 @@ function describeJsonValue(value) {
|
|
|
8374
9392
|
}
|
|
8375
9393
|
function writeFileOrExplain(target, content) {
|
|
8376
9394
|
try {
|
|
8377
|
-
|
|
9395
|
+
let stats = null;
|
|
9396
|
+
try {
|
|
9397
|
+
stats = fs15.lstatSync(target);
|
|
9398
|
+
} catch {
|
|
9399
|
+
stats = null;
|
|
9400
|
+
}
|
|
9401
|
+
if (stats !== null && stats.isSymbolicLink()) {
|
|
9402
|
+
throw new Error(
|
|
9403
|
+
`Cannot write ${target}: it is a symbolic link, and writing through it would modify whatever it points at.`
|
|
9404
|
+
);
|
|
9405
|
+
}
|
|
9406
|
+
if (stats !== null && !stats.isFile()) {
|
|
9407
|
+
throw new Error(
|
|
9408
|
+
`Cannot write ${target}: ${stats.isDirectory() ? "it is a directory" : "it is not a regular file"}.`
|
|
9409
|
+
);
|
|
9410
|
+
}
|
|
9411
|
+
const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
|
|
9412
|
+
fs15.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
|
|
9413
|
+
try {
|
|
9414
|
+
fs15.renameSync(temporary, target);
|
|
9415
|
+
} catch (err) {
|
|
9416
|
+
try {
|
|
9417
|
+
fs15.unlinkSync(temporary);
|
|
9418
|
+
} catch {
|
|
9419
|
+
}
|
|
9420
|
+
throw err;
|
|
9421
|
+
}
|
|
8378
9422
|
} catch (err) {
|
|
9423
|
+
const message = err.message;
|
|
9424
|
+
if (message.startsWith(`Cannot write ${target}:`)) throw err;
|
|
8379
9425
|
const code = err.code;
|
|
8380
|
-
const reason = code === "EACCES" || code === "EPERM" || code === "EROFS" ? `permission denied (${code})` : code === "EISDIR" ? "it is a directory" :
|
|
9426
|
+
const reason = code === "EACCES" || code === "EPERM" || code === "EROFS" ? `permission denied (${code})` : code === "EISDIR" ? "it is a directory" : message;
|
|
8381
9427
|
throw new Error(`Cannot write ${target}: ${reason}`);
|
|
8382
9428
|
}
|
|
8383
9429
|
}
|
|
@@ -8421,14 +9467,14 @@ function updatePackageJson(cwd, notes) {
|
|
|
8421
9467
|
scripts: [],
|
|
8422
9468
|
dependency: { name: GENERATOR_NAME, range: null, added: false }
|
|
8423
9469
|
};
|
|
8424
|
-
if (!
|
|
9470
|
+
if (!fs15.existsSync(packagePath)) {
|
|
8425
9471
|
notes.push("No package.json found, so npm scripts and the devDependency were not added.");
|
|
8426
9472
|
return unchanged;
|
|
8427
9473
|
}
|
|
8428
9474
|
let raw;
|
|
8429
9475
|
let parsed;
|
|
8430
9476
|
try {
|
|
8431
|
-
raw =
|
|
9477
|
+
raw = fs15.readFileSync(packagePath, "utf8");
|
|
8432
9478
|
parsed = parsePackageJson(raw);
|
|
8433
9479
|
} catch {
|
|
8434
9480
|
notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
|
|
@@ -8499,7 +9545,7 @@ function updatePackageJson(cwd, notes) {
|
|
|
8499
9545
|
writeFileOrExplain(packagePath, serializePackageJson(raw, parsed));
|
|
8500
9546
|
return { scripts: added, dependency };
|
|
8501
9547
|
}
|
|
8502
|
-
var GITIGNORE_ENTRIES = ["snapshot/", "snapshot.tmp/"];
|
|
9548
|
+
var GITIGNORE_ENTRIES = ["/snapshot/", "/snapshot.tmp/"];
|
|
8503
9549
|
function resolvePresetChoice(detectedName, presetName) {
|
|
8504
9550
|
return {
|
|
8505
9551
|
value: presetName,
|
|
@@ -8737,7 +9783,7 @@ async function runInit(options) {
|
|
|
8737
9783
|
const configText = renderConfig(answers);
|
|
8738
9784
|
const preferredName = chooseConfigFileName(options.cwd);
|
|
8739
9785
|
const presentConfigs = CONFIG_CANDIDATES.filter(
|
|
8740
|
-
(name) =>
|
|
9786
|
+
(name) => fs15.existsSync(path16.join(options.cwd, name))
|
|
8741
9787
|
);
|
|
8742
9788
|
const present = presentConfigs[0] ?? null;
|
|
8743
9789
|
if (presentConfigs.length > 1) {
|
|
@@ -8780,7 +9826,7 @@ async function runInit(options) {
|
|
|
8780
9826
|
'package.json already defines a "snapshot" config. Remove that key, or re-run with --force to write a config file that takes precedence over it.'
|
|
8781
9827
|
);
|
|
8782
9828
|
}
|
|
8783
|
-
if (
|
|
9829
|
+
if (fs15.existsSync(configPath) && !options.force && !reused) {
|
|
8784
9830
|
throw new Error(`${configName} already exists. Re-run with --force to replace it.`);
|
|
8785
9831
|
}
|
|
8786
9832
|
if (!reused) writeFileOrExplain(configPath, configText);
|
|
@@ -8803,10 +9849,10 @@ async function runInit(options) {
|
|
|
8803
9849
|
};
|
|
8804
9850
|
}
|
|
8805
9851
|
function describeTarget(cwd) {
|
|
8806
|
-
const
|
|
8807
|
-
if (
|
|
8808
|
-
if (
|
|
8809
|
-
return
|
|
9852
|
+
const relative10 = path16.relative(process.cwd(), cwd);
|
|
9853
|
+
if (relative10 === "") return "this directory";
|
|
9854
|
+
if (relative10.startsWith("..") || path16.isAbsolute(relative10)) return cwd;
|
|
9855
|
+
return relative10;
|
|
8810
9856
|
}
|
|
8811
9857
|
function firstRunMessage(reason, cwd) {
|
|
8812
9858
|
const where = describeTarget(cwd);
|
|
@@ -8829,7 +9875,7 @@ function planFirstRun(facts) {
|
|
|
8829
9875
|
var NOT_CONTENT = /* @__PURE__ */ new Set([".git", ".hg", ".svn", ".bzr", ".DS_Store", "Thumbs.db"]);
|
|
8830
9876
|
function isEffectivelyEmpty(cwd) {
|
|
8831
9877
|
try {
|
|
8832
|
-
return
|
|
9878
|
+
return fs15.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
|
|
8833
9879
|
} catch {
|
|
8834
9880
|
return false;
|
|
8835
9881
|
}
|
|
@@ -8837,7 +9883,7 @@ function isEffectivelyEmpty(cwd) {
|
|
|
8837
9883
|
function hasPriorSnapshot(cwd, outDir) {
|
|
8838
9884
|
let parsed;
|
|
8839
9885
|
try {
|
|
8840
|
-
parsed = JSON.parse(
|
|
9886
|
+
parsed = JSON.parse(fs15.readFileSync(path16.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
|
|
8841
9887
|
} catch {
|
|
8842
9888
|
return false;
|
|
8843
9889
|
}
|
|
@@ -8863,9 +9909,17 @@ set -e
|
|
|
8863
9909
|
SNAPSHOT_DIR="${dir}"
|
|
8864
9910
|
|
|
8865
9911
|
if [ ! -f "$SNAPSHOT_DIR/manifest.json" ]; then
|
|
8866
|
-
|
|
8867
|
-
|
|
8868
|
-
|
|
9912
|
+
# Fail closed. A missing snapshot used to exit 0 with a reassuring message, so deleting or
|
|
9913
|
+
# renaming the output directory disabled the gate while every commit still succeeded \u2014 the one
|
|
9914
|
+
# failure mode a commit gate must not have. The opt-out is explicit and documented.
|
|
9915
|
+
if [ "\${CODEBASE_SNAPSHOT_ALLOW_MISSING:-}" = "1" ]; then
|
|
9916
|
+
echo "${GENERATOR_NAME}: no snapshot in $SNAPSHOT_DIR; skipping the check (CODEBASE_SNAPSHOT_ALLOW_MISSING=1)." >&2
|
|
9917
|
+
exit 0
|
|
9918
|
+
fi
|
|
9919
|
+
echo "${GENERATOR_NAME}: refusing the commit: no snapshot in $SNAPSHOT_DIR." >&2
|
|
9920
|
+
echo " Run \\"npx ${GENERATOR_NAME} generate\\", stage it, and commit again." >&2
|
|
9921
|
+
echo " To disable this gate, set CODEBASE_SNAPSHOT_ALLOW_MISSING=1." >&2
|
|
9922
|
+
exit 1
|
|
8869
9923
|
fi
|
|
8870
9924
|
|
|
8871
9925
|
if ! npx --no-install ${GENERATOR_NAME} validate >/dev/null 2>&1; then
|
|
@@ -8880,26 +9934,69 @@ function gitDirectory(cwd) {
|
|
|
8880
9934
|
const dotGit = path16.join(cwd, ".git");
|
|
8881
9935
|
let stats;
|
|
8882
9936
|
try {
|
|
8883
|
-
stats =
|
|
9937
|
+
stats = fs15.statSync(dotGit);
|
|
8884
9938
|
} catch {
|
|
8885
9939
|
return null;
|
|
8886
9940
|
}
|
|
8887
9941
|
if (stats.isDirectory()) return dotGit;
|
|
8888
9942
|
if (!stats.isFile()) return null;
|
|
8889
9943
|
try {
|
|
8890
|
-
const contents =
|
|
9944
|
+
const contents = fs15.readFileSync(dotGit, "utf8");
|
|
8891
9945
|
const match = /^gitdir:\s*(.+)$/m.exec(contents);
|
|
8892
9946
|
if (!match) return null;
|
|
8893
9947
|
const target = match[1];
|
|
8894
9948
|
const resolved = path16.isAbsolute(target.trim()) ? target.trim() : path16.join(cwd, target.trim());
|
|
8895
|
-
|
|
9949
|
+
if (!fs15.statSync(resolved).isDirectory()) return null;
|
|
9950
|
+
if (isInside2(path16.resolve(cwd), path16.resolve(resolved))) return resolved;
|
|
9951
|
+
return isRegisteredWorktree(path16.resolve(resolved), cwd) ? resolved : null;
|
|
9952
|
+
} catch {
|
|
9953
|
+
return null;
|
|
9954
|
+
}
|
|
9955
|
+
}
|
|
9956
|
+
function isInside2(parent, child) {
|
|
9957
|
+
const relative10 = path16.relative(parent, child);
|
|
9958
|
+
return relative10 === "" || !relative10.startsWith("..") && !path16.isAbsolute(relative10);
|
|
9959
|
+
}
|
|
9960
|
+
function isRegisteredWorktree(gitDir, cwd) {
|
|
9961
|
+
try {
|
|
9962
|
+
const back = fs15.readFileSync(path16.join(gitDir, "gitdir"), "utf8").trim();
|
|
9963
|
+
return path16.resolve(gitDir, back) === path16.join(path16.resolve(cwd), ".git");
|
|
9964
|
+
} catch {
|
|
9965
|
+
return false;
|
|
9966
|
+
}
|
|
9967
|
+
}
|
|
9968
|
+
function gitOutput(cwd, args) {
|
|
9969
|
+
try {
|
|
9970
|
+
const output = childProcess.execFileSync("git", args, {
|
|
9971
|
+
cwd,
|
|
9972
|
+
encoding: "utf8",
|
|
9973
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
9974
|
+
});
|
|
9975
|
+
const trimmed = output.trim();
|
|
9976
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
8896
9977
|
} catch {
|
|
8897
9978
|
return null;
|
|
8898
9979
|
}
|
|
8899
9980
|
}
|
|
9981
|
+
function configuredHooksDirectory(cwd) {
|
|
9982
|
+
const hooks = gitOutput(cwd, ["rev-parse", "--git-path", "hooks"]);
|
|
9983
|
+
if (hooks === null) return null;
|
|
9984
|
+
const resolved = path16.resolve(cwd, hooks);
|
|
9985
|
+
const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
|
|
9986
|
+
const commonDir = common === null ? null : path16.resolve(cwd, common);
|
|
9987
|
+
if (isInside2(path16.resolve(cwd), resolved)) return { dir: resolved };
|
|
9988
|
+
if (commonDir !== null && isInside2(commonDir, resolved)) return { dir: resolved };
|
|
9989
|
+
return {
|
|
9990
|
+
refusal: `The hooks directory git reports (${resolved}) is outside this repository, so no hook was written. Add \`npx ${GENERATOR_NAME} validate\` to the hook manager that owns it instead.`
|
|
9991
|
+
};
|
|
9992
|
+
}
|
|
8900
9993
|
function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
8901
|
-
const
|
|
8902
|
-
if (
|
|
9994
|
+
const configured = configuredHooksDirectory(cwd);
|
|
9995
|
+
if (configured !== null && "refusal" in configured) {
|
|
9996
|
+
return { path: null, written: false, notes: [configured.refusal] };
|
|
9997
|
+
}
|
|
9998
|
+
const gitDir = configured === null ? gitDirectory(cwd) : null;
|
|
9999
|
+
if (configured === null && gitDir === null) {
|
|
8903
10000
|
return {
|
|
8904
10001
|
path: null,
|
|
8905
10002
|
written: false,
|
|
@@ -8908,10 +10005,10 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
|
8908
10005
|
]
|
|
8909
10006
|
};
|
|
8910
10007
|
}
|
|
8911
|
-
const hooksDir = path16.join(gitDir, "hooks");
|
|
10008
|
+
const hooksDir = configured === null ? path16.join(gitDir, "hooks") : configured.dir;
|
|
8912
10009
|
const hookPath = path16.join(hooksDir, "pre-commit");
|
|
8913
10010
|
try {
|
|
8914
|
-
|
|
10011
|
+
fs15.mkdirSync(hooksDir, { recursive: true });
|
|
8915
10012
|
} catch (err) {
|
|
8916
10013
|
return {
|
|
8917
10014
|
path: hookPath,
|
|
@@ -8921,7 +10018,7 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
|
8921
10018
|
}
|
|
8922
10019
|
let existing = null;
|
|
8923
10020
|
try {
|
|
8924
|
-
existing =
|
|
10021
|
+
existing = fs15.readFileSync(hookPath, "utf8");
|
|
8925
10022
|
} catch {
|
|
8926
10023
|
existing = null;
|
|
8927
10024
|
}
|
|
@@ -8936,8 +10033,8 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
|
|
|
8936
10033
|
};
|
|
8937
10034
|
}
|
|
8938
10035
|
try {
|
|
8939
|
-
|
|
8940
|
-
|
|
10036
|
+
fs15.writeFileSync(hookPath, hookScript(outDir), "utf8");
|
|
10037
|
+
fs15.chmodSync(hookPath, 493);
|
|
8941
10038
|
} catch (err) {
|
|
8942
10039
|
return {
|
|
8943
10040
|
path: hookPath,
|
|
@@ -8994,14 +10091,14 @@ const { parentPort, workerData } = require("node:worker_threads");
|
|
|
8994
10091
|
})();
|
|
8995
10092
|
`;
|
|
8996
10093
|
function generateInWorker(cwd, cliOptions) {
|
|
8997
|
-
return new Promise((
|
|
10094
|
+
return new Promise((resolve7) => {
|
|
8998
10095
|
let settled = false;
|
|
8999
10096
|
let worker = null;
|
|
9000
10097
|
const finish = (result) => {
|
|
9001
10098
|
if (settled) return;
|
|
9002
10099
|
settled = true;
|
|
9003
10100
|
if (worker !== null) void worker.terminate();
|
|
9004
|
-
|
|
10101
|
+
resolve7(result);
|
|
9005
10102
|
};
|
|
9006
10103
|
const isCjs = typeof __dirname !== "undefined";
|
|
9007
10104
|
const directory = isCjs ? __dirname : path16.dirname(fileURLToPath(import.meta.url));
|
|
@@ -9034,7 +10131,6 @@ function generateInWorker(cwd, cliOptions) {
|
|
|
9034
10131
|
}
|
|
9035
10132
|
|
|
9036
10133
|
// src/index.ts
|
|
9037
|
-
var SCHEMA_VERSION = "3.0.0";
|
|
9038
10134
|
var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
|
|
9039
10135
|
var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
|
|
9040
10136
|
var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
|
|
@@ -9042,12 +10138,21 @@ var fileDerivationBytes = 0;
|
|
|
9042
10138
|
function takeDerivation(path17, hash, settings) {
|
|
9043
10139
|
const cached = FILE_DERIVATIONS.get(path17);
|
|
9044
10140
|
if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
|
|
10141
|
+
FILE_DERIVATIONS.delete(path17);
|
|
10142
|
+
FILE_DERIVATIONS.set(path17, cached);
|
|
9045
10143
|
return cached;
|
|
9046
10144
|
}
|
|
9047
10145
|
function rememberDerivation(path17, hash, settings, derivation) {
|
|
9048
10146
|
const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
|
|
9049
10147
|
const bytes = bodyBytes * 2 + 512;
|
|
9050
10148
|
if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
|
|
10149
|
+
const previous = FILE_DERIVATIONS.get(path17);
|
|
10150
|
+
if (previous !== void 0) {
|
|
10151
|
+
FILE_DERIVATIONS.delete(path17);
|
|
10152
|
+
fileDerivationBytes -= previous.bytes;
|
|
10153
|
+
} else {
|
|
10154
|
+
FILE_DERIVATIONS.delete(path17);
|
|
10155
|
+
}
|
|
9051
10156
|
while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
|
|
9052
10157
|
const oldest = FILE_DERIVATIONS.keys().next();
|
|
9053
10158
|
if (oldest.done === true) break;
|
|
@@ -9068,11 +10173,12 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
|
|
|
9068
10173
|
const lineCount = countLines(rawContent);
|
|
9069
10174
|
const { redacted, findings } = scanAndRedactSecrets(rawContent, config.secretRules, relativePath);
|
|
9070
10175
|
const isLarge = sizeBytes > config.largeFileBytes;
|
|
10176
|
+
const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
|
|
9071
10177
|
let finalContent = redacted;
|
|
9072
10178
|
let isPreviewTruncated = false;
|
|
9073
10179
|
let includedLines = lineCount;
|
|
9074
10180
|
let inclusionMode = "full";
|
|
9075
|
-
if (config.skeleton === true && isSkeletonizable(relativePath)) {
|
|
10181
|
+
if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
|
|
9076
10182
|
const skeleton = skeletonizeTypeScript(redacted, relativePath);
|
|
9077
10183
|
if (skeleton.collapsed > 0) {
|
|
9078
10184
|
finalContent = skeleton.text;
|
|
@@ -9092,7 +10198,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
|
|
|
9092
10198
|
let summarySkip = null;
|
|
9093
10199
|
let summaryWarning = null;
|
|
9094
10200
|
let dependentImports = null;
|
|
9095
|
-
if (
|
|
10201
|
+
if (oversizeForSummary) {
|
|
9096
10202
|
summarySkip = "oversize";
|
|
9097
10203
|
dependentImports = [];
|
|
9098
10204
|
} else if (isPreviewTruncated && hasStructuralSummary(relativePath)) {
|
|
@@ -9179,8 +10285,8 @@ function retain(items, keep) {
|
|
|
9179
10285
|
}
|
|
9180
10286
|
items.length = write;
|
|
9181
10287
|
}
|
|
9182
|
-
function buildIndexes(files) {
|
|
9183
|
-
const resolver = buildImportResolver(files);
|
|
10288
|
+
function buildIndexes(files, tsconfigPaths) {
|
|
10289
|
+
const resolver = buildImportResolver(files, { tsconfig: tsconfigPaths });
|
|
9184
10290
|
const importerCounts = /* @__PURE__ */ new Map();
|
|
9185
10291
|
const byFile = files.filter((file) => isSourceSummary(file.summary)).map((file) => {
|
|
9186
10292
|
const summary = file.summary;
|
|
@@ -9323,20 +10429,20 @@ function listEntries(dir) {
|
|
|
9323
10429
|
const walk = (absolute, prefix) => {
|
|
9324
10430
|
let children;
|
|
9325
10431
|
try {
|
|
9326
|
-
children =
|
|
10432
|
+
children = fs15.readdirSync(absolute, { withFileTypes: true });
|
|
9327
10433
|
} catch {
|
|
9328
10434
|
return;
|
|
9329
10435
|
}
|
|
9330
10436
|
for (const child of children) {
|
|
9331
|
-
const
|
|
9332
|
-
entries.push(
|
|
9333
|
-
if (child.isDirectory()) walk(path16.join(absolute, child.name),
|
|
10437
|
+
const relative10 = prefix === "" ? child.name : `${prefix}/${child.name}`;
|
|
10438
|
+
entries.push(relative10);
|
|
10439
|
+
if (child.isDirectory()) walk(path16.join(absolute, child.name), relative10);
|
|
9334
10440
|
}
|
|
9335
10441
|
};
|
|
9336
10442
|
walk(dir, "");
|
|
9337
10443
|
return entries.sort();
|
|
9338
10444
|
}
|
|
9339
|
-
function markerInventory(dir) {
|
|
10445
|
+
function markerInventory(dir, written) {
|
|
9340
10446
|
const entries = listEntries(dir);
|
|
9341
10447
|
const files = [];
|
|
9342
10448
|
for (const entry of entries) {
|
|
@@ -9345,14 +10451,19 @@ function markerInventory(dir) {
|
|
|
9345
10451
|
const full = path16.join(dir, ...entry.split("/"));
|
|
9346
10452
|
let stats;
|
|
9347
10453
|
try {
|
|
9348
|
-
stats =
|
|
10454
|
+
stats = fs15.lstatSync(full);
|
|
9349
10455
|
} catch {
|
|
9350
10456
|
continue;
|
|
9351
10457
|
}
|
|
9352
10458
|
if (!stats.isFile()) continue;
|
|
10459
|
+
const recorded = written?.get(entry);
|
|
10460
|
+
if (recorded !== void 0 && recorded.digest.bytes === stats.size && recorded.mtimeMs === stats.mtimeMs) {
|
|
10461
|
+
files.push(recorded.digest);
|
|
10462
|
+
continue;
|
|
10463
|
+
}
|
|
9353
10464
|
let digest;
|
|
9354
10465
|
try {
|
|
9355
|
-
digest = sha256Hex2(
|
|
10466
|
+
digest = sha256Hex2(fs15.readFileSync(full));
|
|
9356
10467
|
} catch {
|
|
9357
10468
|
continue;
|
|
9358
10469
|
}
|
|
@@ -9360,8 +10471,8 @@ function markerInventory(dir) {
|
|
|
9360
10471
|
}
|
|
9361
10472
|
return { entries, files };
|
|
9362
10473
|
}
|
|
9363
|
-
function markerPayload(dir, state, id, createdAt) {
|
|
9364
|
-
const { entries, files } = markerInventory(dir);
|
|
10474
|
+
function markerPayload(dir, state, id, createdAt, written) {
|
|
10475
|
+
const { entries, files } = markerInventory(dir, written);
|
|
9365
10476
|
const marker2 = {
|
|
9366
10477
|
generator: GENERATOR_NAME,
|
|
9367
10478
|
version: GENERATOR_VERSION,
|
|
@@ -9374,13 +10485,13 @@ function markerPayload(dir, state, id, createdAt) {
|
|
|
9374
10485
|
files
|
|
9375
10486
|
};
|
|
9376
10487
|
const manifestPath = path16.join(dir, "manifest.json");
|
|
9377
|
-
if (
|
|
9378
|
-
marker2.manifestSha256 = sha256Hex2(
|
|
10488
|
+
if (fs15.existsSync(manifestPath)) {
|
|
10489
|
+
marker2.manifestSha256 = sha256Hex2(fs15.readFileSync(manifestPath));
|
|
9379
10490
|
}
|
|
9380
10491
|
return marker2;
|
|
9381
10492
|
}
|
|
9382
10493
|
function writeOwnershipMarker(dir, marker2) {
|
|
9383
|
-
|
|
10494
|
+
fs15.writeFileSync(
|
|
9384
10495
|
path16.join(dir, OWNERSHIP_MARKER),
|
|
9385
10496
|
`${JSON.stringify(marker2, null, 2)}
|
|
9386
10497
|
`,
|
|
@@ -9394,12 +10505,12 @@ function markerBelongsTo(dir, id) {
|
|
|
9394
10505
|
}
|
|
9395
10506
|
function readOwnershipMarker(dir) {
|
|
9396
10507
|
const markerPath = path16.join(dir, OWNERSHIP_MARKER);
|
|
9397
|
-
if (!
|
|
10508
|
+
if (!fs15.existsSync(markerPath)) {
|
|
9398
10509
|
return { marker: null, problem: "it holds no .codebase-snapshot marker" };
|
|
9399
10510
|
}
|
|
9400
10511
|
let raw;
|
|
9401
10512
|
try {
|
|
9402
|
-
raw =
|
|
10513
|
+
raw = fs15.readFileSync(markerPath, "utf8");
|
|
9403
10514
|
} catch {
|
|
9404
10515
|
return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
|
|
9405
10516
|
}
|
|
@@ -9502,7 +10613,7 @@ function verifyMarkerInventory(dir, entries, files) {
|
|
|
9502
10613
|
const full = path16.join(dir, ...entry.split("/"));
|
|
9503
10614
|
let stats;
|
|
9504
10615
|
try {
|
|
9505
|
-
stats =
|
|
10616
|
+
stats = fs15.lstatSync(full);
|
|
9506
10617
|
} catch {
|
|
9507
10618
|
return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
|
|
9508
10619
|
}
|
|
@@ -9527,7 +10638,7 @@ function verifyMarkerInventory(dir, entries, files) {
|
|
|
9527
10638
|
}
|
|
9528
10639
|
let digest;
|
|
9529
10640
|
try {
|
|
9530
|
-
digest = sha256Hex2(
|
|
10641
|
+
digest = sha256Hex2(fs15.readFileSync(full));
|
|
9531
10642
|
} catch {
|
|
9532
10643
|
return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
|
|
9533
10644
|
}
|
|
@@ -9549,11 +10660,11 @@ function assessSnapshotDirectory(dir) {
|
|
|
9549
10660
|
};
|
|
9550
10661
|
}
|
|
9551
10662
|
const manifestPath = path16.join(dir, "manifest.json");
|
|
9552
|
-
const hasManifest =
|
|
10663
|
+
const hasManifest = fs15.existsSync(manifestPath);
|
|
9553
10664
|
if (hasManifest) {
|
|
9554
10665
|
let raw;
|
|
9555
10666
|
try {
|
|
9556
|
-
raw =
|
|
10667
|
+
raw = fs15.readFileSync(manifestPath, "utf8");
|
|
9557
10668
|
} catch {
|
|
9558
10669
|
return {
|
|
9559
10670
|
owned: false,
|
|
@@ -9648,7 +10759,7 @@ function containsNoFiles(dir) {
|
|
|
9648
10759
|
const current = pending.pop();
|
|
9649
10760
|
let entries;
|
|
9650
10761
|
try {
|
|
9651
|
-
entries =
|
|
10762
|
+
entries = fs15.readdirSync(current, { withFileTypes: true });
|
|
9652
10763
|
} catch {
|
|
9653
10764
|
return false;
|
|
9654
10765
|
}
|
|
@@ -9663,13 +10774,13 @@ function containsNoFiles(dir) {
|
|
|
9663
10774
|
return true;
|
|
9664
10775
|
}
|
|
9665
10776
|
function assertReplaceable(target, label, secretRules) {
|
|
9666
|
-
if (!
|
|
9667
|
-
if (!
|
|
10777
|
+
if (!fs15.existsSync(target)) return;
|
|
10778
|
+
if (!fs15.statSync(target).isDirectory()) {
|
|
9668
10779
|
throw new Error(
|
|
9669
10780
|
`Refusing to write into ${label} ${target}: it exists but is not a directory.`
|
|
9670
10781
|
);
|
|
9671
10782
|
}
|
|
9672
|
-
const entries =
|
|
10783
|
+
const entries = fs15.readdirSync(target);
|
|
9673
10784
|
if (entries.length === 0) return;
|
|
9674
10785
|
if (entries.every((name) => IGNORABLE_ENTRIES.has(name))) return;
|
|
9675
10786
|
if (containsNoFiles(target)) return;
|
|
@@ -9689,18 +10800,18 @@ function assertReplaceable(target, label, secretRules) {
|
|
|
9689
10800
|
);
|
|
9690
10801
|
}
|
|
9691
10802
|
function assertStagingRootUsable(tmpDir, secretRules) {
|
|
9692
|
-
if (!
|
|
9693
|
-
if (!
|
|
10803
|
+
if (!fs15.existsSync(tmpDir)) return;
|
|
10804
|
+
if (!fs15.statSync(tmpDir).isDirectory()) {
|
|
9694
10805
|
throw new Error(`Refusing to write into tmpDir ${tmpDir}: it exists but is not a directory.`);
|
|
9695
10806
|
}
|
|
9696
|
-
const entries =
|
|
10807
|
+
const entries = fs15.readdirSync(tmpDir);
|
|
9697
10808
|
if (entries.length === 0) return;
|
|
9698
10809
|
const foreign = entries.filter((name) => {
|
|
9699
10810
|
const full = path16.join(tmpDir, name);
|
|
9700
10811
|
if (!name.startsWith(RUN_DIR_PREFIX)) return true;
|
|
9701
10812
|
let stats;
|
|
9702
10813
|
try {
|
|
9703
|
-
stats =
|
|
10814
|
+
stats = fs15.statSync(full);
|
|
9704
10815
|
} catch {
|
|
9705
10816
|
return true;
|
|
9706
10817
|
}
|
|
@@ -9708,7 +10819,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
|
|
|
9708
10819
|
const { marker: marker2 } = readOwnershipMarker(full);
|
|
9709
10820
|
if (marker2) return false;
|
|
9710
10821
|
try {
|
|
9711
|
-
return
|
|
10822
|
+
return fs15.readdirSync(full).length > 0;
|
|
9712
10823
|
} catch {
|
|
9713
10824
|
return true;
|
|
9714
10825
|
}
|
|
@@ -9723,7 +10834,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
|
|
|
9723
10834
|
function cleanStaleRunDirs(tmpDir) {
|
|
9724
10835
|
let entries;
|
|
9725
10836
|
try {
|
|
9726
|
-
entries =
|
|
10837
|
+
entries = fs15.readdirSync(tmpDir);
|
|
9727
10838
|
} catch {
|
|
9728
10839
|
return;
|
|
9729
10840
|
}
|
|
@@ -9737,58 +10848,101 @@ function cleanStaleRunDirs(tmpDir) {
|
|
|
9737
10848
|
const abandoned = typeof marker2.pid === "number" && !isProcessAlive(marker2.pid);
|
|
9738
10849
|
if (aged || abandoned) {
|
|
9739
10850
|
try {
|
|
9740
|
-
|
|
10851
|
+
fs15.rmSync(full, { recursive: true, force: true });
|
|
9741
10852
|
} catch {
|
|
9742
10853
|
}
|
|
9743
10854
|
}
|
|
9744
10855
|
continue;
|
|
9745
10856
|
}
|
|
9746
10857
|
try {
|
|
9747
|
-
if (
|
|
10858
|
+
if (fs15.readdirSync(full).length === 0) fs15.rmSync(full, { recursive: true, force: true });
|
|
9748
10859
|
} catch {
|
|
9749
10860
|
}
|
|
9750
10861
|
}
|
|
9751
10862
|
}
|
|
9752
10863
|
function removeIfEmpty(dir) {
|
|
9753
10864
|
try {
|
|
9754
|
-
if (
|
|
10865
|
+
if (fs15.readdirSync(dir).length === 0) fs15.rmSync(dir, { recursive: true, force: true });
|
|
9755
10866
|
} catch {
|
|
9756
10867
|
}
|
|
9757
10868
|
}
|
|
9758
10869
|
function ensureParentDirectory(target, label) {
|
|
9759
10870
|
const parent = path16.dirname(target);
|
|
9760
|
-
if (
|
|
10871
|
+
if (fs15.existsSync(parent) && !fs15.statSync(parent).isDirectory()) {
|
|
9761
10872
|
throw new Error(
|
|
9762
10873
|
`Refusing to create ${label} ${target}: ${parent} exists but is not a directory.`
|
|
9763
10874
|
);
|
|
9764
10875
|
}
|
|
9765
10876
|
try {
|
|
9766
|
-
|
|
10877
|
+
fs15.mkdirSync(parent, { recursive: true });
|
|
9767
10878
|
} catch (err) {
|
|
9768
10879
|
throw new Error(
|
|
9769
10880
|
`Refusing to create ${label} ${target}: its parent ${parent} could not be created (${err.message}).`
|
|
9770
10881
|
);
|
|
9771
10882
|
}
|
|
9772
10883
|
}
|
|
10884
|
+
var LOCK_HEARTBEAT_MS = 5e3;
|
|
10885
|
+
var LOCK_STALE_HEARTBEAT_MS = 12e4;
|
|
10886
|
+
var LOCK_HEARTBEAT_SOURCE = `
|
|
10887
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
10888
|
+
const fs = require("node:fs");
|
|
10889
|
+
const { lockPath, intervalMs } = workerData;
|
|
10890
|
+
const timer = setInterval(() => {
|
|
10891
|
+
try {
|
|
10892
|
+
const now = new Date();
|
|
10893
|
+
fs.utimesSync(lockPath, now, now);
|
|
10894
|
+
} catch (err) {
|
|
10895
|
+
// The lock was reclaimed or removed; nothing left to keep alive.
|
|
10896
|
+
}
|
|
10897
|
+
}, intervalMs);
|
|
10898
|
+
timer.unref();
|
|
10899
|
+
if (parentPort) {
|
|
10900
|
+
parentPort.on("message", (message) => {
|
|
10901
|
+
if (message === "stop") {
|
|
10902
|
+
clearInterval(timer);
|
|
10903
|
+
process.exit(0);
|
|
10904
|
+
}
|
|
10905
|
+
});
|
|
10906
|
+
}
|
|
10907
|
+
`;
|
|
10908
|
+
function startLockHeartbeat(lockPath) {
|
|
10909
|
+
try {
|
|
10910
|
+
const worker = new Worker(LOCK_HEARTBEAT_SOURCE, {
|
|
10911
|
+
eval: true,
|
|
10912
|
+
workerData: { lockPath, intervalMs: LOCK_HEARTBEAT_MS }
|
|
10913
|
+
});
|
|
10914
|
+
worker.unref();
|
|
10915
|
+
return () => {
|
|
10916
|
+
void worker.terminate().catch(() => void 0);
|
|
10917
|
+
};
|
|
10918
|
+
} catch {
|
|
10919
|
+
return () => void 0;
|
|
10920
|
+
}
|
|
10921
|
+
}
|
|
9773
10922
|
function acquireRunLock(stagingRoot) {
|
|
9774
10923
|
const lockPath = lockPathFor(stagingRoot);
|
|
9775
10924
|
const payload = `${JSON.stringify({
|
|
9776
10925
|
pid: process.pid,
|
|
9777
10926
|
stagingRoot,
|
|
10927
|
+
host: os.hostname(),
|
|
10928
|
+
runId: crypto2.randomUUID(),
|
|
10929
|
+
heartbeatMs: LOCK_HEARTBEAT_MS,
|
|
9778
10930
|
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
9779
10931
|
})}
|
|
9780
10932
|
`;
|
|
9781
10933
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
9782
10934
|
try {
|
|
9783
|
-
const handle =
|
|
10935
|
+
const handle = fs15.openSync(lockPath, "wx");
|
|
9784
10936
|
try {
|
|
9785
|
-
|
|
10937
|
+
fs15.writeSync(handle, payload);
|
|
9786
10938
|
} finally {
|
|
9787
|
-
|
|
10939
|
+
fs15.closeSync(handle);
|
|
9788
10940
|
}
|
|
10941
|
+
const stopHeartbeat = startLockHeartbeat(lockPath);
|
|
9789
10942
|
return () => {
|
|
10943
|
+
stopHeartbeat();
|
|
9790
10944
|
try {
|
|
9791
|
-
|
|
10945
|
+
fs15.rmSync(lockPath, { force: true });
|
|
9792
10946
|
} catch {
|
|
9793
10947
|
}
|
|
9794
10948
|
};
|
|
@@ -9796,7 +10950,7 @@ function acquireRunLock(stagingRoot) {
|
|
|
9796
10950
|
if (err.code !== "EEXIST") throw err;
|
|
9797
10951
|
if (attempt === 0 && reclaimStaleLock(lockPath)) continue;
|
|
9798
10952
|
throw new Error(
|
|
9799
|
-
`Another generate run is already using the staging directory ${stagingRoot}. Wait for it to finish, or delete
|
|
10953
|
+
`Another generate run is already using the staging directory ${stagingRoot} (lock ${lockPath}, heartbeat ${Math.round(lockHeartbeatAgeMs(lockPath) / 1e3)}s old). Wait for it to finish, or delete the lock if no other run is active.`
|
|
9800
10954
|
);
|
|
9801
10955
|
}
|
|
9802
10956
|
}
|
|
@@ -9813,7 +10967,7 @@ function canonicalLockTarget(targetPath) {
|
|
|
9813
10967
|
const tail = [];
|
|
9814
10968
|
for (; ; ) {
|
|
9815
10969
|
try {
|
|
9816
|
-
return path16.join(
|
|
10970
|
+
return path16.join(fs15.realpathSync(existing), ...tail);
|
|
9817
10971
|
} catch {
|
|
9818
10972
|
const parent = path16.dirname(existing);
|
|
9819
10973
|
if (parent === existing) return resolved;
|
|
@@ -9825,10 +10979,17 @@ function canonicalLockTarget(targetPath) {
|
|
|
9825
10979
|
function lockPathFor(stagingRoot) {
|
|
9826
10980
|
return path16.join(os.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
|
|
9827
10981
|
}
|
|
10982
|
+
function lockHeartbeatAgeMs(lockPath) {
|
|
10983
|
+
try {
|
|
10984
|
+
return Date.now() - fs15.statSync(lockPath).mtimeMs;
|
|
10985
|
+
} catch {
|
|
10986
|
+
return Number.POSITIVE_INFINITY;
|
|
10987
|
+
}
|
|
10988
|
+
}
|
|
9828
10989
|
function lockOwnerIsGone(lockPath) {
|
|
9829
10990
|
let raw;
|
|
9830
10991
|
try {
|
|
9831
|
-
raw =
|
|
10992
|
+
raw = fs15.readFileSync(lockPath, "utf8");
|
|
9832
10993
|
} catch {
|
|
9833
10994
|
return false;
|
|
9834
10995
|
}
|
|
@@ -9841,96 +11002,120 @@ function lockOwnerIsGone(lockPath) {
|
|
|
9841
11002
|
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
|
|
9842
11003
|
try {
|
|
9843
11004
|
process.kill(pid, 0);
|
|
9844
|
-
return
|
|
11005
|
+
return lockFileIsAncient(lockPath);
|
|
9845
11006
|
} catch (err) {
|
|
9846
|
-
|
|
11007
|
+
if (err.code !== "ESRCH") return lockFileIsAncient(lockPath);
|
|
11008
|
+
return true;
|
|
9847
11009
|
}
|
|
9848
11010
|
}
|
|
9849
11011
|
function reclaimStaleLock(lockPath) {
|
|
9850
11012
|
let before;
|
|
9851
11013
|
try {
|
|
9852
|
-
before =
|
|
11014
|
+
before = fs15.statSync(lockPath);
|
|
9853
11015
|
} catch {
|
|
9854
11016
|
return true;
|
|
9855
11017
|
}
|
|
9856
11018
|
if (!lockOwnerIsGone(lockPath)) return false;
|
|
9857
11019
|
try {
|
|
9858
|
-
const current =
|
|
11020
|
+
const current = fs15.statSync(lockPath);
|
|
9859
11021
|
const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
|
|
9860
11022
|
if (!sameFile) return false;
|
|
9861
|
-
|
|
11023
|
+
fs15.rmSync(lockPath, { force: true });
|
|
9862
11024
|
return true;
|
|
9863
11025
|
} catch {
|
|
9864
11026
|
return false;
|
|
9865
11027
|
}
|
|
9866
11028
|
}
|
|
9867
11029
|
function lockFileIsAncient(lockPath) {
|
|
9868
|
-
|
|
9869
|
-
return Date.now() - fs14.statSync(lockPath).mtimeMs > STALE_RUN_MS;
|
|
9870
|
-
} catch {
|
|
9871
|
-
return false;
|
|
9872
|
-
}
|
|
11030
|
+
return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
|
|
9873
11031
|
}
|
|
9874
11032
|
function writeManifestAtomically(manifestPath, manifest) {
|
|
9875
11033
|
const tempPath = `${manifestPath}.${process.pid}.tmp`;
|
|
9876
|
-
|
|
11034
|
+
fs15.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
|
|
9877
11035
|
try {
|
|
9878
|
-
|
|
11036
|
+
fs15.renameSync(tempPath, manifestPath);
|
|
9879
11037
|
} catch (err) {
|
|
9880
11038
|
try {
|
|
9881
|
-
|
|
11039
|
+
fs15.rmSync(tempPath, { force: true });
|
|
9882
11040
|
} catch {
|
|
9883
11041
|
}
|
|
9884
11042
|
throw err;
|
|
9885
11043
|
}
|
|
9886
11044
|
}
|
|
9887
|
-
function swapIntoPlace(stagingDir, outDir) {
|
|
11045
|
+
function swapIntoPlace(stagingDir, outDir, beforeSwap) {
|
|
9888
11046
|
ensureParentDirectory(outDir, "outDir");
|
|
9889
11047
|
const deadline = Date.now() + 3e3;
|
|
9890
|
-
|
|
11048
|
+
let delay = 25;
|
|
11049
|
+
for (; ; ) {
|
|
9891
11050
|
try {
|
|
9892
|
-
swapOnce(stagingDir, outDir);
|
|
11051
|
+
swapOnce(stagingDir, outDir, beforeSwap);
|
|
9893
11052
|
return;
|
|
9894
11053
|
} catch (err) {
|
|
9895
11054
|
const code = err.code;
|
|
9896
|
-
const
|
|
9897
|
-
|
|
9898
|
-
|
|
11055
|
+
const retryable = code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM";
|
|
11056
|
+
const remaining = deadline - Date.now();
|
|
11057
|
+
if (!retryable || remaining <= 0) throw err;
|
|
11058
|
+
sleepSync(Math.min(delay, remaining));
|
|
11059
|
+
delay = Math.min(delay * 2, 400);
|
|
9899
11060
|
}
|
|
9900
11061
|
}
|
|
9901
11062
|
}
|
|
9902
|
-
function
|
|
11063
|
+
function recoverInterruptedPublish(outDir) {
|
|
11064
|
+
if (fs15.existsSync(outDir)) return;
|
|
11065
|
+
const parent = path16.dirname(outDir);
|
|
11066
|
+
const base = path16.basename(outDir);
|
|
11067
|
+
let backups;
|
|
11068
|
+
try {
|
|
11069
|
+
backups = fs15.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
|
|
11070
|
+
} catch {
|
|
11071
|
+
return;
|
|
11072
|
+
}
|
|
11073
|
+
if (backups.length !== 1) return;
|
|
11074
|
+
const backupDir = path16.join(parent, backups[0]);
|
|
11075
|
+
const { marker: marker2, problem } = readOwnershipMarker(backupDir);
|
|
11076
|
+
if (problem !== null || marker2 === null || marker2.state !== "complete") return;
|
|
11077
|
+
try {
|
|
11078
|
+
fs15.renameSync(backupDir, outDir);
|
|
11079
|
+
process.stderr.write(
|
|
11080
|
+
`\u26A0 Recovered ${outDir} from ${backupDir}, left by an interrupted run. That snapshot is the one from before the interrupted run.
|
|
11081
|
+
`
|
|
11082
|
+
);
|
|
11083
|
+
} catch {
|
|
11084
|
+
}
|
|
11085
|
+
}
|
|
11086
|
+
function swapOnce(stagingDir, outDir, beforeSwap) {
|
|
9903
11087
|
const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
|
|
9904
|
-
const hadPrevious =
|
|
9905
|
-
if (hadPrevious)
|
|
11088
|
+
const hadPrevious = fs15.existsSync(outDir);
|
|
11089
|
+
if (hadPrevious) beforeSwap?.();
|
|
11090
|
+
if (hadPrevious) fs15.renameSync(outDir, backupDir);
|
|
9906
11091
|
try {
|
|
9907
11092
|
try {
|
|
9908
|
-
|
|
11093
|
+
fs15.renameSync(stagingDir, outDir);
|
|
9909
11094
|
} catch (err) {
|
|
9910
11095
|
if (err.code !== "EXDEV") throw err;
|
|
9911
11096
|
const partialDir = `${outDir}.partial-${process.pid}-${Date.now()}`;
|
|
9912
11097
|
try {
|
|
9913
|
-
|
|
9914
|
-
|
|
9915
|
-
|
|
11098
|
+
fs15.cpSync(stagingDir, partialDir, { recursive: true });
|
|
11099
|
+
fs15.renameSync(partialDir, outDir);
|
|
11100
|
+
fs15.rmSync(stagingDir, { recursive: true, force: true });
|
|
9916
11101
|
} catch (copyErr) {
|
|
9917
11102
|
try {
|
|
9918
|
-
|
|
11103
|
+
fs15.rmSync(partialDir, { recursive: true, force: true });
|
|
9919
11104
|
} catch {
|
|
9920
11105
|
}
|
|
9921
11106
|
throw copyErr;
|
|
9922
11107
|
}
|
|
9923
11108
|
}
|
|
9924
11109
|
} catch (err) {
|
|
9925
|
-
if (hadPrevious &&
|
|
9926
|
-
if (
|
|
9927
|
-
|
|
11110
|
+
if (hadPrevious && fs15.existsSync(backupDir)) {
|
|
11111
|
+
if (fs15.existsSync(outDir)) fs15.rmSync(outDir, { recursive: true, force: true });
|
|
11112
|
+
fs15.renameSync(backupDir, outDir);
|
|
9928
11113
|
}
|
|
9929
11114
|
throw err;
|
|
9930
11115
|
}
|
|
9931
11116
|
if (hadPrevious) {
|
|
9932
11117
|
try {
|
|
9933
|
-
|
|
11118
|
+
fs15.rmSync(backupDir, { recursive: true, force: true });
|
|
9934
11119
|
} catch (err) {
|
|
9935
11120
|
process.stderr.write(
|
|
9936
11121
|
`\u26A0 The previous snapshot could not be removed from ${backupDir} (${err.message}). The new snapshot is in place; delete that directory by hand when convenient.
|
|
@@ -10007,6 +11192,13 @@ function generateSnapshot(configInput, options) {
|
|
|
10007
11192
|
const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
|
|
10008
11193
|
const dryRun = options?.dryRun ?? false;
|
|
10009
11194
|
const gitInfo = getGitInfo(config.cwd, config.branch);
|
|
11195
|
+
const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
|
|
11196
|
+
...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
|
|
11197
|
+
...config.staged === true ? { staged: true } : {}
|
|
11198
|
+
}) : null;
|
|
11199
|
+
const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
|
|
11200
|
+
const stagedPaths = changedScope?.stagedPaths ?? /* @__PURE__ */ new Set();
|
|
11201
|
+
const stagedDeletedPaths = changedScope?.deletedPaths ?? /* @__PURE__ */ new Set();
|
|
10010
11202
|
const collection = collectFiles(config.cwd, {
|
|
10011
11203
|
includePatterns: config.include,
|
|
10012
11204
|
excludePatterns: [...config.excludePatterns, ...config.presetExclude],
|
|
@@ -10018,13 +11210,11 @@ function generateSnapshot(configInput, options) {
|
|
|
10018
11210
|
// output — but only at these exact paths, not at every directory that shares the name.
|
|
10019
11211
|
toolOwnedPaths: [config.outDir, config.tmpDir].map(
|
|
10020
11212
|
(directory) => path16.relative(config.cwd, path16.resolve(config.cwd, directory)).replace(/\\/g, "/")
|
|
10021
|
-
).filter((
|
|
11213
|
+
).filter((relative10) => relative10.length > 0 && !relative10.startsWith("..")),
|
|
11214
|
+
// A staged path can be absent from the working tree while its index blob exists. Discovery
|
|
11215
|
+
// lists the working tree, so those paths would never reach the scan at all.
|
|
11216
|
+
...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
|
|
10022
11217
|
});
|
|
10023
|
-
const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
|
|
10024
|
-
...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
|
|
10025
|
-
...config.staged === true ? { staged: true } : {}
|
|
10026
|
-
}) : null;
|
|
10027
|
-
const changedPaths = changedScope === null ? null : new Set(changedScope.paths);
|
|
10028
11218
|
const unchangedPaths = [];
|
|
10029
11219
|
const candidateFiles = changedPaths !== null && config.withDependents !== true ? collection.files.filter((relativePath) => {
|
|
10030
11220
|
if (changedPaths.has(relativePath)) return true;
|
|
@@ -10046,45 +11236,92 @@ function generateSnapshot(configInput, options) {
|
|
|
10046
11236
|
const oversizeSummaryPaths = [];
|
|
10047
11237
|
const previewSummaryPaths = [];
|
|
10048
11238
|
const skippedSummaryImports = /* @__PURE__ */ new Map();
|
|
10049
|
-
const layerCounts =
|
|
10050
|
-
const kindCounts =
|
|
11239
|
+
const layerCounts = /* @__PURE__ */ Object.create(null);
|
|
11240
|
+
const kindCounts = /* @__PURE__ */ Object.create(null);
|
|
10051
11241
|
let totalLines = 0;
|
|
10052
11242
|
let totalSizeBytes = 0;
|
|
10053
11243
|
let largeFileCount = 0;
|
|
10054
11244
|
for (const relativePath of candidateFiles) {
|
|
10055
11245
|
const absolutePath = path16.join(config.cwd, relativePath);
|
|
10056
|
-
|
|
10057
|
-
|
|
10058
|
-
|
|
10059
|
-
|
|
10060
|
-
|
|
10061
|
-
|
|
10062
|
-
|
|
11246
|
+
const fromIndex = stagedPaths.has(relativePath);
|
|
11247
|
+
let buffer;
|
|
11248
|
+
let sizeBytes;
|
|
11249
|
+
if (fromIndex && stagedDeletedPaths.has(relativePath)) {
|
|
11250
|
+
skipped.push({
|
|
11251
|
+
path: relativePath,
|
|
11252
|
+
reason: "deleted",
|
|
11253
|
+
detail: "staged for deletion; it is not part of the next commit"
|
|
11254
|
+
});
|
|
11255
|
+
continue;
|
|
11256
|
+
}
|
|
11257
|
+
if (fromIndex) {
|
|
11258
|
+
const staged = readStagedBlob(config.cwd, relativePath);
|
|
11259
|
+
if (staged === null) {
|
|
11260
|
+
skipped.push({
|
|
11261
|
+
path: relativePath,
|
|
11262
|
+
reason: "deleted",
|
|
11263
|
+
detail: "staged path has no blob in the index; it is not part of the next commit"
|
|
11264
|
+
});
|
|
11265
|
+
continue;
|
|
11266
|
+
}
|
|
11267
|
+
if (isBinaryExtension(absolutePath)) {
|
|
11268
|
+
skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${staged.length} B` });
|
|
11269
|
+
continue;
|
|
11270
|
+
}
|
|
11271
|
+
buffer = staged;
|
|
11272
|
+
sizeBytes = staged.length;
|
|
11273
|
+
} else {
|
|
11274
|
+
let stats;
|
|
11275
|
+
try {
|
|
11276
|
+
stats = fs15.statSync(absolutePath);
|
|
11277
|
+
if (!stats.isFile()) {
|
|
11278
|
+
const nestedRepository = stats.isDirectory() && fs15.existsSync(path16.join(absolutePath, ".git"));
|
|
11279
|
+
skipped.push(
|
|
11280
|
+
nestedRepository ? {
|
|
11281
|
+
path: relativePath,
|
|
11282
|
+
reason: "nested-repository",
|
|
11283
|
+
detail: "a directory belonging to another repository (nested checkout or submodule); its contents are not scanned"
|
|
11284
|
+
} : { path: relativePath, reason: "not-file" }
|
|
11285
|
+
);
|
|
11286
|
+
continue;
|
|
11287
|
+
}
|
|
11288
|
+
} catch (err) {
|
|
11289
|
+
const code = err.code;
|
|
11290
|
+
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
11291
|
+
skipped.push({
|
|
10063
11292
|
path: relativePath,
|
|
10064
|
-
reason: "
|
|
10065
|
-
detail: "
|
|
10066
|
-
}
|
|
10067
|
-
|
|
11293
|
+
reason: "missing",
|
|
11294
|
+
detail: "tracked but absent from disk (deleted without staging)"
|
|
11295
|
+
});
|
|
11296
|
+
} else {
|
|
11297
|
+
skipped.push({
|
|
11298
|
+
path: relativePath,
|
|
11299
|
+
reason: "read-error",
|
|
11300
|
+
detail: String(err.message).replace(/\s+/g, " ")
|
|
11301
|
+
});
|
|
11302
|
+
}
|
|
10068
11303
|
continue;
|
|
10069
11304
|
}
|
|
10070
|
-
|
|
10071
|
-
|
|
10072
|
-
|
|
10073
|
-
|
|
10074
|
-
|
|
10075
|
-
|
|
10076
|
-
|
|
10077
|
-
|
|
10078
|
-
|
|
10079
|
-
|
|
10080
|
-
|
|
10081
|
-
|
|
10082
|
-
|
|
10083
|
-
|
|
10084
|
-
|
|
10085
|
-
|
|
10086
|
-
|
|
10087
|
-
|
|
11305
|
+
if (isBinaryExtension(absolutePath)) {
|
|
11306
|
+
skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
|
|
11307
|
+
continue;
|
|
11308
|
+
}
|
|
11309
|
+
if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) {
|
|
11310
|
+
skipped.push({ path: relativePath, reason: "binary", detail: `Size: ${stats.size} B` });
|
|
11311
|
+
continue;
|
|
11312
|
+
}
|
|
11313
|
+
try {
|
|
11314
|
+
buffer = fs15.readFileSync(absolutePath);
|
|
11315
|
+
} catch (err) {
|
|
11316
|
+
const code = err.code;
|
|
11317
|
+
skipped.push({
|
|
11318
|
+
path: relativePath,
|
|
11319
|
+
reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "read-error",
|
|
11320
|
+
detail: String(err.message).replace(/\s+/g, " ")
|
|
11321
|
+
});
|
|
11322
|
+
continue;
|
|
11323
|
+
}
|
|
11324
|
+
sizeBytes = stats.size;
|
|
10088
11325
|
}
|
|
10089
11326
|
let decoded;
|
|
10090
11327
|
try {
|
|
@@ -10093,7 +11330,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10093
11330
|
skipped.push({
|
|
10094
11331
|
path: relativePath,
|
|
10095
11332
|
reason: "read-error",
|
|
10096
|
-
detail: `Size: ${
|
|
11333
|
+
detail: `Size: ${sizeBytes} B; could not be decoded: ${err.message}`.replace(
|
|
10097
11334
|
/\s+/g,
|
|
10098
11335
|
" "
|
|
10099
11336
|
)
|
|
@@ -10104,13 +11341,13 @@ function generateSnapshot(configInput, options) {
|
|
|
10104
11341
|
skipped.push({
|
|
10105
11342
|
path: relativePath,
|
|
10106
11343
|
reason: "binary",
|
|
10107
|
-
detail: `Size: ${
|
|
11344
|
+
detail: `Size: ${sizeBytes} B; ${decoded.binaryReason ?? "binary content"}`
|
|
10108
11345
|
});
|
|
10109
11346
|
continue;
|
|
10110
11347
|
}
|
|
10111
11348
|
const hashSha256 = sha256Hex2(buffer);
|
|
10112
11349
|
const rawContent = decoded.text;
|
|
10113
|
-
totalSizeBytes +=
|
|
11350
|
+
totalSizeBytes += sizeBytes;
|
|
10114
11351
|
if (decoded.encoding !== "utf-8") {
|
|
10115
11352
|
encodingNotes.push({
|
|
10116
11353
|
path: relativePath,
|
|
@@ -10124,7 +11361,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10124
11361
|
bump(layerCounts, layer2);
|
|
10125
11362
|
bump(kindCounts, kind);
|
|
10126
11363
|
const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
|
|
10127
|
-
const fresh = deriveFile(relativePath, rawContent,
|
|
11364
|
+
const fresh = deriveFile(relativePath, rawContent, sizeBytes, config);
|
|
10128
11365
|
rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
|
|
10129
11366
|
return fresh;
|
|
10130
11367
|
})();
|
|
@@ -10145,7 +11382,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10145
11382
|
}
|
|
10146
11383
|
files.push({
|
|
10147
11384
|
relativePath,
|
|
10148
|
-
sizeBytes
|
|
11385
|
+
sizeBytes,
|
|
10149
11386
|
lines: lineCount,
|
|
10150
11387
|
hashSha256,
|
|
10151
11388
|
part: "",
|
|
@@ -10166,7 +11403,10 @@ function generateSnapshot(configInput, options) {
|
|
|
10166
11403
|
}
|
|
10167
11404
|
if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
|
|
10168
11405
|
const keep = new Set(changedPaths);
|
|
10169
|
-
const resolver = buildImportResolver(files
|
|
11406
|
+
const resolver = buildImportResolver(files, {
|
|
11407
|
+
extraPaths: changedPaths,
|
|
11408
|
+
tsconfig: tsconfigPathsFor(config.cwd)
|
|
11409
|
+
});
|
|
10170
11410
|
for (const file of files) {
|
|
10171
11411
|
const fileImports = isSourceSummary(file.summary) ? file.summary.imports : skippedSummaryImports.get(file.relativePath) ?? [];
|
|
10172
11412
|
if (fileImports.length === 0) continue;
|
|
@@ -10260,7 +11500,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10260
11500
|
const fingerprint = sha256Hex2(
|
|
10261
11501
|
[
|
|
10262
11502
|
...files.map(
|
|
10263
|
-
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}
|
|
11503
|
+
(file) => `${file.relativePath}:${file.hashSha256}:${file.sizeBytes}`
|
|
10264
11504
|
),
|
|
10265
11505
|
`settings:${configDigest(config)}`
|
|
10266
11506
|
].join("\n")
|
|
@@ -10347,6 +11587,8 @@ function generateSnapshot(configInput, options) {
|
|
|
10347
11587
|
skippedFiles: skipped.length,
|
|
10348
11588
|
totalSourceBytes: totalSizeBytes,
|
|
10349
11589
|
totalContentBytes,
|
|
11590
|
+
sourceLines: totalLines,
|
|
11591
|
+
emittedLines: files.reduce((total, file) => total + file.includedLines, 0),
|
|
10350
11592
|
// The parts are what a model is handed, so the estimate is over the parts rather than
|
|
10351
11593
|
// over the sources: previews and the byte budget both shrink the number.
|
|
10352
11594
|
estimatedTokens: parts.reduce((total, part) => total + part.metadata.estimatedTokens, 0),
|
|
@@ -10365,7 +11607,7 @@ function generateSnapshot(configInput, options) {
|
|
|
10365
11607
|
},
|
|
10366
11608
|
layers: layerCounts,
|
|
10367
11609
|
kinds: kindCounts,
|
|
10368
|
-
indexes: buildIndexes(files),
|
|
11610
|
+
indexes: buildIndexes(files, tsconfigPathsFor(config.cwd)),
|
|
10369
11611
|
parts: parts.map((part) => part.metadata),
|
|
10370
11612
|
files: files.map((file) => {
|
|
10371
11613
|
const { content: _content, ...rest } = file;
|
|
@@ -10382,6 +11624,23 @@ function generateSnapshot(configInput, options) {
|
|
|
10382
11624
|
);
|
|
10383
11625
|
manifest.totals.warningCount = manifest.warnings.length;
|
|
10384
11626
|
}
|
|
11627
|
+
if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes <= config.maxPartBytes) {
|
|
11628
|
+
manifest.warnings.push(
|
|
11629
|
+
`${files.filter((file) => file.isPreviewTruncated).length} file(s) were previewed because largeFileBytes (${config.largeFileBytes} B) is not above maxPartBytes (${config.maxPartBytes} B). Raise largeFileBytes if a whole file is wanted.`
|
|
11630
|
+
);
|
|
11631
|
+
manifest.totals.warningCount = manifest.warnings.length;
|
|
11632
|
+
}
|
|
11633
|
+
if (config.maxPartTokens !== void 0) {
|
|
11634
|
+
const overTokenBudget = parts.filter(
|
|
11635
|
+
(part) => part.metadata.estimatedTokens > (config.maxPartTokens ?? 0)
|
|
11636
|
+
);
|
|
11637
|
+
if (overTokenBudget.length > 0) {
|
|
11638
|
+
manifest.warnings.push(
|
|
11639
|
+
`${overTokenBudget.length} part(s) exceed the estimated token ceiling of ${config.maxPartTokens}: the partitioner enforces the equivalent byte budget (tokens \xD7 4), and estimatedTokens is an estimate, not a hard bound.`
|
|
11640
|
+
);
|
|
11641
|
+
manifest.totals.warningCount = manifest.warnings.length;
|
|
11642
|
+
}
|
|
11643
|
+
}
|
|
10385
11644
|
if (secretFindings.length > 0 && !config.artifacts.audit) {
|
|
10386
11645
|
manifest.warnings.push(
|
|
10387
11646
|
`${secretFindings.length} line(s) contain redacted values; reports/audit.md is disabled, so the per-line detail was not written.`
|
|
@@ -10410,6 +11669,18 @@ function generateSnapshot(configInput, options) {
|
|
|
10410
11669
|
sha256: sha256Hex2(sarifText)
|
|
10411
11670
|
};
|
|
10412
11671
|
}
|
|
11672
|
+
const artifacts = config.artifacts;
|
|
11673
|
+
const artifactRecord = (text2) => ({
|
|
11674
|
+
byteSize: Buffer.byteLength(text2, "utf8"),
|
|
11675
|
+
sha256: sha256Hex2(text2)
|
|
11676
|
+
});
|
|
11677
|
+
const navigationText = artifacts.navigation ? generateNavigation(manifest) : null;
|
|
11678
|
+
if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
|
|
11679
|
+
const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
|
|
11680
|
+
if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
|
|
11681
|
+
const readmeText = artifacts.readme ? generateReadme(manifest, artifacts) : null;
|
|
11682
|
+
if (readmeText !== null) manifest.artifacts.readme = artifactRecord(readmeText);
|
|
11683
|
+
if (projectTree !== null) manifest.artifacts.projectTree = artifactRecord(projectTree);
|
|
10413
11684
|
let monolithJson = null;
|
|
10414
11685
|
let monolithMarkdown = null;
|
|
10415
11686
|
if (config.includeMonolith) {
|
|
@@ -10424,26 +11695,33 @@ function generateSnapshot(configInput, options) {
|
|
|
10424
11695
|
includedLines: countLines(content)
|
|
10425
11696
|
};
|
|
10426
11697
|
});
|
|
10427
|
-
const
|
|
10428
|
-
const
|
|
10429
|
-
if (
|
|
11698
|
+
const bodyBytes = fullFiles.reduce((total, file) => total + file.includedBytes, 0);
|
|
11699
|
+
const definitelyTooLarge = config.maxMonolithBytes !== null && bodyBytes > config.maxMonolithBytes;
|
|
11700
|
+
if (definitelyTooLarge) {
|
|
11701
|
+
const reason = `their bodies total ${bodyBytes} B, which already exceeds maxMonolithBytes ${config.maxMonolithBytes ?? 0} B`;
|
|
11702
|
+
manifest.warnings.push(`full-codebase.md skipped: ${reason}`);
|
|
11703
|
+
manifest.warnings.push(`full-codebase.json skipped: ${reason}`);
|
|
11704
|
+
}
|
|
11705
|
+
const markdown = definitelyTooLarge ? null : generateMonolithMarkdown(manifest, fullFiles);
|
|
11706
|
+
const markdownBytes = markdown === null ? 0 : Buffer.byteLength(markdown, "utf8");
|
|
11707
|
+
if (markdown !== null && (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes)) {
|
|
10430
11708
|
monolithMarkdown = markdown;
|
|
10431
11709
|
manifest.artifacts.fullMarkdown = {
|
|
10432
11710
|
byteSize: markdownBytes,
|
|
10433
11711
|
sha256: sha256Hex2(markdown)
|
|
10434
11712
|
};
|
|
10435
|
-
} else {
|
|
11713
|
+
} else if (!definitelyTooLarge) {
|
|
10436
11714
|
manifest.warnings.push(
|
|
10437
11715
|
`full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
|
|
10438
11716
|
);
|
|
10439
11717
|
}
|
|
10440
11718
|
manifest.totals.warningCount = manifest.warnings.length;
|
|
10441
|
-
const json = generateMonolithJson(manifest, fullFiles);
|
|
10442
|
-
const jsonBytes = Buffer.byteLength(json, "utf8");
|
|
10443
|
-
if (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes) {
|
|
11719
|
+
const json = definitelyTooLarge ? null : generateMonolithJson(manifest, fullFiles);
|
|
11720
|
+
const jsonBytes = json === null ? 0 : Buffer.byteLength(json, "utf8");
|
|
11721
|
+
if (json !== null && (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes)) {
|
|
10444
11722
|
monolithJson = json;
|
|
10445
11723
|
manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
|
|
10446
|
-
} else {
|
|
11724
|
+
} else if (!definitelyTooLarge) {
|
|
10447
11725
|
manifest.warnings.push(
|
|
10448
11726
|
`full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
|
|
10449
11727
|
);
|
|
@@ -10451,7 +11729,6 @@ function generateSnapshot(configInput, options) {
|
|
|
10451
11729
|
manifest.totals.warningCount = manifest.warnings.length;
|
|
10452
11730
|
}
|
|
10453
11731
|
const { outDir, tmpDir } = resolveSafeOutputDirs(config);
|
|
10454
|
-
const { artifacts } = config;
|
|
10455
11732
|
assertReplaceable(outDir, "outDir", config.secretRules);
|
|
10456
11733
|
assertStagingRootUsable(tmpDir, config.secretRules);
|
|
10457
11734
|
if (dryRun) {
|
|
@@ -10468,15 +11745,18 @@ function generateSnapshot(configInput, options) {
|
|
|
10468
11745
|
const releaseLock = () => {
|
|
10469
11746
|
for (const release of [...releases].reverse()) release();
|
|
10470
11747
|
};
|
|
11748
|
+
recoverInterruptedPublish(outDir);
|
|
11749
|
+
assertReplaceable(outDir, "outDir", config.secretRules);
|
|
10471
11750
|
let stagingDir = null;
|
|
11751
|
+
let releaseDeferred = false;
|
|
10472
11752
|
try {
|
|
10473
11753
|
ensureParentDirectory(outDir, "outDir");
|
|
10474
|
-
|
|
11754
|
+
fs15.mkdirSync(tmpDir, { recursive: true });
|
|
10475
11755
|
cleanStaleRunDirs(tmpDir);
|
|
10476
11756
|
const snapshotId = crypto2.randomUUID();
|
|
10477
11757
|
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
10478
11758
|
stagingDir = path16.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
|
|
10479
|
-
|
|
11759
|
+
fs15.mkdirSync(stagingDir);
|
|
10480
11760
|
writeOwnershipMarker(stagingDir, {
|
|
10481
11761
|
generator: GENERATOR_NAME,
|
|
10482
11762
|
version: GENERATOR_VERSION,
|
|
@@ -10488,45 +11768,66 @@ function generateSnapshot(configInput, options) {
|
|
|
10488
11768
|
});
|
|
10489
11769
|
const partsDir = path16.join(stagingDir, "parts");
|
|
10490
11770
|
const reportsDir = path16.join(stagingDir, "reports");
|
|
10491
|
-
if (artifacts.parts)
|
|
11771
|
+
if (artifacts.parts) fs15.mkdirSync(partsDir, { recursive: true });
|
|
10492
11772
|
if (artifacts.navigation || artifacts.projectTree || artifacts.audit || config.sarif === true) {
|
|
10493
|
-
|
|
10494
|
-
}
|
|
11773
|
+
fs15.mkdirSync(reportsDir, { recursive: true });
|
|
11774
|
+
}
|
|
11775
|
+
const writtenArtifacts = /* @__PURE__ */ new Map();
|
|
11776
|
+
const writeArtifact = (targetDir, relativeEntry, data) => {
|
|
11777
|
+
const full = path16.join(targetDir, ...relativeEntry.split("/"));
|
|
11778
|
+
fs15.writeFileSync(full, data, "utf8");
|
|
11779
|
+
const stats = fs15.statSync(full);
|
|
11780
|
+
writtenArtifacts.set(relativeEntry, {
|
|
11781
|
+
digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
|
|
11782
|
+
mtimeMs: stats.mtimeMs
|
|
11783
|
+
});
|
|
11784
|
+
};
|
|
11785
|
+
const recordArtifact = (targetDir, relativeEntry) => {
|
|
11786
|
+
const full = path16.join(targetDir, ...relativeEntry.split("/"));
|
|
11787
|
+
const stats = fs15.statSync(full);
|
|
11788
|
+
writtenArtifacts.set(relativeEntry, {
|
|
11789
|
+
digest: {
|
|
11790
|
+
path: relativeEntry,
|
|
11791
|
+
bytes: stats.size,
|
|
11792
|
+
sha256: sha256Hex2(fs15.readFileSync(full))
|
|
11793
|
+
},
|
|
11794
|
+
mtimeMs: stats.mtimeMs
|
|
11795
|
+
});
|
|
11796
|
+
};
|
|
10495
11797
|
if (artifacts.parts) {
|
|
10496
11798
|
for (const part of parts) {
|
|
10497
|
-
|
|
11799
|
+
writeArtifact(partsDir, part.filename, part.markdown);
|
|
10498
11800
|
}
|
|
10499
11801
|
}
|
|
10500
11802
|
if (projectTree !== null) {
|
|
10501
|
-
|
|
11803
|
+
writeArtifact(reportsDir, "project-tree.md", projectTree);
|
|
10502
11804
|
}
|
|
10503
|
-
if (
|
|
10504
|
-
|
|
11805
|
+
if (navigationText !== null) {
|
|
11806
|
+
writeArtifact(reportsDir, "navigation.md", navigationText);
|
|
10505
11807
|
}
|
|
10506
|
-
if (
|
|
10507
|
-
|
|
10508
|
-
path16.join(reportsDir, "audit.md"),
|
|
10509
|
-
generateAuditReport(manifest, secretFindings, config.secretRules),
|
|
10510
|
-
"utf8"
|
|
10511
|
-
);
|
|
11808
|
+
if (auditText !== null) {
|
|
11809
|
+
writeArtifact(reportsDir, "audit.md", auditText);
|
|
10512
11810
|
}
|
|
10513
11811
|
if (sarifText !== null) {
|
|
10514
|
-
|
|
11812
|
+
writeArtifact(reportsDir, "audit.sarif", sarifText);
|
|
10515
11813
|
}
|
|
10516
|
-
if (
|
|
10517
|
-
|
|
11814
|
+
if (readmeText !== null) {
|
|
11815
|
+
writeArtifact(stagingDir, "README.md", readmeText);
|
|
10518
11816
|
}
|
|
10519
11817
|
if (artifacts.manifest) {
|
|
10520
|
-
|
|
11818
|
+
writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
|
|
10521
11819
|
}
|
|
10522
11820
|
if (monolithJson !== null) {
|
|
10523
|
-
|
|
11821
|
+
writeArtifact(stagingDir, "full-codebase.json", monolithJson);
|
|
10524
11822
|
}
|
|
10525
11823
|
if (monolithMarkdown !== null) {
|
|
10526
|
-
|
|
11824
|
+
writeArtifact(stagingDir, "full-codebase.md", monolithMarkdown);
|
|
10527
11825
|
}
|
|
10528
|
-
writeOwnershipMarker(
|
|
10529
|
-
|
|
11826
|
+
writeOwnershipMarker(
|
|
11827
|
+
stagingDir,
|
|
11828
|
+
markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
|
|
11829
|
+
);
|
|
11830
|
+
swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
|
|
10530
11831
|
stagingDir = null;
|
|
10531
11832
|
const warningsBeforeHook = manifest.warnings.length;
|
|
10532
11833
|
const pendingHook = runAfterGenerate(config, manifest);
|
|
@@ -10534,8 +11835,12 @@ function generateSnapshot(configInput, options) {
|
|
|
10534
11835
|
if (!markerBelongsTo(outDir, snapshotId)) return;
|
|
10535
11836
|
if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
|
|
10536
11837
|
writeManifestAtomically(path16.join(outDir, "manifest.json"), manifest);
|
|
11838
|
+
recordArtifact(outDir, "manifest.json");
|
|
10537
11839
|
}
|
|
10538
|
-
writeOwnershipMarker(
|
|
11840
|
+
writeOwnershipMarker(
|
|
11841
|
+
outDir,
|
|
11842
|
+
markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
|
|
11843
|
+
);
|
|
10539
11844
|
};
|
|
10540
11845
|
if (config.hooks.afterGenerate) shipHookState();
|
|
10541
11846
|
if (pendingHook) {
|
|
@@ -10562,19 +11867,26 @@ function generateSnapshot(configInput, options) {
|
|
|
10562
11867
|
if (pendingHooks.get(outDir) === tracked) pendingHooks.delete(outDir);
|
|
10563
11868
|
});
|
|
10564
11869
|
pendingHooks.set(outDir, tracked);
|
|
11870
|
+
releaseDeferred = true;
|
|
11871
|
+
void tracked.finally(() => {
|
|
11872
|
+
removeIfEmpty(tmpDir);
|
|
11873
|
+
releaseLock();
|
|
11874
|
+
});
|
|
10565
11875
|
}
|
|
10566
11876
|
return manifest;
|
|
10567
11877
|
} catch (err) {
|
|
10568
11878
|
if (stagingDir !== null) {
|
|
10569
11879
|
try {
|
|
10570
|
-
|
|
11880
|
+
fs15.rmSync(stagingDir, { recursive: true, force: true });
|
|
10571
11881
|
} catch {
|
|
10572
11882
|
}
|
|
10573
11883
|
}
|
|
10574
11884
|
throw err;
|
|
10575
11885
|
} finally {
|
|
10576
|
-
|
|
10577
|
-
|
|
11886
|
+
if (!releaseDeferred) {
|
|
11887
|
+
removeIfEmpty(tmpDir);
|
|
11888
|
+
releaseLock();
|
|
11889
|
+
}
|
|
10578
11890
|
}
|
|
10579
11891
|
}
|
|
10580
11892
|
var pendingHooks = /* @__PURE__ */ new Map();
|
|
@@ -10590,4 +11902,4 @@ async function generateSnapshotAsync(configInput, options) {
|
|
|
10590
11902
|
return manifest;
|
|
10591
11903
|
}
|
|
10592
11904
|
|
|
10593
|
-
export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, anchorForPath, appendGitignoreEntries, assertReplaceable, assertUsableConfigInput, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, collectFiles, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, decodeText, defaultIO, defineConfig, describeManifestShapeProblem, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, escapeControls, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findConfigFile, findSecretInPath, firstRunMessage, formatNumber, formatTokens, formatUpdateNotice, generateInWorker, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isDiscoveryMode, isEffectivelyEmpty, isInteractive, isNewer, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, partitionFiles, planFirstRun, profileForPath, renderConfig, renderDiffText, renderExplainText, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, runWithStdoutCapture, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, truncatePreview, truncateToBytes, unknownPresetMessage, updateCommand, validateSnapshot, workerEntry, wrapLines };
|
|
11905
|
+
export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, anchorForPath, appendGitignoreEntries, assertReplaceable, assertUsableConfigInput, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, collectFiles, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, decodeText, defaultIO, defineConfig, describeManifestShapeProblem, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, escapeControls, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findConfigFile, findSecretInPath, firstRunMessage, formatNumber, formatTokens, formatUpdateNotice, generateInWorker, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isDiscoveryMode, isEffectivelyEmpty, isInteractive, isNewer, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, partitionFiles, planFirstRun, profileForPath, renderConfig, renderDiffText, renderExplainText, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, runWithStdoutCapture, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, truncatePreview, truncateToBytes, tsconfigPathsFor, unknownPresetMessage, updateCommand, validateSnapshot, workerEntry, wrapLines };
|