@deveco-test/deveco-cli-common 1.3.13-23.2 → 1.3.13-23.3

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.
@@ -3,7 +3,6 @@
3
3
 
4
4
  const path = require('path');
5
5
  const fs = require('fs');
6
- const { createRequire } = require('module');
7
6
 
8
7
  // --- Argument parsing ---
9
8
 
@@ -74,43 +73,6 @@ function findEtsLoader(devecoHome) {
74
73
  return null;
75
74
  }
76
75
 
77
- // Resolves `BuildProfile` per importer when set; see loadEtsChecker.
78
- let resolveBuildProfilePath;
79
-
80
- // BuildProfile is per-module, but one checker run resolves every module's
81
- // `import ... from 'BuildProfile'` through the same wildcard `paths` (issue
82
- // #688 1b). Wrap the SDK's own typescript `resolveModuleName` while loading the
83
- // checker so `BuildProfile` resolves against the importer's module instead.
84
- // The checker keeps the wrapped reference, reading resolveBuildProfilePath on
85
- // each call; the rest of the process keeps the original module.
86
- function loadEtsChecker(etsLoaderPath) {
87
- const checkerPath = path.join(etsLoaderPath, 'lib', 'ets_checker.js');
88
- if (require.cache[checkerPath]) return require(checkerPath);
89
-
90
- const sdkRequire = createRequire(checkerPath);
91
- const compilerPath = sdkRequire.resolve('typescript');
92
- const compiler = sdkRequire(compilerPath);
93
- const descriptors = Object.getOwnPropertyDescriptors(compiler);
94
- const resolveModuleName = compiler.resolveModuleName;
95
- descriptors.resolveModuleName = {
96
- enumerable: true,
97
- value(name, importer, options, host, ...rest) {
98
- const profile = name === 'BuildProfile' && resolveBuildProfilePath?.(importer);
99
- if (!profile) return resolveModuleName(name, importer, options, host, ...rest);
100
- return resolveModuleName(
101
- name, importer, { ...options, paths: { BuildProfile: [profile] } }, host, ...rest,
102
- );
103
- },
104
- };
105
- const compilerModule = require.cache[compilerPath];
106
- compilerModule.exports = Object.create(Object.getPrototypeOf(compiler), descriptors);
107
- try {
108
- return require(checkerPath);
109
- } finally {
110
- compilerModule.exports = compiler;
111
- }
112
- }
113
-
114
76
  // --- Collect .ets files from project ---
115
77
 
