@code-sentinel-cli/code-sentinel-cli 4.0.13-avtest.1 → 4.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,11 @@ Bạn là senior Angular reviewer. Đánh giá Angular review unit dưới đây
2
2
 
3
3
  ## CRITICAL RULES
4
4
 
5
+ Framework/contract evidence requirements:
6
+
7
+ - Resolve the exact type import module (including aliases and re-exports) before reporting a missing response field. A same-named interface in an unused support file is not the caller's contract. For example `IAuthResponse` imported from `@core/auth` may include a reset `token` even when an old UI-local interface does not. Missing canonical support is insufficient evidence of a mismatch. A field truly absent from the canonical imported contract remains reportable.
8
+
9
+
5
10
  1. **CHỈ report lỗi có bằng chứng cụ thể** trong primary hoặc support files. Không đoán convention ngoài cluster.
6
11
  2. **`line` BẮT BUỘC trỏ về PRIMARY file**.
7
12
  3. **Confidence `<50` → KHÔNG emit**.
@@ -21,6 +26,22 @@ Bạn là senior Angular reviewer. Đánh giá Angular review unit dưới đây
21
26
  - Deprecated API được dùng trong wrapper chính với compatibility comment, nhưng caller bên ngoài không bypass contract.
22
27
  - Không đủ evidence về service/wrapper/caller contract trong cluster.
23
28
 
29
+ ## Kiểm chứng contract trước khi kết luận
30
+
31
+ - Raw HttpClient vẫn đi qua interceptor đã đăng ký. Raw trả envelope `{detail}`, wrapper có thể unwrap detail; caller đọc res.detail từ raw response là nhất quán. Không đổi wrapper rồi giữ caller gây double unwrap.
32
+ - `%26` là encoding hợp lệ của `&`; backend decode query value. `.join("&")` sai danh sách khi có contract List/string[] hoặc repeated params; nếu backend nhận scalar tự tách thì có thể đúng. Thiếu backend contract thì không đoán delimiter.
33
+ - List<String> và encoder hỗ trợ array: truyền array để sinh `paths=a&paths=b`, giữ ký tự đặc biệt trong mỗi phần tử.
34
+ - Reset-password token khác OAuth accessToken/refreshToken. Field thiếu trong interface là typing gap cần xác minh; không thay reset token bằng accessToken chỉ vì field chưa khai báo.
35
+
36
+ ## Trace contract qua callee, không suy luận từ tên/type đơn lẻ
37
+
38
+ - Lần theo method được caller gọi và pipeline thực tế trong support files: `map(res => res?.detail ?? res)` đã unwrap một lần. Caller đọc `res.content`/`res.totalElements` là đúng khi đó; thêm `.detail` sẽ gây double unwrap. Nếu generic `Observable<Wrapped>` còn giữ envelope dù pipeline unwrap, báo **typing mismatch ở service** khi service là PRIMARY, không khẳng định caller runtime sai.
39
+ - `ResponseDetailType<T>` không đồng nghĩa `{detail:T}`: đọc định nghĩa field. Nếu type thực có `content`, caller `res.content` là nhất quán. Một method `getProcessEmployees` không thừa hưởng contract `getUnconfirmedList` chỉ vì cùng service hoặc tên kiểu gần giống.
40
+ - Raw HttpClient trên service được inject vẫn chạy interceptors. Caller cố ý đọc raw envelope `res.detail`, gắn `SKIP_LOADING`, không có mismatch error handling đã chứng minh thì không flag chỉ vì không thêm wrapper method. Nếu headers/org/auth khác là lỗi, phải chỉ ra endpoint cần chúng trong support evidence; không giả định mọi endpoint có cùng yêu cầu.
41
+ - `fetch(..., {keepalive:true})` trong beforeunload/ngOnDestroy có mục đích hoàn tất request khi page đóng. Không đề nghị thay bằng HttpClient hay sendBeacon chỉ vì khác kiến trúc: phải giữ keepalive và Authorization contract (sendBeacon không hỗ trợ header Authorization tùy ý). URL query chứa giá trị chưa encode vẫn là lỗi riêng; encodeURIComponent/HttpParams đã encode thì không flag query.
42
+ - PUT khai báo `null` và caller đọc `res.detail` có contract mismatch; generic không chứng minh server thực trả null. Tách evidence compile contract với response backend chưa biết. Callback không đọc response, cache request snapshot sau success thì không flag mismatch; không tự đoán response object để đổi type.
43
+ - Khi wrapper/interceptors nằm ngoài phạm vi context được phép gửi, thiếu support là **thiếu bằng chứng**. Không suy diễn runtime envelope hoặc framework auth từ khai báo return type `any` hay shared convention. Chỉ dùng source thực có trong primary/support; không coi import path là nội dung callee đã được xem.
44
+
24
45
  ## Primary file
25
46
 
26
47
  Additional non-violations:
@@ -1,6 +1,7 @@
1
1
  id: angular/api-service-contract-risk
