@hamsterbase/evidra 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/sdk/conformance-rules.js +1454 -0
  2. package/dist/sdk/conformance.js +5 -0
  3. package/dist/sdk/index.d.ts +10 -0
  4. package/dist/sdk/main.js +65 -37
  5. package/dist/sdk/rules.d.ts +149 -0
  6. package/dist/sdk/types-B6cBsknY.d.ts +12 -0
  7. package/dist/service/cli.js +697 -332
  8. package/dist/web/assets/{cssMode-B8lMpRZk.js → cssMode-N9cXKwMi.js} +1 -1
  9. package/dist/web/assets/{editor.api-v7kHj8A9.js → editor.api-DQVi2UMW.js} +1 -1
  10. package/dist/web/assets/{freemarker2-DGeBHzes.js → freemarker2-Bvgs91Zz.js} +1 -1
  11. package/dist/web/assets/{handlebars-CJj8r50C.js → handlebars-BjYNaKwZ.js} +1 -1
  12. package/dist/web/assets/{html-DjzDFsf0.js → html-DYaGhp1Y.js} +1 -1
  13. package/dist/web/assets/{htmlMode-CkwZJBoD.js → htmlMode-Cytjzdia.js} +1 -1
  14. package/dist/web/assets/index-C1ua-VrZ.css +2 -0
  15. package/dist/web/assets/index-CnwObt1E.js +35 -0
  16. package/dist/web/assets/{javascript-C-MAHJiN.js → javascript-BG3RI78V.js} +1 -1
  17. package/dist/web/assets/{jsonMode-CkXjaZv2.js → jsonMode-tKunAGWo.js} +1 -1
  18. package/dist/web/assets/{liquid-7k8-ZDme.js → liquid-CyQio9RN.js} +1 -1
  19. package/dist/web/assets/{lspLanguageFeatures-CUP45dUg.js → lspLanguageFeatures-CkQ_7-NP.js} +1 -1
  20. package/dist/web/assets/{mdx-D-hYSOvW.js → mdx-C7agFNoG.js} +1 -1
  21. package/dist/web/assets/{monaco-Dq3bzBUw.js → monaco-CdRk6sx6.js} +4 -4
  22. package/dist/web/assets/{python-BpkAjkSI.js → python-Xk-DSDx5.js} +1 -1
  23. package/dist/web/assets/{razor-CxgXgZt1.js → razor-SQg0PKrI.js} +1 -1
  24. package/dist/web/assets/{tsMode-BUKs-FlJ.js → tsMode-njI9r4C-.js} +1 -1
  25. package/dist/web/assets/{typescript-DVSIawmK.js → typescript-BHUW13-O.js} +1 -1
  26. package/dist/web/assets/{workers-v4-uKnr3.js → workers-ZUzAKd5C.js} +1 -1
  27. package/dist/web/assets/{xml-D2x86430.js → xml-B6qKvuxn.js} +1 -1
  28. package/dist/web/assets/{yaml-nb07hHZ9.js → yaml-BhUHqKCu.js} +1 -1
  29. package/dist/web/index.html +2 -2
  30. package/package.json +22 -12
  31. package/packages/conformance/rules/commit-message/RULE.md +29 -0
  32. package/packages/conformance/rules/duplicate-localization/RULE.md +37 -0
  33. package/packages/conformance/rules/e2e-scenarios-structure/RULE.md +39 -0
  34. package/packages/conformance/rules/index.md +18 -0
  35. package/packages/conformance/rules/same-dir-import-only/RULE.md +35 -0
  36. package/packages/conformance/rules/single-component-file/RULE.md +33 -0
  37. package/packages/conformance/rules/source-locale-defaults/RULE.md +48 -0
  38. package/packages/conformance/rules/sync-locales/RULE.md +45 -0
  39. package/packages/conformance/rules/ui-scenarios-structure/RULE.md +43 -0
  40. package/skills/evidra/SKILL.md +8 -3
  41. package/dist/web/assets/index-CSk5TcTU.js +0 -37
  42. package/dist/web/assets/index-jRxy440Y.css +0 -2
