tokless 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,8 @@
2
2
 
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
+ const { estimateTokens, splitLines, formatInt } = require('./core/lexer');
6
+ const { SUPPORTED_EXTS, getLanguageHandler } = require('./core/registry');
5
7
 
6
8
  const IGNORED_DIRS = new Set([
7
9
  'node_modules',
@@ -14,1265 +16,14 @@ const IGNORED_DIRS = new Set([
14
16
  '__pycache__',
15
17
  ]);
16
18
 
17
- const JS_TS_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx']);
18
- const C_FAMILY_EXTS = new Set(['.java', '.c', '.cpp', '.cc', '.h', '.hpp', '.cs']);
19
- const SFC_EXTS = new Set(['.vue', '.svelte']);
20
- const SUPPORTED_EXTS = new Set([
21
- ...JS_TS_EXTS,
22
- '.py',
23
- '.go',
24
- '.rs',
25
- '.md',
26
- ...C_FAMILY_EXTS,
27
- ...SFC_EXTS,
28
- ]);
29
-
30
- const CONTROL_KEYWORDS = new Set([
31
- 'if',
32
- 'else',
33
- 'for',
34
- 'while',
35
- 'do',
36
- 'switch',
37
- 'case',
38
- 'catch',
39
- 'finally',
40
- 'try',
41
- 'with',
42
- 'return',
43
- 'throw',
44
- 'new',
45
- 'typeof',
46
- 'delete',
47
- 'await',
48
- 'yield',
49
- 'sizeof',
50
- ]);
51
-
52
- const REGEX_PREV_KEYWORDS = new Set([
53
- 'return',
54
- 'throw',
55
- 'case',
56
- 'typeof',
57
- 'void',
58
- 'delete',
59
- 'in',
60
- 'instanceof',
61
- 'new',
62
- 'await',
63
- 'yield',
64
- 'else',
65
- 'do',
66
- 'of',
67
- ]);
68
-
69
- /**
70
- * 估算文本的 Token 数量(纯 JS 零依赖,兼顾英文代码与中文字符)
71
- * @param {string} text
72
- * @returns {number}
73
- */
74
- function estimateTokens(text) {
75
- if (!text) return 0;
76
- let cjk = 0;
77
- for (let i = 0; i < text.length; i++) {
78
- const code = text.charCodeAt(i);
79
- if (
80
- (code >= 0x4e00 && code <= 0x9fff) ||
81
- (code >= 0x3400 && code <= 0x4dbf) ||
82
- (code >= 0x3000 && code <= 0x303f) ||
83
- (code >= 0xff00 && code <= 0xffef)
84
- ) {
85
- cjk++;
86
- }
87
- }
88
- const nonCjk = text.length - cjk;
89
- return Math.max(1, Math.ceil(cjk * 1.5 + nonCjk / 3.8));
90
- }
91
-
92
- /**
93
- * 按行切分文件内容,对齐编辑器行号(忽略末尾单个换行产生的空行)
94
- * @param {string} content
95
- * @returns {string[]}
96
- */
97
- function splitLines(content) {
98
- if (!content) return [];
99
- const normalized = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
100
- const lines = normalized.split('\n');
101
- if (lines.length > 0 && lines[lines.length - 1] === '') {
102
- lines.pop();
103
- }
104
- return lines;
105
- }
106
-
107
- /**
108
- * 词法预处理:剥离注释、字符串字面量、模板字符串内部文本与正则字面量,保留精确的括号与语法骨架
109
- * @param {string[]} lines
110
- * @param {'js'|'go'|'rust'|'c'} lang
111
- */
112
- function preprocessBraceLines(lines, lang) {
113
- const result = new Array(lines.length);
114
- let braceDepth = 0;
115
- let parenDepth = 0;
116
- let inBlockComment = false;
117
- let blockCommentNested = 0; // Rust 支持嵌套 /* /* */ */
118
- let inBacktick = false; // JS 模板字符串 或 Go raw string
119
- let templateExprBraceStack = []; // JS `${ ... }` 嵌套栈
120
- let inRustRawString = false;
121
- let rustRawHashes = 0;
122
-
123
- for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
124
- const raw = lines[lineIdx];
125
- const len = raw.length;
126
- const out = [];
127
- const braceStart = braceDepth;
128
- const parenStart = parenDepth;
129
-
130
- let inLineComment = false;
131
- let inStringQuote = null; // '\'' or '"'
132
- let inRegex = false;
133
- let inRegexClass = false;
134
- let prevSigToken = ''; // 上一个显著 token(用于 JS 正则 vs 除法判断)
135
-
136
- for (let i = 0; i < len; i++) {
137
- const ch = raw[i];
138
- const next = i + 1 < len ? raw[i + 1] : '';
139
-
140
- if (inLineComment) {
141
- out.push(' ');
142
- continue;
143
- }
144
-
145
- if (inBlockComment) {
146
- if (lang === 'rust' && ch === '/' && next === '*') {
147
- blockCommentNested++;
148
- out.push(' ');
149
- i++;
150
- continue;
151
- }
152
- if (ch === '*' && next === '/') {
153
- out.push(' ');
154
- i++;
155
- if (lang === 'rust' && blockCommentNested > 0) {
156
- blockCommentNested--;
157
- } else {
158
- inBlockComment = false;
159
- }
160
- continue;
161
- }
162
- out.push(' ');
163
- continue;
164
- }
165
-
166
- if (inRustRawString) {
167
- if (ch === '"') {
168
- let hashes = 0;
169
- while (i + 1 + hashes < len && raw[i + 1 + hashes] === '#' && hashes < rustRawHashes) {
170
- hashes++;
171
- }
172
- if (hashes === rustRawHashes) {
173
- out.push('"');
174
- for (let h = 0; h < hashes; h++) out.push('#');
175
- i += hashes;
176
- inRustRawString = false;
177
- prevSigToken = '"';
178
- continue;
179
- }
180
- }
181
- out.push(' ');
182
- continue;
183
- }
184
-
185
- if (inBacktick) {
186
- if (lang === 'js') {
187
- if (ch === '\\') {
188
- out.push(' ');
189
- i++;
190
- continue;
191
- }
192
- if (ch === '$' && next === '{') {
193
- templateExprBraceStack.push(braceDepth);
194
- braceDepth++;
195
- out.push(' ');
196
- out.push('{');
197
- i++;
198
- inBacktick = false;
199
- prevSigToken = '{';
200
- continue;
201
- }
202
- if (ch === '`') {
203
- inBacktick = false;
204
- out.push('`');
205
- prevSigToken = '`';
206
- continue;
207
- }
208
- out.push(' ');
209
- continue;
210
- } else {
211
- // Go raw string `...` 无转义
212
- if (ch === '`') {
213
- inBacktick = false;
214
- out.push('`');
215
- prevSigToken = '`';
216
- } else {
217
- out.push(' ');
218
- }
219
- continue;
220
- }
221
- }
222
-
223
- if (inStringQuote) {
224
- if (ch === '\\') {
225
- out.push(' ');
226
- i++;
227
- continue;
228
- }
229
- if (ch === inStringQuote) {
230
- out.push(ch);
231
- inStringQuote = null;
232
- prevSigToken = ch;
233
- continue;
234
- }
235
- out.push(' ');
236
- continue;
237
- }
238
-
239
- if (inRegex) {
240
- if (ch === '\\') {
241
- out.push(' ');
242
- i++;
243
- continue;
244
- }
245
- if (ch === '[') {
246
- inRegexClass = true;
247
- out.push(' ');
248
- continue;
249
- }
250
- if (ch === ']' && inRegexClass) {
251
- inRegexClass = false;
252
- out.push(' ');
253
- continue;
254
- }
255
- if (ch === '/' && !inRegexClass) {
256
- inRegex = false;
257
- out.push('/');
258
- prevSigToken = '/';
259
- // 跳过 flags 如 g, i, m, s, u, y, d
260
- while (i + 1 < len && /[a-z]/i.test(raw[i + 1])) {
261
- out.push(' ');
262
- i++;
263
- }
264
- continue;
265
- }
266
- out.push(' ');
267
- continue;
268
- }
269
-
270
- // 注释开始
271
- if (ch === '/' && next === '/') {
272
- inLineComment = true;
273
- out.push(' ');
274
- i++;
275
- continue;
276
- }
277
- if (ch === '/' && next === '*') {
278
- inBlockComment = true;
279
- blockCommentNested = 0;
280
- out.push(' ');
281
- i++;
282
- continue;
283
- }
284
-
285
- // Rust raw string r"..." / r#"..."# / br#"..."#
286
- if (lang === 'rust' && (ch === 'r' || (ch === 'b' && next === 'r'))) {
287
- let pos = ch === 'b' ? i + 2 : i + 1;
288
- let hashes = 0;
289
- while (pos < len && raw[pos] === '#') {
290
- hashes++;
291
- pos++;
292
- }
293
- if (pos < len && raw[pos] === '"' && (i === 0 || !/[A-Za-z0-9_]/.test(raw[i - 1]))) {
294
- inRustRawString = true;
295
- rustRawHashes = hashes;
296
- for (let k = i; k <= pos; k++) out.push(raw[k]);
297
- i = pos;
298
- continue;
299
- }
300
- }
301
-
302
- // JS regex 字面量检测
303
- if (lang === 'js' && ch === '/') {
304
- const startsRegex =
305
- prevSigToken === '' ||
306
- '([{,;:=!?&|^~+-*%<>'.includes(prevSigToken) ||
307
- REGEX_PREV_KEYWORDS.has(prevSigToken);
308
- if (startsRegex) {
309
- inRegex = true;
310
- inRegexClass = false;
311
- out.push('/');
312
- continue;
313
- }
314
- }
315
-
316
- // 字符串开始
317
- if (ch === '"') {
318
- inStringQuote = '"';
319
- out.push('"');
320
- continue;
321
- }
322
-
323
- if (ch === "'") {
324
- if (lang === 'rust') {
325
- // 区分 Rust 字符字面量 ('a', '\n', '\x7f', '\u{1234}') 与生命周期 ('a, 'static)
326
- const tail = raw.slice(i);
327
- const charLitMatch = tail.match(/^'(?:\\(?:x[0-9a-fA-F]{2}|u\{[0-9a-fA-F_]+\}|.)|[^'\\])'/);
328
- if (charLitMatch) {
329
- out.push("'");
330
- for (let k = 1; k < charLitMatch[0].length - 1; k++) out.push(' ');
331
- out.push("'");
332
- i += charLitMatch[0].length - 1;
333
- prevSigToken = "'";
334
- continue;
335
- }
336
- // 否则视为 Rust lifetime
337
- out.push("'");
338
- prevSigToken = "'";
339
- continue;
340
- }
341
- inStringQuote = "'";
342
- out.push("'");
343
- continue;
344
- }
345
-
346
- if (ch === '`' && (lang === 'js' || lang === 'go')) {
347
- inBacktick = true;
348
- out.push('`');
349
- continue;
350
- }
351
-
352
- // 括号计数
353
- if (ch === '{') {
354
- braceDepth++;
355
- } else if (ch === '}') {
356
- braceDepth = Math.max(0, braceDepth - 1);
357
- if (
358
- lang === 'js' &&
359
- templateExprBraceStack.length > 0 &&
360
- braceDepth === templateExprBraceStack[templateExprBraceStack.length - 1]
361
- ) {
362
- templateExprBraceStack.pop();
363
- out.push('}');
364
- inBacktick = true;
365
- prevSigToken = '}';
366
- continue;
367
- }
368
- } else if (ch === '(') {
369
- parenDepth++;
370
- } else if (ch === ')') {
371
- parenDepth = Math.max(0, parenDepth - 1);
372
- }
373
-
374
- out.push(ch);
375
-
376
- // 更新 prevSigToken
377
- if (!/\s/.test(ch)) {
378
- if (/[A-Za-z0-9_$]/.test(ch)) {
379
- if (i > 0 && /[A-Za-z0-9_$]/.test(raw[i - 1]) && /[A-Za-z0-9_$]/.test(prevSigToken)) {
380
- prevSigToken += ch;
381
- } else {
382
- prevSigToken = ch;
383
- }
384
- } else {
385
- prevSigToken = ch;
386
- }
387
- }
388
- }
389
-
390
- result[lineIdx] = {
391
- raw,
392
- clean: out.join(''),
393
- braceStart,
394
- braceEnd: braceDepth,
395
- parenStart,
396
- parenEnd: parenDepth,
397
- };
398
- }
399
-
400
- return result;
401
- }
402
-
403
- /**
404
- * 向上/向后查找声明块的精确结束行索引(0-based)
405
- * @param {Array} analyzed
406
- * @param {number} startIdx
407
- * @param {'js'|'go'|'rust'|'c'} lang
408
- * @returns {{ endIdx: number, headerEndIdx: number, hasBlock: boolean }}
409
- */
410
- function findDeclarationRange(analyzed, startIdx, lang) {
411
- let paren = 0;
412
- let bracket = 0;
413
- let brace = 0;
414
- let blockStarted = false;
415
- let headerEndIdx = startIdx;
416
-
417
- for (let j = startIdx; j < analyzed.length; j++) {
418
- const line = analyzed[j].clean;
419
- for (let k = 0; k < line.length; k++) {
420
- const ch = line[k];
421
- if (ch === '(') paren++;
422
- else if (ch === ')') paren = Math.max(0, paren - 1);
423
- else if (ch === '[') bracket++;
424
- else if (ch === ']') bracket = Math.max(0, bracket - 1);
425
- else if (ch === '{') {
426
- if (!blockStarted && paren === 0 && bracket === 0) {
427
- blockStarted = true;
428
- headerEndIdx = j;
429
- }
430
- brace++;
431
- } else if (ch === '}') {
432
- brace = Math.max(0, brace - 1);
433
- if (blockStarted && brace === 0) {
434
- // 如果同一行后面紧跟着另一个 `{`(例如 TS 返回类型 `{ a: string } {`),继续扫完本行
435
- const rest = line.slice(k + 1).trim();
436
- if (rest.startsWith('{') || rest.startsWith('=>')) {
437
- blockStarted = false;
438
- } else {
439
- return { endIdx: j, headerEndIdx, hasBlock: true };
440
- }
441
- }
442
- }
443
- }
444
-
445
- if (blockStarted && brace === 0) {
446
- return { endIdx: j, headerEndIdx, hasBlock: true };
447
- }
448
-
449
- if (!blockStarted && brace === 0 && paren === 0 && bracket === 0) {
450
- const trimmed = line.trim();
451
- if (trimmed.endsWith(';')) {
452
- return { endIdx: j, headerEndIdx: j, hasBlock: false };
453
- }
454
- // 如果末尾是延续符号,则继续下一行
455
- if (
456
- trimmed.endsWith('=>') ||
457
- trimmed.endsWith('=') ||
458
- trimmed.endsWith(':') ||
459
- trimmed.endsWith(',') ||
460
- trimmed.endsWith('(') ||
461
- trimmed.endsWith('|') ||
462
- trimmed.endsWith('&') ||
463
- /\b(?:extends|implements|where)\s*$/.test(trimmed)
464
- ) {
465
- continue;
466
- }
467
-
468
- // 偷看下一个非空 clean 行是否以 `{`、`=>`、`|`、`&`、`where` 开头
469
- let nextTrimmed = '';
470
- for (let n = j + 1; n < analyzed.length && n <= j + 4; n++) {
471
- const t = analyzed[n].clean.trim();
472
- if (t) {
473
- nextTrimmed = t;
474
- break;
475
- }
476
- }
477
- if (
478
- nextTrimmed.startsWith('{') ||
479
- nextTrimmed.startsWith('=>') ||
480
- nextTrimmed.startsWith('|') ||
481
- nextTrimmed.startsWith('&') ||
482
- (lang === 'rust' && nextTrimmed.startsWith('where'))
483
- ) {
484
- continue;
485
- }
486
-
487
- return { endIdx: j, headerEndIdx: j, hasBlock: false };
488
- }
489
- }
490
-
491
- return { endIdx: analyzed.length - 1, headerEndIdx, hasBlock: blockStarted };
492
- }
493
-
494
- /**
495
- * 构建紧凑的单行签名字符串(剥离函数体 `{ ... }` 与多余空白)
496
- * @param {Array} analyzed
497
- * @param {number} startIdx
498
- * @param {number} headerEndIdx
499
- * @param {boolean} hasBlock
500
- * @param {number} [maxLen=140]
501
- * @returns {string}
502
- */
503
- function buildCompactSignature(analyzed, startIdx, headerEndIdx, hasBlock, maxLen = 140) {
504
- let sig = '';
505
-
506
- if (hasBlock) {
507
- let p = 0;
508
- let b = 0;
509
- let cutLine = -1;
510
- let cutCol = -1;
511
-
512
- for (let i = startIdx; i <= headerEndIdx; i++) {
513
- const cleanLine = analyzed[i].clean;
514
- for (let k = 0; k < cleanLine.length; k++) {
515
- const ch = cleanLine[k];
516
- if (ch === '(') p++;
517
- else if (ch === ')') p = Math.max(0, p - 1);
518
- else if (ch === '[') b++;
519
- else if (ch === ']') b = Math.max(0, b - 1);
520
- else if (ch === '{' && p === 0 && b === 0) {
521
- const after = cleanLine.slice(k + 1);
522
- const closeIdx = after.indexOf('}');
523
- if (closeIdx !== -1 && after.slice(closeIdx + 1).trim().startsWith('{')) {
524
- continue;
525
- }
526
- cutLine = i;
527
- cutCol = k;
528
- break;
529
- }
530
- }
531
- if (cutLine !== -1) break;
532
- }
533
-
534
- const effectiveEnd = cutLine !== -1 ? cutLine : headerEndIdx;
535
- const sliceEnd = Math.min(effectiveEnd, startIdx + 5);
536
- const parts = [];
537
- for (let i = startIdx; i <= sliceEnd; i++) {
538
- let rawLine = analyzed[i].raw;
539
- if (i === cutLine && cutCol !== -1) {
540
- rawLine = rawLine.slice(0, cutCol);
541
- }
542
- const trimmed = rawLine.trim();
543
- if (trimmed) parts.push(trimmed);
544
- }
545
- sig = parts.join(' ').replace(/\s+/g, ' ').trim();
546
- } else {
547
- const sliceEnd = Math.min(headerEndIdx, startIdx + 5);
548
- const parts = [];
549
- for (let i = startIdx; i <= sliceEnd; i++) {
550
- const trimmed = analyzed[i].raw.trim();
551
- if (trimmed) parts.push(trimmed);
552
- }
553
- sig = parts.join(' ').replace(/\s+/g, ' ').replace(/;+\s*$/, '').trim();
554
- }
555
-
556
- if (sig.length > maxLen) {
557
- sig = sig.slice(0, maxLen - 3).trimEnd() + '...';
558
- }
559
- return sig;
560
- }
561
-
562
- /**
563
- * 在范围内判断 clean 文本是否包含 `=>` 或 `function`(在 top-level assignment 中)
564
- */
565
- function hasFunctionRhs(analyzed, startIdx, headerEndIdx) {
566
- let text = '';
567
- for (let i = startIdx; i <= Math.min(headerEndIdx, startIdx + 5); i++) {
568
- text += ' ' + analyzed[i].clean;
569
- }
570
- return /=>/.test(text) || /=\s*(?:async\s+)?function\b/.test(text);
571
- }
572
-
573
- /**
574
- * 解析 JS / TS / JSX / TSX / MJS / CJS 文件
575
- */
576
- function parseJsTs(lines, lineOffset = 0) {
577
- const analyzed = preprocessBraceLines(lines, 'js');
578
- const items = [];
579
- let activeClassEnd = -1;
580
- let activeClassBodyDepth = -1;
581
-
582
- for (let i = 0; i < analyzed.length; i++) {
583
- const info = analyzed[i];
584
- const trimmed = info.clean.trim();
585
- if (!trimmed) continue;
586
-
587
- if (activeClassEnd !== -1 && i > activeClassEnd) {
588
- activeClassEnd = -1;
589
- activeClassBodyDepth = -1;
590
- }
591
-
592
- const inClassBody =
593
- activeClassEnd !== -1 &&
594
- i <= activeClassEnd &&
595
- info.braceStart === activeClassBodyDepth;
596
-
597
- // 1. 顶层声明 (braceStart === 0)
598
- if (info.braceStart === 0) {
599
- let kind = null;
600
- let name = '';
601
-
602
- let m;
603
- if (
604
- (m = trimmed.match(
605
- /^(?:export\s+(?:default\s+)?)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/
606
- )) ||
607
- (m = trimmed.match(/^(?:module\.)?exports\s*=\s*(?:abstract\s+)?class\s*([A-Za-z_$][\w$]*)?/))
608
- ) {
609
- kind = 'class';
610
- name = m[1] || 'default';
611
- } else if (
612
- (m = trimmed.match(
613
- /^(?:export\s+(?:default\s+)?)?(?:declare\s+)?interface\s+([A-Za-z_$][\w$]*)/
614
- ))
615
- ) {
616
- kind = 'interface';
617
- name = m[1];
618
- } else if (
619
- (m = trimmed.match(
620
- /^(?:export\s+(?:default\s+)?)?(?:declare\s+)?type\s+([A-Za-z_$][\w$]*)\b/
621
- ))
622
- ) {
623
- kind = 'type';
624
- name = m[1];
625
- } else if (
626
- (m = trimmed.match(
627
- /^(?:export\s+(?:default\s+)?)?(?:declare\s+)?(?:const\s+)?enum\s+([A-Za-z_$][\w$]*)/
628
- ))
629
- ) {
630
- kind = 'enum';
631
- name = m[1];
632
- } else if (
633
- (m = trimmed.match(
634
- /^(?:export\s+(?:default\s+)?)?(?:declare\s+)?namespace\s+([A-Za-z_$][\w$]*)/
635
- ))
636
- ) {
637
- kind = 'namespace';
638
- name = m[1];
639
- } else if (
640
- (m = trimmed.match(
641
- /^(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)?\s*(?:<[^>]*>)?\s*\(/
642
- ))
643
- ) {
644
- kind = 'function';
645
- name = m[1] || 'default';
646
- } else if (
647
- (m = trimmed.match(/^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\b/))
648
- ) {
649
- const rangeProbe = findDeclarationRange(analyzed, i, 'js');
650
- if (hasFunctionRhs(analyzed, i, rangeProbe.headerEndIdx)) {
651
- kind = 'function';
652
- name = m[1];
653
- } else if (/=\s*(?:abstract\s+)?class\b/.test(trimmed)) {
654
- kind = 'class';
655
- name = m[1];
656
- }
657
- } else if (
658
- (m = trimmed.match(/^(?:module\.)?exports\.([A-Za-z_$][\w$]*)\s*=/))
659
- ) {
660
- const rangeProbe = findDeclarationRange(analyzed, i, 'js');
661
- if (hasFunctionRhs(analyzed, i, rangeProbe.headerEndIdx)) {
662
- kind = 'function';
663
- name = m[1];
664
- }
665
- } else if (/^module\.exports\s*=\s*\{/.test(trimmed)) {
666
- kind = 'export';
667
- name = 'module.exports';
668
- } else if (/^export\s+default\s+(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>/.test(trimmed)) {
669
- kind = 'function';
670
- name = 'default';
671
- } else if (/^export\s+default\s+(?:async\s+)?function\b/.test(trimmed)) {
672
- kind = 'function';
673
- name = 'default';
674
- }
675
-
676
- if (kind) {
677
- const range = findDeclarationRange(analyzed, i, 'js');
678
- let signature = buildCompactSignature(analyzed, i, range.headerEndIdx, range.hasBlock);
679
- if (kind === 'export' && name === 'module.exports') {
680
- // 对 module.exports = { a, b, c } 做紧凑汇总
681
- const exportNames = [];
682
- for (let k = i; k <= range.endIdx; k++) {
683
- const lineClean = analyzed[k].clean.replace(/^module\.exports\s*=\s*\{?/, '').replace(/\}?;?\s*$/, '');
684
- for (const token of lineClean.split(',')) {
685
- const keyMatch = token.trim().match(/^([A-Za-z_$][\w$]*)/);
686
- if (keyMatch) exportNames.push(keyMatch[1]);
687
- }
688
- }
689
- if (exportNames.length > 0) {
690
- const joined = exportNames.join(', ');
691
- signature =
692
- joined.length > 100
693
- ? `module.exports = { ${joined.slice(0, 97)}... }`
694
- : `module.exports = { ${joined} }`;
695
- }
696
- }
697
-
698
- items.push({
699
- kind,
700
- name,
701
- signature,
702
- startLine: i + 1 + lineOffset,
703
- endLine: range.endIdx + 1 + lineOffset,
704
- depth: 0,
705
- });
706
-
707
- if (kind === 'class' && range.hasBlock) {
708
- activeClassEnd = range.endIdx;
709
- activeClassBodyDepth = 1;
710
- i = range.headerEndIdx; // 继续扫描 class 内部方法
711
- } else {
712
- i = range.endIdx;
713
- }
714
- continue;
715
- }
716
- }
717
-
718
- // 2. Class 内部方法与箭头字段
719
- if (inClassBody) {
720
- let methodMatch = trimmed.match(
721
- /^(?:(?:public|private|protected|static|async|readonly|override|abstract|get|set)\s+)*\*?\s*(#?[A-Za-z_$][\w$]*|\[[^\]]+\])\s*(?:<[^>]*>)?\s*\(/
722
- );
723
- let isArrowField = false;
724
- if (!methodMatch) {
725
- methodMatch = trimmed.match(
726
- /^(?:(?:public|private|protected|static|readonly|override)\s+)*(#?[A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>/
727
- );
728
- if (methodMatch) isArrowField = true;
729
- }
730
-
731
- if (methodMatch) {
732
- const methodName = methodMatch[1];
733
- if (!CONTROL_KEYWORDS.has(methodName)) {
734
- const range = findDeclarationRange(analyzed, i, 'js');
735
- if (range.hasBlock || isArrowField || trimmed.endsWith(';')) {
736
- const signature = buildCompactSignature(
737
- analyzed,
738
- i,
739
- range.headerEndIdx,
740
- range.hasBlock
741
- );
742
- items.push({
743
- kind: 'method',
744
- name: methodName,
745
- signature,
746
- startLine: i + 1 + lineOffset,
747
- endLine: range.endIdx + 1 + lineOffset,
748
- depth: 1,
749
- });
750
- i = range.endIdx;
751
- continue;
752
- }
753
- }
754
- }
755
- }
756
- }
757
-
758
- return items;
759
- }
760
-
761
- /**
762
- * 解析 Go 文件
763
- */
764
- function parseGo(lines) {
765
- const analyzed = preprocessBraceLines(lines, 'go');
766
- const items = [];
767
-
768
- for (let i = 0; i < analyzed.length; i++) {
769
- const info = analyzed[i];
770
- if (info.braceStart !== 0) continue;
771
- const trimmed = info.clean.trim();
772
- if (!trimmed) continue;
773
-
774
- let kind = null;
775
- let name = '';
776
- let m;
777
-
778
- if ((m = trimmed.match(/^func\s+(?:\([^)]+\)\s+)?([A-Za-z_]\w*)\b/))) {
779
- kind = 'func';
780
- name = m[1];
781
- } else if ((m = trimmed.match(/^type\s+([A-Za-z_]\w*)\s+struct\b/))) {
782
- kind = 'struct';
783
- name = m[1];
784
- } else if ((m = trimmed.match(/^type\s+([A-Za-z_]\w*)\s+interface\b/))) {
785
- kind = 'interface';
786
- name = m[1];
787
- } else if ((m = trimmed.match(/^type\s+([A-Za-z_]\w*)\b/))) {
788
- kind = 'type';
789
- name = m[1];
790
- }
791
-
792
- if (kind) {
793
- const range = findDeclarationRange(analyzed, i, 'go');
794
- const signature = buildCompactSignature(analyzed, i, range.headerEndIdx, range.hasBlock);
795
- items.push({
796
- kind,
797
- name,
798
- signature,
799
- startLine: i + 1,
800
- endLine: range.endIdx + 1,
801
- depth: 0,
802
- });
803
- i = range.endIdx;
804
- }
805
- }
806
-
807
- return items;
808
- }
809
-
810
- /**
811
- * 解析 Rust 文件
812
- */
813
- function parseRust(lines) {
814
- const analyzed = preprocessBraceLines(lines, 'rust');
815
- const items = [];
816
- let containerEnd = -1;
817
- let containerBodyDepth = -1;
818
-
819
- for (let i = 0; i < analyzed.length; i++) {
820
- const info = analyzed[i];
821
- const trimmed = info.clean.trim();
822
- if (!trimmed) continue;
823
-
824
- if (containerEnd !== -1 && i > containerEnd) {
825
- containerEnd = -1;
826
- containerBodyDepth = -1;
827
- }
828
-
829
- const inContainer =
830
- containerEnd !== -1 && i <= containerEnd && info.braceStart === containerBodyDepth;
831
-
832
- if (info.braceStart !== 0 && !inContainer) continue;
833
-
834
- let kind = null;
835
- let name = '';
836
- let m;
837
-
838
- if (
839
- (m = trimmed.match(
840
- /^(?:pub(?:\([^)]+\))?\s+)?(?:default\s+)?(?:const\s+)?(?:async\s+)?(?:unsafe\s+)?(?:extern\s+(?:"[^"]+"\s+)?)?fn\s+([A-Za-z_]\w*)/
841
- ))
842
- ) {
843
- kind = 'fn';
844
- name = m[1];
845
- } else if ((m = trimmed.match(/^(?:pub(?:\([^)]+\))?\s+)?struct\s+([A-Za-z_]\w*)/))) {
846
- kind = 'struct';
847
- name = m[1];
848
- } else if ((m = trimmed.match(/^(?:pub(?:\([^)]+\))?\s+)?enum\s+([A-Za-z_]\w*)/))) {
849
- kind = 'enum';
850
- name = m[1];
851
- } else if ((m = trimmed.match(/^(?:pub(?:\([^)]+\))?\s+)?trait\s+([A-Za-z_]\w*)/))) {
852
- kind = 'trait';
853
- name = m[1];
854
- } else if ((m = trimmed.match(/^(?:unsafe\s+)?impl\b(.*)$/))) {
855
- kind = 'impl';
856
- name = m[1].replace(/\{.*$/, '').trim() || 'impl';
857
- } else if ((m = trimmed.match(/^(?:pub(?:\([^)]+\))?\s+)?mod\s+([A-Za-z_]\w*)/))) {
858
- kind = 'mod';
859
- name = m[1];
860
- } else if ((m = trimmed.match(/^(?:pub(?:\([^)]+\))?\s+)?type\s+([A-Za-z_]\w*)/))) {
861
- kind = 'type';
862
- name = m[1];
863
- } else if ((m = trimmed.match(/^(?:pub(?:\([^)]+\))?\s+)?macro_rules!\s+([A-Za-z_]\w*)/))) {
864
- kind = 'macro';
865
- name = m[1];
866
- }
867
-
868
- if (kind) {
869
- const range = findDeclarationRange(analyzed, i, 'rust');
870
- const signature = buildCompactSignature(analyzed, i, range.headerEndIdx, range.hasBlock);
871
- const depth = inContainer ? 1 : 0;
872
- items.push({
873
- kind,
874
- name,
875
- signature,
876
- startLine: i + 1,
877
- endLine: range.endIdx + 1,
878
- depth,
879
- });
880
-
881
- if (
882
- !inContainer &&
883
- (kind === 'impl' || kind === 'trait' || kind === 'mod') &&
884
- range.hasBlock
885
- ) {
886
- containerEnd = range.endIdx;
887
- containerBodyDepth = 1;
888
- i = range.headerEndIdx;
889
- } else {
890
- i = range.endIdx;
891
- }
892
- }
893
- }
894
-
895
- return items;
896
- }
897
-
898
- /**
899
- * 解析 Java / C / C++ / C# 文件
900
- */
901
- function parseCFamily(lines) {
902
- const analyzed = preprocessBraceLines(lines, 'c');
903
- const items = [];
904
- let classEnd = -1;
905
- let classDepth = -1;
906
-
907
- for (let i = 0; i < analyzed.length; i++) {
908
- const info = analyzed[i];
909
- const trimmed = info.clean.trim();
910
- if (!trimmed || trimmed.startsWith('#')) continue;
911
-
912
- if (classEnd !== -1 && i > classEnd) {
913
- classEnd = -1;
914
- classDepth = -1;
915
- }
916
-
917
- const inClass = classEnd !== -1 && i <= classEnd && info.braceStart === classDepth;
918
- if (info.braceStart !== 0 && !inClass) continue;
919
-
920
- let kind = null;
921
- let name = '';
922
- let m;
923
-
924
- if (
925
- (m = trimmed.match(
926
- /^(?:(?:public|private|protected|internal|abstract|final|static|sealed|partial|export)\s+)*(class|interface|struct|enum|namespace)\s+([A-Za-z_]\w*)/
927
- ))
928
- ) {
929
- kind = m[1];
930
- name = m[2];
931
- } else if (
932
- (m = trimmed.match(/^(?:[\w:<>&*\[\]\s]+?\s+)?([A-Za-z_~]\w*)\s*\([^;]*$/))
933
- ) {
934
- const candidate = m[1];
935
- if (!CONTROL_KEYWORDS.has(candidate)) {
936
- const rangeProbe = findDeclarationRange(analyzed, i, 'c');
937
- if (rangeProbe.hasBlock) {
938
- kind = inClass ? 'method' : 'function';
939
- name = candidate;
940
- }
941
- }
942
- }
943
-
944
- if (kind) {
945
- const range = findDeclarationRange(analyzed, i, 'c');
946
- const signature = buildCompactSignature(analyzed, i, range.headerEndIdx, range.hasBlock);
947
- items.push({
948
- kind,
949
- name,
950
- signature,
951
- startLine: i + 1,
952
- endLine: range.endIdx + 1,
953
- depth: inClass ? 1 : 0,
954
- });
955
-
956
- if (
957
- (kind === 'class' || kind === 'interface' || kind === 'struct' || kind === 'namespace') &&
958
- range.hasBlock
959
- ) {
960
- classEnd = range.endIdx;
961
- classDepth = info.braceStart + 1;
962
- i = range.headerEndIdx;
963
- } else {
964
- i = range.endIdx;
965
- }
966
- }
967
- }
968
-
969
- return items;
970
- }
971
-
972
- /**
973
- * 预处理 Python 行(识别三引号字符串与注释,避免 docstring 内的 def/class 误判)
974
- */
975
- function preprocessPythonLines(lines) {
976
- const result = new Array(lines.length);
977
- let tripleQuote = null; // '"""' or "'''"
978
-
979
- for (let i = 0; i < lines.length; i++) {
980
- const raw = lines[i];
981
- const startedInTriple = tripleQuote !== null;
982
- let inSingle = false;
983
- let inDouble = false;
984
- const out = [];
985
-
986
- for (let k = 0; k < raw.length; k++) {
987
- const ch = raw[k];
988
- if (tripleQuote) {
989
- if (raw.slice(k, k + 3) === tripleQuote) {
990
- tripleQuote = null;
991
- out.push(' ');
992
- k += 2;
993
- } else {
994
- out.push(' ');
995
- }
996
- continue;
997
- }
998
- if (inSingle) {
999
- if (ch === '\\') {
1000
- out.push(' ');
1001
- k++;
1002
- continue;
1003
- }
1004
- if (ch === "'") inSingle = false;
1005
- out.push(' ');
1006
- continue;
1007
- }
1008
- if (inDouble) {
1009
- if (ch === '\\') {
1010
- out.push(' ');
1011
- k++;
1012
- continue;
1013
- }
1014
- if (ch === '"') inDouble = false;
1015
- out.push(' ');
1016
- continue;
1017
- }
1018
-
1019
- if (ch === '#') {
1020
- while (k < raw.length) {
1021
- out.push(' ');
1022
- k++;
1023
- }
1024
- break;
1025
- }
1026
- if (raw.slice(k, k + 3) === '"""' || raw.slice(k, k + 3) === "'''") {
1027
- tripleQuote = raw.slice(k, k + 3);
1028
- out.push(' ');
1029
- k += 2;
1030
- continue;
1031
- }
1032
- if (ch === "'") {
1033
- inSingle = true;
1034
- out.push("'");
1035
- continue;
1036
- }
1037
- if (ch === '"') {
1038
- inDouble = true;
1039
- out.push('"');
1040
- continue;
1041
- }
1042
- out.push(ch);
1043
- }
1044
-
1045
- const expanded = raw.replace(/^\t+/, (m) => ' '.repeat(m.length));
1046
- const indent = expanded.length - expanded.trimStart().length;
1047
-
1048
- result[i] = {
1049
- raw,
1050
- clean: out.join(''),
1051
- indent,
1052
- startedInTriple,
1053
- endedInTriple: tripleQuote !== null,
1054
- };
1055
- }
1056
-
1057
- return result;
1058
- }
1059
-
1060
- /**
1061
- * 解析 Python 文件
1062
- */
1063
- function parsePython(lines) {
1064
- const analyzed = preprocessPythonLines(lines);
1065
- const items = [];
1066
- const classStack = []; // [{ indent, endIdx }]
1067
-
1068
- for (let i = 0; i < analyzed.length; i++) {
1069
- const info = analyzed[i];
1070
- if (info.startedInTriple) continue;
1071
-
1072
- const trimmed = info.clean.trim();
1073
- if (!trimmed) continue;
1074
-
1075
- while (classStack.length > 0 && info.indent <= classStack[classStack.length - 1].indent) {
1076
- classStack.pop();
1077
- }
1078
-
1079
- const m = trimmed.match(/^(class|async\s+def|def)\s+([A-Za-z_]\w*)\b/);
1080
- if (!m) continue;
1081
-
1082
- const rawKind = m[1];
1083
- const name = m[2];
1084
- const isClass = rawKind === 'class';
1085
- const headerIndent = info.indent;
1086
-
1087
- // 仅采集顶层 def/class 与 class 内部方法(跳过函数体内的局部嵌套 def,保持骨架紧凑)
1088
- if (headerIndent > 0 && classStack.length === 0) continue;
1089
- if (classStack.length > 1) continue;
1090
-
1091
- // 查找多行签名结尾的 `:`
1092
- let headerEndIdx = i;
1093
- let paren = 0;
1094
- for (let j = i; j < analyzed.length && j <= i + 10; j++) {
1095
- const c = analyzed[j].clean;
1096
- for (let k = 0; k < c.length; k++) {
1097
- if (c[k] === '(') paren++;
1098
- else if (c[k] === ')') paren = Math.max(0, paren - 1);
1099
- }
1100
- if (paren === 0 && c.trimEnd().endsWith(':')) {
1101
- headerEndIdx = j;
1102
- break;
1103
- }
1104
- }
1105
-
1106
- // 向下查找缩进块结束行
1107
- let lastContentIdx = headerEndIdx;
1108
- for (let j = headerEndIdx + 1; j < analyzed.length; j++) {
1109
- const nextInfo = analyzed[j];
1110
- if (nextInfo.startedInTriple || nextInfo.endedInTriple) {
1111
- lastContentIdx = j;
1112
- continue;
1113
- }
1114
- const nextTrimmed = nextInfo.clean.trim();
1115
- if (!nextTrimmed) continue; // 忽略空行与纯注释行
1116
- if (nextInfo.indent <= headerIndent) {
1117
- break;
1118
- }
1119
- lastContentIdx = j;
1120
- }
1121
-
1122
- // 构造紧凑签名
1123
- const sigParts = [];
1124
- for (let j = i; j <= headerEndIdx; j++) {
1125
- const t = analyzed[j].raw.trim();
1126
- if (t) sigParts.push(t);
1127
- }
1128
- let signature = sigParts.join(' ').replace(/\s+/g, ' ').replace(/:\s*$/, '').trim();
1129
- if (signature.length > 140) {
1130
- signature = signature.slice(0, 137).trimEnd() + '...';
1131
- }
1132
-
1133
- const depth = classStack.length > 0 ? 1 : 0;
1134
- items.push({
1135
- kind: isClass ? 'class' : depth === 1 ? 'method' : 'def',
1136
- name,
1137
- signature,
1138
- startLine: i + 1,
1139
- endLine: lastContentIdx + 1,
1140
- depth,
1141
- });
1142
-
1143
- if (isClass) {
1144
- classStack.push({ indent: headerIndent, endIdx: lastContentIdx });
1145
- i = headerEndIdx;
1146
- } else {
1147
- i = lastContentIdx;
1148
- }
1149
- }
1150
-
1151
- return items;
1152
- }
1153
-
1154
- /**
1155
- * 解析 Markdown 文件(按标题层级计算起止行号,自动跳过代码块内的 # 注释)
1156
- */
1157
- function parseMarkdown(lines) {
1158
- const headings = [];
1159
- let inFence = false;
1160
- let fenceChar = '';
1161
-
1162
- for (let i = 0; i < lines.length; i++) {
1163
- const line = lines[i];
1164
- const trimmed = line.trim();
1165
-
1166
- const fenceMatch = trimmed.match(/^(`{3,}|~{3,})/);
1167
- if (fenceMatch) {
1168
- const marker = fenceMatch[1][0];
1169
- if (!inFence) {
1170
- inFence = true;
1171
- fenceChar = marker;
1172
- } else if (marker === fenceChar) {
1173
- inFence = false;
1174
- fenceChar = '';
1175
- }
1176
- continue;
1177
- }
1178
- if (inFence) continue;
1179
-
1180
- const hMatch = line.match(/^(#{1,6})\s+(.+?)\s*#*$/);
1181
- if (hMatch) {
1182
- headings.push({
1183
- level: hMatch[1].length,
1184
- signature: `${hMatch[1]} ${hMatch[2].trim()}`,
1185
- name: hMatch[2].trim(),
1186
- startIdx: i,
1187
- });
1188
- }
1189
- }
1190
-
1191
- if (headings.length === 0) return [];
1192
- const minLevel = Math.min(...headings.map((h) => h.level));
1193
-
1194
- return headings.map((h, idx) => {
1195
- let endIdx = lines.length - 1;
1196
- for (let next = idx + 1; next < headings.length; next++) {
1197
- if (headings[next].level <= h.level) {
1198
- endIdx = headings[next].startIdx - 1;
1199
- break;
1200
- }
1201
- }
1202
- // 回退跳过结尾空行
1203
- while (endIdx > h.startIdx && !lines[endIdx].trim()) {
1204
- endIdx--;
1205
- }
1206
- return {
1207
- kind: 'heading',
1208
- name: h.name,
1209
- signature: h.signature,
1210
- startLine: h.startIdx + 1,
1211
- endLine: endIdx + 1,
1212
- depth: h.level - minLevel,
1213
- level: h.level,
1214
- };
1215
- });
1216
- }
1217
-
1218
- /**
1219
- * 解析 Vue / Svelte 单文件组件
1220
- */
1221
- function parseSfc(lines) {
1222
- const items = [];
1223
- const blockRegex = /^<(template|script|style)(\b[^>]*)?>/i;
1224
-
1225
- for (let i = 0; i < lines.length; i++) {
1226
- const trimmed = lines[i].trim();
1227
- const m = trimmed.match(blockRegex);
1228
- if (!m) continue;
1229
-
1230
- const tag = m[1].toLowerCase();
1231
- const closeTag = `</${tag}>`;
1232
- let endIdx = i;
1233
- for (let j = i; j < lines.length; j++) {
1234
- if (lines[j].toLowerCase().includes(closeTag)) {
1235
- endIdx = j;
1236
- break;
1237
- }
1238
- }
1239
-
1240
- items.push({
1241
- kind: 'section',
1242
- name: tag,
1243
- signature: trimmed.replace(/>.*$/, '>'),
1244
- startLine: i + 1,
1245
- endLine: endIdx + 1,
1246
- depth: 0,
1247
- });
1248
-
1249
- if (tag === 'script' && endIdx > i + 1) {
1250
- const innerLines = lines.slice(i + 1, endIdx);
1251
- const scriptItems = parseJsTs(innerLines, i + 1);
1252
- for (const si of scriptItems) {
1253
- items.push({ ...si, depth: si.depth + 1 });
1254
- }
1255
- }
1256
-
1257
- i = endIdx;
1258
- }
1259
-
1260
- return items;
1261
- }
1262
-
1263
- /**
1264
- * 将提取的结构项格式化为紧凑的 `[L起-L止] 签名` 文本
1265
- * @param {object} result
1266
- * @param {object} [options]
1267
- * @returns {string}
1268
- */
1269
19
  function formatSkeletonItems(result, options = {}) {
1270
20
  const { includeHeader = false } = options;
1271
21
  const lines = [];
1272
22
 
1273
23
  if (includeHeader) {
24
+ const charCount = result.charCount ?? result.rawChars ?? 0;
1274
25
  lines.push(
1275
- `📄 ${result.filePath} (${result.totalLines} lines | ~${result.rawTokens} → ~${result.skeletonTokens} tokens, -${result.savedPercent}%)`
26
+ `${result.filePath} (${result.totalLines} 行 · ${formatInt(charCount)} 字 | ~${result.rawTokens} → ~${result.skeletonTokens} tokens, -${result.savedPercent}%)`
1276
27
  );
1277
28
  }
1278
29
 
@@ -1288,39 +39,28 @@ function formatSkeletonItems(result, options = {}) {
1288
39
  return lines.join('\n');
1289
40
  }
1290
41
 
1291
- /**
1292
- * 生成单个文件的紧凑语法骨架
1293
- * @param {string} filePath
1294
- * @param {object} [options]
1295
- * @param {boolean} [options.includeHeader=false]
1296
- * @returns {object}
1297
- */
1298
42
  function generateFileSkeleton(filePath, options = {}) {
1299
43
  const resolved = path.resolve(filePath);
1300
44
  const content = fs.readFileSync(resolved, 'utf8');
1301
45
  const ext = path.extname(resolved).toLowerCase();
1302
46
  const lines = splitLines(content);
1303
47
  const totalLines = lines.length;
48
+ const charCount = content.length;
1304
49
 
1305
50
  let items = [];
1306
- if (JS_TS_EXTS.has(ext)) {
1307
- items = parseJsTs(lines);
1308
- } else if (ext === '.py') {
1309
- items = parsePython(lines);
1310
- } else if (ext === '.go') {
1311
- items = parseGo(lines);
1312
- } else if (ext === '.rs') {
1313
- items = parseRust(lines);
1314
- } else if (ext === '.md') {
1315
- items = parseMarkdown(lines);
1316
- } else if (C_FAMILY_EXTS.has(ext)) {
1317
- items = parseCFamily(lines);
1318
- } else if (SFC_EXTS.has(ext)) {
1319
- items = parseSfc(lines);
51
+ const handler = getLanguageHandler(ext);
52
+ if (handler) {
53
+ items =
54
+ typeof handler === 'function'
55
+ ? handler(lines, ext, options)
56
+ : handler.parse(lines, ext, options);
1320
57
  }
1321
58
 
1322
59
  const rawTokens = estimateTokens(content);
1323
- const bodyOnly = formatSkeletonItems({ filePath: resolved, totalLines, items }, { includeHeader: false });
60
+ const bodyOnly = formatSkeletonItems(
61
+ { filePath: resolved, totalLines, charCount, items },
62
+ { includeHeader: false }
63
+ );
1324
64
  const skeletonTokens = estimateTokens(bodyOnly);
1325
65
  const savedTokens = Math.max(0, rawTokens - skeletonTokens);
1326
66
  const savedPercent = rawTokens > 0 ? Number(((savedTokens / rawTokens) * 100).toFixed(1)) : 0;
@@ -1328,8 +68,10 @@ function generateFileSkeleton(filePath, options = {}) {
1328
68
  const result = {
1329
69
  filePath: resolved,
1330
70
  ext,
71
+ lineCount: totalLines,
1331
72
  totalLines,
1332
- rawChars: content.length,
73
+ charCount,
74
+ rawChars: charCount,
1333
75
  rawTokens,
1334
76
  skeletonLines: bodyOnly.split('\n').length,
1335
77
  skeletonChars: bodyOnly.length,
@@ -1343,15 +85,33 @@ function generateFileSkeleton(filePath, options = {}) {
1343
85
  return result;
1344
86
  }
1345
87
 
1346
- /**
1347
- * 扫描目录生成浓缩代码地图(排除 node_modules/.git/dist/build/exports/.next/target/__pycache__)
1348
- * @param {string} dirPath
1349
- * @param {object} [options]
1350
- * @param {number} [options.depth=2]
1351
- * @returns {object}
1352
- */
88
+ function scanFileLightweight(filePath) {
89
+ const resolved = path.resolve(filePath);
90
+ const content = fs.readFileSync(resolved, 'utf8');
91
+ const ext = path.extname(resolved).toLowerCase();
92
+ const totalLines = splitLines(content).length;
93
+ const charCount = content.length;
94
+ const rawTokens = estimateTokens(content);
95
+ return {
96
+ filePath: resolved,
97
+ ext,
98
+ lineCount: totalLines,
99
+ totalLines,
100
+ charCount,
101
+ rawChars: charCount,
102
+ rawTokens,
103
+ };
104
+ }
105
+
1353
106
  function scanDirectorySkeleton(dirPath, options = {}) {
1354
- const maxDepth = Number.isInteger(options.depth) && options.depth >= 0 ? options.depth : 2;
107
+ const isMap = Boolean(options.map);
108
+ const explicitMaxDepth =
109
+ Number.isInteger(options.maxDepth) && options.maxDepth >= 0
110
+ ? options.maxDepth
111
+ : Number.isInteger(options.depth) && options.depth >= 0
112
+ ? options.depth
113
+ : null;
114
+ const maxDepth = explicitMaxDepth !== null ? explicitMaxDepth : isMap ? 8 : 2;
1355
115
  const root = path.resolve(dirPath);
1356
116
  const files = [];
1357
117
 
@@ -1376,14 +136,22 @@ function scanDirectorySkeleton(dirPath, options = {}) {
1376
136
  if (!SUPPORTED_EXTS.has(ext)) continue;
1377
137
  const fullPath = path.join(currentDir, entry.name);
1378
138
  try {
1379
- const skel = generateFileSkeleton(fullPath, { includeHeader: false });
1380
139
  const relPath = path.relative(root, fullPath).replace(/\\/g, '/');
1381
- files.push({
1382
- relPath,
1383
- ...skel,
1384
- });
140
+ if (isMap) {
141
+ const statItem = scanFileLightweight(fullPath);
142
+ files.push({
143
+ relPath,
144
+ ...statItem,
145
+ });
146
+ } else {
147
+ const skel = generateFileSkeleton(fullPath, { includeHeader: false });
148
+ files.push({
149
+ relPath,
150
+ ...skel,
151
+ });
152
+ }
1385
153
  } catch (_) {
1386
- // 跳过无法读取的文件
154
+ // 陷阱: 遇到无权限或损坏软链单文件时静默跳过,防止中断整个仓库目录树遍历
1387
155
  }
1388
156
  }
1389
157
  }
@@ -1392,13 +160,31 @@ function scanDirectorySkeleton(dirPath, options = {}) {
1392
160
  walk(root, 0);
1393
161
 
1394
162
  let totalLines = 0;
163
+ let totalChars = 0;
1395
164
  let totalRawTokens = 0;
1396
165
  let totalSkeletonTokens = 0;
1397
166
  for (const f of files) {
1398
167
  totalLines += f.totalLines;
168
+ totalChars += f.charCount;
1399
169
  totalRawTokens += f.rawTokens;
1400
- totalSkeletonTokens += f.skeletonTokens;
170
+ if (!isMap) {
171
+ totalSkeletonTokens += f.skeletonTokens;
172
+ }
1401
173
  }
174
+
175
+ if (isMap) {
176
+ return {
177
+ root,
178
+ depth: maxDepth,
179
+ map: true,
180
+ fileCount: files.length,
181
+ totalLines,
182
+ totalChars,
183
+ totalRawTokens,
184
+ files,
185
+ };
186
+ }
187
+
1402
188
  const totalSavedTokens = Math.max(0, totalRawTokens - totalSkeletonTokens);
1403
189
  const totalSavedPercent =
1404
190
  totalRawTokens > 0 ? Number(((totalSavedTokens / totalRawTokens) * 100).toFixed(1)) : 0;
@@ -1408,6 +194,7 @@ function scanDirectorySkeleton(dirPath, options = {}) {
1408
194
  depth: maxDepth,
1409
195
  fileCount: files.length,
1410
196
  totalLines,
197
+ totalChars,
1411
198
  totalRawTokens,
1412
199
  totalSkeletonTokens,
1413
200
  totalSavedTokens,
@@ -1416,27 +203,41 @@ function scanDirectorySkeleton(dirPath, options = {}) {
1416
203
  };
1417
204
  }
1418
205
 
1419
- /**
1420
- * 格式化目录骨架扫描结果为紧凑人类/模型可读文本
1421
- * @param {object} dirResult - scanDirectorySkeleton 的返回对象
1422
- * @param {object} [options]
1423
- * @param {number} [options.elapsedMs]
1424
- * @returns {string}
1425
- */
206
+ function formatDirectoryMap(dirResult, options = {}) {
207
+ const lines = [];
208
+ const elapsedPart =
209
+ typeof options.elapsedMs === 'number' ? `, 耗时 ${options.elapsedMs}ms` : '';
210
+ const totalChars = dirResult.totalChars ?? 0;
211
+
212
+ lines.push(
213
+ `目录地图: ${dirResult.root} (共 ${dirResult.fileCount} 个文件 | ${formatInt(dirResult.totalLines)} 行 | ${formatInt(totalChars)} 字 | 估算 ${formatInt(dirResult.totalRawTokens)} tokens${elapsedPart})`
214
+ );
215
+
216
+ for (const file of dirResult.files) {
217
+ const fileLines = file.lineCount ?? file.totalLines ?? 0;
218
+ const fileChars = file.charCount ?? file.rawChars ?? 0;
219
+ lines.push(`${file.relPath} (${fileLines} 行 | ${formatInt(fileChars)} 字)`);
220
+ }
221
+
222
+ return lines.join('\n');
223
+ }
224
+
1426
225
  function formatDirectorySkeleton(dirResult, options = {}) {
1427
226
  const lines = [];
1428
227
  const elapsedPart =
1429
228
  typeof options.elapsedMs === 'number' ? `, 耗时 ${options.elapsedMs}ms` : '';
229
+ const totalChars = dirResult.totalChars ?? 0;
1430
230
 
1431
231
  lines.push(`目录: ${dirResult.root} (深度 <= ${dirResult.depth})`);
1432
232
  lines.push(
1433
- `统计: 共 ${dirResult.fileCount} 个文件, ${dirResult.totalLines} 行 | 全文估算 ${dirResult.totalRawTokens} tokens → 骨架估算 ${dirResult.totalSkeletonTokens} tokens (节省 ${dirResult.totalSavedPercent}%${elapsedPart})`
233
+ `统计: 共 ${dirResult.fileCount} 个文件, ${dirResult.totalLines} 行 · ${formatInt(totalChars)} 字 | 全文估算 ${dirResult.totalRawTokens} tokens → 骨架估算 ${dirResult.totalSkeletonTokens} tokens (节省 ${dirResult.totalSavedPercent}%${elapsedPart})`
1434
234
  );
1435
235
 
1436
236
  for (const file of dirResult.files) {
237
+ const fileChars = file.charCount ?? file.rawChars ?? 0;
1437
238
  lines.push('');
1438
239
  lines.push(
1439
- `## ${file.relPath} (${file.totalLines} 行 | ${file.rawTokens} → ${file.skeletonTokens} tokens, -${file.savedPercent}%)`
240
+ `## ${file.relPath} (${file.totalLines} 行 | ${formatInt(fileChars)} 字 | ${file.rawTokens} → ${file.skeletonTokens} tokens, -${file.savedPercent}%)`
1440
241
  );
1441
242
  if (!file.items || file.items.length === 0) {
1442
243
  lines.push(' (无显式函数/类签名)');
@@ -1451,27 +252,45 @@ function formatDirectorySkeleton(dirResult, options = {}) {
1451
252
  return lines.join('\n');
1452
253
  }
1453
254
 
1454
- /**
1455
- * 自动识别文件或目录并生成语法骨架(统一编程入口)
1456
- * @param {string} targetPath
1457
- * @param {object} [options]
1458
- * @param {number} [options.depth=2]
1459
- * @param {boolean} [options.includeHeader=false]
1460
- * @returns {object}
1461
- */
255
+ function generateRepoMap(targetPath, options = {}) {
256
+ return generateSkeleton(targetPath, { ...options, map: true });
257
+ }
258
+
1462
259
  function generateSkeleton(targetPath, options = {}) {
1463
260
  const resolved = path.resolve(targetPath);
1464
261
  const stat = fs.statSync(resolved);
1465
262
  const t0 = performance.now();
263
+ const isMap = Boolean(options.map);
1466
264
 
1467
265
  if (stat.isFile()) {
266
+ if (isMap) {
267
+ const item = scanFileLightweight(resolved);
268
+ const relPath = path.basename(resolved);
269
+ const elapsedMs = Number((performance.now() - t0).toFixed(2));
270
+ const text = `${relPath} (${item.totalLines} 行 | ${formatInt(item.charCount)} 字)`;
271
+ return {
272
+ mode: 'map',
273
+ elapsedMs,
274
+ root: path.dirname(resolved),
275
+ depth: 0,
276
+ map: true,
277
+ fileCount: 1,
278
+ totalLines: item.totalLines,
279
+ totalChars: item.charCount,
280
+ totalRawTokens: item.rawTokens,
281
+ files: [{ relPath, ...item }],
282
+ formatted: text,
283
+ text,
284
+ };
285
+ }
286
+
1468
287
  const result = generateFileSkeleton(resolved, {
1469
288
  includeHeader: Boolean(options.includeHeader),
1470
289
  });
1471
290
  const elapsedMs = Number((performance.now() - t0).toFixed(2));
1472
291
  const text = [
1473
292
  `文件: ${result.filePath}`,
1474
- `统计: 总行数 ${result.totalLines} 行 | 全文估算 ${result.rawTokens} tokens → 骨架估算 ${result.skeletonTokens} tokens (节省 ${result.savedPercent}%, 耗时 ${elapsedMs}ms)`,
293
+ `统计: 总行数 ${result.totalLines} 行 · ${formatInt(result.charCount)} 字 | 全文估算 ${result.rawTokens} tokens → 骨架估算 ${result.skeletonTokens} tokens (节省 ${result.savedPercent}%, 耗时 ${elapsedMs}ms)`,
1475
294
  '---',
1476
295
  result.formatted,
1477
296
  ].join('\n');
@@ -1484,6 +303,19 @@ function generateSkeleton(targetPath, options = {}) {
1484
303
  }
1485
304
 
1486
305
  if (stat.isDirectory()) {
306
+ if (isMap) {
307
+ const result = scanDirectorySkeleton(resolved, { ...options, map: true });
308
+ const elapsedMs = Number((performance.now() - t0).toFixed(2));
309
+ const formatted = formatDirectoryMap(result, { elapsedMs });
310
+ return {
311
+ mode: 'map',
312
+ elapsedMs,
313
+ ...result,
314
+ formatted,
315
+ text: formatted,
316
+ };
317
+ }
318
+
1487
319
  const result = scanDirectorySkeleton(resolved, options);
1488
320
  const elapsedMs = Number((performance.now() - t0).toFixed(2));
1489
321
  const formatted = formatDirectorySkeleton(result, { elapsedMs });
@@ -1503,9 +335,12 @@ module.exports = {
1503
335
  IGNORED_DIRS,
1504
336
  SUPPORTED_EXTS,
1505
337
  estimateTokens,
338
+ scanFileLightweight,
1506
339
  generateFileSkeleton,
1507
340
  scanDirectorySkeleton,
1508
341
  formatSkeletonItems,
1509
342
  formatDirectorySkeleton,
343
+ formatDirectoryMap,
344
+ generateRepoMap,
1510
345
  generateSkeleton,
1511
346
  };