2
- # v3 (ADR-0065 calibration): conf 60→85 (đo 26/26 TP)
3
- version: 3
2
+ # v5: trace actual unwrap/raw interceptor/unload transport contracts.
3
+ # Prior calibration is not evidence of precision for this changed prompt.
4
+ version: 6
4
5
  kind: ai
5
6
  title: "Angular API service/error contract có rủi ro không?"
6
7
  description: |
@@ -2,6 +2,12 @@ Bạn là senior Angular reviewer. Đánh giá Angular review unit dưới đây
2
2
 
3
3
  ## CRITICAL RULES
4
4
 
5
+ Framework/contract evidence requirements:
6
+
7
+ - Angular computed tracks signal reads transitively through ordinary methods and inherited service methods. Follow the implementation of `service.format()` (including its base class) before claiming it is non-reactive. If it reads a signal, the computed is reactive; if support implementation is missing, state this evidence gap rather than asserting stale countdown. A method returning only a mutable plain field can still be a real stale-derived-state issue.
8
+ - Zone.js normally patches FileReader callbacks. Do not assert they run outside NgZone solely because they are FileReader events; require explicit unpatched/zoneless/runOutsideAngular evidence and evaluate signal/ChangeDetectorRef scheduling.
9
+
10
+
5
11
  CRITICAL NON-VIOLATIONS:
6
12
 
7
13
  - NEVER report `form.patchValue(...)`, `form.reset()`, `form.getRawValue()`, or `form.controls.x.value` as an OnPush/change-detection issue by itself.
@@ -1,6 +1,6 @@
1
1
  id: angular/component-state-flow
2
2
  # v4 (ADR-0065 calibration): conf 60→85 (đo 49/49 TP)
3
- version: 4
3
+ version: 5
4
4
  kind: ai
5
5
  title: "Angular component state/change detection flow có rủi ro không?"
6
6
  description: |
@@ -2,6 +2,12 @@ Bạn là senior Angular reviewer. Đánh giá Angular review unit dưới đây
2
2
 
3
3
  ## CRITICAL RULES
4
4
 
5
+ Framework/contract evidence requirements:
6
+
7
+ - Angular `FormGroupDirective` intercepts a normal `<form [formGroup]>` submit and prevents browser reload even without an `(ngSubmit)` binding. A `type="submit"` button with `(click)` is not proof of default navigation. Report submit loss only with a demonstrated trigger that fails to call the handler, and avoid recommending both click and ngSubmit handlers that duplicate submission.
8
+ - An input with `formControlName` is synchronized by its ControlValueAccessor. A custom `(input)` filter may call `setValue` only when normalization changes the text. Do not claim valid keystrokes never reach the control unless the actual accessor/binding is missing or proven broken. A manual input with no form binding still requires explicit synchronization.
9
+
10
+
5
11
  CRITICAL NON-VIOLATIONS:
6
12
 
7
13
  - NEVER report a required-validator issue when the external template renders a reusable error component bound to that control, such as `[control]="form.controls.title"`.
@@ -1,6 +1,6 @@
1
1
  id: angular/reactive-form-flow
2
2
  # v5 (ADR-0065 calibration): conf 60→85 (đo 46/46 TP)
3
- version: 5
3
+ version: 6
4
4
  kind: ai
5
5
  title: "Angular reactive form flow có rủi ro submit/validation không?"
6
6
  description: |
@@ -5,7 +5,7 @@ Bạn là senior Angular/RxJS reviewer. Đánh giá Angular review unit dưới
5
5
  CRITICAL NON-VIOLATIONS:
6
6
 
7
7
  - NEVER report a component call to an injected signal store / NgRx signal-store `rxMethod` as a direct Observable subscription.
8
- - NEVER report missing component-level `catchError`, `finalize`, or unsubscribe when the support store/service method owns the Observable pipeline with `tapResponse`, `catchError`, `finalize`, `withCallState`, or equivalent error/loading handling.
8
+ - Do not require duplicate component-level error/loading handling when support evidence proves that the invoked store/service owns that exact state (e.g. `tapResponse` / `withCallState`). A `catchError` that rethrows, a `finalize` that resets a different flag, or a global toast alone does NOT prove the component state is safe.
9
9
  - NEVER report `ngOnDestroy()` containing only `form.reset()` as an RxJS leak or cancellation issue.
10
10
  - NEVER report plain component calls like `this.articleStore.getArticle(...)` / `this.articleStore.getComments(...)` as missing unsubscribe when support evidence shows those methods are NgRx signal-store `rxMethod` pipelines.
11
11
 
@@ -17,7 +17,7 @@ CRITICAL NON-VIOLATIONS:
17
17
 
18
18
  - Nested `subscribe` hoặc subscribe bên trong callback async tạo race/duplicate side effects/khó cancel.
19
19
  - Search/filter/autocomplete/load-latest flow dùng `mergeMap`, subscribe thủ công, hoặc Promise mà không cancel request cũ; nên dùng `switchMap`, `takeUntilDestroyed`, hoặc stream composition.
