Skip to content

Commit bcbfb35

Browse files
committed
refactor(src): split oversized modules
1 parent b2179de commit bcbfb35

675 files changed

Lines changed: 91482 additions & 73459 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,8 @@
119119
"protocol:gen": "tsx scripts/protocol-gen.ts",
120120
"protocol:gen:swift": "tsx scripts/protocol-gen-swift.ts",
121121
"protocol:check": "pnpm protocol:gen && pnpm protocol:gen:swift && git diff --exit-code -- dist/protocol.schema.json apps/macos/Sources/ClawdbotProtocol/GatewayModels.swift",
122-
"canvas:a2ui:bundle": "bash scripts/bundle-a2ui.sh"
122+
"canvas:a2ui:bundle": "bash scripts/bundle-a2ui.sh",
123+
"check:loc": "tsx scripts/check-ts-max-loc.ts --max 500"
123124
},
124125
"keywords": [],
125126
"author": "",

‎scripts/check-ts-max-loc.ts‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { existsSync } from "node:fs";
2+
import { readFile } from "node:fs/promises";
3+
import { execFileSync } from "node:child_process";
4+
5+
type ParsedArgs = {
6+
maxLines: number;
7+
};
8+
9+
function parseArgs(argv: string[]): ParsedArgs {
10+
let maxLines = 500;
11+
12+
for (let index = 0; index < argv.length; index++) {
13+
const arg = argv[index];
14+
if (arg === "--max") {
15+
const next = argv[index + 1];
16+
if (!next || Number.isNaN(Number(next))) throw new Error("Missing/invalid --max value");
17+
maxLines = Number(next);
18+
index++;
19+
continue;
20+
}
21+
}
22+
23+
return { maxLines };
24+
}
25+
26+
function gitLsFilesAll(): string[] {
27+
// Include untracked files too so local refactors don’t “pass” by accident.
28+
const stdout = execFileSync("git", ["ls-files", "--cached", "--others", "--exclude-standard"], {
29+
encoding: "utf8",
30+
});
31+
return stdout
32+
.split("\n")
33+
.map((line) => line.trim())
34+
.filter(Boolean);
35+
}
36+
37+
async function countLines(filePath: string): Promise<number> {
38+
const content = await readFile(filePath, "utf8");
39+
// Count physical lines. Keeps the rule simple + predictable.
40+
return content.split("\n").length;
41+
}
42+
43+
async function main() {
44+
// Makes `... | head` safe.
45+
process.stdout.on("error", (error: NodeJS.ErrnoException) => {
46+
if (error.code === "EPIPE") process.exit(0);
47+
throw error;
48+
});
49+
50+
const { maxLines } = parseArgs(process.argv.slice(2));
51+
const files = gitLsFilesAll()
52+
.filter((filePath) => existsSync(filePath))
53+
.filter((filePath) => filePath.endsWith(".ts") || filePath.endsWith(".tsx"));
54+
55+
const results = await Promise.all(
56+
files.map(async (filePath) => ({ filePath, lines: await countLines(filePath) })),
57+
);
58+
59+
const offenders = results
60+
.filter((result) => result.lines > maxLines)
61+
.sort((a, b) => b.lines - a.lines);
62+
63+
if (!offenders.length) return;
64+
65+
// Minimal, grep-friendly output.
66+
for (const offender of offenders) {
67+
// eslint-disable-next-line no-console
68+
console.log(`${offender.lines}\t${offender.filePath}`);
69+
}
70+
71+
process.exitCode = 1;
72+
}
73+
74+
await main();

‎src/.DS_Store‎

14 KB
Binary file not shown.

‎src/agents/.DS_Store‎

8 KB
Binary file not shown.