116
78
  function collectEtsFiles(projectPath) {
@@ -236,12 +198,6 @@ function computeEpoch(projectPath, devecoHome) {
236
198
  for (const abs of collectAmbientDeclarations(projectPath)) {
237
199
  parts.push(path.relative(projectPath, abs), fileHash(abs));
238
200
  }
239
- // Per-module BuildProfile is resolved by importer (loadEtsChecker), so a
240
- // regenerated profile changes a file's diagnostics without touching that file.
241
- for (const { genDir } of moduleDirEntries(projectPath)) {
242
- const profile = path.join(genDir, 'BuildProfile.ets');
243
- if (fs.existsSync(profile)) parts.push(path.relative(projectPath, profile), fileHash(profile));
244
- }
245
201
  return hashText(parts.join('\n'));
246
202
  }
247
203
 
@@ -406,191 +362,8 @@ const APP_RESOURCE_REF_RE = /\$r\(\s*['"]app\.([a-z]+)\.([A-Za-z0-9_]+)['"]\s*\)
406
362
  // so an unknown-name check does not apply to them here.
407
363
  const APP_RESOURCE_INDEXED_KINDS = new Set(['media', 'color', 'string', 'float', 'integer', 'boolean', 'intarray', 'strarray', 'pattern', 'plural', 'profile', 'symbol']);
408
364
 
409
- // Keywords after which a `/` begins a regex literal even though the preceding
410
- // char is an identifier char (computeCommentStringSpans).
411
- const REGEX_AFTER_KEYWORDS = new Set([
412
- 'return', 'typeof', 'case', 'in', 'of', 'new', 'delete', 'void',
413
- 'throw', 'do', 'else', 'instanceof', 'yield', 'await',
414
- ]);
415
-
416
- // End (exclusive) of a regex literal starting at `start`, or -1 when the slash
417
- // is division. A quote inside a regex (e.g. /'/) must not open a string span,
418
- // or every following $r('app.*') reference is masked (issue #710). `/` is
419
- // division when the preceding token can end an expression, unless that token
420
- // is a keyword (return /x/, typeof /x/) where a regex follows.
421
- function regexLiteralEnd(line, start) {
422
- let k = start - 1;
423
- while (k >= 0 && (line[k] === ' ' || line[k] === '\t')) k--;
424
- const prev = k >= 0 ? line[k] : '';
425
- let isRegex = !/[\w$)\]}]/.test(prev);
426
- if (!isRegex && /[A-Za-z$]/.test(prev)) {
427
- let w = k;
428
- while (w >= 0 && /[\w$]/.test(line[w])) w--;
429
- if (REGEX_AFTER_KEYWORDS.has(line.slice(w + 1, k + 1))) isRegex = true;
430
- }
431
- if (!isRegex) return -1;
432
- let j = start + 1;
433
- let inClass = false;
434
- for (; j < line.length; j++) {
435
- const c = line[j];
436
- if (c === '\\') { j++; continue; }
437
- if (c === '[') inClass = true;
438
- else if (c === ']') inClass = false;
439
- else if (c === '/' && !inClass) break;
440
- }
441
- if (j >= line.length) return -1;
442
- j++;
443
- while (j < line.length && /[a-z]/.test(line[j])) j++; // flags
444
- return j;
445
- }
446
-
447
- // Comment/string spans of one source line, for telling real `$r('app.*')`
448
- // calls from mere mentions in comments or string literals (issue #688).
449
- // `state.block` carries an unterminated `/*` block comment across lines;
450
- // `state.stringQuote` likewise carries an unterminated string/template across
451
- // lines (continuation lines stay string until the closing quote — multi-line
452
- // template `${}` is NOT re-opened as code, the same safe-direction miss as the
453
- // single-line interpolation skip).
454
- // Returns [{ start, end }] half-open spans; positions are preserved so
455
- // match indices stay valid against the original line.
456
- function computeCommentStringSpans(line, state) {
457
- const spans = [];
458
- const n = line.length;
459
- let i = 0;
460
- if (state.stringQuote) {
461
- let j = 0;
462
- while (j < n) {
463
- if (line[j] === '\\') { j += 2; continue; }
464
- if (line[j] === state.stringQuote) break;
465
- j++;
466
- }
467
- if (j >= n) { spans.push({ start: 0, end: n }); return spans; }
468
- spans.push({ start: 0, end: j + 1 });
469
- state.stringQuote = null;
470
- i = j + 1;
471
- }
472
- while (i < n) {
473
- if (state.block) {
474
- const end = line.indexOf('*/', i);
475
- if (end === -1) { spans.push({ start: i, end: n }); i = n; continue; }
476
- spans.push({ start: i, end: end + 2 });
477
- state.block = false;
478
- i = end + 2;
479
- continue;
480
- }
481
- const ch = line[i];
482
- const next = line[i + 1];
483
- if (ch === '/' && next === '/') { spans.push({ start: i, end: n }); break; }
484
- if (ch === '/' && next === '*') {
485
- const end = line.indexOf('*/', i + 2);
486
- if (end === -1) { spans.push({ start: i, end: n }); state.block = true; break; }
487
- spans.push({ start: i, end: end + 2 });
488
- i = end + 2;
489
- continue;
490
- }
491
- // Regex literals are skipped whole so their quotes cannot open a string
492
- // span (issue #710); -1 means this slash is division or unterminated.
493
- if (ch === '/') {
494
- const regexEnd = regexLiteralEnd(line, i);
495
- if (regexEnd > i) { i = regexEnd; continue; }
496
- }
497
- if (ch === "'" || ch === '"' || ch === '`') {
498
- const quote = ch;
499
- let j = i + 1;
500
- while (j < n) {
501
- if (line[j] === '\\') { j += 2; continue; }
502
- if (line[j] === quote) break;
503
- if (quote === '`' && line[j] === '$' && line[j + 1] === '{') {
504
- let depth = 1;
505
- j += 2;
506
- while (j < n && depth > 0) {
507
- if (line[j] === '{') depth++;
508
- else if (line[j] === '}') depth--;
509
- j++;
510
- }
511
- continue;
512
- }
513
- j++;
514
- }
515
- if (j >= n) {
516
- // Unterminated on this line: the string continues on the next line.
517
- spans.push({ start: i, end: n });
518
- state.stringQuote = quote;
519
- i = n;
520
- continue;
521
- }
522
- const end = j + 1;
523
- spans.push({ start: i, end });
524
- i = end;
525
- continue;
526
- }
527
- i++;
528
- }
529
- return spans;
530
- }
531
-
532
- // Collect the resource names of one module into `names`.
533
- function collectModuleResourceNames(modulePath, names) {
534
- const resourcesDir = path.join(modulePath, 'src', 'main', 'resources');
535
- let qualifiers;
536
- try {
537
- qualifiers = fs.readdirSync(resourcesDir, { withFileTypes: true }).filter((d) => d.isDirectory());
538
- } catch {
539
- return;
540
- }
541
-
542
- for (const qualifier of qualifiers) {
543
- const qualifierDir = path.join(resourcesDir, qualifier.name);
544
-
545
- // media/profile: the file's basename (minus extension) is the resource name.
546
- for (const kind of ['media', 'profile']) {
547
- const kindDir = path.join(qualifierDir, kind);
548
- let files;
549
- try { files = fs.readdirSync(kindDir); } catch { continue; }
550
- for (const file of files) {
551
- names.add(`${kind}.${file.replace(/\.[^.]+$/, '')}`);
552
- }
553
- }
554
-
555
- // element/*.json: {"color": [{"name": "primary", ...}], ...}
556
- const elementDir = path.join(qualifierDir, 'element');
557
- let elementFiles;
558
- try { elementFiles = fs.readdirSync(elementDir); } catch { continue; }
559
- for (const file of elementFiles) {
560
- if (!file.endsWith('.json')) continue;
561
- let parsed;
562
- try {
563
- parsed = JSON.parse(fs.readFileSync(path.join(elementDir, file), 'utf-8'));
564
- } catch {
565
- // A malformed element file is its own build error; skipping it here
566
- // only means we cannot vouch for names it would have defined, and the
567
- // unknown-name diagnostics below are suppressed for that kind.
568
- continue;
569
- }
570
- for (const [kind, entries] of Object.entries(parsed)) {
571
- if (!Array.isArray(entries)) continue;
572
- for (const entry of entries) {
573
- if (entry && typeof entry.name === 'string') names.add(`${kind}.${entry.name}`);
574
- }
575
- }
576
- }
577
- }
578
- }
579
-
580
365
  function loadAppResourceNames(projectPath) {
581
366
  const names = new Set();
582
-
583
- // Authoritative module list from build-profile.json5 first: modules can
584
- // nest (e.g. commons/lib_foundation), and the flat top-level scan below
585
- // never reaches their resources (issue #688).
586
- const declared = readProjectModules(projectPath).modules;
587
- if (declared.length > 0) {
588
- for (const mod of declared) {
589
- collectModuleResourceNames(path.resolve(projectPath, mod.srcPath), names);
590
- }
591
- return names;
592
- }
593
-
594
367
  let moduleDirs;
595
368
  try {
596
369
  moduleDirs = fs.readdirSync(projectPath, { withFileTypes: true }).filter((d) => d.isDirectory());
@@ -600,7 +373,50 @@ function loadAppResourceNames(projectPath) {
600
373
 
601
374
  for (const mod of moduleDirs) {
602
375
  if (mod.name === 'node_modules' || mod.name === 'oh_modules' || mod.name.startsWith('.')) continue;
603
- collectModuleResourceNames(path.join(projectPath, mod.name), names);
376
+ const resourcesDir = path.join(projectPath, mod.name, 'src', 'main', 'resources');
377
+ let qualifiers;
378
+ try {
379
+ qualifiers = fs.readdirSync(resourcesDir, { withFileTypes: true }).filter((d) => d.isDirectory());
380
+ } catch {
381
+ continue;
382
+ }
383
+
384
+ for (const qualifier of qualifiers) {
385
+ const qualifierDir = path.join(resourcesDir, qualifier.name);
386
+
387
+ // media/profile: the file's basename (minus extension) is the resource name.
388
+ for (const kind of ['media', 'profile']) {
389
+ const kindDir = path.join(qualifierDir, kind);
390
+ let files;
391
+ try { files = fs.readdirSync(kindDir); } catch { continue; }
392
+ for (const file of files) {
393
+ names.add(`${kind}.${file.replace(/\.[^.]+$/, '')}`);
394
+ }
395
+ }
396
+
397
+ // element/*.json: {"color": [{"name": "primary", ...}], ...}
398
+ const elementDir = path.join(qualifierDir, 'element');
399
+ let elementFiles;
400
+ try { elementFiles = fs.readdirSync(elementDir); } catch { continue; }
401
+ for (const file of elementFiles) {
402
+ if (!file.endsWith('.json')) continue;
403
+ let parsed;
404
+ try {
405
+ parsed = JSON.parse(fs.readFileSync(path.join(elementDir, file), 'utf-8'));
406
+ } catch {
407
+ // A malformed element file is its own build error; skipping it here
408
+ // only means we cannot vouch for names it would have defined, and the
409
+ // unknown-name diagnostics below are suppressed for that kind.
410
+ continue;
411
+ }
412
+ for (const [kind, entries] of Object.entries(parsed)) {
413
+ if (!Array.isArray(entries)) continue;
414
+ for (const entry of entries) {
415
+ if (entry && typeof entry.name === 'string') names.add(`${kind}.${entry.name}`);
416
+ }
417
+ }
418
+ }
419
+ }
604
420
  }
605
421
  return names;
606
422
  }
@@ -623,15 +439,10 @@ function validateAppResources(files, projectPath) {
623
439
  try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
624
440
  const relFile = path.relative(projectPath, filePath);
625
441
  const fileLines = content.split('\n');
626
- const commentState = { block: false, stringQuote: null };
627
442
  for (let i = 0; i < fileLines.length; i++) {
628
- const spans = computeCommentStringSpans(fileLines[i], commentState);
629
443
  let match;
630
444
  APP_RESOURCE_REF_RE.lastIndex = 0;
631
445
  while ((match = APP_RESOURCE_REF_RE.exec(fileLines[i])) !== null) {
632
- // A `$r('app.*')` mention inside a comment or another string literal
633
- // is not a real reference — only validate calls in actual code.
634
- if (spans.some((s) => match.index >= s.start && match.index < s.end)) continue;
635
446
  const kind = match[1];
636
447
  const resName = match[2];
637
448
  if (!APP_RESOURCE_INDEXED_KINDS.has(kind)) continue;
@@ -1075,16 +886,14 @@ function validateComponentDecorators(files, projectPath) {
1075
886
  // decorator vs. its OWN struct's decorator), this needs real cross-file
1076
887
  // resolution — the property's decorator lives in the component file, but the
1077
888
  // referenced type's @ObservedV2 decorator often lives in a different model
1078
- // file entirely. Implemented in two passes over the whole project file set:
1079
- // 1) index every top-level class with its decorator set, per file
889
+ // file entirely. Implemented as two passes over the whole project file set:
890
+ // 1) index every top-level class decorated with @ObservedV2, by name
1080
891
  // 2) flag every @State/@Prop/@Provide/@Consume property whose simple type
1081
- // resolves — via imports, aliases and re-export chains — to a class that
1082
- // is decorated @ObservedV2
1083
- // A usage whose type origin cannot be resolved (bare package or ambient
1084
- // import) falls back to the conservative global name index, so genuinely V2
1085
- // types keep being detected. Name-only matching is not enough: two
1086
- // same-named classes in different files, only one of them @ObservedV2, are
1087
- // common once pages and models split (issue #688).
892
+ // annotation matches a name in that index
893
+ // Deliberately name-keyed (no module/import resolution): two same-named
894
+ // classes in different files where only one is @ObservedV2 would be a false
895
+ // negative, but that pattern does not occur in generated ArkTS and a real
896
+ // symbol table is out of scope for this lightweight heuristic.
1088
897
  const V1_TYPE_SENSITIVE_DECORATORS = new Set(['State', 'Prop', 'Provide', 'Consume']);
1089
898
 
1090
899
  const CLASS_DECL_RE = /^(\s*)((?:@\w+(?:\([^)]*\))?\s*)*)(?:export\s+(?:default\s+)?)?class\s+(\w+)\b/;
@@ -1126,209 +935,22 @@ const SDK_OBSERVED_V2_CLASSES = new Set();
1126
935
  // false positive on a file the caller did not ask about.
1127
936
  function collectObservedV2ClassNames(files, projectPath) {
1128
937
  const names = new Set(SDK_OBSERVED_V2_CLASSES);
1129
- const index = buildProjectClassIndex(files, projectPath);
1130
- for (const perFile of index.values()) {
1131
- for (const [name, entry] of perFile) {
1132
- if (entry.decorators.has('ObservedV2')) names.add(name);
1133
- }
1134
- }
1135
- return names;
1136
- }
1137
-
1138
- // --- Import-aware class origin resolution (issue #688) ---
1139
- //
1140
- // Same-named classes in different files must not be decided by a global name
1141
- // set: `@Provide model: Model` is only a violation when the Model IMPORTED at
1142
- // that usage site is the @ObservedV2 one. These helpers follow a file's
1143
- // named/default imports and `export ... from` re-export chains (aliases
1144
- // included) to the declaring file, then read that class's decorators. Bare
1145
- // package or unresolvable specifiers yield null and callers fall back to the
1146
- // conservative global name set.
1147
-
1148
- // classIndexCache: projectPath -> Map(absFile -> Map(className -> { decorators, isDefault })).
1149
- // Cached per project like projectEtsFileCache; cleared per request in serve mode.
1150
- const classIndexCache = new Map();
1151
-
1152
- function buildProjectClassIndex(files, projectPath) {
1153
- const cached = projectPath ? classIndexCache.get(projectPath) : null;
1154
- if (cached) return cached;
1155
938
  const declarationFiles = projectPath ? unionProjectFiles(files, projectPath) : files;
1156
- const index = new Map();
1157
939
  for (const filePath of declarationFiles) {
1158
940
  let content;
1159
941
  try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
1160
942
  const lines = content.split('\n');
1161
- const perFile = new Map();
1162
943
  for (let i = 0; i < lines.length; i++) {
1163
944
  const m = CLASS_DECL_RE.exec(lines[i]);
1164
945
  if (!m) continue;
1165
946
  const decorators = collectStructDecorators(lines, i, m[2]);
1166
- perFile.set(m[3], { decorators, isDefault: /export\s+default\s+class\b/.test(lines[i]) });
1167
- }
1168
- index.set(path.resolve(filePath), perFile);
1169
- }
1170
- if (projectPath) classIndexCache.set(projectPath, index);
1171
- return index;
1172
- }
1173
-
1174
- // fileImportCache: absFile -> Map(localName -> { spec, remote }); remote is
1175
- // the name exported by the target module ('*default*' for default imports).
1176
- // Plain imports and `export ... from` re-exports both land here, so barrel
1177
- // files resolve transparently.
1178
- const fileImportCache = new Map();
1179
-
1180
- const FROM_CLAUSE_RE = /(?:^|\n)[ \t]*(?:import|export)[ \t]+(?:type[ \t]+)?([\s\S]*?)[ \t]*from[ \t]*['"]([^'"]+)['"]/g;
1181
-
1182
- // Flags every offset that lies inside a comment or string span, so callers can
1183
- // reject a regex match whose start is not real code — a `from` inside a
1184
- // comment or string would otherwise bind a fake local name and shadow the true
1185
- // import of the same name (issue #710). The import specifier itself is a
1186
- // string span, but the match starts at `import`/`export`, outside it.
1187
- function maskedOffsets(content) {
1188
- const state = { block: false };
1189
- const flags = new Uint8Array(content.length);
1190
- let offset = 0;
1191
- for (const line of content.split('\n')) {
1192
- for (const s of computeCommentStringSpans(line, state)) {
1193
- flags.fill(1, offset + s.start, offset + s.end);
1194
- }
1195
- offset += line.length + 1;
1196
- }
1197
- return flags;
1198
- }
1199
-
1200
- // Start offset of the leading `import`/`export` keyword in a FROM_CLAUSE_RE
1201
- // match. The match itself begins at the preceding newline, which is outside
1202
- // any span even when the keyword line sits inside a multi-line string.
1203
- function clauseKeywordOffset(m) {
1204
- return m.index + m[0].search(/import|export/);
1205
- }
1206
-
1207
- function getFileBindings(absFile) {
1208
- const cached = fileImportCache.get(absFile);
1209
- if (cached) return cached;
1210
- const bindings = new Map();
1211
- let content;
1212
- try {
1213
- content = fs.readFileSync(absFile, 'utf-8');
1214
- } catch {
1215
- fileImportCache.set(absFile, bindings);
1216
- return bindings;
1217
- }
1218
- const masked = maskedOffsets(content);
1219
- FROM_CLAUSE_RE.lastIndex = 0;
1220
- for (;;) {
1221
- const m = FROM_CLAUSE_RE.exec(content);
1222
- if (!m) break;
1223
- if (masked[clauseKeywordOffset(m)]) continue;
1224
- const clause = m[1];
1225
- const spec = m[2];
1226
- const brace = /\{([^}]*)\}/.exec(clause);
1227
- if (brace) {
1228
- for (const part of brace[1].split(',')) {
1229
- // `import { type Foo }` — strip the type-only marker before matching.
1230
- const p = part.trim().replace(/^type[ \t]+/, '');
1231
- if (!p) continue;
1232
- const b = /^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/.exec(p);
1233
- if (b) bindings.set(b[2] || b[1], { spec, remote: b[1] });
1234
- }
1235
- }
1236
- const head = clause
1237
- .replace(/\{[^}]*\}/, '')
1238
- .replace(/^\*\s+as\s+[A-Za-z_$][\w$]*$/, '')
1239
- .replace(/,\s*$/, '')
1240
- .trim();
1241
- const dm = /^([A-Za-z_$][\w$]*)$/.exec(head);
1242
- if (dm) bindings.set(dm[1], { spec, remote: '*default*' });
1243
- }
1244
- fileImportCache.set(absFile, bindings);
1245
- return bindings;
1246
- }
1247
-
1248
- // fileStarExportCache: absFile -> string[] of `export * from` specifiers. Star
1249
- // re-exports bind no local name, so getFileBindings cannot see them; origin
1250
- // resolution walks these explicitly.
1251
- const fileStarExportCache = new Map();
1252
-
1253
- const STAR_EXPORT_RE = /(?:^|\n)[ \t]*export[ \t]+\*[ \t]*from[ \t]*['"]([^'"]+)['"]/g;
1254
-
1255
- function getFileStarExports(absFile) {
1256
- const cached = fileStarExportCache.get(absFile);
1257
- if (cached) return cached;
1258
- const specs = [];
1259
- let content;
1260
- try {
1261
- content = fs.readFileSync(absFile, 'utf-8');
1262
- } catch {
1263
- fileStarExportCache.set(absFile, specs);
1264
- return specs;
1265
- }
1266
- const masked = maskedOffsets(content);
1267
- STAR_EXPORT_RE.lastIndex = 0;
1268
- for (;;) {
1269
- const m = STAR_EXPORT_RE.exec(content);
1270
- if (!m) break;
1271
- if (masked[clauseKeywordOffset(m)]) continue;
1272
- specs.push(m[1]);
1273
- }
1274
- fileStarExportCache.set(absFile, specs);
1275
- return specs;
1276
- }
1277
-
1278
- function resolveClassOrigin(absFile, typeName, classIndex, visited) {
1279
- if (!visited) visited = new Set();
1280
- const step = absFile + '::' + typeName;
1281
- if (visited.has(step) || visited.size >= 16) return null;
1282
- visited.add(step);
1283
- const binding = getFileBindings(absFile).get(typeName);
1284
- if (!binding) {
1285
- // No direct binding: the name may arrive via `export * from` — check each
1286
- // star-exported module for the declaration, then follow its star chains.
1287
- for (const spec of getFileStarExports(absFile)) {
1288
- const target = resolveClosureDependency(absFile, spec);
1289
- if (!target) continue;
1290
- const targetAbs = path.resolve(target);
1291
- const perFile = classIndex.get(targetAbs);
1292
- if (perFile && perFile.has(typeName)) return { file: targetAbs, name: typeName };
1293
- const found = resolveClassOrigin(targetAbs, typeName, classIndex, visited);
1294
- if (found) return found;
947
+ if (decorators.has('ObservedV2')) names.add(m[3]);
1295
948
  }
1296
- return null;
1297
- }
1298
- const target = resolveClosureDependency(absFile, binding.spec);
1299
- if (!target) return null;
1300
- const targetAbs = path.resolve(target);
1301
- const perFile = classIndex.get(targetAbs);
1302
- if (!perFile) return null; // target outside the indexed project sources
1303
- // `import X from` records '*default*'; `export { default as X } from` and
1304
- // `import { default as X } from` record remote 'default' — both mean the
1305
- // target module's default export (issue #710).
1306
- if (binding.remote === '*default*' || binding.remote === 'default') {
1307
- for (const [name, entry] of perFile) {
1308
- if (entry.isDefault) return { file: targetAbs, name };
1309
- }
1310
- return null;
1311
949
  }
1312
- if (perFile.has(binding.remote)) return { file: targetAbs, name: binding.remote };
1313
- // Not declared here (indirect barrel): follow the re-export chain onward.
1314
- return resolveClassOrigin(targetAbs, binding.remote, classIndex, visited);
1315
- }
1316
-
1317
- // Verdict for one usage site (`@X prop: Type`, `new Type(...)`,
1318
- // `AppStorage.setOrCreate<Type>`): resolve, then read the resolved class's
1319
- // decorators; fall back to the global name set when unresolvable.
1320
- function isObservedV2Usage(absFile, typeName, classIndex, fallbackNames) {
1321
- if (!typeName) return false;
1322
- const origin = resolveClassOrigin(absFile, typeName, classIndex);
1323
- if (origin) {
1324
- const entry = classIndex.get(origin.file)?.get(origin.name);
1325
- return !!entry && entry.decorators.has('ObservedV2');
1326
- }
1327
- return fallbackNames.has(typeName);
950
+ return names;
1328
951
  }
1329
952
 
1330
953
  function validateObservedV2PropertyTypes(files, projectPath) {
1331
- const classIndex = buildProjectClassIndex(files, projectPath);
1332
954
  const observedV2Classes = collectObservedV2ClassNames(files, projectPath);
1333
955
  if (observedV2Classes.size === 0) return [];
1334
956
 
@@ -1338,13 +960,12 @@ function validateObservedV2PropertyTypes(files, projectPath) {
1338
960
  try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
1339
961
  const lines = content.split('\n');
1340
962
  const relFile = path.relative(projectPath, filePath);
1341
- const absFile = path.resolve(filePath);
1342
963
  for (let i = 0; i < lines.length; i++) {
1343
964
  const m = STATE_PROPERTY_TYPE_RE.exec(lines[i]);
1344
965
  if (!m) continue;
1345
966
  const decoratorName = m[1];
1346
967
  const typeName = m[2];
1347
- if (!isObservedV2Usage(absFile, typeName, classIndex, observedV2Classes)) continue;
968
+ if (!observedV2Classes.has(typeName)) continue;
1348
969
  diagnostics.push({
1349
970
  file: relFile,
1350
971
  line: i + 1,
@@ -2276,7 +1897,6 @@ function validateAppStorageV2Mixing(files, projectPath) {
2276
1897
  // exactly what this index holds while SDK_OBSERVED_V2_CLASSES stays empty. If a
2277
1898
  // name is ever seeded there, re-check whether it also crashes AppStorage before
2278
1899
  // letting it reach this rule.
2279
- const classIndex = buildProjectClassIndex(files, projectPath);
2280
1900
  const observedV2Classes = collectObservedV2ClassNames(files, projectPath);
2281
1901
  if (observedV2Classes.size === 0) return [];
2282
1902
 
@@ -2286,7 +1906,6 @@ function validateAppStorageV2Mixing(files, projectPath) {
2286
1906
  try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
2287
1907
  const lines = content.split('\n');
2288
1908
  const relFile = path.relative(projectPath, filePath);
2289
- const absFile = path.resolve(filePath);
2290
1909
 
2291
1910
  // Local `name: Type` declarations, so a bare `this.viewModel` argument can
2292
1911
  // be resolved back to its @ObservedV2 class.
@@ -2306,11 +1925,9 @@ function validateAppStorageV2Mixing(files, projectPath) {
2306
1925
  const argName = /^(?:this\s*\.\s*)?([A-Za-z_$][\w$]*)$/.exec(argExpr);
2307
1926
  const newed = /^new\s+([A-Za-z_$][\w$]*)/.exec(argExpr);
2308
1927
  const resolved =
2309
- (explicit && isObservedV2Usage(absFile, explicit, classIndex, observedV2Classes) && explicit) ||
2310
- (newed && isObservedV2Usage(absFile, newed[1], classIndex, observedV2Classes) && newed[1]) ||
2311
- (argName &&
2312
- isObservedV2Usage(absFile, declaredTypes.get(argName[1]), classIndex, observedV2Classes) &&
2313
- declaredTypes.get(argName[1]));
1928
+ (explicit && observedV2Classes.has(explicit) && explicit) ||
1929
+ (newed && observedV2Classes.has(newed[1]) && newed[1]) ||
1930
+ (argName && observedV2Classes.has(declaredTypes.get(argName[1])) && declaredTypes.get(argName[1]));
2314
1931
  if (!resolved) continue;
2315
1932
 
2316
1933
  diagnostics.push({
@@ -2703,17 +2320,9 @@ const STATE_DECORATORS = [
2703
2320
 
2704
2321
  // State-field decorator matcher. Compiled once at module load (the pattern is
2705
2322
  // built from the constant STATE_DECORATORS) instead of on every call. It carries
2706
- // the global flag, so reset lastIndex before each reuse. Between the state
2707
- // decorator and the field name it tolerates stacked decorators (e.g.
2708
- // `@Watch('onChanged')`) and access modifiers (`private`/`public`/`protected`/
2709
- // `static`/`readonly`) — `@State private visible` must yield `visible`, not
2710
- // `private`, and `@State @Watch('cb') selected` must yield `selected`, not
2711
- // nothing.
2323
+ // the global flag, so reset lastIndex before each reuse.
2712
2324
  const STATE_FIELD_RE = new RegExp(
2713
- '@(?:' + STATE_DECORATORS.join('|') + ')(?:\\([^)]*\\))?' +
2714
- '(?:\\s+@\\w+(?:\\([^)]*\\))?)*' +
2715
- '(?:\\s+(?:private|public|protected|static|readonly))*' +
2716
- '\\s+([A-Za-z_$][\\w$]*)',
2325
+ '@(?:' + STATE_DECORATORS.join('|') + ')(?:\\([^)]*\\))?\\s+([A-Za-z_$][\\w$]*)',
2717
2326
  'g',
2718
2327
  );
2719
2328
 
@@ -3289,23 +2898,6 @@ function buildProfileNotBuiltHint(projectPath) {
3289
2898
 
3290
2899
  const resolveModulePathsCache = new Map();
3291
2900
 
3292
- // One place that derives a declared module's on-disk dirs; both
3293
- // collectResolveModulePaths and groupFilesByModule compose their path lists
3294
- // from these entries (issue #710 P3). genDir is exactly hvigor's
3295
- // buildGeneratedProfilePath shape; a missing dir is simply not added —
3296
- // runCheck then attaches buildProfileNotBuiltHint to the diagnostic.
3297
- function moduleDirEntries(projectPath) {
3298
- const { productName, modules } = readProjectModules(projectPath);
3299
- return modules.map((m) => {
3300
- const modulePath = path.resolve(projectPath, m.srcPath);
3301
- return {
3302
- modulePath,
3303
- srcMain: path.join(modulePath, 'src', 'main'),
3304
- genDir: path.join(modulePath, 'build', productName, 'generated', 'profile', m.target),
3305
- };
3306
- });
3307
- }
3308
-
3309
2901
  function collectResolveModulePaths(projectPath) {
3310
2902
  const cached = resolveModulePathsCache.get(projectPath);
3311
2903
  if (cached) return cached;
@@ -3322,11 +2914,15 @@ function collectResolveModulePaths(projectPath) {
3322
2914
  } catch { /* ignore */ }
3323
2915
  };
3324
2916
 
3325
- const entries = moduleDirEntries(projectPath);
3326
- if (entries.length > 0) {
3327
- for (const e of entries) {
3328
- push(e.srcMain);
3329
- push(e.genDir);
2917
+ const { productName, modules } = readProjectModules(projectPath);
2918
+ if (modules.length > 0) {
2919
+ for (const m of modules) {
2920
+ const modulePath = path.resolve(projectPath, m.srcPath);
2921
+ push(path.join(modulePath, 'src', 'main'));
2922
+ // Exactly hvigor's buildGeneratedProfilePath shape. A missing dir (module
2923
+ // not built for this product yet) is simply not added — runCheck then
2924
+ // attaches buildProfileNotBuiltHint to the resulting diagnostic.
2925
+ push(path.join(modulePath, 'build', productName, 'generated', 'profile', m.target));
3330
2926
  }
3331
2927
  } else {
3332
2928
  // No declared modules (minimal or unparseable profile): fall back to
@@ -3382,160 +2978,6 @@ function findModuleSrcMainOnDisk(projectPath, push) {
3382
2978
  walkBuildGenerated(projectPath);
3383
2979
  }
3384
2980
 
3385
- // Modules may import their own sources through the package name declared in the
3386
- // module's oh-package.json5 (`import { Item } from '@sample/widget/ets/model/Item'`).
3387
- // hvigor maps that name back to the module itself; the standalone checker has no
3388
- // such mapping, and the SDK's wildcard `paths: {"*": [...]}` only tries each
3389
- // resolveModulePaths entry as a literal prefix, so the import would resolve to
3390
- // <module>/src/main/@sample/widget/... and fail. Mirror each declared package
3391
- // name to the module's src/main via a link under .cache/arkts-check-pkgs and add
3392
- // that dir to resolveModulePaths — the wildcard then maps the package specifier
3393
- // to the real sources. Links share the checker cache's lifecycle and are removed
3394
- // together with it, so nothing lingers in the project (issue #688).
3395
- const SELF_PACKAGE_NAME_RE = /^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/i;
3396
-
3397
- function collectSelfPackageRoots(projectPath) {
3398
- const { modules } = readProjectModules(projectPath);
3399
- const roots = [];
3400
- const seen = new Set();
3401
- for (const m of modules) {
3402
- const modulePath = path.resolve(projectPath, m.srcPath);
3403
- const srcMain = path.join(modulePath, 'src', 'main');
3404
- let name = null;
3405
- try {
3406
- const parsed = parseJson5Loose(fs.readFileSync(path.join(modulePath, 'oh-package.json5'), 'utf-8'));
3407
- if (parsed && typeof parsed.name === 'string') name = parsed.name.trim();
3408
- } catch { /* no readable package name: nothing to mirror */ }
3409
- if (!name || !SELF_PACKAGE_NAME_RE.test(name) || seen.has(name)) continue;
3410
- if (!fs.existsSync(srcMain)) continue;
3411
- seen.add(name);
3412
- roots.push({ name, srcMain });
3413
- }
3414
- return roots;
3415
- }
3416
-
3417
- function sameLinkTarget(linkPath, target) {
3418
- let resolved;
3419
- try { resolved = path.resolve(path.dirname(linkPath), fs.readlinkSync(linkPath)); } catch { return false; }
3420
- return process.platform === 'win32'
3421
- ? resolved.toLowerCase() === target.toLowerCase()
3422
- : resolved === target;
3423
- }
3424
-
3425
- // Per-process exclusive mirror dir name under <project>/.cache. A fixed name
3426
- // would clash with — and be recursively deleted by cleanup alongside — any
3427
- // real directory already sitting there; cleanup removes only the dir this
3428
- // process actually created (issue #710 P1). Lazily created once per process
3429
- // and reset after cleanup, so repeated checks in one --serve process each get
3430
- // a fresh dir.
3431
- let cachedSelfPkgMirrorDirName = null;
3432
-
3433
- function selfPkgMirrorDirName() {
3434
- if (!cachedSelfPkgMirrorDirName) {
3435
- cachedSelfPkgMirrorDirName = `arkts-check-pkgs-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
3436
- }
3437
- return cachedSelfPkgMirrorDirName;
3438
- }
3439
-
3440
- // Idempotent: re-running against an up-to-date mirror only stats links. Returns
3441
- // the mirror dir, or null when no module declares a package name.
3442
- function ensureSelfPackageMirror(projectPath) {
3443
- const roots = collectSelfPackageRoots(projectPath);
3444
- if (roots.length === 0) return null;
3445
- const mirrorDir = path.join(projectPath, '.cache', selfPkgMirrorDirName());
3446
- for (const { name, srcMain } of roots) {
3447
- const linkPath = path.join(mirrorDir, ...name.split('/'));
3448
- if (sameLinkTarget(linkPath, srcMain)) continue;
3449
- try {
3450
- // 只清理链接/普通文件;linkPath 若是真实目录则保留——rmSync 会递归删除
3451
- // 真实内容(symlinkSync 随后因 EEXIST 失败,导入保持未解析诊断,方向安全)。
3452
- const st = fs.lstatSync(linkPath);
3453
- if (st.isSymbolicLink() || !st.isDirectory()) {
3454
- fs.rmSync(linkPath, { recursive: true, force: true });
3455
- }
3456
- } catch { /* best-effort(不存在时无需清理) */ }
3457
- try {
3458
- fs.mkdirSync(path.dirname(linkPath), { recursive: true });
3459
- // Junctions need no elevated rights on Windows, unlike file symlinks.
3460
- fs.symlinkSync(srcMain, linkPath, process.platform === 'win32' ? 'junction' : 'dir');
3461
- } catch { /* best-effort: the import stays an unresolved diagnostic */ }
3462
- }
3463
- return mirrorDir;
3464
- }
3465
-
3466
- function isSubPath(parent, child) {
3467
- const rel = path.relative(parent, child);
3468
- return rel === '' || (!!rel && !rel.startsWith('..') && !path.isAbsolute(rel));
3469
- }
3470
-
3471
- // BuildProfile and other generated-profile classes are per-module, but
3472
- // collectResolveModulePaths returns one flat list, so a single checker run lets
3473
- // the SDK's wildcard `paths` resolve one module's generated class against
3474
- // another module's copy (issue #688 1b). Group `files` by owning module so each
3475
- // run sees that module's own generated profile dir — mirroring hvigor, which
3476
- // compiles every module with only its own dirs. Every module's src/main stays
3477
- // in each group's paths (they contain no generated classes), so cross-module
3478
- // source imports keep resolving as before. Files under no declared module keep
3479
- // the global list. `resolveModulePaths: null` means "use the global list".
3480
- function groupFilesByModule(files, projectPath) {
3481
- const declared = moduleDirEntries(projectPath)
3482
- .filter((e) => fs.existsSync(e.srcMain))
3483
- .sort((a, b) => b.modulePath.length - a.modulePath.length);
3484
- if (declared.length === 0) return [{ files, resolveModulePaths: null, modulePath: null }];
3485
-
3486
- const globalSrcMains = declared.map((e) => e.srcMain);
3487
- // 只有一个模块存在 generated profile 目录时,全局 resolveModulePaths 里最多
3488
- // 一个 BuildProfile,不存在跨模块串扰;保持单次全局运行,避免 N 个模块 N 次
3489
- // checker 冷启动(SDK 类型图每组重建,大工程明显变慢)。
3490
- if (declared.filter((e) => fs.existsSync(e.genDir)).length <= 1) {
3491
- return [{ files, resolveModulePaths: null, modulePath: null }];
3492
- }
3493
- const groups = [];
3494
- const byModulePath = new Map();
3495
- const rest = [];
3496
- for (const f of files) {
3497
- const abs = path.resolve(f);
3498
- const owner = declared.find((e) => isSubPath(e.modulePath, abs));
3499
- if (!owner) { rest.push(f); continue; }
3500
- if (!byModulePath.has(owner.modulePath)) {
3501
- const entry = { modulePath: owner.modulePath, files: [] };
3502
- byModulePath.set(owner.modulePath, entry);
3503
- groups.push(entry);
3504
- }
3505
- byModulePath.get(owner.modulePath).files.push(f);
3506
- }
3507
-
3508
- const result = groups.map(({ modulePath, files: groupFiles }) => ({
3509
- files: groupFiles,
3510
- modulePath,
3511
- resolveModulePaths: [
3512
- ...globalSrcMains,
3513
- declared.find((e) => e.modulePath === modulePath).genDir,
3514
- ].filter((p) => fs.existsSync(p)),
3515
- }));
3516
- // A rest file belongs to no declared module, so no module's generated
3517
- // profile is authoritative for it. Handing it the flat global list would
3518
- // push every module's BuildProfile back into one run and let the cross-talk
3519
- // the gate above just avoided leak back in through the rest group.
3520
- if (rest.length > 0) result.push({ files: rest, resolveModulePaths: globalSrcMains, modulePath: null });
3521
- return result;
3522
- }
3523
-
3524
- // Whether a diagnostic on absFile may be reported by the groupIndex run.
3525
- // Checked files report only from their owning group. A file owned by another
3526
- // declared module — pulled into this group's program as an import dependency,
3527
- // where the SDK type-checks it under THIS module's BuildProfile — is the wrong
3528
- // context (issue #688/#710), so it never reports here; its own module's group
3529
- // run reports it instead. Files under no declared module (external deps) keep
3530
- // the legacy report-everything behavior.
3531
- function shouldReportDiagnostic(absFile, groupIndex, groups, declaredModulePaths, diagOwner) {
3532
- const owner = diagOwner.get(absFile);
3533
- if (owner !== undefined) return owner === groupIndex;
3534
- const ownerModule = declaredModulePaths.find((mp) => isSubPath(mp, absFile));
3535
- if (!ownerModule) return true;
3536
- return groups[groupIndex].modulePath === ownerModule;
3537
- }
3538
-
3539
2981
  // Project-level diagnostics read only immutable config/SDK files (module.json5,
3540
2982
  // main_pages.json, hvigor-config.json5, PermissionDefinitions.json, string.json,
3541
2983
  // resources/*/{media,profile,element}) plus a scan of `files` and — for the
@@ -3586,12 +3028,6 @@ function computeProjectDiagnostics(files, env, hasExplicitFiles) {
3586
3028
  function cleanupCheckerCache(projectPath) {
3587
3029
  const cachePath = path.join(projectPath, '.cache', 'arkts-check');
3588
3030
  try { fs.rmSync(cachePath, { recursive: true, force: true }); } catch { /* best-effort */ }
3589
- // Only the mirror dir created by this process is removed — never the fixed
3590
- // .cache/arkts-check-pkgs path, which may hold user content (#710 P1).
3591
- if (cachedSelfPkgMirrorDirName) {
3592
- try { fs.rmSync(path.join(projectPath, '.cache', cachedSelfPkgMirrorDirName), { recursive: true, force: true }); } catch { /* best-effort */ }
3593
- cachedSelfPkgMirrorDirName = null;
3594
- }
3595
3031
  // `.cache` 可能被其它工具使用,仅在为空时移除。
3596
3032
  try {
3597
3033
  const parent = path.dirname(cachePath);
@@ -3599,49 +3035,16 @@ function cleanupCheckerCache(projectPath) {
3599
3035
  } catch { /* best-effort */ }
3600
3036
  }
3601
3037
 
3602
- // Diagnostics can be attributed to a file the checker reached through the
3603
- // self-package mirror (a wildcard-paths resolution of `@scope/name/...`), in
3604
- // which case the reported path lives under .cache/arkts-check-pkgs and is
3605
- // deleted with the mirror when the run ends. Map such a path back to the real
3606
- // module source file so reported paths stay navigable. Returns null when the
3607
- // path is not under any mirrored package.
3608
- function remapMirrorDiagnosticPath(absFile, mirrorDir, pkgRoots) {
3609
- if (!absFile || !path.isAbsolute(absFile)) return null;
3610
- for (const { name, srcMain } of pkgRoots) {
3611
- const linkPath = path.join(mirrorDir, ...name.split('/'));
3612
- const rel = path.relative(linkPath, absFile);
3613
- if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
3614
- return path.join(srcMain, rel);
3615
- }
3616
- }
3617
- return null;
3618
- }
3619
-
3620
- // Generated-profile specifier target for the module owning `importer`, or null
3621
- // to keep the default resolution. Modules are expected deepest-first so a
3622
- // nested module wins over its parent. A module without a generated profile
3623
- // returns null: leave the missing import to the checker's own diagnostic.
3624
- function buildProfilePathFor(importer, modules, selfPkgMirror, mirrorPkgRoots) {
3625
- if (!importer || !path.isAbsolute(importer) || modules.length === 0) return null;
3626
- const source = selfPkgMirror
3627
- ? remapMirrorDiagnosticPath(importer, selfPkgMirror, mirrorPkgRoots) || importer
3628
- : importer;
3629
- const owner = modules.find(({ modulePath }) => isSubPath(modulePath, source));
3630
- if (!owner) return null;
3631
- const profile = path.join(owner.genDir, 'BuildProfile');
3632
- return fs.existsSync(profile + '.ets') ? profile : null;
3633
- }
3634
-
3635
3038
  function runChecker(files, env) {
3636
3039
  const { devecoHome, etsLoaderPath, projectPath, aceModuleJsonPath } = env;
3637
3040
  // Carried on env when runCheck computed it (one profile read per request);
3638
3041
  // read here so runChecker stays usable standalone, as in tests.
3639
3042
  const sdkConfig = env.sdkConfig || readProjectSdkConfig(projectPath, env.devecoHome);
3640
3043
 
3044
+ const fileMap = {};
3045
+ files.forEach((f, i) => { fileMap[`file_${i}`] = f; });
3046
+
3641
3047
  const captured = [];
3642
- // Function scope: filled inside the try block, appended to after it (project
3643
- // diagnostics) and returned, so it must outlive the try/catch/finally.
3644
- const diagnostics = [];
3645
3048
  let checkerFailure;
3646
3049
  const origLog = console.log;
3647
3050
  const origError = console.error;
@@ -3651,16 +3054,6 @@ function runChecker(files, env) {
3651
3054
  console.error = capture;
3652
3055
  console.warn = capture;
3653
3056
 
3654
- // runChecker mutates process.env for the SDK checker. A --serve process serves
3655
- // many requests and projects, so restore the previous values when the run ends
3656
- // instead of leaking compileTool/externalApiPaths into later requests (and into
3657
- // other tools in the same process).
3658
- const prevEnv = {
3659
- compileTool: process.env.compileTool,
3660
- compileMode: process.env.compileMode,
3661
- externalApiPaths: process.env.externalApiPaths,
3662
- };
3663
-
3664
3057
  const hmsSdkEts = path.join(devecoHome, 'sdk', 'default', 'hms', 'ets');
3665
3058
  if (fs.existsSync(hmsSdkEts) && !(process.env.externalApiPaths || '').includes(hmsSdkEts)) {
3666
3059
  const existing = process.env.externalApiPaths || '';
@@ -3668,7 +3061,7 @@ function runChecker(files, env) {
3668
3061
  }
3669
3062
 
3670
3063
  try {
3671
- const etsChecker = loadEtsChecker(etsLoaderPath);
3064
+ const etsChecker = require(path.join(etsLoaderPath, 'lib', 'ets_checker.js'));
3672
3065
  const mainModule = require(path.join(etsLoaderPath, 'main.js'));
3673
3066
 
3674
3067
  Object.assign(mainModule.partialUpdateConfig, {
@@ -3703,39 +3096,6 @@ function runChecker(files, env) {
3703
3096
  process.env.compileTool = 'rollup';
3704
3097
  process.env.compileMode = 'moduleJson';
3705
3098
 
3706
- // Generated-profile classes (BuildProfile) are per-module, so files are
3707
- // checked per owning module with that module's own generated profile dir;
3708
- // see groupFilesByModule. The self-package mirror (issue #688) is appended
3709
- // to every group: any module may import any workspace package by name.
3710
- const selfPkgMirror = ensureSelfPackageMirror(projectPath);
3711
- const mirrorPaths = selfPkgMirror ? [selfPkgMirror] : [];
3712
- const mirrorPkgRoots = selfPkgMirror ? collectSelfPackageRoots(projectPath) : [];
3713
- const baseResolvePaths = [...collectResolveModulePaths(projectPath), ...mirrorPaths];
3714
- // Deepest-first so a module nested under another directory wins.
3715
- const profileModules = moduleDirEntries(projectPath)
3716
- .sort((a, b) => b.modulePath.length - a.modulePath.length);
3717
- resolveBuildProfilePath = (importer) =>
3718
- buildProfilePathFor(importer, profileModules, selfPkgMirror, mirrorPkgRoots);
3719
- const moduleGroups = groupFilesByModule(files, projectPath);
3720
- // Grouped runs share every src/main (and the mirror) across groups, so a
3721
- // group's program also contains files owned by other modules — checked
3722
- // under THIS group's BuildProfile. A file's diagnostics are therefore
3723
- // reported only by its owning group's run; files outside the check list
3724
- // entirely (external deps pulled in via wildcard paths) keep the
3725
- // existing keep-everything behavior.
3726
- const diagOwner = new Map();
3727
- let declaredModulePaths = [];
3728
- if (moduleGroups.length > 1) {
3729
- moduleGroups.forEach((g, gi) => {
3730
- for (const f of g.files) diagOwner.set(path.resolve(f), gi);
3731
- });
3732
- declaredModulePaths = moduleDirEntries(projectPath)
3733
- .map((e) => e.modulePath)
3734
- .filter((mp) => fs.existsSync(path.join(mp, 'src', 'main')));
3735
- }
3736
-
3737
- let capturedMark = 0;
3738
- for (const [groupIndex, group] of moduleGroups.entries()) {
3739
3099
  const projectConfig = {
3740
3100
  projectPath,
3741
3101
  modulePath: projectPath,
@@ -3760,12 +3120,7 @@ function runChecker(files, env) {
3760
3120
  originCompatibleSdkVersion: sdkConfig.compatibleSdkVersion,
3761
3121
  bundleType: '',
3762
3122
  compilerTypes: [],
3763
- resolveModulePaths: group.resolveModulePaths ? [...group.resolveModulePaths, ...mirrorPaths] : baseResolvePaths,
3764
- // SDK ETS annotations such as @Available in ets/api/@ohos.annotation.d.ets
3765
- // are only parsed/exported when this flag is set — the ets-loader build
3766
- // config sets it; without it the checker reports the annotation as an
3767
- // unexported member and the decorator as invalid.
3768
- allowEtsAnnotations: true,
3123
+ resolveModulePaths: collectResolveModulePaths(projectPath),
3769
3124
  };
3770
3125
 
3771
3126
  // The checker persists .tsbuildinfo/.tsbuildinfo.linter under cachePath.
@@ -3775,46 +3130,8 @@ function runChecker(files, env) {
3775
3130
  try { fs.rmSync(projectConfig.cachePath, { recursive: true, force: true }); } catch { /* best-effort */ }
3776
3131
  fs.mkdirSync(projectConfig.cachePath, { recursive: true });
3777
3132
 
3778
- const fileMap = {};
3779
- group.files.forEach((f, i) => { fileMap[`file_${i}`] = f; });
3780
3133
  const logger = { debug: capture, info: capture, warn: capture, error: capture };
3781
3134
  etsChecker.etsStandaloneChecker(fileMap, logger, projectConfig);
3782
-
3783
- // Parse this group's output before the next group appends to `captured`.
3784
- // Diagnostics on a file reached through the self-package mirror are
3785
- // re-attributed to the real module source: the mirror is deleted when the
3786
- // run ends, so its paths are dead on arrival. In grouped runs a file's
3787
- // diagnostics are reported only by its owning group's run — any other
3788
- // group's program contains the file under the wrong BuildProfile.
3789
- const groupLines = captured.slice(capturedMark).flatMap((entry) => entry.split('\n'));
3790
- capturedMark = captured.length;
3791
- let current = null;
3792
- for (const line of groupLines) {
3793
- const clean = line.replace(/\x1b\[\d+m/g, '').replace(/\[(\d+)m/g, '');
3794
- const loc = parseDiagnosticLine(clean);
3795
- if (loc) { current = loc; continue; }
3796
- if (current && clean.trim() && !clean.includes('ArkTS:') && !clean.includes('For details about')) {
3797
- const remapped = mirrorPkgRoots.length
3798
- ? remapMirrorDiagnosticPath(current.file, selfPkgMirror, mirrorPkgRoots)
3799
- : null;
3800
- const diagFile = remapped || current.file;
3801
- if (diagOwner.size > 0 && !shouldReportDiagnostic(path.resolve(diagFile), groupIndex, moduleGroups, declaredModulePaths, diagOwner)) {
3802
- current = null;
3803
- continue;
3804
- }
3805
- const { message, rule } = parseMessageLine(clean);
3806
- diagnostics.push({
3807
- file: path.relative(projectPath, diagFile),
3808
- line: current.line,
3809
- column: current.column,
3810
- severity: current.severity === 'error' ? 'error' : 'warning',
3811
- message,
3812
- rule,
3813
- });
3814
- current = null;
3815
- }
3816
- }
3817
- }
3818
3135
  } catch (e) {
3819
3136
  // The checker threw, so it type-checked nothing (or stopped partway) and the
3820
3137
  // diagnostics below describe an incomplete run. Recording this in `captured`
@@ -3829,13 +3146,6 @@ function runChecker(files, env) {
3829
3146
  console.log = origLog;
3830
3147
  console.error = origError;
3831
3148
  console.warn = origWarn;
3832
- if (prevEnv.compileTool === undefined) delete process.env.compileTool;
3833
- else process.env.compileTool = prevEnv.compileTool;
3834
- if (prevEnv.compileMode === undefined) delete process.env.compileMode;
3835
- else process.env.compileMode = prevEnv.compileMode;
3836
- if (prevEnv.externalApiPaths === undefined) delete process.env.externalApiPaths;
3837
- else process.env.externalApiPaths = prevEnv.externalApiPaths;
3838
- resolveBuildProfilePath = undefined;
3839
3149
  // 缓存只在单次检查期间有效(下次运行前会重建),结束后清掉,
3840
3150
  // 避免在用户工程根残留 .cache/arkts-check 目录。
3841
3151
  cleanupCheckerCache(projectPath);
@@ -3855,6 +3165,28 @@ function runChecker(files, env) {
3855
3165
  );
3856
3166
  }
3857
3167
 
3168
+ const diagnostics = [];
3169
+ let current = null;
3170
+ const lines = captured.flatMap(entry => entry.split('\n'));
3171
+
3172
+ for (const line of lines) {
3173
+ const clean = line.replace(/\x1b\[\d+m/g, '').replace(/\[(\d+)m/g, '');
3174
+ const loc = parseDiagnosticLine(clean);
3175
+ if (loc) { current = loc; continue; }
3176
+ if (current && clean.trim() && !clean.includes('ArkTS:') && !clean.includes('For details about')) {
3177
+ const { message, rule } = parseMessageLine(clean);
3178
+ diagnostics.push({
3179
+ file: path.relative(projectPath, current.file),
3180
+ line: current.line,
3181
+ column: current.column,
3182
+ severity: current.severity === 'error' ? 'error' : 'warning',
3183
+ message,
3184
+ rule,
3185
+ });
3186
+ current = null;
3187
+ }
3188
+ }
3189
+
3858
3190
  // Reuse the project-level diagnostics computed once in main(); fall back to
3859
3191
  // computing them here so runChecker stays usable standalone (e.g. in tests).
3860
3192
  const projectDiagnostics = env.skipProjectDiagnostics
@@ -3862,17 +3194,7 @@ function runChecker(files, env) {
3862
3194
  : (env.projectDiagnostics || computeProjectDiagnostics(files, env, env.hasExplicitFiles));
3863
3195
  diagnostics.push(...projectDiagnostics);
3864
3196
 
3865
- // 分组运行时 checker 会把诊断归因到 fileMap 之外的依赖文件,同一
3866
- // file|line|message 可能被多组重复报告,按 diagKey 去重。
3867
- const seenDiagKeys = new Set();
3868
- const uniqueDiagnostics = diagnostics.filter((d) => {
3869
- const key = diagKey(d);
3870
- if (seenDiagKeys.has(key)) return false;
3871
- seenDiagKeys.add(key);
3872
- return true;
3873
- });
3874
-
3875
- return dropFalsePositives(uniqueDiagnostics, projectPath, aceModuleJsonPath);
3197
+ return dropFalsePositives(diagnostics, projectPath, aceModuleJsonPath);
3876
3198
  }
3877
3199
 
3878
3200
  // The checker type-checks the whole program, so SDK `.d.ets` files are pulled in
@@ -4430,9 +3752,6 @@ function handleRequest(line) {
4430
3752
  projectEtsFileCache.clear();
4431
3753
  stateFieldCache.clear();
4432
3754
  resolveModulePathsCache.clear();
4433
- classIndexCache.clear();
4434
- fileImportCache.clear();
4435
- fileStarExportCache.clear();
4436
3755
 
4437
3756
  const result = (() => {
4438
3757
  try {
@@ -4484,10 +3803,7 @@ module.exports = {
4484
3803
  validateComponentDecoratorConsistency, collectStructDecorators,
4485
3804
  V1_ONLY_MEMBER_DECORATORS, V2_ONLY_MEMBER_DECORATORS,
4486
3805
  validateObservedV2PropertyTypes, collectObservedV2ClassNames, V1_TYPE_SENSITIVE_DECORATORS,
4487
- buildProjectClassIndex, getFileBindings, resolveClassOrigin, isObservedV2Usage,
4488
- classIndexCache, fileImportCache,
4489
3806
  validateAppResources, loadAppResourceNames, APP_RESOURCE_INDEXED_KINDS,
4490
- computeCommentStringSpans, collectModuleResourceNames,
4491
3807
  collectProjectEtsFiles, unionProjectFiles, projectEtsFileCache,
4492
3808
  STRUCT_DECL_RE, collectStructs,
4493
3809
  validateRegularPropertyInit, collectComponentRegularProperties,
@@ -4506,9 +3822,6 @@ module.exports = {
4506
3822
  DEFAULT_SDK_INFO, DEFAULT_RUNTIME_OS,
4507
3823
  collectResolveModulePaths, readProjectModules, pickTargetNameForProduct,
4508
3824
  buildProfileNotBuiltHint, resolveModulePathsCache,
4509
- collectSelfPackageRoots, ensureSelfPackageMirror, remapMirrorDiagnosticPath,
4510
- buildProfilePathFor, loadEtsChecker, cleanupCheckerCache,
4511
- groupFilesByModule,
4512
3825
  closureHash, computeEpoch, resolveClosureDependency, collectAmbientDeclarations,
4513
3826
  fileDiagCache, invalidateFileDiagCache, dropFalsePositives, hashText,
4514
3827
  isOutsideProject, isDeclarationFile,