20
- - Loading/saving flag được set `true` nhưng không reset trong error/cancel path (`finalize` thiếu).
20
+ - Loading/saving flag được set `true` nhưng không reset trong error/cancel/empty-completion path. Kiểm tra hành vi mọi nhánh; không yêu cầu `finalize` nếu cleanup tương đương đã đủ.
21
21
  - Error bị swallow trong Observable/Promise chain khiến UI giữ trạng thái success/loading sai.
22
22
  - Side effect phụ thuộc order response nhưng code không bảo vệ out-of-order response.
23
23
  - Component gọi service Observable/Subject theo flow làm mất cancellation/error propagation/loading consistency.
@@ -25,16 +25,29 @@ CRITICAL NON-VIOLATIONS:
25
25
  ## KHÔNG flag
26
26
 
27
27
  - `.subscribe()` chỉ vì thiếu unsubscribe nếu static `angular/no-leaky-subscription` đã bắt và không có bug flow khác.
28
- - Stream đơn giản dùng `async` pipe, `take(1)`, `firstValueFrom` có `try/catch`, hoặc `switchMap` đúng chỗ.
28
+ - Stream đơn giản an toàn qua `async` pipe, hoặc composition có cancellation/error-state phù hợp. `take(1)` và `firstValueFrom` + `try/catch` KHÔNG tự bảo vệ thứ tự response của nhiều lần gọi.
29
29
  - Vấn đề naming/style thuần túy.
30
30
  - Test/spec/generated files.
31
31
 
32
+ ## Kiểm chứng theo owner và timeline
33
+
34
+ - `takeUntilDestroyed` chỉ hủy khi owner bị destroy; nó KHÔNG hủy request cũ khi search/tab/blur được gọi lại. Ngược lại, `takeUntil` với notifier phát trước mỗi lần đọc, explicit `unsubscribe`, hoặc request-id/selection guard bảo vệ đúng response là cancellation/latest-response hợp lệ, không bắt buộc `switchMap`.
35
+ - Nested subscription không tự chứng minh lỗi. Nếu inner request là tác vụ application-owned, phải hoàn tất qua navigation, không cập nhật component và xử lý lỗi/fallback riêng, KHÔNG đề xuất gắn teardown của component chỉ để loại bỏ nesting. Vẫn bắt nếu có bằng chứng stale component update, thứ tự bị đảo hoặc duplicate command.
36
+ - Guard chống submit/load-more phải được kiểm tra TRƯỚC khi phát request và reset cả khi lỗi/hủy. Nút disabled là hỗ trợ UX; chỉ đổi disabled mà handler vẫn gửi trùng chưa chứng minh an toàn.
37
+ - Promise `await` bị reject sẽ dừng các statement tiếp theo: KHÔNG nói refresh/success vẫn chạy nếu không có recovery/finally tiếp tục flow. SDK trả `{ data, error }` đã resolve là trường hợp khác: phải kiểm tra contract và `result.error` trước success/refresh. Không đoán kiểu trả về khi thiếu bằng chứng SDK.
38
+ - Những response của các tab KHÁC NHAU ghi đúng key riêng không tự tạo race. Chỉ bắt khi cùng key/state có thể bị ghi đè bởi request cũ hoặc callback đọc selection/filter đã thay đổi sau await.
39
+ - Cleanup phụ thất bại sau khi bản ghi đã được lưu là partial success. Cảnh báo riêng, không báo hoàn tất toàn bộ, không gợi ý retry lại create đã thành công. Nếu đã thông báo đúng partial success thì không bắt lỗi swallow.
40
+ - Một subscribe chỉ thiếu teardown và không có flow bug riêng thuộc `angular/no-leaky-subscription`. Không lặp lại finding đó, kể cả static result không được cung cấp.
41
+
42
+ Ví dụ an toàn: mỗi lần search gọi `cancel$.next()` rồi `api.search(q).pipe(takeUntil(cancel$), takeUntilDestroyed(ref))`; callback Promise capture title/filter/request-id trước await và chỉ apply khi còn khớp; pagination khóa request đang chạy và chỉ tăng page trong success.
43
+ Ví dụ lỗi thật gần giống: chỉ có `takeUntilDestroyed(ref)` trong search; callback await ghi `this.selectedTab` hiện tại; page++ trước API rồi không rollback khi lỗi; cờ saving chỉ reset trong next.
44
+
32
45
  ## Code cần review
33
46
 
34
47
  Additional non-violations:
35
48
 
36
49
  - Calling an injected signal store method / NgRx signal-store `rxMethod` from a component is NOT a direct Observable subscription. Do not flag missing `catchError`, `finalize`, or unsubscribe in the component when the support store method owns the Observable pipeline.
37
- - If the support store/service uses `tapResponse`, `catchError`, `finalize`, `withCallState`, or an equivalent error/loading handler for the invoked method, do not report the component call site as missing error handling.
50
+ - Inspect the exact invoked support method and the state it owns. `catchError(() => throwError(...))` still propagates failure; a global error toast does not reset a component saving flag.
38
51
  - `ngOnDestroy()` with only `form.reset()` or other Reactive Form cleanup is NOT an RxJS subscription leak.