‎src/agents/apply-patch-update.ts‎

Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
import fs from "node:fs/promises";
2+
3+
type UpdateFileChunk = {
4+
changeContext?: string;
5+
oldLines: string[];
6+
newLines: string[];
7+
isEndOfFile: boolean;
8+
};
9+
10+
export async function applyUpdateHunk(
11+
filePath: string,
12+
chunks: UpdateFileChunk[],
13+
): Promise<string> {
14+
const originalContents = await fs.readFile(filePath, "utf8").catch((err) => {
15+
throw new Error(`Failed to read file to update ${filePath}: ${err}`);
16+
});
17+
18+
const originalLines = originalContents.split("\n");
19+
if (
20+
originalLines.length > 0 &&
21+
originalLines[originalLines.length - 1] === ""
22+
) {
23+
originalLines.pop();
24+
}
25+
26+
const replacements = computeReplacements(originalLines, filePath, chunks);
27+
let newLines = applyReplacements(originalLines, replacements);
28+
if (newLines.length === 0 || newLines[newLines.length - 1] !== "") {
29+
newLines = [...newLines, ""];
30+
}
31+
return newLines.join("\n");
32+
}
33+
34+
function computeReplacements(
35+
originalLines: string[],
36+
filePath: string,
37+
chunks: UpdateFileChunk[],
38+
): Array<[number, number, string[]]> {
39+
const replacements: Array<[number, number, string[]]> = [];
40+
let lineIndex = 0;
41+
42+
for (const chunk of chunks) {
43+
if (chunk.changeContext) {
44+
const ctxIndex = seekSequence(
45+
originalLines,
46+
[chunk.changeContext],
47+
lineIndex,
48+
false,
49+
);
50+
if (ctxIndex === null) {
51+
throw new Error(
52+
`Failed to find context '${chunk.changeContext}' in ${filePath}`,
53+
);
54+
}
55+
lineIndex = ctxIndex + 1;
56+
}
57+
58+
if (chunk.oldLines.length === 0) {
59+
const insertionIndex =
60+
originalLines.length > 0 &&
61+
originalLines[originalLines.length - 1] === ""
62+
? originalLines.length - 1
63+
: originalLines.length;
64+
replacements.push([insertionIndex, 0, chunk.newLines]);
65+
continue;
66+
}
67+
68+
let pattern = chunk.oldLines;
69+
let newSlice = chunk.newLines;
70+
let found = seekSequence(
71+
originalLines,
72+
pattern,
73+
lineIndex,
74+
chunk.isEndOfFile,
75+
);
76+
77+
if (found === null && pattern[pattern.length - 1] === "") {
78+
pattern = pattern.slice(0, -1);
79+
if (newSlice.length > 0 && newSlice[newSlice.length - 1] === "") {
80+
newSlice = newSlice.slice(0, -1);
81+
}
82+
found = seekSequence(
83+
originalLines,
84+
pattern,
85+
lineIndex,
86+
chunk.isEndOfFile,
87+
);
88+
}
89+
90+
if (found === null) {
91+
throw new Error(
92+
`Failed to find expected lines in ${filePath}:\n${chunk.oldLines.join("\n")}`,
93+
);
94+
}
95+
96+
replacements.push([found, pattern.length, newSlice]);
97+
lineIndex = found + pattern.length;
98+
}
99+
100+
replacements.sort((a, b) => a[0] - b[0]);
101+
return replacements;
102+
}
103+
104+
function applyReplacements(
105+
lines: string[],
106+
replacements: Array<[number, number, string[]]>,
107+
): string[] {
108+
const result = [...lines];
109+
for (const [startIndex, oldLen, newLines] of [...replacements].reverse()) {
110+
for (let i = 0; i < oldLen; i += 1) {
111+
if (startIndex < result.length) {
112+
result.splice(startIndex, 1);
113+
}
114+
}
115+
for (let i = 0; i < newLines.length; i += 1) {
116+
result.splice(startIndex + i, 0, newLines[i]);
117+
}
118+
}
119+
return result;
120+
}
121+
122+
function seekSequence(
123+
lines: string[],
124+
pattern: string[],
125+
start: number,
126+
eof: boolean,
127+
): number | null {
128+
if (pattern.length === 0) return start;
129+
if (pattern.length > lines.length) return null;
130+
131+
const maxStart = lines.length - pattern.length;
132+
const searchStart = eof && lines.length >= pattern.length ? maxStart : start;
133+
if (searchStart > maxStart) return null;
134+
135+
for (let i = searchStart; i <= maxStart; i += 1) {
136+
if (linesMatch(lines, pattern, i, (value) => value)) return i;
137+
}
138+
for (let i = searchStart; i <= maxStart; i += 1) {
139+
if (linesMatch(lines, pattern, i, (value) => value.trimEnd())) return i;
140+
}
141+
for (let i = searchStart; i <= maxStart; i += 1) {
142+
if (linesMatch(lines, pattern, i, (value) => value.trim())) return i;
143+
}
144+
for (let i = searchStart; i <= maxStart; i += 1) {
145+
if (
146+
linesMatch(lines, pattern, i, (value) =>
147+
normalizePunctuation(value.trim()),
148+
)
149+
) {
150+
return i;
151+
}
152+
}
153+
154+
return null;
155+
}
156+
157+
function linesMatch(
158+
lines: string[],
159+
pattern: string[],
160+
start: number,
161+
normalize: (value: string) => string,
162+
): boolean {
163+
for (let idx = 0; idx < pattern.length; idx += 1) {
164+
if (normalize(lines[start + idx]) !== normalize(pattern[idx])) {
165+
return false;
166+
}
167+
}
168+
return true;
169+
}
170+
171+
function normalizePunctuation(value: string): string {
172+
return Array.from(value)
173+
.map((char) => {
174+
switch (char) {
175+
case "\u2010":
176+
case "\u2011":
177+
case "\u2012":
178+
case "\u2013":
179+
case "\u2014":
180+
case "\u2015":
181+
case "\u2212":
182+
return "-";
183+
case "\u2018":
184+
case "\u2019":
185+
case "\u201A":
186+
case "\u201B":
187+
return "'";
188+
case "\u201C":
189+
case "\u201D":
190+
case "\u201E":
191+
case "\u201F":
192+
return '"';
193+
case "\u00A0":
194+
case "\u2002":
195+
case "\u2003":
196+
case "\u2004":
197+
case "\u2005":
198+
case "\u2006":
199+
case "\u2007":
200+
case "\u2008":
201+
case "\u2009":
202+
case "\u200A":
203+
case "\u202F":
204+
case "\u205F":
205+
case "\u3000":
206+
return " ";
207+
default:
208+
return char;
209+
}
210+
})
211+
.join("");
212+
}

0 commit comments

Comments
 (0)