@@ -0,0 +1,1454 @@
1
+ import path from "node:path";
2
+ import { promisify } from "node:util";
3
+ import { promises } from "node:fs";
4
+ import { execFile } from "node:child_process";
5
+ import { parseSync } from "oxc-parser";
6
+ // packages/conformance/rules/commit-message/index.ts
7
+ const execFileAsync = promisify(execFile);
8
+ function commitMessage(config = {}) {
9
+ return async (common) => {
10
+ const { commits, scope } = await collectCommitSubjects(common.projectRoot, config.base);
11
+ const violations = commits.filter((commit) => (config.forbiddenPrefixes ?? ["```"]).some((prefix) => commit.subject.startsWith(prefix)));
12
+ const lines = [`扫描${scope} ${commits.length} 个提交 message。`];
13
+ if (violations.length === 0) {
14
+ lines.push("未发现以禁止的前缀开头的提交 message。");
15
+ return {
16
+ name: "commit-message",
17
+ success: true,
18
+ messages: lines.join("\n"),
19
+ howToFix: ""
20
+ };
21
+ }
22
+ lines.push(`发现 ${violations.length} 个提交 message 以禁止的前缀开头:`);
23
+ for (const violation of violations) lines.push(` - ${violation.hash.slice(0, 7)} ${violation.subject}`);
24
+ return {
25
+ name: "commit-message",
26
+ success: false,
27
+ messages: lines.join("\n"),
28
+ howToFix: "修改对应提交 message,移除禁止的前缀。"
29
+ };
30
+ };
31
+ }
32
+ async function collectCommitSubjects(repoRoot, base) {
33
+ const upstream = base ?? await readUpstream(repoRoot);
34
+ const logArgs = ["log", "--format=%x1e%H%x00%s"];
35
+ const scope = upstream ? `当前分支相对 ${upstream} 的` : "未推送到远端的";
36
+ logArgs.push(...upstream ? [`${upstream}..HEAD`] : [
37
+ "HEAD",
38
+ "--not",
39
+ "--remotes"
40
+ ]);
41
+ const { stdout } = await execFileAsync("git", logArgs, {
42
+ cwd: repoRoot,
43
+ encoding: "utf8",
44
+ maxBuffer: 16777216
45
+ });
46
+ return {
47
+ scope,
48
+ commits: stdout.split("").map((record) => record.trimEnd()).filter((record) => record.length > 0).map((record) => {
49
+ const separatorIndex = record.indexOf("\0");
50
+ return {
51
+ hash: record.slice(0, separatorIndex),
52
+ subject: record.slice(separatorIndex + 1)
53
+ };
54
+ })
55
+ };
56
+ }
57
+ async function readUpstream(repoRoot) {
58
+ try {
59
+ const { stdout } = await execFileAsync("git", [
60
+ "rev-parse",
61
+ "--abbrev-ref",
62
+ "--symbolic-full-name",
63
+ "@{upstream}"
64
+ ], {
65
+ cwd: repoRoot,
66
+ encoding: "utf8"
67
+ });
68
+ return stdout.trim() || void 0;
69
+ } catch {
70
+ return;
71
+ }
72
+ }
73
+ // packages/conformance/rules/duplicate-localization/index.ts
74
+ const SKIP_AST_KEYS$6 = /* @__PURE__ */ new Set([
75
+ "loc",
76
+ "range",
77
+ "start",
78
+ "end",
79
+ "parent",
80
+ "leadingComments",
81
+ "trailingComments"
82
+ ]);
83
+ function duplicateLocalization(config) {
84
+ return async (common) => {
85
+ const options = {
86
+ ...config,
87
+ repoRoot: common.projectRoot,
88
+ scanRoot: path.resolve(common.projectRoot, config.scanRoot),
89
+ excludeDirs: (config.excludeDirs ?? []).map((dir) => path.resolve(common.projectRoot, dir))
90
+ };
91
+ const files = await collectSourceFiles$2(options.scanRoot, options.excludeDirs, config.skipDirNames);
92
+ const keys = /* @__PURE__ */ new Map();
93
+ const conflicts = [];
94
+ const templateLiterals = [];
95
+ for (const file of files) {
96
+ const { ast, code } = await parseSourceFile$6(file);
97
+ const lineStarts = collectLineStarts$1(code);
98
+ walk$6(ast.program, (node) => {
99
+ if (!isLocalizeCall$1(node, config.callName ?? "localize")) return;
100
+ const keyNode = node.arguments[config.keyArgument ?? 0];
101
+ const valueNode = node.arguments[config.valueArgument ?? 1];
102
+ const location = locationFor$1(file, node, lineStarts);
103
+ if (isTemplateLiteral(keyNode) || isTemplateLiteral(valueNode)) {
104
+ templateLiterals.push({ location });
105
+ return;
106
+ }
107
+ const key = readStringLiteral$5(keyNode);
108
+ const value = readStringLiteral$5(valueNode);
109
+ if (key === void 0 || value === void 0) return;
110
+ const existing = keys.get(key);
111
+ if (!existing) {
112
+ keys.set(key, {
113
+ value,
114
+ location
115
+ });
116
+ return;
117
+ }
118
+ if (existing.value !== value) conflicts.push({
119
+ key,
120
+ current: {
121
+ value,
122
+ location
123
+ },
124
+ previous: existing
125
+ });
126
+ });
127
+ }
128
+ const lines = [`Localization keys: ${keys.size}`];
129
+ let success = true;
130
+ if (templateLiterals.length > 0) {
131
+ success = false;
132
+ lines.push(`Found ${templateLiterals.length} localize() call(s) using template literals:`);
133
+ for (const item of templateLiterals) lines.push(` - ${relativeLocation$1(options.repoRoot, item.location)}`);
134
+ }
135
+ if (conflicts.length > 0) {
136
+ success = false;
137
+ lines.push(`Found ${conflicts.length} duplicate localization key(s) with different values:`);
138
+ for (const conflict of conflicts) {
139
+ lines.push(` - '${conflict.key}'`);
140
+ lines.push(` current: '${conflict.current.value}' at ${relativeLocation$1(options.repoRoot, conflict.current.location)}`);
141
+ lines.push(` previously: '${conflict.previous.value}' at ${relativeLocation$1(options.repoRoot, conflict.previous.location)}`);
142
+ }
143
+ }
144
+ if (success) lines.push("No duplicate localization keys found.");
145
+ return {
146
+ name: "duplicate-localization",
147
+ success,
148
+ messages: lines.join("\n"),
149
+ howToFix: success ? "" : "Replace template literals with string literals, and unify duplicate keys to share a single default message."
150
+ };
151
+ };
152
+ }
153
+ async function collectSourceFiles$2(root, excludeDirs, skipDirNames = [
154
+ "node_modules",
155
+ "dist",
156
+ "coverage"
157
+ ]) {
158
+ const out = [];
159
+ const resolvedExcludeDirs = excludeDirs.map((item) => path.resolve(item));
160
+ async function visit(dir) {
161
+ const entries = await promises.readdir(dir, { withFileTypes: true });
162
+ for (const entry of entries) {
163
+ const full = path.join(dir, entry.name);
164
+ if (entry.isDirectory()) {
165
+ if (entry.name.startsWith(".")) continue;
166
+ if (skipDirNames.includes(entry.name)) continue;
167
+ if (isExcluded$2(full, resolvedExcludeDirs)) continue;
168
+ await visit(full);
169
+ continue;
170
+ }
171
+ if (!entry.isFile()) continue;
172
+ if (!full.endsWith(".ts") && !full.endsWith(".tsx")) continue;
173
+ out.push(full);
174
+ }
175
+ }
176
+ await visit(root);
177
+ return out.sort();
178
+ }
179
+ async function parseSourceFile$6(file) {
180
+ const code = await promises.readFile(file, "utf8");
181
+ const ast = parseSync(file, code);
182
+ if (ast.errors.length) throw new Error(`${file}: ${ast.errors.map((error) => error.message).join("; ")}`);
183
+ return {
184
+ ast,
185
+ code
186
+ };
187
+ }
188
+ function walk$6(node, visit) {
189
+ if (!node || typeof node !== "object") return;
190
+ const current = node;
191
+ if (typeof current.type === "string") visit(current);
192
+ for (const key of Object.keys(current)) {
193
+ if (SKIP_AST_KEYS$6.has(key)) continue;
194
+ const value = current[key];
195
+ if (Array.isArray(value)) for (const child of value) walk$6(child, visit);
196
+ else if (value && typeof value === "object") walk$6(value, visit);
197
+ }
198
+ }
199
+ function locationFor$1(file, node, lineStarts) {
200
+ if (node.loc?.start.line) return `${file}:${node.loc.start.line}`;
201
+ const offset = node.start ?? 0;
202
+ let low = 0;
203
+ let high = lineStarts.length - 1;
204
+ while (low < high) {
205
+ const mid = Math.ceil((low + high) / 2);
206
+ if (lineStarts[mid] <= offset) low = mid;
207
+ else high = mid - 1;
208
+ }
209
+ return `${file}:${low + 1}`;
210
+ }
211
+ function collectLineStarts$1(code) {
212
+ const starts = [0];
213
+ for (let index = code.indexOf("\n"); index !== -1; index = code.indexOf("\n", index + 1)) starts.push(index + 1);
214
+ return starts;
215
+ }
216
+ function relativeLocation$1(repoRoot, location) {
217
+ const index = location.lastIndexOf(":");
218
+ if (index === -1) return path.relative(repoRoot, location);
219
+ const file = location.slice(0, index);
220
+ const line = location.slice(index + 1);
221
+ return `${path.relative(repoRoot, file)}:${line}`;
222
+ }
223
+ function isLocalizeCall$1(node, name) {
224
+ return node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === name;
225
+ }
226
+ function readStringLiteral$5(node) {
227
+ if (!node) return void 0;
228
+ if (node.type === "Literal" && typeof node.value === "string") return node.value;
229
+ if (node.type === "StringLiteral" && typeof node.value === "string") return node.value;
230
+ }
231
+ function isTemplateLiteral(node) {
232
+ return node?.type === "TemplateLiteral";
233
+ }
234
+ function isExcluded$2(filePath, excludeDirs) {
235
+ return excludeDirs.some((dir) => filePath === dir || filePath.startsWith(dir + path.sep));
236
+ }
237
+ // packages/conformance/rules/sync-locales/index.ts
238
+ const SKIP_AST_KEYS$5 = /* @__PURE__ */ new Set([
239
+ "loc",
240
+ "range",
241
+ "start",
242
+ "end",
243
+ "parent",
244
+ "leadingComments",
245
+ "trailingComments"
246
+ ]);
247
+ function syncLocales(config) {
248
+ return async (common) => {
249
+ const options = {
250
+ ...config,
251
+ repoRoot: common.projectRoot,
252
+ scanRoot: path.resolve(common.projectRoot, config.scanRoot),
253
+ excludeDirs: (config.excludeDirs ?? []).map((dir) => path.resolve(common.projectRoot, dir))
254
+ };
255
+ const localesDir = path.resolve(options.repoRoot, options.localesDir);
256
+ const files = await collectSourceFiles$1(options.scanRoot, options.excludeDirs, config.skipDirNames);
257
+ const sourceLocale = /* @__PURE__ */ new Map();
258
+ for (const file of files) walk$5((await parseSourceFile$5(file)).program, (node) => {
259
+ if (!isLocalizeCall(node, config.callName ?? "localize")) return;
260
+ const key = readStringLiteral$4(node.arguments[config.keyArgument ?? 0]);
261
+ if (key === void 0) return;
262
+ const value = readStringLiteral$4(node.arguments[config.valueArgument ?? 1]);
263
+ const existing = sourceLocale.get(key);
264
+ if (existing === void 0 || !existing && value) sourceLocale.set(key, value ?? "");
265
+ });
266
+ const defaultPath = path.join(localesDir, `${options.defaultLocale}.json`);
267
+ const defaultMerged = mergeDefaultLocale(await readLocaleFile(defaultPath, config.metadataKey), sourceLocale, config.metadataKey);
268
+ const changedFiles = [];
269
+ if (await writeIfChanged(defaultPath, defaultMerged)) changedFiles.push(defaultPath);
270
+ const untranslatedByLocale = /* @__PURE__ */ new Map();
271
+ for (const locale of options.otherLocales) {
272
+ const localePath = path.join(localesDir, `${locale}.json`);
273
+ const merged = mergeOtherLocale(await readLocaleFile(localePath, config.metadataKey), defaultMerged, config.metadataKey);
274
+ if (await writeIfChanged(localePath, merged)) changedFiles.push(localePath);
275
+ const untranslated = [];
276
+ for (const [key, value] of Object.entries(merged)) {
277
+ if (key === config.metadataKey) continue;
278
+ if (typeof value === "object" && !value.content) untranslated.push({
279
+ key,
280
+ defaultMessage: value.defaultMessage
281
+ });
282
+ else if (typeof value === "string" && !value) untranslated.push({
283
+ key,
284
+ defaultMessage: ""
285
+ });
286
+ }
287
+ if (untranslated.length > 0) untranslatedByLocale.set(locale, untranslated);
288
+ }
289
+ const lines = [`Localization sync: scanned ${files.length} file(s), ${sourceLocale.size} key(s) in source.`];
290
+ const hasOutOfSyncFiles = changedFiles.length > 0;
291
+ const hasUntranslatedKeys = untranslatedByLocale.size > 0;
292
+ const howToFix = [];
293
+ const success = !hasOutOfSyncFiles && !hasUntranslatedKeys;
294
+ if (hasOutOfSyncFiles) {
295
+ lines.push(`Locale files are out of sync with source. Updated ${changedFiles.length} file(s):`);
296
+ for (const file of changedFiles) lines.push(` - ${path.relative(options.repoRoot, file)}`);
297
+ howToFix.push("Locale files have been regenerated - commit them, then run the check again.");
298
+ } else lines.push("Locale files are in sync with source.");
299
+ for (const [locale, entries] of untranslatedByLocale) {
300
+ lines.push(`Found ${entries.length} untranslated key(s) in ${locale}:`);
301
+ for (const entry of entries) lines.push(` - '${entry.key}' (default: '${entry.defaultMessage}')`);
302
+ }
303
+ if (hasUntranslatedKeys) howToFix.push("Translate the listed key(s) in non-default locale files, then run the check again.");
304
+ return {
305
+ name: "sync-locales",
306
+ success,
307
+ messages: lines.join("\n"),
308
+ howToFix: howToFix.join(" ")
309
+ };
310
+ };
311
+ }
312
+ function mergeDefaultLocale(oldConfig, newLocale, metadataKey) {
313
+ const result = {};
314
+ for (const [key, value] of newLocale) {
315
+ const existing = oldConfig[key];
316
+ if (!value && existing) result[key] = existing;
317
+ else result[key] = {
318
+ defaultMessage: value,
319
+ content: value
320
+ };
321
+ }
322
+ return sortObject(result, metadataKey);
323
+ }
324
+ function mergeOtherLocale(oldConfig, defaultConfig, metadataKey) {
325
+ const result = {};
326
+ for (const [key, defaultValue] of Object.entries(defaultConfig)) {
327
+ if (key === metadataKey) continue;
328
+ const defaultMessage = typeof defaultValue === "string" ? defaultValue : defaultValue.defaultMessage;
329
+ const current = oldConfig[key];
330
+ if (!current) result[key] = {
331
+ defaultMessage,
332
+ content: ""
333
+ };
334
+ else if (typeof current === "string") result[key] = {
335
+ defaultMessage,
336
+ content: current
337
+ };
338
+ else if (current.defaultMessage !== defaultMessage) result[key] = {
339
+ defaultMessage,
340
+ content: ""
341
+ };
342
+ else result[key] = current;
343
+ }
344
+ return sortObject(result, metadataKey);
345
+ }
346
+ function sortObject(obj, metadataKey) {
347
+ const sorted = metadataKey ? { [metadataKey]: "true" } : {};
348
+ const keys = Object.keys(obj).filter((key) => key !== metadataKey).sort((a, b) => a.localeCompare(b));
349
+ for (const key of keys) sorted[key] = obj[key];
350
+ return sorted;
351
+ }
352
+ async function readLocaleFile(filePath, metadataKey) {
353
+ let content;
354
+ try {
355
+ content = await promises.readFile(filePath, "utf8");
356
+ } catch (error) {
357
+ if (hasCode(error, "ENOENT")) return metadataKey ? { [metadataKey]: "true" } : {};
358
+ throw error;
359
+ }
360
+ const json = JSON.parse(content);
361
+ if (metadataKey && !json[metadataKey]) throw new Error(`${filePath} is missing metadata ${metadataKey}.`);
362
+ return json;
363
+ }
364
+ async function writeIfChanged(filePath, value) {
365
+ const next = `${JSON.stringify(value, null, 2)}\n`;
366
+ let prev = "";
367
+ try {
368
+ prev = await promises.readFile(filePath, "utf8");
369
+ } catch (error) {
370
+ if (!hasCode(error, "ENOENT")) throw error;
371
+ }
372
+ if (prev === next) return false;
373
+ await promises.mkdir(path.dirname(filePath), { recursive: true });
374
+ await promises.writeFile(filePath, next);
375
+ return true;
376
+ }
377
+ async function collectSourceFiles$1(root, excludeDirs, skipDirNames = [
378
+ "node_modules",
379
+ "dist",
380
+ "coverage"
381
+ ]) {
382
+ const out = [];
383
+ const resolvedExcludeDirs = excludeDirs.map((item) => path.resolve(item));
384
+ async function visit(dir) {
385
+ const entries = await promises.readdir(dir, { withFileTypes: true });
386
+ for (const entry of entries) {
387
+ const full = path.join(dir, entry.name);
388
+ if (entry.isDirectory()) {
389
+ if (entry.name.startsWith(".")) continue;
390
+ if (skipDirNames.includes(entry.name)) continue;
391
+ if (isExcluded$1(full, resolvedExcludeDirs)) continue;
392
+ await visit(full);
393
+ continue;
394
+ }
395
+ if (!entry.isFile()) continue;
396
+ if (!full.endsWith(".ts") && !full.endsWith(".tsx")) continue;
397
+ out.push(full);
398
+ }
399
+ }
400
+ await visit(root);
401
+ return out.sort();
402
+ }
403
+ async function parseSourceFile$5(file) {
404
+ const code = await promises.readFile(file, "utf8");
405
+ const ast = parseSync(file, code);
406
+ if (ast.errors.length) throw new Error(`${file}: ${ast.errors.map((error) => error.message).join("; ")}`);
407
+ return ast;
408
+ }
409
+ function walk$5(node, visit) {
410
+ if (!node || typeof node !== "object") return;
411
+ const current = node;
412
+ if (typeof current.type === "string") visit(current);
413
+ for (const key of Object.keys(current)) {
414
+ if (SKIP_AST_KEYS$5.has(key)) continue;
415
+ const value = current[key];
416
+ if (Array.isArray(value)) for (const child of value) walk$5(child, visit);
417
+ else if (value && typeof value === "object") walk$5(value, visit);
418
+ }
419
+ }
420
+ function isLocalizeCall(node, name) {
421
+ return node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === name;
422
+ }
423
+ function readStringLiteral$4(node) {
424
+ if (!node) return void 0;
425
+ if (node.type === "Literal" && typeof node.value === "string") return node.value;
426
+ if (node.type === "StringLiteral" && typeof node.value === "string") return node.value;
427
+ }
428
+ function isExcluded$1(filePath, excludeDirs) {
429
+ return excludeDirs.some((dir) => filePath === dir || filePath.startsWith(dir + path.sep));
430
+ }
431
+ function hasCode(error, code) {
432
+ return Boolean(error && typeof error === "object" && "code" in error && error.code === code);
433
+ }
434
+ // packages/conformance/rules/same-dir-import-only/index.ts
435
+ const SKIP_AST_KEYS$4 = /* @__PURE__ */ new Set([
436
+ "loc",
437
+ "range",
438
+ "start",
439
+ "end",
440
+ "parent",
441
+ "leadingComments",
442
+ "trailingComments"
443
+ ]);
444
+ const SOURCE_EXTENSIONS = [".ts", ".tsx"];
445
+ /** ESM 导入写编译产物后缀时对应的源码后缀。 */
446
+ const ESM_SOURCE_EXTENSIONS = {
447
+ ".js": [".ts", ".tsx"],
448
+ ".jsx": [".tsx"]
449
+ };
450
+ function sameDirImportOnly(config) {
451
+ return async (common) => {
452
+ const marker = config.marker ?? "@import-scope same-dir";
453
+ const aliases = Object.entries(config.aliases ?? {}).sort(([a], [b]) => b.length - a.length).map(([prefix, target]) => [prefix, path.resolve(common.projectRoot, target)]);
454
+ const options = {
455
+ ...config,
456
+ repoRoot: common.projectRoot,
457
+ scanRoot: path.resolve(common.projectRoot, config.scanRoot),
458
+ excludeDirs: (config.excludeDirs ?? []).map((dir) => path.resolve(common.projectRoot, dir))
459
+ };
460
+ const files = await collectSourceFiles(options.scanRoot, options.excludeDirs, config.skipDirNames);
461
+ const sourceFiles = await Promise.all(files.map(parseSourceFile$4));
462
+ const sourceFileSet = new Set(sourceFiles.map((item) => item.file));
463
+ const protectedFiles = new Set(sourceFiles.filter((file) => hasSameDirMarker(file, marker)).map((sourceFile) => sourceFile.file));
464
+ const violations = [];
465
+ for (const sourceFile of sourceFiles) for (const importEntry of collectImportEntries(sourceFile)) {
466
+ const target = resolveImportTarget(importEntry.importer, importEntry.specifier, aliases, sourceFileSet);
467
+ if (!target) continue;
468
+ if (!protectedFiles.has(target)) continue;
469
+ if (path.dirname(importEntry.importer) === path.dirname(target)) continue;
470
+ violations.push({
471
+ importer: importEntry.importer,
472
+ target,
473
+ specifier: importEntry.specifier,
474
+ location: importEntry.location
475
+ });
476
+ }
477
+ const lines = [`Scanned ${files.length} file(s) for files marked with '${marker}'.`, `Protected files: ${protectedFiles.size}`];
478
+ if (violations.length === 0) {
479
+ lines.push("No cross-directory imports of protected files found.");
480
+ return {
481
+ name: "same-dir-import-only",
482
+ success: true,
483
+ messages: lines.join("\n"),
484
+ howToFix: ""
485
+ };
486
+ }
487
+ lines.push(`Found ${violations.length} cross-directory import(s) of protected files:`);
488
+ for (const violation of violations) {
489
+ lines.push(` - ${relativeLocation(options.repoRoot, violation.location)} imports '${violation.specifier}'`);
490
+ lines.push(` protected file: ${path.relative(options.repoRoot, violation.target)}`);
491
+ }
492
+ return {
493
+ name: "same-dir-import-only",
494
+ success: false,
495
+ messages: lines.join("\n"),
496
+ howToFix: `Only import files marked with '${marker}' from files in the same directory, or move shared API into an unmarked file.`
497
+ };
498
+ };
499
+ }
500
+ async function collectSourceFiles(root, excludeDirs, skipDirNames = [
501
+ "node_modules",
502
+ "dist",
503
+ "coverage"
504
+ ]) {
505
+ const out = [];
506
+ const resolvedExcludeDirs = excludeDirs.map((item) => path.resolve(item));
507
+ async function visit(dir) {
508
+ const entries = await promises.readdir(dir, { withFileTypes: true });
509
+ for (const entry of entries) {
510
+ const full = path.join(dir, entry.name);
511
+ if (entry.isDirectory()) {
512
+ if (entry.name.startsWith(".")) continue;
513
+ if (skipDirNames.includes(entry.name)) continue;
514
+ if (isExcluded(full, resolvedExcludeDirs)) continue;
515
+ await visit(full);
516
+ continue;
517
+ }
518
+ if (!entry.isFile()) continue;
519
+ if (!SOURCE_EXTENSIONS.some((extension) => full.endsWith(extension))) continue;
520
+ out.push(full);
521
+ }
522
+ }
523
+ await visit(root);
524
+ return out.sort();
525
+ }
526
+ async function parseSourceFile$4(file) {
527
+ const code = await promises.readFile(file, "utf8");
528
+ const ast = parseSync(file, code);
529
+ if (ast.errors.length) throw new Error(`${file}: ${ast.errors.map((error) => error.message).join("; ")}`);
530
+ return {
531
+ file,
532
+ ast,
533
+ lineStarts: collectLineStarts(code)
534
+ };
535
+ }
536
+ function hasSameDirMarker(sourceFile, marker) {
537
+ return sourceFile.ast.comments.some((comment) => comment.value.trim() === marker);
538
+ }
539
+ function collectImportEntries(sourceFile) {
540
+ const imports = [];
541
+ walk$4(sourceFile.ast.program, (node) => {
542
+ const specifier = readImportSpecifier(node);
543
+ if (!specifier) return;
544
+ imports.push({
545
+ importer: sourceFile.file,
546
+ specifier,
547
+ location: locationFor(sourceFile.file, node, sourceFile.lineStarts)
548
+ });
549
+ });
550
+ return imports;
551
+ }
552
+ function readImportSpecifier(node) {
553
+ if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ImportExpression") return readStringLiteral$3(node.source);
554
+ }
555
+ function resolveImportTarget(importer, specifier, aliases, sourceFileSet) {
556
+ const base = resolveImportBase(importer, specifier, aliases);
557
+ if (!base) return void 0;
558
+ return buildImportCandidates(base).find((candidate) => sourceFileSet.has(candidate));
559
+ }
560
+ function resolveImportBase(importer, specifier, aliases) {
561
+ if (specifier.startsWith("./") || specifier.startsWith("../")) return path.resolve(path.dirname(importer), specifier);
562
+ for (const [prefix, root] of aliases) if (specifier.startsWith(prefix)) return path.resolve(root, specifier.slice(prefix.length));
563
+ }
564
+ function buildImportCandidates(base) {
565
+ const extension = path.extname(base);
566
+ if (SOURCE_EXTENSIONS.includes(extension)) return [base];
567
+ const candidates = (ESM_SOURCE_EXTENSIONS[extension] ?? []).map((sourceExtension) => `${base.slice(0, -extension.length)}${sourceExtension}`);
568
+ candidates.push(...SOURCE_EXTENSIONS.map((sourceExtension) => `${base}${sourceExtension}`));
569
+ for (const sourceExtension of SOURCE_EXTENSIONS) candidates.push(path.join(base, `index${sourceExtension}`));
570
+ return candidates;
571
+ }
572
+ function walk$4(node, visit) {
573
+ if (!node || typeof node !== "object") return;
574
+ const current = node;
575
+ if (typeof current.type === "string") visit(current);
576
+ for (const key of Object.keys(current)) {
577
+ if (SKIP_AST_KEYS$4.has(key)) continue;
578
+ const value = current[key];
579
+ if (Array.isArray(value)) for (const child of value) walk$4(child, visit);
580
+ else if (value && typeof value === "object") walk$4(value, visit);
581
+ }
582
+ }
583
+ function readStringLiteral$3(node) {
584
+ if (!node) return void 0;
585
+ if (node.type === "Literal" && typeof node.value === "string") return node.value;
586
+ if (node.type === "StringLiteral" && typeof node.value === "string") return node.value;
587
+ }
588
+ function collectLineStarts(code) {
589
+ const starts = [0];
590
+ for (let index = 0; index < code.length; index += 1) if (code[index] === "\n") starts.push(index + 1);
591
+ return starts;
592
+ }
593
+ function locationFor(file, node, lineStarts) {
594
+ if (node.loc?.start.line) return `${file}:${node.loc.start.line}`;
595
+ if (typeof node.start !== "number") return `${file}:0`;
596
+ return `${file}:${lineForOffset(node.start, lineStarts)}`;
597
+ }
598
+ function lineForOffset(offset, lineStarts) {
599
+ let low = 0;
600
+ let high = lineStarts.length - 1;
601
+ while (low <= high) {
602
+ const mid = Math.floor((low + high) / 2);
603
+ if (lineStarts[mid] <= offset) low = mid + 1;
604
+ else high = mid - 1;
605
+ }
606
+ return high + 1;
607
+ }
608
+ function relativeLocation(repoRoot, location) {
609
+ const index = location.lastIndexOf(":");
610
+ if (index === -1) return path.relative(repoRoot, location);
611
+ const file = location.slice(0, index);
612
+ const line = location.slice(index + 1);
613
+ return `${path.relative(repoRoot, file)}:${line}`;
614
+ }
615
+ function isExcluded(filePath, excludeDirs) {
616
+ return excludeDirs.some((dir) => filePath === dir || filePath.startsWith(dir + path.sep));
617
+ }
618
+ // packages/conformance/rules/source-locale-defaults/ast.ts
619
+ const SKIP_AST_KEYS$3 = /* @__PURE__ */ new Set([
620
+ "loc",
621
+ "range",
622
+ "start",
623
+ "end",
624
+ "parent",
625
+ "leadingComments",
626
+ "trailingComments"
627
+ ]);
628
+ async function parseSourceFile$3(file) {
629
+ const code = await promises.readFile(file, "utf8");
630
+ const lineStarts = [0];
631
+ for (let index = 0; index < code.length; index += 1) if (code[index] === "\n") lineStarts.push(index + 1);
632
+ const parsed = parseSync(file, code);
633
+ if (parsed.errors.length) throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
634
+ return {
635
+ file,
636
+ program: parsed.program,
637
+ lineStarts
638
+ };
639
+ }
640
+ /** 深度优先遍历所有 AST 节点。 */
641
+ function walk$3(node, visit) {
642
+ if (!node || typeof node !== "object") return;
643
+ const current = node;
644
+ if (typeof current.type === "string") visit(current);
645
+ for (const key of Object.keys(current)) {
646
+ if (SKIP_AST_KEYS$3.has(key)) continue;
647
+ const value = current[key];
648
+ if (Array.isArray(value)) for (const child of value) walk$3(child, visit);
649
+ else if (value && typeof value === "object") walk$3(value, visit);
650
+ }
651
+ }
652
+ /** 节点所在行(从 1 开始)。 */
653
+ function lineOf$3(source, node) {
654
+ if (typeof node.start !== "number") return 0;
655
+ let low = 0;
656
+ let high = source.lineStarts.length - 1;
657
+ while (low <= high) {
658
+ const mid = Math.floor((low + high) / 2);
659
+ if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
660
+ else high = mid - 1;
661
+ }
662
+ return high + 1;
663
+ }
664
+ function readStringLiteral$2(node) {
665
+ if (!node) return void 0;
666
+ if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") return node.value;
667
+ }
668
+ /** 标识符名或字符串形式的导入导出名。 */
669
+ function readName$3(node) {
670
+ if (!node) return void 0;
671
+ if (typeof node.name === "string") return node.name;
672
+ if (typeof node.value === "string") return node.value;
673
+ }
674
+ // packages/conformance/rules/source-locale-defaults/files.ts
675
+ const DEFAULT_SKIP_DIR_NAMES$3 = [
676
+ "node_modules",
677
+ "dist",
678
+ "coverage"
679
+ ];
680
+ /**
681
+ * 递归收集指定扩展名的文件,相对路径基于 repoRoot 解析;扫描根目录不存在时报错。
682
+ * 结果按路径排序,保证输出稳定。
683
+ */
684
+ async function collectFiles$3(repoRoot, options, extensions) {
685
+ const files = [];
686
+ const excludeDirs = (options.excludeDirs ?? []).map((dir) => path.resolve(repoRoot, dir));
687
+ const skipDirNames = new Set(options.skipDirNames ?? DEFAULT_SKIP_DIR_NAMES$3);
688
+ async function visit(dir) {
689
+ const entries = await readDirIfExists$3(dir);
690
+ for (const entry of entries ?? []) {
691
+ const full = path.join(dir, entry.name);
692
+ if (entry.isDirectory()) {
693
+ if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
694
+ if (excludeDirs.some((excluded) => isInsidePath$3(full, excluded))) continue;
695
+ await visit(full);
696
+ continue;
697
+ }
698
+ if (entry.isFile() && extensions.some((extension) => full.endsWith(extension))) files.push(full);
699
+ }
700
+ }
701
+ await promises.access(path.resolve(repoRoot, options.scanRoot));
702
+ await visit(path.resolve(repoRoot, options.scanRoot));
703
+ return files.sort((left, right) => left.localeCompare(right));
704
+ }
705
+ async function readDirIfExists$3(dir) {
706
+ try {
707
+ return await promises.readdir(dir, { withFileTypes: true });
708
+ } catch (error) {
709
+ if (error.code === "ENOENT") return void 0;
710
+ throw error;
711
+ }
712
+ }
713
+ function isInsidePath$3(filePath, dir) {
714
+ const relative = path.relative(dir, filePath);
715
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
716
+ }
717
+ function formatLocation$3(repoRoot, file, line) {
718
+ return `${path.relative(repoRoot, file)}:${line}`;
719
+ }
720
+ // packages/conformance/rules/source-locale-defaults/index.ts
721
+ /** 汉字、CJK 标点和全角字符;可用于检查英文默认文案。 */
722
+ const CJK_PATTERN = /[\u4e00-\u9fff\u3400-\u4dbf\u3000-\u303f\uff00-\uffef]/;
723
+ /** 本地化调用在代码中的默认文案必须使用源语言(不匹配 pattern),翻译放在语言文件中。 */
724
+ function sourceLocaleDefaults(options) {
725
+ return async (context) => {
726
+ const files = await collectFiles$3(context.projectRoot, options, [".ts", ".tsx"]);
727
+ const findings = [];
728
+ for (const file of files) {
729
+ const source = await parseSourceFile$3(file);
730
+ walk$3(source.program, (node) => {
731
+ if (node.type !== "CallExpression") return;
732
+ const call = matchCall(options.calls, node.callee);
733
+ if (!call) return;
734
+ const value = readStringLiteral$2(node.arguments?.[call.valueArgument]);
735
+ if (value === void 0 || !new RegExp(options.pattern.source, options.pattern.flags).test(value)) return;
736
+ findings.push(` - ${call.name}() 文案 '${value}' 位于 ${formatLocation$3(context.projectRoot, file, lineOf$3(source, node))}`);
737
+ });
738
+ }
739
+ const names = options.calls.map((call) => `${call.name}()`).join("、");
740
+ const lines = [`扫描 ${files.length} 个文件中 ${names} 的默认文案。`];
741
+ if (findings.length === 0) {
742
+ lines.push("未发现违规文案。");
743
+ return {
744
+ name: "source-locale-defaults",
745
+ success: true,
746
+ messages: lines.join("\n"),
747
+ howToFix: ""
748
+ };
749
+ }
750
+ lines.push(`发现 ${findings.length} 处违规文案:`, ...findings);
751
+ return {
752
+ name: "source-locale-defaults",
753
+ success: false,
754
+ messages: lines.join("\n"),
755
+ howToFix: "默认文案改用源语言,其他语言的翻译写入语言文件。"
756
+ };
757
+ };
758
+ }
759
+ function matchCall(calls, callee) {
760
+ if (!callee) return void 0;
761
+ if (callee.type === "Identifier") return calls.find((call) => call.name === callee.name);
762
+ if (callee.type === "MemberExpression" || callee.type === "StaticMemberExpression") {
763
+ const name = readName$3(callee.property);
764
+ return calls.find((call) => call.member && call.name === name);
765
+ }
766
+ }
767
+ // packages/conformance/rules/single-component-file/ast.ts
768
+ const SKIP_AST_KEYS$2 = /* @__PURE__ */ new Set([
769
+ "loc",
770
+ "range",
771
+ "start",
772
+ "end",
773
+ "parent",
774
+ "leadingComments",
775
+ "trailingComments"
776
+ ]);
777
+ async function parseSourceFile$2(file) {
778
+ const code = await promises.readFile(file, "utf8");
779
+ const lineStarts = [0];
780
+ for (let index = 0; index < code.length; index += 1) if (code[index] === "\n") lineStarts.push(index + 1);
781
+ const parsed = parseSync(file, code);
782
+ if (parsed.errors.length) throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
783
+ return {
784
+ file,
785
+ program: parsed.program,
786
+ lineStarts
787
+ };
788
+ }
789
+ /** 深度优先遍历所有 AST 节点。 */
790
+ function walk$2(node, visit) {
791
+ if (!node || typeof node !== "object") return;
792
+ const current = node;
793
+ if (typeof current.type === "string") visit(current);
794
+ for (const key of Object.keys(current)) {
795
+ if (SKIP_AST_KEYS$2.has(key)) continue;
796
+ const value = current[key];
797
+ if (Array.isArray(value)) for (const child of value) walk$2(child, visit);
798
+ else if (value && typeof value === "object") walk$2(value, visit);
799
+ }
800
+ }
801
+ /** 节点所在行(从 1 开始)。 */
802
+ function lineOf$2(source, node) {
803
+ if (typeof node.start !== "number") return 0;
804
+ let low = 0;
805
+ let high = source.lineStarts.length - 1;
806
+ while (low <= high) {
807
+ const mid = Math.floor((low + high) / 2);
808
+ if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
809
+ else high = mid - 1;
810
+ }
811
+ return high + 1;
812
+ }
813
+ /** 标识符名或字符串形式的导入导出名。 */
814
+ function readName$2(node) {
815
+ if (!node) return void 0;
816
+ if (typeof node.name === "string") return node.name;
817
+ if (typeof node.value === "string") return node.value;
818
+ }
819
+ function isFunctionLike$2(node) {
820
+ return node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression" || node?.type === "ArrowFunctionExpression";
821
+ }
822
+ function containsJsx(node) {
823
+ let found = false;
824
+ walk$2(node, (current) => {
825
+ if (current.type === "JSXElement" || current.type === "JSXFragment") found = true;
826
+ });
827
+ return found;
828
+ }
829
+ // packages/conformance/rules/single-component-file/files.ts
830
+ const DEFAULT_SKIP_DIR_NAMES$2 = [
831
+ "node_modules",
832
+ "dist",
833
+ "coverage"
834
+ ];
835
+ /**
836
+ * 递归收集指定扩展名的文件,相对路径基于 repoRoot 解析;扫描根目录不存在时报错。
837
+ * 结果按路径排序,保证输出稳定。
838
+ */
839
+ async function collectFiles$2(repoRoot, options, extensions) {
840
+ const files = [];
841
+ const excludeDirs = (options.excludeDirs ?? []).map((dir) => path.resolve(repoRoot, dir));
842
+ const skipDirNames = new Set(options.skipDirNames ?? DEFAULT_SKIP_DIR_NAMES$2);
843
+ async function visit(dir) {
844
+ const entries = await readDirIfExists$2(dir);
845
+ for (const entry of entries ?? []) {
846
+ const full = path.join(dir, entry.name);
847
+ if (entry.isDirectory()) {
848
+ if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
849
+ if (excludeDirs.some((excluded) => isInsidePath$2(full, excluded))) continue;
850
+ await visit(full);
851
+ continue;
852
+ }
853
+ if (entry.isFile() && extensions.some((extension) => full.endsWith(extension))) files.push(full);
854
+ }
855
+ }
856
+ await promises.access(path.resolve(repoRoot, options.scanRoot));
857
+ await visit(path.resolve(repoRoot, options.scanRoot));
858
+ return files.sort((left, right) => left.localeCompare(right));
859
+ }
860
+ async function readDirIfExists$2(dir) {
861
+ try {
862
+ return await promises.readdir(dir, { withFileTypes: true });
863
+ } catch (error) {
864
+ if (error.code === "ENOENT") return void 0;
865
+ throw error;
866
+ }
867
+ }
868
+ function isInsidePath$2(filePath, dir) {
869
+ const relative = path.relative(dir, filePath);
870
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
871
+ }
872
+ function formatLocation$2(repoRoot, file, line) {
873
+ return `${path.relative(repoRoot, file)}:${line}`;
874
+ }
875
+ // packages/conformance/rules/single-component-file/index.ts
876
+ /** 每个 TSX 文件只定义一个返回 JSX 的组件。 */
877
+ function singleComponentFile(options) {
878
+ return async (context) => {
879
+ const wrappers = new Set(options.componentWrappers ?? ["memo", "forwardRef"]);
880
+ const files = await collectFiles$2(context.projectRoot, options, [".tsx"]);
881
+ const findings = [];
882
+ for (const file of files) {
883
+ const source = await parseSourceFile$2(file);
884
+ const components = /* @__PURE__ */ new Map();
885
+ walk$2(source.program, (node) => {
886
+ const name = readComponentName(node, wrappers);
887
+ if (name && !components.has(name)) components.set(name, lineOf$2(source, node));
888
+ });
889
+ if (components.size <= 1) continue;
890
+ findings.push(` - ${path.relative(context.projectRoot, file)}`);
891
+ for (const [name, line] of components) findings.push(` ${name} 位于 ${formatLocation$2(context.projectRoot, file, line)}`);
892
+ }
893
+ const lines = [`扫描 ${files.length} 个 TSX 文件。`];
894
+ if (findings.length === 0) {
895
+ lines.push("未发现包含多个组件的 TSX 文件。");
896
+ return {
897
+ name: "single-component-file",
898
+ success: true,
899
+ messages: lines.join("\n"),
900
+ howToFix: ""
901
+ };
902
+ }
903
+ lines.push("以下 TSX 文件包含多个组件:", ...findings);
904
+ return {
905
+ name: "single-component-file",
906
+ success: false,
907
+ messages: lines.join("\n"),
908
+ howToFix: "把多出的组件移到各自的 TSX 文件,每个文件只保留一个组件。"
909
+ };
910
+ };
911
+ }
912
+ function readComponentName(node, wrappers) {
913
+ if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
914
+ const name = readName$2(node.id);
915
+ return name && containsJsx(node.body) ? name : void 0;
916
+ }
917
+ if (node.type === "VariableDeclarator") {
918
+ const name = readName$2(node.id);
919
+ return name && isComponentInitializer(node.init, wrappers) ? name : void 0;
920
+ }
921
+ if (node.type === "ExportDefaultDeclaration") {
922
+ const declaration = node.declaration;
923
+ if (!declaration || readName$2(declaration.id)) return void 0;
924
+ return (isFunctionLike$2(declaration) || declaration.type === "ClassDeclaration") && containsJsx(declaration) || isComponentInitializer(declaration, wrappers) ? "default export" : void 0;
925
+ }
926
+ }
927
+ function isComponentInitializer(node, wrappers) {
928
+ if (!node) return false;
929
+ if (isFunctionLike$2(node)) return containsJsx(node.body);
930
+ if (node.type !== "CallExpression" && node.type !== "NewExpression") return false;
931
+ const callee = node.callee;
932
+ const calleeName = callee?.type === "Identifier" ? callee.name : readName$2(callee?.property);
933
+ if (!calleeName || !wrappers.has(calleeName)) return false;
934
+ return (node.arguments ?? []).some((argument) => isFunctionLike$2(argument) && containsJsx(argument.body));
935
+ }
936
+ // packages/conformance/rules/e2e-scenarios-structure/ast.ts
937
+ const SKIP_AST_KEYS$1 = /* @__PURE__ */ new Set([
938
+ "loc",
939
+ "range",
940
+ "start",
941
+ "end",
942
+ "parent",
943
+ "leadingComments",
944
+ "trailingComments"
945
+ ]);
946
+ async function parseSourceFile$1(file) {
947
+ const code = await promises.readFile(file, "utf8");
948
+ const lineStarts = [0];
949
+ for (let index = 0; index < code.length; index += 1) if (code[index] === "\n") lineStarts.push(index + 1);
950
+ const parsed = parseSync(file, code);
951
+ if (parsed.errors.length) throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
952
+ return {
953
+ file,
954
+ program: parsed.program,
955
+ lineStarts
956
+ };
957
+ }
958
+ /** 深度优先遍历所有 AST 节点。 */
959
+ function walk$1(node, visit) {
960
+ if (!node || typeof node !== "object") return;
961
+ const current = node;
962
+ if (typeof current.type === "string") visit(current);
963
+ for (const key of Object.keys(current)) {
964
+ if (SKIP_AST_KEYS$1.has(key)) continue;
965
+ const value = current[key];
966
+ if (Array.isArray(value)) for (const child of value) walk$1(child, visit);
967
+ else if (value && typeof value === "object") walk$1(value, visit);
968
+ }
969
+ }
970
+ /** 节点所在行(从 1 开始)。 */
971
+ function lineOf$1(source, node) {
972
+ if (typeof node.start !== "number") return 0;
973
+ let low = 0;
974
+ let high = source.lineStarts.length - 1;
975
+ while (low <= high) {
976
+ const mid = Math.floor((low + high) / 2);
977
+ if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
978
+ else high = mid - 1;
979
+ }
980
+ return high + 1;
981
+ }
982
+ function readStringLiteral$1(node) {
983
+ if (!node) return void 0;
984
+ if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") return node.value;
985
+ }
986
+ /** 标识符名或字符串形式的导入导出名。 */
987
+ function readName$1(node) {
988
+ if (!node) return void 0;
989
+ if (typeof node.name === "string") return node.name;
990
+ if (typeof node.value === "string") return node.value;
991
+ }
992
+ function isFunctionLike$1(node) {
993
+ if (node && [
994
+ "ParenthesizedExpression",
995
+ "TSAsExpression",
996
+ "TSSatisfiesExpression",
997
+ "TSTypeAssertion",
998
+ "TSNonNullExpression"
999
+ ].includes(node.type ?? "")) return isFunctionLike$1(node.expression);
1000
+ return node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression" || node?.type === "ArrowFunctionExpression";
1001
+ }
1002
+ /** import / export ... from 的模块路径。 */
1003
+ function readModuleSpecifier$1(node) {
1004
+ if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") return readStringLiteral$1(node.source);
1005
+ }
1006
+ // packages/conformance/rules/e2e-scenarios-structure/files.ts
1007
+ const DEFAULT_SKIP_DIR_NAMES$1 = [
1008
+ "node_modules",
1009
+ "dist",
1010
+ "coverage"
1011
+ ];
1012
+ /**
1013
+ * 递归收集 helper 目录中的 TS/TSX 文件;目录不存在时返回空列表。
1014
+ * 结果按路径排序,保证输出稳定。
1015
+ */
1016
+ async function collectFiles$1(root) {
1017
+ const files = [];
1018
+ const skipDirNames = new Set(DEFAULT_SKIP_DIR_NAMES$1);
1019
+ async function visit(dir) {
1020
+ const entries = await readDirIfExists$1(dir);
1021
+ for (const entry of entries ?? []) {
1022
+ const full = path.join(dir, entry.name);
1023
+ if (entry.isDirectory()) {
1024
+ if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
1025
+ await visit(full);
1026
+ continue;
1027
+ }
1028
+ if (entry.isFile() && [".ts", ".tsx"].some((extension) => full.endsWith(extension))) files.push(full);
1029
+ }
1030
+ }
1031
+ await visit(root);
1032
+ return files.sort((left, right) => left.localeCompare(right));
1033
+ }
1034
+ async function readDirIfExists$1(dir) {
1035
+ try {
1036
+ return await promises.readdir(dir, { withFileTypes: true });
1037
+ } catch (error) {
1038
+ if (error.code === "ENOENT") return void 0;
1039
+ throw error;
1040
+ }
1041
+ }
1042
+ function isInsidePath$1(filePath, dir) {
1043
+ const relative = path.relative(dir, filePath);
1044
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
1045
+ }
1046
+ function formatLocation$1(repoRoot, file, line) {
1047
+ return `${path.relative(repoRoot, file)}:${line}`;
1048
+ }
1049
+ // packages/conformance/rules/e2e-scenarios-structure/index.ts
1050
+ /**
1051
+ * 场景目录结构:入口文件只组织用例,helper 放在 utils/<入口名>(专属)或 shared(共用),
1052
+ * 且 shared 与 utils 互不引用。
1053
+ */
1054
+ function e2eScenariosStructure(options) {
1055
+ return async (context) => {
1056
+ const repoRoot = context.projectRoot;
1057
+ const entrySuffix = options.entrySuffix ?? ".spec.ts";
1058
+ const strictRoot = options.strictRoot ?? false;
1059
+ const root = path.resolve(repoRoot, options.root);
1060
+ const name = options.name ?? "e2e-scenarios-structure";
1061
+ const sharedName = options.sharedDir ?? "shared";
1062
+ const utilsName = options.utilsDir ?? "utils";
1063
+ const threshold = options.sharedThreshold ?? 3;
1064
+ const sharedRoot = path.join(root, sharedName);
1065
+ const utilsRoot = path.join(root, utilsName);
1066
+ const utilsPrefix = `./${utilsName}/`;
1067
+ const at = (file, line) => formatLocation$1(repoRoot, file, line);
1068
+ const violations = [];
1069
+ const entries = await readDirIfExists$1(root);
1070
+ if (!entries) return {
1071
+ name,
1072
+ success: false,
1073
+ messages: `场景根目录不存在:${path.relative(repoRoot, root)}`,
1074
+ howToFix: "确认传入的场景根目录路径。"
1075
+ };
1076
+ const entryFiles = [];
1077
+ for (const entry of entries) {
1078
+ if (entry.name.startsWith(".")) continue;
1079
+ const full = path.join(root, entry.name);
1080
+ if (entry.name === sharedName || entry.name === utilsName) {
1081
+ if (!entry.isDirectory()) violations.push(` - ${at(full, 1)} ${entry.name} 必须是目录`);
1082
+ continue;
1083
+ }
1084
+ if (entry.isFile() && entry.name.endsWith(entrySuffix)) {
1085
+ entryFiles.push(full);
1086
+ continue;
1087
+ }
1088
+ if (strictRoot) violations.push(` - ${at(full, 1)} 根目录只允许 *${entrySuffix} 入口与 ${sharedName}/${utilsName} 目录`);
1089
+ }
1090
+ entryFiles.sort((left, right) => left.localeCompare(right));
1091
+ const usages = /* @__PURE__ */ new Map();
1092
+ const importViolations = [];
1093
+ for (const file of entryFiles) {
1094
+ const source = await parseSourceFile$1(file);
1095
+ const entryName = path.basename(file, entrySuffix);
1096
+ walk$1(source.program, (node) => {
1097
+ const functionName = readFunctionName$1(node);
1098
+ if (functionName) violations.push(` - ${at(file, lineOf$1(source, node))} 入口内定义辅助函数 ${functionName}`);
1099
+ });
1100
+ const expected = `${utilsPrefix}${entryName}`;
1101
+ for (const entry of collectImports$1(source, utilsPrefix)) {
1102
+ for (const importedName of entry.importedNames) {
1103
+ const key = `${entry.specifier}#${importedName}`;
1104
+ usages.set(key, (usages.get(key) ?? /* @__PURE__ */ new Set()).add(file));
1105
+ }
1106
+ if (entry.specifier === expected || entry.specifier.startsWith(`${expected}/`)) continue;
1107
+ importViolations.push({
1108
+ file,
1109
+ entry,
1110
+ expected
1111
+ });
1112
+ }
1113
+ }
1114
+ for (const { file, entry, expected } of importViolations) {
1115
+ violations.push(` - ${at(file, entry.line)} 导入 '${entry.specifier}',入口只能导入 ${expected}/... 或 ./${sharedName}/...`);
1116
+ for (const importedName of entry.importedNames) {
1117
+ const count = usages.get(`${entry.specifier}#${importedName}`)?.size ?? 0;
1118
+ violations.push(count >= threshold ? ` ${importedName} 已被 ${count} 个入口使用,建议移到 ${sharedName}。` : ` ${importedName} 被 ${count} 个入口使用,建议在各入口的 ${utilsName} 目录分别实现。`);
1119
+ }
1120
+ }
1121
+ const helperFiles = [...await collectFiles$1(sharedRoot), ...await collectFiles$1(utilsRoot)];
1122
+ for (const file of helperFiles) {
1123
+ const fromArea = isInsidePath$1(file, sharedRoot) ? sharedName : utilsName;
1124
+ const source = await parseSourceFile$1(file);
1125
+ for (const node of source.program.body) {
1126
+ const specifier = readModuleSpecifier$1(node);
1127
+ if (!specifier?.startsWith(".")) continue;
1128
+ const target = path.resolve(path.dirname(file), specifier);
1129
+ const toArea = isInsidePath$1(target, sharedRoot) ? sharedName : isInsidePath$1(target, utilsRoot) ? utilsName : void 0;
1130
+ if (!toArea || toArea === fromArea) continue;
1131
+ violations.push(` - ${at(file, lineOf$1(source, node))} ${fromArea} 不能引用 ${toArea} '${specifier}'`);
1132
+ }
1133
+ }
1134
+ const rules = [
1135
+ "入口文件内不定义辅助函数",
1136
+ `入口只能导入 ${utilsPrefix}<入口名> 或 ./${sharedName}`,
1137
+ `${sharedName} 与 ${utilsName} 互不引用`,
1138
+ strictRoot ? `根目录只放入口与 ${sharedName}/${utilsName}` : void 0
1139
+ ].filter(Boolean);
1140
+ const lines = [`扫描 ${path.relative(repoRoot, root)} 下 ${entryFiles.length} 个入口。`, `规则:${rules.join(";")}。`];
1141
+ const success = violations.length === 0;
1142
+ if (success) lines.push("未发现结构违规。");
1143
+ else lines.push(`发现 ${violations.filter((line) => line.startsWith(" - ")).length} 处违规:`, ...violations);
1144
+ return {
1145
+ name,
1146
+ success,
1147
+ messages: lines.join("\n"),
1148
+ howToFix: success ? "" : `helper 移出入口文件:被 ${threshold} 个及以上入口使用的放到 ${sharedName},其余放到 ${utilsName}/<入口名>;${sharedName} 与 ${utilsName} 不要互相引用。`
1149
+ };
1150
+ };
1151
+ }
1152
+ function readFunctionName$1(node) {
1153
+ if (node.type === "FunctionDeclaration") return readName$1(node.id) ?? "匿名函数";
1154
+ if (node.type === "VariableDeclarator" && isFunctionLike$1(node.init)) return readName$1(node.id) ?? "匿名函数";
1155
+ }
1156
+ function collectImports$1(source, prefix) {
1157
+ const imports = [];
1158
+ for (const node of source.program.body) {
1159
+ if (node.type !== "ImportDeclaration") continue;
1160
+ const specifier = readModuleSpecifier$1(node);
1161
+ if (!specifier?.startsWith(prefix)) continue;
1162
+ const importedNames = (node.specifiers ?? []).map((item) => item.type === "ImportDefaultSpecifier" ? "default" : item.type === "ImportNamespaceSpecifier" ? "*" : readName$1(item.imported) ?? readName$1(item.local) ?? "anonymous");
1163
+ imports.push({
1164
+ specifier,
1165
+ importedNames,
1166
+ line: lineOf$1(source, node)
1167
+ });
1168
+ }
1169
+ return imports;
1170
+ }
1171
+ // packages/conformance/rules/ui-scenarios-structure/ast.ts
1172
+ const SKIP_AST_KEYS = /* @__PURE__ */ new Set([
1173
+ "loc",
1174
+ "range",
1175
+ "start",
1176
+ "end",
1177
+ "parent",
1178
+ "leadingComments",
1179
+ "trailingComments"
1180
+ ]);
1181
+ async function parseSourceFile(file) {
1182
+ const code = await promises.readFile(file, "utf8");
1183
+ const lineStarts = [0];
1184
+ for (let index = 0; index < code.length; index += 1) if (code[index] === "\n") lineStarts.push(index + 1);
1185
+ const parsed = parseSync(file, code);
1186
+ if (parsed.errors.length) throw new Error(`${file}: ${parsed.errors.map((error) => error.message).join("; ")}`);
1187
+ return {
1188
+ file,
1189
+ program: parsed.program,
1190
+ lineStarts
1191
+ };
1192
+ }
1193
+ /** 深度优先遍历所有 AST 节点。 */
1194
+ function walk(node, visit) {
1195
+ if (!node || typeof node !== "object") return;
1196
+ const current = node;
1197
+ if (typeof current.type === "string") visit(current);
1198
+ for (const key of Object.keys(current)) {
1199
+ if (SKIP_AST_KEYS.has(key)) continue;
1200
+ const value = current[key];
1201
+ if (Array.isArray(value)) for (const child of value) walk(child, visit);
1202
+ else if (value && typeof value === "object") walk(value, visit);
1203
+ }
1204
+ }
1205
+ /** 节点所在行(从 1 开始)。 */
1206
+ function lineOf(source, node) {
1207
+ if (typeof node.start !== "number") return 0;
1208
+ let low = 0;
1209
+ let high = source.lineStarts.length - 1;
1210
+ while (low <= high) {
1211
+ const mid = Math.floor((low + high) / 2);
1212
+ if ((source.lineStarts[mid] ?? Infinity) <= node.start) low = mid + 1;
1213
+ else high = mid - 1;
1214
+ }
1215
+ return high + 1;
1216
+ }
1217
+ function readStringLiteral(node) {
1218
+ if (!node) return void 0;
1219
+ if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") return node.value;
1220
+ }
1221
+ /** 标识符名或字符串形式的导入导出名。 */
1222
+ function readName(node) {
1223
+ if (!node) return void 0;
1224
+ if (typeof node.name === "string") return node.name;
1225
+ if (typeof node.value === "string") return node.value;
1226
+ }
1227
+ function isFunctionLike(node) {
1228
+ if (node && [
1229
+ "ParenthesizedExpression",
1230
+ "TSAsExpression",
1231
+ "TSSatisfiesExpression",
1232
+ "TSTypeAssertion",
1233
+ "TSNonNullExpression"
1234
+ ].includes(node.type ?? "")) return isFunctionLike(node.expression);
1235
+ return node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression" || node?.type === "ArrowFunctionExpression";
1236
+ }
1237
+ /** import / export ... from 的模块路径。 */
1238
+ function readModuleSpecifier(node) {
1239
+ if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") return readStringLiteral(node.source);
1240
+ }
1241
+ // packages/conformance/rules/ui-scenarios-structure/files.ts
1242
+ const DEFAULT_SKIP_DIR_NAMES = [
1243
+ "node_modules",
1244
+ "dist",
1245
+ "coverage"
1246
+ ];
1247
+ /**
1248
+ * 递归收集 helper 目录中的 TS/TSX 文件;目录不存在时返回空列表。
1249
+ * 结果按路径排序,保证输出稳定。
1250
+ */
1251
+ async function collectFiles(root) {
1252
+ const files = [];
1253
+ const skipDirNames = new Set(DEFAULT_SKIP_DIR_NAMES);
1254
+ async function visit(dir) {
1255
+ const entries = await readDirIfExists(dir);
1256
+ for (const entry of entries ?? []) {
1257
+ const full = path.join(dir, entry.name);
1258
+ if (entry.isDirectory()) {
1259
+ if (entry.name.startsWith(".") || skipDirNames.has(entry.name)) continue;
1260
+ await visit(full);
1261
+ continue;
1262
+ }
1263
+ if (entry.isFile() && [".ts", ".tsx"].some((extension) => full.endsWith(extension))) files.push(full);
1264
+ }
1265
+ }
1266
+ await visit(root);
1267
+ return files.sort((left, right) => left.localeCompare(right));
1268
+ }
1269
+ async function readDirIfExists(dir) {
1270
+ try {
1271
+ return await promises.readdir(dir, { withFileTypes: true });
1272
+ } catch (error) {
1273
+ if (error.code === "ENOENT") return void 0;
1274
+ throw error;
1275
+ }
1276
+ }
1277
+ function isInsidePath(filePath, dir) {
1278
+ const relative = path.relative(dir, filePath);
1279
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
1280
+ }
1281
+ function formatLocation(repoRoot, file, line) {
1282
+ return `${path.relative(repoRoot, file)}:${line}`;
1283
+ }
1284
+ // packages/conformance/rules/ui-scenarios-structure/index.ts
1285
+ /**
1286
+ * 场景目录结构:入口文件只组织用例,helper 放在 utils/<入口名>(专属)或 shared(共用),
1287
+ * 且 shared 与 utils 互不引用。
1288
+ */
1289
+ function uiScenariosStructure(options) {
1290
+ return async (context) => {
1291
+ const repoRoot = context.projectRoot;
1292
+ const entrySuffix = options.entrySuffix ?? ".ts";
1293
+ const strictRoot = options.strictRoot ?? true;
1294
+ const exportName = options.exportName ?? "lint";
1295
+ const root = path.resolve(repoRoot, options.root);
1296
+ const name = options.name ?? "ui-scenarios-structure";
1297
+ const sharedName = options.sharedDir ?? "shared";
1298
+ const utilsName = options.utilsDir ?? "utils";
1299
+ const threshold = options.sharedThreshold ?? 3;
1300
+ const sharedRoot = path.join(root, sharedName);
1301
+ const utilsRoot = path.join(root, utilsName);
1302
+ const utilsPrefix = `./${utilsName}/`;
1303
+ const at = (file, line) => formatLocation(repoRoot, file, line);
1304
+ const violations = [];
1305
+ const entries = await readDirIfExists(root);
1306
+ if (!entries) return {
1307
+ name,
1308
+ success: false,
1309
+ messages: `场景根目录不存在:${path.relative(repoRoot, root)}`,
1310
+ howToFix: "确认传入的场景根目录路径。"
1311
+ };
1312
+ const entryFiles = [];
1313
+ for (const entry of entries) {
1314
+ if (entry.name.startsWith(".")) continue;
1315
+ const full = path.join(root, entry.name);
1316
+ if (entry.name === sharedName || entry.name === utilsName) {
1317
+ if (!entry.isDirectory()) violations.push(` - ${at(full, 1)} ${entry.name} 必须是目录`);
1318
+ continue;
1319
+ }
1320
+ if (entry.isFile() && entry.name.endsWith(entrySuffix)) {
1321
+ entryFiles.push(full);
1322
+ continue;
1323
+ }
1324
+ if (strictRoot) violations.push(` - ${at(full, 1)} 根目录只允许 *${entrySuffix} 入口与 ${sharedName}/${utilsName} 目录`);
1325
+ }
1326
+ entryFiles.sort((left, right) => left.localeCompare(right));
1327
+ const usages = /* @__PURE__ */ new Map();
1328
+ const importViolations = [];
1329
+ for (const file of entryFiles) {
1330
+ const source = await parseSourceFile(file);
1331
+ const entryName = path.basename(file, entrySuffix);
1332
+ const entryFunctions = collectEntryFunctions(source, exportName);
1333
+ walk(source.program, (node) => {
1334
+ const functionName = readFunctionName(node);
1335
+ if (functionName && !entryFunctions.has(node)) violations.push(` - ${at(file, lineOf(source, node))} 入口内定义辅助函数 ${functionName}`);
1336
+ });
1337
+ if (!hasNamedExport(source, exportName)) violations.push(` - ${at(file, 1)} 入口必须导出 ${exportName}`);
1338
+ const expected = `${utilsPrefix}${entryName}`;
1339
+ for (const entry of collectImports(source, utilsPrefix)) {
1340
+ for (const importedName of entry.importedNames) {
1341
+ const key = `${entry.specifier}#${importedName}`;
1342
+ usages.set(key, (usages.get(key) ?? /* @__PURE__ */ new Set()).add(file));
1343
+ }
1344
+ if (entry.specifier === expected || entry.specifier.startsWith(`${expected}/`)) continue;
1345
+ importViolations.push({
1346
+ file,
1347
+ entry,
1348
+ expected
1349
+ });
1350
+ }
1351
+ }
1352
+ for (const { file, entry, expected } of importViolations) {
1353
+ violations.push(` - ${at(file, entry.line)} 导入 '${entry.specifier}',入口只能导入 ${expected}/... 或 ./${sharedName}/...`);
1354
+ for (const importedName of entry.importedNames) {
1355
+ const count = usages.get(`${entry.specifier}#${importedName}`)?.size ?? 0;
1356
+ violations.push(count >= threshold ? ` ${importedName} 已被 ${count} 个入口使用,建议移到 ${sharedName}。` : ` ${importedName} 被 ${count} 个入口使用,建议在各入口的 ${utilsName} 目录分别实现。`);
1357
+ }
1358
+ }
1359
+ const helperFiles = [...await collectFiles(sharedRoot), ...await collectFiles(utilsRoot)];
1360
+ for (const file of helperFiles) {
1361
+ const fromArea = isInsidePath(file, sharedRoot) ? sharedName : utilsName;
1362
+ const source = await parseSourceFile(file);
1363
+ for (const node of source.program.body) {
1364
+ const specifier = readModuleSpecifier(node);
1365
+ if (!specifier?.startsWith(".")) continue;
1366
+ const target = path.resolve(path.dirname(file), specifier);
1367
+ const toArea = isInsidePath(target, sharedRoot) ? sharedName : isInsidePath(target, utilsRoot) ? utilsName : void 0;
1368
+ if (!toArea || toArea === fromArea) continue;
1369
+ violations.push(` - ${at(file, lineOf(source, node))} ${fromArea} 不能引用 ${toArea} '${specifier}'`);
1370
+ }
1371
+ }
1372
+ const rules = [
1373
+ `入口必须导出 ${exportName},只允许该导出对应的顶层函数`,
1374
+ `入口只能导入 ${utilsPrefix}<入口名> 或 ./${sharedName}`,
1375
+ `${sharedName} 与 ${utilsName} 互不引用`,
1376
+ strictRoot ? `根目录只放入口与 ${sharedName}/${utilsName}` : void 0
1377
+ ].filter(Boolean);
1378
+ const lines = [`扫描 ${path.relative(repoRoot, root)} 下 ${entryFiles.length} 个入口。`, `规则:${rules.join(";")}。`];
1379
+ const success = violations.length === 0;
1380
+ if (success) lines.push("未发现结构违规。");
1381
+ else lines.push(`发现 ${violations.filter((line) => line.startsWith(" - ")).length} 处违规:`, ...violations);
1382
+ return {
1383
+ name,
1384
+ success,
1385
+ messages: lines.join("\n"),
1386
+ howToFix: success ? "" : `helper 移出入口文件:被 ${threshold} 个及以上入口使用的放到 ${sharedName},其余放到 ${utilsName}/<入口名>;${sharedName} 与 ${utilsName} 不要互相引用。`
1387
+ };
1388
+ };
1389
+ }
1390
+ function readFunctionName(node) {
1391
+ if (node.type === "FunctionDeclaration") return readName(node.id) ?? "匿名函数";
1392
+ if (node.type === "VariableDeclarator" && isFunctionLike(node.init)) return readName(node.id) ?? "匿名函数";
1393
+ }
1394
+ /** 按节点识别允许的顶层函数,避免同名的嵌套 helper 被豁免。 */
1395
+ function collectEntryFunctions(source, exportName) {
1396
+ const localNames = /* @__PURE__ */ new Set();
1397
+ for (const node of source.program.body) {
1398
+ if (node.type !== "ExportNamedDeclaration" || node.source || node.exportKind === "type") continue;
1399
+ const declaration = node.declaration;
1400
+ if (declaration?.type === "FunctionDeclaration" && readName(declaration.id) === exportName) localNames.add(exportName);
1401
+ if (declaration?.type === "VariableDeclaration") {
1402
+ for (const item of declaration.declarations ?? []) if (readName(item.id) === exportName) localNames.add(exportName);
1403
+ }
1404
+ for (const specifier of node.specifiers ?? []) {
1405
+ if (specifier.exportKind === "type") continue;
1406
+ if (readName(specifier.exported) === exportName) {
1407
+ const local = readName(specifier.local);
1408
+ if (local) localNames.add(local);
1409
+ }
1410
+ }
1411
+ }
1412
+ const allowed = /* @__PURE__ */ new Set();
1413
+ for (const node of source.program.body) {
1414
+ const declaration = node.type === "ExportNamedDeclaration" ? node.declaration : node;
1415
+ if (declaration?.type === "FunctionDeclaration" && localNames.has(readName(declaration.id) ?? "")) allowed.add(declaration);
1416
+ if (declaration?.type === "VariableDeclaration") {
1417
+ for (const item of declaration.declarations ?? []) if (localNames.has(readName(item.id) ?? "") && isFunctionLike(item.init)) allowed.add(item);
1418
+ }
1419
+ }
1420
+ return allowed;
1421
+ }
1422
+ function hasNamedExport(source, exportName) {
1423
+ for (const node of source.program.body) {
1424
+ if (node.type !== "ExportNamedDeclaration" || node.exportKind === "type") continue;
1425
+ const declaration = node.declaration;
1426
+ if (!declaration?.declare && (declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration")) {
1427
+ if (readName(declaration.id) === exportName) return true;
1428
+ }
1429
+ if (declaration?.type === "VariableDeclaration" && !declaration.declare) {
1430
+ if ((declaration.declarations ?? []).some((item) => readName(item.id) === exportName)) return true;
1431
+ }
1432
+ for (const specifier of node.specifiers ?? []) {
1433
+ if (specifier.exportKind === "type") continue;
1434
+ if ((readName(specifier.exported) ?? readName(specifier.local)) === exportName) return true;
1435
+ }
1436
+ }
1437
+ return false;
1438
+ }
1439
+ function collectImports(source, prefix) {
1440
+ const imports = [];
1441
+ for (const node of source.program.body) {
1442
+ if (node.type !== "ImportDeclaration") continue;
1443
+ const specifier = readModuleSpecifier(node);
1444
+ if (!specifier?.startsWith(prefix)) continue;
1445
+ const importedNames = (node.specifiers ?? []).map((item) => item.type === "ImportDefaultSpecifier" ? "default" : item.type === "ImportNamespaceSpecifier" ? "*" : readName(item.imported) ?? readName(item.local) ?? "anonymous");
1446
+ imports.push({
1447
+ specifier,
1448
+ importedNames,
1449
+ line: lineOf(source, node)
1450
+ });
1451
+ }
1452
+ return imports;
1453
+ }
1454
+ export { CJK_PATTERN, commitMessage, duplicateLocalization, e2eScenariosStructure, sameDirImportOnly, singleComponentFile, sourceLocaleDefaults, syncLocales, uiScenariosStructure };