39
52
  - A resolver or component that triggers a store load method is not a race/cancellation bug unless there are multiple competing requests or stale response ordering shown in the cluster.
40
53
 
@@ -1,6 +1,7 @@
1
1
  id: angular/rxjs-flow-risk
2
- # v5 (ADR-0065 calibration): conf 60→90 (đo 233/233 TP — rule AI bị định giá thấp nhất catalog)
3
- version: 5
2
+ # v5 calibration retained; v6 adds ownership/timeline/error-contract guidance.
3
+ # Prompt regression tests do not measure live-model precision.
4
+ version: 6
4
5
  kind: ai
5
6
  title: "Angular RxJS async flow có rủi ro không?"
6
7
  description: |
@@ -2,6 +2,12 @@ Bạn là senior Angular reviewer. Đánh giá Angular review unit dưới đây
2
2
 
3
3
  ## CRITICAL RULES
4
4
 
5
+ Framework/contract evidence requirements:
6
+
7
+ - Angular `@for` and `*ngFor` accept null/undefined collections and render zero items. A nullable iterable alone is not a crash or missing-guard violation. Unguarded nested property access before iteration, such as `nullableOwner.files`, can still be a bug.
8
+ - Distinguish a missing optional field from a nullable receiver: `item.name` is safe property access when `item` exists even if `name?: string`; `item?.name` does not make a missing name defined. Require a concrete non-null API requirement or downstream dereference before reporting optional primitive fields as unsafe bindings.
9
+
10
+
5
11
  1. **CHỈ report lỗi có bằng chứng cụ thể** trong primary hoặc support files. Không đoán convention ngoài cluster.
6
12
  2. **`line` BẮT BUỘC trỏ về PRIMARY file**.
7
13
  3. **Confidence `<50` → KHÔNG emit**.
@@ -22,7 +28,7 @@ Bạn là senior Angular reviewer. Đánh giá Angular review unit dưới đây
22
28
  - External template trong cluster tham chiếu property/method không tồn tại trong component class.
23
29
  - Template gọi method với số lượng/thứ tự/kiểu tham số rõ ràng không khớp signature.
24
30
  - Template truy cập nested property có thể `undefined` mà không guard (`?.`, `@if`, `*ngIf`) trong khi class khởi tạo nullable/optional.
25
- - `*ngFor` hoặc `@for` render collection có thể undefined/null mà không fallback/guard.
31
+ - Collection chứa phần tử nullable được template dereference mà không guard, hoặc biểu thức lấy collection dereference nullable owner.
26
32
  - Two-way binding trỏ vào object path có thể undefined.
27
33
 
28
34
  ## KHÔNG flag
@@ -1,6 +1,6 @@
1
1
  id: angular/template-contract-risk
2
2
  # v5 (ADR-0065 calibration): conf 60→70 (đo 7/7 TP — mẫu nhỏ, nâng dè dặt)
3
- version: 5
3
+ version: 6
4
4
  kind: ai
5
5
  title: "Angular template/component contract có rủi ro runtime không?"
6
6
  description: |
@@ -33,6 +33,10 @@ Language: {{language}}
33
33
  {{code}}
34
34
  ```
35
35
 
36
+ ## TypeScript union và giá trị khởi tạo
37
+
38
+ `otpTtl: string | number | undefined = 0` là khai báo hợp lệ: giá trị khởi tạo thuộc union. Không báo kiểu không nhất quán chỉ vì union cho phép `undefined` nhưng khởi tạo bằng số; cũng không yêu cầu đổi mặc định sang `undefined` hoặc thu hẹp type khi API có thể trả nhiều kiểu. Chỉ báo khi có bằng chứng cách sử dụng giá trị gây hiểu nhầm hoặc trái contract; tách nhận xét naming khỏi nhận xét về type.
39
+
36
40
  ## Output yêu cầu
37
41
 
38
42
  Trả về **JSON HỢP LỆ DUY NHẤT** (không markdown fence, không text khác) theo schema:
@@ -5,7 +5,7 @@ id: general/code-clarity
5
5
  # MỘT pattern (`const R = VauthzResource`) lặp ở 27 file; 6 FP là param 1 ký
6
6
  # tự trong callback (`.map(b => b.brand)`). Cả hai đều là quy ước hợp lệ,
7
7
  # prompt v4 miễn tường minh.
8
- version: 4
8
+ version: 5
9
9
  kind: ai
10
10
  title: "Code có rõ ràng và dễ đọc không?"
11
11
  description: |
@@ -1,4 +1,8 @@
1
+ import { existsSync, readFileSync } from 'fs';
2
+ import { dirname, join, relative, sep, resolve } from 'path';
1
3
  import { asTreeSitterTree } from '@code-sentinel/parsers';
4
+ import { globSync } from 'tinyglobby';
5
+ import { Project, Node } from 'ts-morph';
2
6
 
3
7
  // builtin-rules/static/angular/button-accessible-name.rule.ts
4
8
  var ACCESSIBLE_NAME_ATTRS = /* @__PURE__ */ new Set([
@@ -36,7 +40,237 @@ function normalizeAttrName(name) {
36
40
  function attributeValue(attr) {
37
41
  const quoted = namedChildOfType(attr, "quoted_attribute_value");
38
42
  const value = quoted ? namedChildOfType(quoted, "attribute_value") : null;
39
- return value?.text ?? "";
43
+ return value?.text ?? namedChildOfType(attr, "attribute_value")?.text ?? "";
44
+ }
45
+ function provenTailwindStyles(file) {
46
+ try {
47
+ let root = dirname(file);
48
+ while (!existsSync(join(root, "angular.json")) || !existsSync(join(root, "package.json"))) {
49
+ const parent = dirname(root);
50
+ if (parent === root) return null;
51
+ root = parent;
52
+ }
53
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
54
+ const version = pkg.dependencies?.tailwindcss ?? pkg.devDependencies?.tailwindcss;
55
+ if (typeof version !== "string" || !/^[~^]?3\./.test(version)) return null;
56
+ const configPath = ["tailwind.config.js", "tailwind.config.cjs", "tailwind.config.ts"].map((name) => join(root, name)).find(existsSync);
57
+ if (!configPath) return null;
58
+ const config = new Project({ useInMemoryFileSystem: true }).createSourceFile(
59
+ "config.ts",
60
+ readFileSync(configPath, "utf8")
61
+ );
62
+ const expression = config.getStatements().map((statement) => {
63
+ if (Node.isExpressionStatement(statement)) {
64
+ const expr = statement.getExpression();
65
+ if (Node.isBinaryExpression(expr) && expr.getLeft().getText() === "module.exports")
66
+ return expr.getRight();
67
+ }
68
+ if (Node.isExportAssignment(statement)) return statement.getExpression();
69
+ return void 0;
70
+ }).find((expression2) => expression2 && Node.isObjectLiteralExpression(expression2));
71
+ if (!expression || !Node.isObjectLiteralExpression(expression) || config.getStatements().length !== 1)
72
+ return null;
73
+ if (expression.getDescendants().some(
74
+ (node) => Node.isCallExpression(node) || Node.isNewExpression(node) || Node.isArrowFunction(node) || Node.isFunctionExpression(node) || Node.isGetAccessorDeclaration(node) || Node.isSpreadAssignment(node)
75
+ ))
76
+ return null;
77
+ const allowed = /* @__PURE__ */ new Set(["content", "theme", "plugins"]);
78
+ if (expression.getProperties().some((prop) => !Node.isPropertyAssignment(prop) || !allowed.has(prop.getName())))
79
+ return null;
80
+ const property = (name) => {
81
+ const prop = expression.getProperty(name);
82
+ return prop && Node.isPropertyAssignment(prop) ? prop.getInitializer() : void 0;
83
+ };
84
+ const plugins = property("plugins");
85
+ if (plugins && (!Node.isArrayLiteralExpression(plugins) || plugins.getElements().length))
86
+ return null;
87
+ const content = property("content");
88
+ if (!content || !Node.isArrayLiteralExpression(content)) return null;
89
+ const patterns = content.getElements().map((value) => Node.isStringLiteral(value) ? value.getLiteralText() : null);
90
+ if (patterns.some((value) => value === null)) return null;
91
+ const template = relative(root, file).split(sep).join("/");
92
+ if (!globSync(patterns, { cwd: root, onlyFiles: true }).includes(template))
93
+ return null;
94
+ const angular = JSON.parse(readFileSync(join(root, "angular.json"), "utf8"));
95
+ if (!angular.projects || Object.keys(angular.projects).length !== 1) return null;
96
+ const styles = /* @__PURE__ */ new Set();
97
+ const collect = (value) => {
98
+ if (!value || typeof value !== "object") return;
99
+ for (const [key, item] of Object.entries(value)) {
100
+ if (key === "styles" && Array.isArray(item)) {
101
+ for (const style of item) {
102
+ const input = typeof style === "string" ? style : style?.input;
103
+ if (typeof input !== "string" || /[{}]/.test(input)) continue;
104
+ styles.add(resolve(root, input));
105
+ }
106
+ } else collect(item);
107
+ }
108
+ };
109
+ collect(angular);
110
+ for (const extension of ["css", "scss", "less"]) {
111
+ const companion = file.replace(/\.html$/, `.${extension}`);
112
+ if (existsSync(companion)) styles.add(companion);
113
+ }
114
+ const texts = [];
115
+ const visited = /* @__PURE__ */ new Set();
116
+ const readStyles = (style) => {
117
+ if (visited.has(style)) return true;
118
+ visited.add(style);
119
+ const text = readFileSync(style, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");
120
+ texts.push(text);
121
+ if (/@(?:import|use|forward)\s+url\(/.test(text)) return false;
122
+ if (/@(?:import|use|forward)[^;]*['"]\s*,/.test(text)) return false;
123
+ for (const match of text.matchAll(/@(?:import|use|forward)\s+(['"])([^'"]+)\1/g)) {
124
+ const specifier = match[2];
125
+ if (!specifier || specifier.includes("#{")) return false;
126
+ const candidate = specifier.startsWith(".") ? resolve(dirname(style), specifier) : resolve(root, "node_modules", specifier.replace(/^~/, ""));
127
+ const resolved = [
128
+ candidate,
129
+ `${candidate}.scss`,
130
+ `${candidate}.css`,
131
+ `${candidate}.less`
132
+ ].find(existsSync);
133
+ if (!resolved || !readStyles(resolved)) return false;
134
+ }
135
+ return true;
136
+ };
137
+ if (![...styles].every(readStyles)) return null;
138
+ if (!texts.some((text) => /@tailwind\s+utilities\s*;/.test(text))) return null;
139
+ if (texts.some(
140
+ (text) => /\.invisible(?:[^\w-]|$)|(?:^|[;{])\s*visibility\s*:|@apply[^;]*(?:visible|visibility)/m.test(
141
+ text
142
+ )
143
+ ))
144
+ return null;
145
+ const componentPath = file.replace(/\.html$/, ".ts");
146
+ if (existsSync(componentPath) && /\bstyles\s*:/.test(readFileSync(componentPath, "utf8")))
147
+ return null;
148
+ if (existsSync(componentPath)) {
149
+ const component = readFileSync(componentPath, "utf8");
150
+ for (const match of component.matchAll(/\bstyleUrls?\s*:\s*(?:\[\s*)?(['"])([^'"]+)\1/g)) {
151
+ if (resolve(dirname(componentPath), match[2] ?? "") !== file.replace(/\.html$/, ".scss") && resolve(dirname(componentPath), match[2] ?? "") !== file.replace(/\.html$/, ".css") && resolve(dirname(componentPath), match[2] ?? "") !== file.replace(/\.html$/, ".less"))
152
+ return null;
153
+ }
154
+ if (/\bstyleUrls\s*:\s*\[/.test(component)) return null;
155
+ }
156
+ return texts;
157
+ } catch {
158
+ return null;
159
+ }
160
+ }
161
+ function hasProvenHiddenUtility(tag, tailwind) {
162
+ if (!tailwind) return false;
163
+ let classes = [];
164
+ for (const attr of tag.namedChildren) {
165
+ if (attr.type !== "attribute") continue;
166
+ const name = namedChildOfType(attr, "attribute_name")?.text ?? "";
167
+ const prop = normalizeAttrName(name);
168
+ if (name.startsWith("[") || name.startsWith("bind-") || prop === "ngclass" || prop === "ngstyle")
169
+ return false;
170
+ if (prop === "style") return false;
171
+ if (prop === "class") {
172
+ const value = attributeValue(attr);
173
+ if (value.includes("{{")) return false;
174
+ classes = value.split(/\s+/);
175
+ }
176
+ }
177
+ if (!classes.includes("invisible")) return false;
178
+ if (classes.some((value) => value !== "invisible" && /(?:visible|visibility|\[|!)/.test(value)))
179
+ return false;
180
+ return true;
181
+ }
182
+ function visibilityOfTag(tagNode, tailwind = false) {
183
+ let uncertain = false;
184
+ let hidden = hasProvenHiddenUtility(tagNode, tailwind);
185
+ for (const attr of tagNode.namedChildren) {
186
+ if (attr.type !== "attribute") continue;
187
+ const rawName = namedChildOfType(attr, "attribute_name")?.text ?? "";
188
+ const prop = normalizeAttrName(rawName);
189
+ const bound = rawName.startsWith("[") || rawName.startsWith("bind-");
190
+ const value = attributeValue(attr).trim().toLowerCase();
191
+ if (bound && (prop === "hidden" || prop === "aria-hidden" || prop.startsWith("style") || prop.startsWith("class") || prop === "ngclass" || prop === "ngstyle")) {
192
+ uncertain = true;
193
+ continue;
194
+ }
195
+ if (!bound && prop === "hidden") hidden = true;
196
+ if (!bound && prop === "aria-hidden" && value === "true") hidden = true;
197
+ if (!bound && prop === "style") {
198
+ if (value.includes("{{")) {
199
+ uncertain = true;
200
+ continue;
201
+ }
202
+ const declarations = /* @__PURE__ */ new Map();
203
+ for (const declaration of value.split(";")) {
204
+ const colon = declaration.indexOf(":");
205
+ if (colon < 0) continue;
206
+ const name = declaration.slice(0, colon).trim();
207
+ const rawValue = declaration.slice(colon + 1).trim();
208
+ const important = /\s*!important$/.test(rawValue);
209
+ if (declarations.get(name)?.important && !important) continue;
210
+ declarations.set(name, { value: rawValue.replace(/\s*!important$/, "").trim(), important });
211
+ }
212
+ if (declarations.get("display")?.value === "none" || declarations.get("visibility")?.value === "hidden" || declarations.get("visibility")?.value === "collapse")
213
+ hidden = true;
214
+ }
215
+ }
216
+ return uncertain ? "uncertain" : hidden ? "hidden" : "visible";
217
+ }
218
+ function visibilityOfNode(node, tailwind = false) {
219
+ let uncertain = false;
220
+ let overridesInheritedVisibility = false;
221
+ let cur = node;
222
+ while (cur) {
223
+ if (cur.type === "element") {
224
+ const tag = namedChildOfType(cur, "start_tag") ?? namedChildOfType(cur, "self_closing_tag");
225
+ if (tag) {
226
+ const visibility = visibilityOfTag(tag, tailwind);
227
+ const attrs = tag.namedChildren.filter((child) => child.type === "attribute");
228
+ const inlineStyle = attrs.find(
229
+ (attr) => namedChildOfType(attr, "attribute_name")?.text.toLowerCase() === "style"
230
+ );
231
+ const style = inlineStyle ? attributeValue(inlineStyle).trim().toLowerCase() : "";
232
+ const onlyInheritedHidden = visibility === "hidden" && (hasProvenHiddenUtility(tag, tailwind) || /visibility\s*:\s*(hidden|collapse)/.test(style)) && !/display\s*:\s*none/.test(style) && !attrs.some((attr) => {
233
+ const name = namedChildOfType(attr, "attribute_name")?.text.toLowerCase();
234
+ return name === "hidden" || name === "aria-hidden" && attributeValue(attr).trim() === "true";
235
+ });
236
+ if (visibility === "hidden" && !(overridesInheritedVisibility && onlyInheritedHidden)) {
237
+ if (onlyInheritedHidden && uncertain) return "uncertain";
238
+ return "hidden";
239
+ }
240
+ uncertain ||= visibility === "uncertain";
241
+ if (visibility !== "uncertain" && (/visibility\s*:\s*visible\s*(?:!important)?\s*(?:;|$)/.test(style) || tailwind && attrs.some(
242
+ (attr) => namedChildOfType(attr, "attribute_name")?.text === "class" && attributeValue(attr).split(/\s+/).includes("visible")
243
+ ))) {
244
+ overridesInheritedVisibility = true;
245
+ }
246
+ }
247
+ }
248
+ cur = cur.parent;
249
+ }
250
+ return uncertain ? "uncertain" : "visible";
251
+ }
252
+ function hasMeaningfulImageAlt(element) {
253
+ const tag = namedChildOfType(element, "start_tag") ?? namedChildOfType(element, "self_closing_tag");
254
+ if (!tag || namedChildOfType(tag, "tag_name")?.text.toLowerCase() !== "img") return false;
255
+ for (const attr of tag.namedChildren) {
256
+ if (attr.type !== "attribute") continue;
257
+ const rawName = namedChildOfType(attr, "attribute_name")?.text ?? "";
258
+ const prop = normalizeAttrName(rawName);
259
+ if (prop === "role" && DECORATIVE_ROLES.has(attributeValue(attr).trim().toLowerCase()))
260
+ return false;
261
+ }
262
+ for (const attr of tag.namedChildren) {
263
+ if (attr.type !== "attribute") continue;
264
+ const rawName = namedChildOfType(attr, "attribute_name")?.text ?? "";
265
+ if (normalizeAttrName(rawName) !== "alt") continue;
266
+ const value = attributeValue(attr).trim();
267
+ if (rawName.startsWith("[") || rawName.startsWith("bind-")) {
268
+ const literal = /^(['"])([^'"\n]+)\1$/.exec(value);
269
+ return Boolean(literal?.[2]?.trim());
270
+ }
271
+ return value.length > 0 && !value.includes("{{");
272
+ }
273
+ return false;
40
274
  }
41
275
  function hasAccessibleAttr(tagNode) {
42
276
  for (let i = 0; i < tagNode.namedChildCount; i++) {
@@ -80,8 +314,22 @@ function isInsideIconTag(node, rootElement) {
80
314
  }
81
315
  return false;
82
316
  }
83
- function hasMeaningfulTextOrDirective(elementNode) {
317
+ function hasUncertainDescendantVisibility(node, root) {
318
+ let current = node;
319
+ while (current && current.id !== root.id) {
320
+ if (current.type === "element") {
321
+ const tag = namedChildOfType(current, "start_tag") ?? namedChildOfType(current, "self_closing_tag");
322
+ if (tag && visibilityOfTag(tag) === "uncertain") return true;
323
+ }
324
+ current = current.parent;
325
+ }
326
+ return false;
327
+ }
328
+ function hasMeaningfulTextOrDirective(elementNode, tailwind = false) {
84
329
  for (const node of walkNodes(elementNode)) {
330
+ if (visibilityOfNode(node, tailwind) === "hidden" || hasUncertainDescendantVisibility(node, elementNode))
331
+ continue;
332
+ if (node.type === "element" && hasMeaningfulImageAlt(node)) return true;
85
333
  if (node.type === "text") {
86
334
  const text = node.text.trim();
87
335
  if (text.length > 0 && !isInsideIconTag(node, elementNode)) return true;
@@ -100,7 +348,7 @@ function hasMeaningfulTextOrDirective(elementNode) {
100
348
  }
101
349
  var rule = {
102
350
  id: "angular/button-accessible-name",
103
- version: 1,
351
+ version: 3,
104
352
  kind: "static-ts",
105
353
  title: "`<button>` v\xE0 `<a>` ph\u1EA3i c\xF3 accessible name (text ho\u1EB7c `aria-label`)",
106
354
  description: "N\xFAt b\u1EA5m (`<button>`) v\xE0 li\xEAn k\u1EBFt (`<a>`) thi\u1EBFu accessible name vi ph\u1EA1m WCAG 4.1.2 / 2.4.4. N\u1EBFu n\xFAt ch\u1EC9 ch\u1EE9a icon (nh\u01B0 `<mat-icon>`, `<i>`, `<svg>`), h\xE3y th\xEAm thu\u1ED9c t\xEDnh `aria-label` ho\u1EB7c text \u1EA9n (`cdk-visually-hidden`) \u0111\u1EC3 ng\u01B0\u1EDDi d\xF9ng screen-reader hi\u1EC3u \u0111\u01B0\u1EE3c ch\u1EE9c n\u0103ng.",
@@ -109,10 +357,12 @@ var rule = {
109
357
  languages: ["html"],
110
358
  scope: "angular",
111
359
  requires: "syntactic",
360
+ usesProjectContext: true,
112
361
  baseConfidence: 85,
113
362
  check(ctx) {
114
363
  const tree = asTreeSitterTree(ctx.parsed);
115
364
  const findings = [];
365
+ const tailwind = /\binvisible\b/.test(ctx.file.content) && provenTailwindStyles(ctx.file.absolutePath) !== null;
116
366
  for (const node of walkNodes(tree.rootNode)) {
117
367
  if (node.type !== "element") continue;
118
368
  const startTag = namedChildOfType(node, "start_tag") ?? namedChildOfType(node, "self_closing_tag");
@@ -122,10 +372,16 @@ var rule = {
122
372
  const tag = tagNameNode.text.toLowerCase();
123
373
  if (tag !== "button" && tag !== "a") continue;
124
374
  if (tag === "a" && !hasInteractiveLinkAttr(startTag)) continue;
375
+ const visibility = visibilityOfNode(node, tailwind);
376
+ if (visibility === "hidden") continue;
125
377
  if (hasAccessibleAttr(startTag)) continue;
126
- if (hasMeaningfulTextOrDirective(node)) continue;
378
+ if (hasMeaningfulTextOrDirective(node, tailwind)) continue;
379
+ const unresolvedHiddenClass = !tailwind && startTag.namedChildren.some(
380
+ (attr) => attr.type === "attribute" && namedChildOfType(attr, "attribute_name")?.text === "class" && attributeValue(attr).split(/\s+/).includes("invisible")
381
+ );
127
382
  findings.push({
128
- message: `<${tag}> thi\u1EBFu accessible name \u2014 screen-reader kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xF4 t\u1EA3 h\xE0nh \u0111\u1ED9ng (l\u1ED7i WCAG 4.1.2). Th\xEAm text b\xEAn trong n\xFAt ho\u1EB7c khai b\xE1o thu\u1ED9c t\xEDnh \`aria-label="m\xF4 t\u1EA3"\`.`,
383
+ confidence: visibility === "uncertain" || [...walkNodes(node)].some((child) => hasUncertainDescendantVisibility(child, node)) ? 70 : 85,
384
+ message: `<${tag}>${unresolvedHiddenClass ? " c\xF3 utility visibility ch\u01B0a ki\u1EC3m ch\u1EE9ng CSS/config; c\u1EA7n review khi control hi\u1EC7n: " : visibility === "uncertain" ? " c\xF3 visibility \u0111\u1ED9ng; c\u1EA7n ki\u1EC3m ch\u1EE9ng khi hi\u1EC7n: " : " "}thi\u1EBFu accessible name${unresolvedHiddenClass || visibility === "uncertain" ? " n\u1EBFu control xu\u1EA5t hi\u1EC7n." : " \u2014 screen-reader kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xF4 t\u1EA3 h\xE0nh \u0111\u1ED9ng (l\u1ED7i WCAG 4.1.2)."} Th\xEAm text b\xEAn trong n\xFAt ho\u1EB7c khai b\xE1o thu\u1ED9c t\xEDnh \`aria-label="m\xF4 t\u1EA3"\`.`,
129
385
  file: ctx.file.path,
130
386
  range: {
131
387
  line: startTag.startPosition.row + 1,