@buaa_smat/hometrans 26.0.6 → 26.0.8

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 (159) hide show
  1. package/README.md +6 -3
  2. package/agents/a2h-executor.md +37 -0
  3. package/dist/cli/editors.json +13 -0
  4. package/dist/platform/compose.js +4 -0
  5. package/dist/platform/registry.js +3 -1
  6. package/dist/platform/transform.js +37 -3
  7. package/env-requirements.json +15 -1
  8. package/i18n/platforms/codebuddy/skills/a2h-app-migrate/SKILL.unique.md +2 -2
  9. package/i18n/platforms/deveco/skills/a2h-app-migrate/SKILL.unique.md +1 -1
  10. package/i18n/platforms/opencode/skills/a2h-app-migrate/SKILL.unique.md +13 -6
  11. package/i18n/skills/a2h-app-migrate/SKILL.md +2 -2
  12. package/i18n/skills/a2h-app-migrate/references/workflow.yaml +27 -4
  13. package/i18n/skills/a2h-app-migrate/scripts/opencode_depth.mjs +418 -0
  14. package/i18n/skills/a2h-arkts-logic-coder/references/ISSUES.md +2 -0
  15. package/i18n/skills/a2h-batch-ui-align/SKILL.md +7 -7
  16. package/i18n/skills/a2h-batch-ui-align/references/cards/alignment.md +1 -1
  17. package/i18n/skills/a2h-batch-ui-align/references/cards/state.md +20 -2
  18. package/i18n/skills/a2h-batch-ui-align/references/cards/widgets.md +2 -2
  19. package/i18n/skills/a2h-batch-ui-align/references/checker-rules.md +3 -3
  20. package/i18n/skills/a2h-batch-ui-align/references/conversion-procedure.md +3 -1
  21. package/i18n/skills/a2h-batch-ui-align/references/incremental-scope.md +2 -2
  22. package/i18n/skills/a2h-batch-ui-align/references/step3-capture.md +10 -6
  23. package/i18n/skills/a2h-batch-ui-align/references/step5-convert.md +13 -9
  24. package/i18n/skills/a2h-batch-ui-align/scripts/build_conversion_set.mjs +59 -7
  25. package/i18n/skills/a2h-batch-ui-align/scripts/group_pack.mjs +3 -0
  26. package/i18n/skills/a2h-batch-ui-align/scripts/interactions.mjs +186 -0
  27. package/i18n/skills/a2h-batch-ui-align/scripts/phase5_check.mjs +33 -7
  28. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/hit_test.ts +83 -22
  29. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/media_tint.ts +39 -5
  30. package/i18n/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_scroll_padding_raster.test.mjs +25 -1
  31. package/i18n/skills/a2h-page-specgen/SKILL.md +1 -1
  32. package/i18n/skills/a2h-page-specgen/references/gates.md +3 -1
  33. package/i18n/skills/a2h-page-specgen/references/scenario-authoring.md +11 -11
  34. package/i18n/skills/a2h-page-specgen/references/spec-template.md +3 -3
  35. package/i18n/skills/a2h-page-specgen/scripts/contract-calls.mjs +40 -3
  36. package/i18n/skills/a2h-page-specgen/scripts/entry-evidence.mjs +73 -5
  37. package/i18n/skills/a2h-page-specgen/scripts/gate.mjs +144 -0
  38. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/PlainDisplayPage.prompt.md +11 -11
  39. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/PlainDisplayPage.worker.md +11 -11
  40. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/SilentFailurePage.prompt.md +11 -11
  41. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/SilentFailurePage.worker.md +11 -11
  42. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.json +10 -10
  43. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.post-review.json +1 -1
  44. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.prompt.md +11 -11
  45. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.worker.md +11 -11
  46. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/ValidatedSearchPage.prompt.md +11 -11
  47. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/ValidatedSearchPage.worker.md +11 -11
  48. package/i18n/skills/a2h-page-specgen/scripts/test/contract-calls.test.mjs +45 -1
  49. package/i18n/skills/a2h-page-specgen/scripts/test/entry-evidence.test.mjs +100 -0
  50. package/i18n/skills/a2h-page-specgen/scripts/test/gate.test.mjs +132 -3
  51. package/i18n/skills/a2h-resource-convert/scripts/a2h_resource_convert.ts +36 -1
  52. package/i18n/skills/a2h-spec-design-pipeline/SKILL.md +1 -1
  53. package/i18n/skills/a2h-spec-design-pipeline/references/coding-loop.md +16 -0
  54. package/i18n/skills/a2h-utg-static/SKILL.md +2 -0
  55. package/package.json +1 -1
  56. package/platforms/atomcode/agents/a2h-executor.frontmatter.md +6 -0
  57. package/platforms/codebuddy/agents/a2h-executor.frontmatter.md +5 -0
  58. package/platforms/codebuddy/skills/a2h-app-migrate/SKILL.unique.md +2 -2
  59. package/platforms/deveco/agents/a2h-executor.frontmatter.md +7 -0
  60. package/platforms/deveco/agents/build-fixer.frontmatter.md +0 -2
  61. package/platforms/deveco/agents/code-reviewer.frontmatter.md +0 -2
  62. package/platforms/deveco/agents/model-render-worker.frontmatter.md +0 -2
  63. package/platforms/deveco/agents/model-worker.frontmatter.md +0 -2
  64. package/platforms/deveco/agents/specgen-worker.frontmatter.md +0 -2
  65. package/platforms/deveco/skills/a2h-app-migrate/SKILL.unique.md +1 -1
  66. package/platforms/opencode/agents/a2h-executor.frontmatter.md +7 -0
  67. package/platforms/opencode/agents/build-fixer.frontmatter.md +0 -2
  68. package/platforms/opencode/agents/code-reviewer.frontmatter.md +0 -2
  69. package/platforms/opencode/agents/model-render-worker.frontmatter.md +0 -2
  70. package/platforms/opencode/agents/model-worker.frontmatter.md +0 -2
  71. package/platforms/opencode/agents/specgen-worker.frontmatter.md +0 -2
  72. package/platforms/opencode/skills/a2h-app-migrate/SKILL.unique.md +13 -6
  73. package/skills/a2h-app-migrate/SKILL.md +29 -3
  74. package/skills/a2h-app-migrate/references/host-rules.md +33 -0
  75. package/skills/a2h-app-migrate/references/workflow.yaml +24 -4
  76. package/skills/a2h-app-migrate/scripts/opencode_depth.mjs +418 -0
  77. package/skills/a2h-app-migrate/test/test_executor_header_sync.mjs +78 -0
  78. package/skills/a2h-app-migrate/test/test_opencode_depth.mjs +312 -0
  79. package/skills/a2h-app-migrate/tools/dag.mjs +267 -0
  80. package/skills/a2h-arkts-logic-coder/references/ISSUES.md +2 -0
  81. package/skills/a2h-batch-ui-align/SKILL.md +7 -7
  82. package/skills/a2h-batch-ui-align/references/cards/alignment.md +1 -1
  83. package/skills/a2h-batch-ui-align/references/cards/state.md +20 -2
  84. package/skills/a2h-batch-ui-align/references/cards/widgets.md +2 -2
  85. package/skills/a2h-batch-ui-align/references/checker-rules.md +3 -3
  86. package/skills/a2h-batch-ui-align/references/conversion-procedure.md +3 -1
  87. package/skills/a2h-batch-ui-align/references/host-dispatch.md +5 -5
  88. package/skills/a2h-batch-ui-align/references/incremental-scope.md +2 -2
  89. package/skills/a2h-batch-ui-align/references/step3-capture.md +10 -6
  90. package/skills/a2h-batch-ui-align/references/step5-convert.md +13 -9
  91. package/skills/a2h-batch-ui-align/scripts/build_conversion_set.mjs +59 -7
  92. package/skills/a2h-batch-ui-align/scripts/group_pack.mjs +3 -0
  93. package/skills/a2h-batch-ui-align/scripts/group_pass.mjs +3 -2
  94. package/skills/a2h-batch-ui-align/scripts/group_queue.mjs +139 -23
  95. package/skills/a2h-batch-ui-align/scripts/host_env.mjs +32 -8
  96. package/skills/a2h-batch-ui-align/scripts/interactions.mjs +186 -0
  97. package/skills/a2h-batch-ui-align/scripts/phase5_check.mjs +33 -7
  98. package/skills/a2h-batch-ui-align/scripts/static_check/rules/hit_test.ts +83 -22
  99. package/skills/a2h-batch-ui-align/scripts/static_check/rules/media_tint.ts +39 -5
  100. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_hit_test.test.mjs +82 -0
  101. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_scroll_padding_raster.test.mjs +25 -1
  102. package/skills/a2h-batch-ui-align/scripts/tests/group_queue.test.mjs +184 -2
  103. package/skills/a2h-batch-ui-align/scripts/tests/host_env.test.mjs +33 -0
  104. package/skills/a2h-batch-ui-align/scripts/tests/interactions.test.mjs +258 -0
  105. package/skills/a2h-page-specgen/SKILL.md +1 -1
  106. package/skills/a2h-page-specgen/references/evidence.md +15 -0
  107. package/skills/a2h-page-specgen/references/gates.md +3 -1
  108. package/skills/a2h-page-specgen/references/scenario-authoring.md +10 -10
  109. package/skills/a2h-page-specgen/references/spec-template.md +2 -2
  110. package/skills/a2h-page-specgen/scripts/contract-calls.mjs +40 -3
  111. package/skills/a2h-page-specgen/scripts/entry-evidence.mjs +73 -5
  112. package/skills/a2h-page-specgen/scripts/gate.mjs +141 -0
  113. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/PlainDisplayPage.prompt.md +10 -10
  114. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/PlainDisplayPage.worker.md +10 -10
  115. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/SilentFailurePage.prompt.md +10 -10
  116. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/SilentFailurePage.worker.md +10 -10
  117. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.json +10 -10
  118. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.post-review.json +1 -1
  119. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.prompt.md +10 -10
  120. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.worker.md +10 -10
  121. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/ValidatedSearchPage.prompt.md +10 -10
  122. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/ValidatedSearchPage.worker.md +10 -10
  123. package/skills/a2h-page-specgen/scripts/test/contract-calls.test.mjs +45 -1
  124. package/skills/a2h-page-specgen/scripts/test/entry-evidence.test.mjs +100 -0
  125. package/skills/a2h-page-specgen/scripts/test/gate.test.mjs +104 -3
  126. package/skills/a2h-resource-convert/references/conversion-rules.md +2 -0
  127. package/skills/a2h-resource-convert/scripts/a2h_resource_convert.ts +36 -1
  128. package/skills/a2h-resource-convert/scripts/tests/adaptive_icon.test.mjs +42 -0
  129. package/skills/a2h-spec-design-pipeline/SKILL.md +1 -1
  130. package/skills/a2h-spec-design-pipeline/references/coding-loop.md +16 -0
  131. package/skills/a2h-spec-design-pipeline/references/execution-model.md +2 -2
  132. package/skills/a2h-spec-design-pipeline/references/static-defect-gate.md +5 -1
  133. package/skills/a2h-spec-design-pipeline/rules/migration-rules/config/ruleMeta.json +5 -0
  134. package/skills/a2h-spec-design-pipeline/rules/migration-rules/config/ruleSet.json +4 -0
  135. package/skills/a2h-spec-design-pipeline/rules/migration-rules/document/checker/hometrans/arkui-runtime-pitfall-cn.md +2 -1
  136. package/skills/a2h-spec-design-pipeline/rules/migration-rules/document/checker/hometrans/arkui-runtime-pitfall-en.md +3 -1
  137. package/skills/a2h-spec-design-pipeline/rules/migration-rules/document/checker/hometrans/arkui-v2-observation-cn.md +105 -0
  138. package/skills/a2h-spec-design-pipeline/rules/migration-rules/document/checker/hometrans/arkui-v2-observation-en.md +122 -0
  139. package/skills/a2h-spec-design-pipeline/rules/migration-rules/lib/checker/ArkUIRuntimePitfallCheck.js +4 -4
  140. package/skills/a2h-spec-design-pipeline/rules/migration-rules/lib/checker/ArkUIV2ObservationCheck.js +1862 -0
  141. package/skills/a2h-spec-design-pipeline/rules/migration-rules/lib/index.js +2 -0
  142. package/skills/a2h-spec-design-pipeline/rules/migration-rules/package.json +1 -1
  143. package/skills/a2h-spec-design-pipeline/scripts/dispatch/wait.mjs +15 -2
  144. package/skills/a2h-spec-design-pipeline/scripts/dispatch.mjs +20 -4
  145. package/skills/a2h-spec-design-pipeline/scripts/test_arkui_v2_observation.ts +284 -0
  146. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_commands.mjs +32 -0
  147. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_wait.mjs +22 -1
  148. package/skills/a2h-utg-static/SKILL.md +2 -0
  149. package/skills/a2h-utg-static/references/extractors.md +16 -0
  150. package/skills/a2h-utg-static/scripts/run_pipeline.mjs +22 -1
  151. package/skills/a2h-utg-static/scripts/tests/regression_matrix.mjs +4 -0
  152. package/skills/a2h-utg-static/scripts/tests/test_pr169_review_fixes.mjs +15 -0
  153. package/skills/a2h-utg-static/scripts/tests/test_view_attachments.mjs +330 -0
  154. package/skills/a2h-utg-static/scripts/view_attachments.mjs +465 -0
  155. package/platforms/codebuddy/agents/build-fixer.frontmatter.md +0 -5
  156. package/platforms/codebuddy/agents/code-reviewer.frontmatter.md +0 -5
  157. package/platforms/codebuddy/agents/model-render-worker.frontmatter.md +0 -5
  158. package/platforms/codebuddy/agents/model-worker.frontmatter.md +0 -5
  159. package/platforms/codebuddy/agents/specgen-worker.frontmatter.md +0 -5
@@ -0,0 +1,1862 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * @hometrans/arkui-v2-observation
5
+ *
6
+ * The V2 observation chain breaks in recurring shapes. They compile clean and only
7
+ * fail when the UI is asked to refresh after a write:
8
+ *
9
+ * [v2-render-read-unobserved] (WARN)
10
+ * A render method (build / @Builder) reaches a plain field of an @ObservedV2 class
11
+ * through a one-level method call (e.g. build -> appRouter.currentRoute() ->
12
+ * this.stack). The upstream @arkui-semantic-correctness/observedv2-untraced-write
13
+ * only collects direct ArkInstanceFieldRef reads inside build, and only discovers
14
+ * target classes from component fields; a module singleton held in `export const`
15
+ * is therefore outside its surface. This sub-code adds exactly those two faces.
16
+ *
17
+ * [v2-render-shadow-state] (ERROR)
18
+ * An @ObservedV2 class mirrors a plain container into an @Trace scalar
19
+ * (`this.depth = this.stack.length`) and the render layer uses the scalar as a
20
+ * branch condition while the branch body reads the container. The mount `if`
21
+ * flips only 0 <-> non-zero, so a second push (1 -> 2) or replaceTop (depth
22
+ * unchanged) never rebuilds the branch. ERROR when the branch reads only the
23
+ * container; WARN when the branch also reads the shadow (push/pop refreshes, only
24
+ * a container write that leaves the shadow unchanged is stale).
25
+ *
26
+ * [v2-nested-class-unobserved] (WARN)
27
+ * A nested custom class reachable from a @Local/@Param/@Provider/@Consumer state
28
+ * field (or from an @ObservedV2 field) is not decorated with @ObservedV2, while the
29
+ * path is read in render and written below the first level. @Local is included: the
30
+ * fixed set's local-nested-write reports the write, this rule reports the class.
31
+ *
32
+ * [v2-deep-write-unobserved] (ERROR)
33
+ * A @Param/@Provider/@Consumer root object is written below the first level
34
+ * (`this.p.inner.x = ...` / `this.p.items.push(...)`), the nested class IS
35
+ * @ObservedV2, but the written field has no @Trace. @Local / @State roots are
36
+ * excluded (local-nested-write / state-nested-write cover them).
37
+ *
38
+ * [v2-monitor-deep-collection] (WARN)
39
+ * `@Monitor('a.b')` watches a dot path whose last segment is a collection and the
40
+ * class mutates that collection element-by-element. The fixed set's
41
+ * monitor-collection expressly exempts dot paths and monitor-nonobservable only
42
+ * checks the last segment's decorator, so this shape is currently unreported.
43
+ *
44
+ * [v2-plain-object-state] (WARN)
45
+ * A @Local/@Param field typed as an interface / object type alias (not a class) is
46
+ * assigned a plain object literal (or Object.assign / spread) and then written
47
+ * below the first level. Interfaces cannot carry @ObservedV2; the raw object has
48
+ * no observation. JSON.parse / structuredClone class-typed assignments are
49
+ * already covered by state-unactivated-observe and are not re-reported here.
50
+ *
51
+ * [v2-monitor-cycle] (WARN)
52
+ * Two @Monitor methods write each other's watched field, or one writes its own
53
+ * watched field, forming a loop. The fixed set's watch-self-write is V1 @Watch
54
+ * only; V2 @Monitor has no equivalent. Only direct `this.x = ...` writes are
55
+ * graded (a helper-indirect loop is a registered false negative).
56
+ *
57
+ * The check is text-based on purpose, like RouteParamCarrierSubCheck: it needs no CFG
58
+ * and decides cross-file relations in one scene pass. Type resolution is import-aware
59
+ * (relative imports, package imports through oh-package.json5 / Index.ets barrels,
60
+ * namespace imports, `export { x } from` and `export * from`, and the
61
+ * `export const appRouter: AppRouter = new AppRouter()` singleton form). Anything that
62
+ * cannot be resolved stays silent; never guess.
63
+ *
64
+ * Deliberate silences are documented per sub-code in
65
+ * document/checker/hometrans/arkui-v2-observation-{cn,en}.md.
66
+ */
67
+
68
+ const fs = require('fs');
69
+ const path = require('path');
70
+
71
+ const hc = require(process.env.HOMECHECK_MODULE_PATH || 'homecheck');
72
+ const { GlobalChecker, Rule, AlertLevel } = hc;
73
+
74
+ const RULE_ID = '@hometrans/arkui-v2-observation';
75
+
76
+ const BUILDER_DECO = 'Builder';
77
+ const TRACE_DECO = 'Trace';
78
+ const OBSERVED_V2_DECO = 'ObservedV2';
79
+ const COMPONENT_V2_DECO = 'ComponentV2';
80
+ const MONITOR_DECO = 'Monitor';
81
+ const V2_STATE_DECOS = new Set(['Local', 'Param', 'Once', 'Provider', 'Consumer']);
82
+ const MUTATORS = new Set([
83
+ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin',
84
+ 'set', 'add', 'delete', 'clear',
85
+ ]);
86
+ const GLOBAL_OBJECTS = new Set([
87
+ 'console', 'Math', 'JSON', 'Object', 'Array', 'Date', 'Promise', 'Number', 'String',
88
+ 'Boolean', 'RegExp', 'Map', 'Set', 'WeakMap', 'WeakSet', 'Reflect', 'Proxy', 'Symbol',
89
+ 'AppStorage', 'AppStorageV2', 'PersistenceV2', 'LocalStorage', 'UIUtils', 'router',
90
+ 'focusControl', 'animateTo', 'getContext',
91
+ ]);
92
+ const MAX_WALK_DEPTH = 3;
93
+
94
+ /* ------------------------------------------------------------------ */
95
+ /* Lexical helpers (same shape as RouteParamCarrierSubCheck) */
96
+ /* ------------------------------------------------------------------ */
97
+
98
+ function safe(fn, fallback) {
99
+ try {
100
+ return fn();
101
+ } catch (_err) {
102
+ return fallback;
103
+ }
104
+ }
105
+
106
+ /** Replace string/template contents with equal-length whitespace (quotes kept). */
107
+ function maskStrings(code) {
108
+ let out = '';
109
+ let q = '';
110
+ for (let i = 0; i < code.length; i++) {
111
+ const c = code[i];
112
+ if (q === '') {
113
+ if (c === '"' || c === "'" || c === '`') { q = c; }
114
+ out += c;
115
+ continue;
116
+ }
117
+ if (c === '\\') { out += ' '; i++; continue; }
118
+ if (c === q) { q = ''; out += c; continue; }
119
+ out += (c === '\n' ? '\n' : ' ');
120
+ }
121
+ return out;
122
+ }
123
+
124
+ /** Remove comments, keeping newlines (line numbers stay stable); strings are preserved. */
125
+ function stripComments(code) {
126
+ let out = '';
127
+ let i = 0;
128
+ let q = '';
129
+ while (i < code.length) {
130
+ const c = code[i];
131
+ const n = code[i + 1];
132
+ if (q !== '') {
133
+ out += c;
134
+ if (c === '\\') { out += (code[i + 1] || ''); i += 2; continue; }
135
+ if (c === q) { q = ''; }
136
+ i++;
137
+ continue;
138
+ }
139
+ if (c === '"' || c === "'" || c === '`') { q = c; out += c; i++; continue; }
140
+ if (c === '/' && n === '/') {
141
+ while (i < code.length && code[i] !== '\n') { out += ' '; i++; }
142
+ continue;
143
+ }
144
+ if (c === '/' && n === '*') {
145
+ out += ' ';
146
+ i += 2;
147
+ while (i < code.length && !(code[i] === '*' && code[i + 1] === '/')) {
148
+ out += (code[i] === '\n' ? '\n' : ' ');
149
+ i++;
150
+ }
151
+ if (i < code.length) { out += ' '; i += 2; }
152
+ continue;
153
+ }
154
+ out += c;
155
+ i++;
156
+ }
157
+ return out;
158
+ }
159
+
160
+ /** When code[open] is ( / { / [, return the balancing close position; brackets in strings do not count. */
161
+ function matchBracket(code, open) {
162
+ const pairs = { '(': ')', '{': '}', '[': ']' };
163
+ const close = pairs[code[open]];
164
+ if (!close) { return -1; }
165
+ let depth = 0;
166
+ let q = '';
167
+ for (let i = open; i < code.length; i++) {
168
+ const c = code[i];
169
+ if (q !== '') {
170
+ if (c === '\\') { i++; continue; }
171
+ if (c === q) { q = ''; }
172
+ continue;
173
+ }
174
+ if (c === '"' || c === "'" || c === '`') { q = c; continue; }
175
+ if (c === '(' || c === '{' || c === '[') { depth++; continue; }
176
+ if (c === ')' || c === '}' || c === ']') {
177
+ depth--;
178
+ if (depth === 0) { return i; }
179
+ }
180
+ }
181
+ return -1;
182
+ }
183
+
184
+ const LINE_STARTS = new Map();
185
+
186
+ function lineOfIndex(code, index) {
187
+ let starts = LINE_STARTS.get(code);
188
+ if (!starts) {
189
+ starts = [0];
190
+ for (let i = 0; i < code.length; i++) {
191
+ if (code[i] === '\n') { starts.push(i + 1); }
192
+ }
193
+ if (LINE_STARTS.size >= 64) { LINE_STARTS.clear(); }
194
+ LINE_STARTS.set(code, starts);
195
+ }
196
+ let lo = 0;
197
+ let hi = starts.length - 1;
198
+ const end = Math.min(index, code.length);
199
+ while (lo <= hi) {
200
+ const mid = (lo + hi) >> 1;
201
+ if (starts[mid] <= end) { lo = mid + 1; } else { hi = mid - 1; }
202
+ }
203
+ return hi + 1;
204
+ }
205
+
206
+ /** Bounded look-ahead after `pos`: skip whitespace and take at most 64 chars. */
207
+ function tailAt(text, pos) {
208
+ let p = pos;
209
+ while (p < text.length && /\s/.test(text[p])) { p++; }
210
+ return text.slice(p, p + 64);
211
+ }
212
+
213
+ /** Split [start, end) on a top-level separator, respecting (), {}, [] and strings. */
214
+ function splitTopLevel(code, start, end, sep) {
215
+ const parts = [];
216
+ let depth = 0;
217
+ let q = '';
218
+ let segStart = start;
219
+ for (let i = start; i < end; i++) {
220
+ const c = code[i];
221
+ if (q !== '') {
222
+ if (c === '\\') { i++; continue; }
223
+ if (c === q) { q = ''; }
224
+ continue;
225
+ }
226
+ if (c === '"' || c === "'" || c === '`') { q = c; continue; }
227
+ if (c === '(' || c === '{' || c === '[') { depth++; continue; }
228
+ if (c === ')' || c === '}' || c === ']') { depth--; continue; }
229
+ if (c === sep && depth === 0) {
230
+ parts.push({ start: segStart, end: i });
231
+ segStart = i + 1;
232
+ }
233
+ }
234
+ parts.push({ start: segStart, end });
235
+ return parts;
236
+ }
237
+
238
+ function topLevelIndexOf(text, needle) {
239
+ let depth = 0;
240
+ let q = '';
241
+ for (let i = 0; i < text.length; i++) {
242
+ const c = text[i];
243
+ if (q !== '') {
244
+ if (c === '\\') { i++; continue; }
245
+ if (c === q) { q = ''; }
246
+ continue;
247
+ }
248
+ if (c === '"' || c === "'" || c === '`') { q = c; continue; }
249
+ if (c === '(' || c === '{' || c === '[') { depth++; continue; }
250
+ if (c === ')' || c === '}' || c === ']') { depth--; continue; }
251
+ if (depth === 0 && text.startsWith(needle, i)) { return i; }
252
+ }
253
+ return -1;
254
+ }
255
+
256
+ /* ------------------------------------------------------------------ */
257
+ /* Type helpers */
258
+ /* ------------------------------------------------------------------ */
259
+
260
+ /** Type candidates of a syntactic type: array wrappers and union members unwrapped. */
261
+ function typeCandidates(type) {
262
+ const out = [];
263
+ const seen = new Set();
264
+ const visit = (raw) => {
265
+ let t = String(raw || '').trim();
266
+ if (t === '') { return; }
267
+ if (seen.has(t)) { return; }
268
+ seen.add(t);
269
+ t = t.replace(/^readonly\s+/, '');
270
+ if (t.startsWith('(') && matchBracket(t, 0) === t.length - 1) {
271
+ visit(t.slice(1, -1));
272
+ return;
273
+ }
274
+ const union = splitTopLevel(t, 0, t.length, '|').map((p) => t.slice(p.start, p.end).trim());
275
+ if (union.length > 1) {
276
+ for (const part of union) { visit(part); }
277
+ return;
278
+ }
279
+ if (t.endsWith('[]')) { visit(t.slice(0, -2)); return; }
280
+ const arr = /^Array\s*<([\s\S]+)>$/.exec(t);
281
+ if (arr) { visit(arr[1]); return; }
282
+ const ro = /^(?:ReadonlyArray|Readonly|Set|ReadonlySet|List|Collection)\s*<([\s\S]+)>$/.exec(t);
283
+ if (ro) { visit(ro[1]); return; }
284
+ const map = /^(?:Map|ReadonlyMap|Record)\s*<[\s\S]*,([\s\S]+)>$/.exec(t);
285
+ if (map) { visit(map[1]); return; }
286
+ const name = /^([A-Za-z_$][\w$]*)(?:\.[A-Za-z_$][\w$]*)?$/.exec(t);
287
+ if (name) { out.push(t); }
288
+ };
289
+ visit(type);
290
+ return out;
291
+ }
292
+
293
+ function isCollectionType(type) {
294
+ const t = String(type || '').replace(/^readonly\s+/, '').trim();
295
+ return /\[\]$/.test(t) ||
296
+ /^(?:Array|ReadonlyArray|Set|ReadonlySet|List|Collection)\s*</.test(t) ||
297
+ /^(?:Map|ReadonlyMap|Record)\s*</.test(t);
298
+ }
299
+
300
+ function escapeRegExp(text) {
301
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
302
+ }
303
+
304
+ /** Property names in a dotted chain that may contain index expressions: `.items[0].count` -> [items, count]. */
305
+ function chainNames(rest) {
306
+ const out = [];
307
+ const re = /\.\s*([A-Za-z_$][\w$]*)/g;
308
+ let m;
309
+ while ((m = re.exec(String(rest || ''))) !== null) { out.push(m[1]); }
310
+ return out;
311
+ }
312
+
313
+ /** Direct writes to a root field: `this.x =`, compound assignments, and `++`/`--` (both sides). */
314
+ function collectDirectWrites(body) {
315
+ const out = [];
316
+ const re = /\bthis\s*\.\s*([A-Za-z_$][\w$]*)\s*(?:(?:[+\-*/%&|^]|\*\*|<<|>>>?|\?\?|&&|\|\|)?=(?!=)|(?:\+\+|--))|\b(?:--|\+\+)\s*this\s*\.\s*([A-Za-z_$][\w$]*)/g;
317
+ let m;
318
+ while ((m = re.exec(body)) !== null) {
319
+ const name = m[1] || m[2];
320
+ if (name) { out.push({ name, index: m.index }); }
321
+ }
322
+ return out;
323
+ }
324
+
325
+ function inferNewType(init) {
326
+ const m = /^\s*new\s+([A-Za-z_$][\w$]*)\s*\(/.exec(String(init || ''));
327
+ return m ? m[1] : '';
328
+ }
329
+
330
+ function hasDeco(decos, name) {
331
+ return Array.isArray(decos) && decos.some((d) => d.name === name);
332
+ }
333
+
334
+ function decoArgs(decos, name) {
335
+ const d = Array.isArray(decos) ? decos.find((x) => x.name === name) : null;
336
+ if (!d) { return []; }
337
+ const raw = String(d.arg || '').trim();
338
+ if (raw === '') { return []; }
339
+ const out = [];
340
+ for (const part of splitTopLevel(raw, 0, raw.length, ',')) {
341
+ const text = raw.slice(part.start, part.end).trim();
342
+ if (text === '') { continue; }
343
+ const quoted = /^(['"`])([\s\S]*)\1$/.exec(text);
344
+ out.push(quoted ? quoted[2] : text);
345
+ }
346
+ return out;
347
+ }
348
+
349
+ function decoArg(decos, name) {
350
+ return decoArgs(decos, name)[0] || '';
351
+ }
352
+
353
+ /* ------------------------------------------------------------------ */
354
+ /* File model */
355
+ /* ------------------------------------------------------------------ */
356
+
357
+ function resolveRelativeImport(fromFile, spec) {
358
+ if (typeof spec !== 'string' || !spec.startsWith('.')) { return null; }
359
+ const base = path.resolve(path.dirname(fromFile), spec);
360
+ const candidates = [
361
+ base,
362
+ `${base}.ets`,
363
+ `${base}.ts`,
364
+ path.join(base, 'index.ets'),
365
+ path.join(base, 'index.ts'),
366
+ ];
367
+ for (const candidate of candidates) {
368
+ if (safe(() => fs.statSync(candidate).isFile(), false)) { return path.normalize(candidate); }
369
+ }
370
+ return null;
371
+ }
372
+
373
+ function parseImports(filePath, code) {
374
+ const imports = new Map(); // local name -> { name, spec, resolved }
375
+ const namespaces = new Map(); // local ns -> { spec, resolved }
376
+ let m;
377
+ const named = /import\s+(?:type\s+)?\{([\s\S]*?)\}\s*from\s*['"]([^'"]+)['"]/g;
378
+ while ((m = named.exec(code)) !== null) {
379
+ const spec = m[2];
380
+ const resolved = resolveRelativeImport(filePath, spec);
381
+ for (const part of m[1].split(',')) {
382
+ const s = part.trim();
383
+ if (s === '') { continue; }
384
+ const alias = /^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/.exec(s);
385
+ if (alias) { imports.set(alias[2], { name: alias[1], spec, resolved }); }
386
+ else if (/^[A-Za-z_$][\w$]*$/.test(s)) { imports.set(s, { name: s, spec, resolved }); }
387
+ }
388
+ }
389
+ const def = /import\s+([A-Za-z_$][\w$]*)\s*(?:,\s*\{[\s\S]*?\}\s*)?from\s*['"]([^'"]+)['"]/g;
390
+ while ((m = def.exec(code)) !== null) {
391
+ imports.set(m[1], { name: m[1], spec: m[2], resolved: resolveRelativeImport(filePath, m[2]) });
392
+ }
393
+ const ns = /import\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s*['"]([^'"]+)['"]/g;
394
+ while ((m = ns.exec(code)) !== null) {
395
+ namespaces.set(m[1], { spec: m[2], resolved: resolveRelativeImport(filePath, m[2]) });
396
+ }
397
+ return { imports, namespaces };
398
+ }
399
+
400
+ /** Decorators written on the same line as the member (m[0] prefix). */
401
+ function decoratorsInPrefix(prefix) {
402
+ const out = [];
403
+ const re = /@([A-Za-z_$][\w$]*)(?:\s*\(([^)]*)\))?/g;
404
+ let m;
405
+ while ((m = re.exec(prefix)) !== null) {
406
+ out.push({ name: m[1], arg: (m[2] || '').trim() });
407
+ }
408
+ return out;
409
+ }
410
+
411
+ /** Decorator-only lines immediately above a member (a line that also declares the member is its own prefix). */
412
+ function decoratorsAbove(code, memberIndex) {
413
+ const out = [];
414
+ const lineStart = code.lastIndexOf('\n', memberIndex - 1) + 1;
415
+ let pos = lineStart - 1;
416
+ while (pos > 0) {
417
+ const start = code.lastIndexOf('\n', pos - 1) + 1;
418
+ const line = code.slice(start, pos);
419
+ const t = line.trim();
420
+ // `@Trace depth: number = 0` is a same-line decorator already captured from m[0];
421
+ // only a bare `@Deco` / `@Deco(args)` line belongs to the member on the next line.
422
+ if (!/^@[A-Za-z_$][\w$]*(?:\s*\([^)]*\))?\s*$/.test(t)) { break; }
423
+ out.push(...decoratorsInPrefix(line));
424
+ pos = start - 1;
425
+ }
426
+ return out;
427
+ }
428
+
429
+ function readInitEnd(masked, start) {
430
+ let depth = 0;
431
+ let q = '';
432
+ for (let i = start; i < masked.length; i++) {
433
+ const c = masked[i];
434
+ if (q !== '') {
435
+ if (c === '\\') { i++; continue; }
436
+ if (c === q) { q = ''; }
437
+ continue;
438
+ }
439
+ if (c === '"' || c === "'" || c === '`') { q = c; continue; }
440
+ if (c === '(' || c === '[' || c === '{') { depth++; continue; }
441
+ if (c === ')' || c === ']' || c === '}') { depth--; continue; }
442
+ if (depth === 0 && (c === ';' || c === '\n')) { return i; }
443
+ }
444
+ return masked.length;
445
+ }
446
+
447
+ /** Fields declared at the top level of an interface / type body. */
448
+ function simpleFields(code, open, close) {
449
+ const fields = [];
450
+ const body = code.slice(open + 1, close);
451
+ const depth = new Int32Array(body.length + 1);
452
+ let d = 0;
453
+ let q = '';
454
+ for (let i = 0; i < body.length; i++) {
455
+ depth[i] = d;
456
+ const c = body[i];
457
+ if (q !== '') {
458
+ if (c === '\\') { i++; continue; }
459
+ if (c === q) { q = ''; }
460
+ continue;
461
+ }
462
+ if (c === '"' || c === "'" || c === '`') { q = c; continue; }
463
+ if (c === '{') { d++; continue; }
464
+ if (c === '}') { d--; continue; }
465
+ }
466
+ depth[body.length] = d;
467
+ const re = /^[ \t]*(?:@[A-Za-z_$][\w$]*(?:\([^)\n]*\))?[ \t]*)*(?:(?:private|public|protected|readonly|static|declare|abstract)\s+)*([A-Za-z_$][\w$]*)\s*\??\s*:\s*([^;=\n]+)/gm;
468
+ let m;
469
+ while ((m = re.exec(body)) !== null) {
470
+ if (depth[m.index] !== 0) { continue; }
471
+ fields.push({ name: m[1], type: m[2].trim() });
472
+ }
473
+ return fields;
474
+ }
475
+
476
+ function parseMembers(code, masked, open, close) {
477
+ const bodyCode = code.slice(open + 1, close);
478
+ const bodyMasked = masked.slice(open + 1, close);
479
+ const depth = new Int32Array(bodyMasked.length + 1);
480
+ let d = 0;
481
+ let q = '';
482
+ for (let i = 0; i < bodyMasked.length; i++) {
483
+ depth[i] = d;
484
+ const c = bodyMasked[i];
485
+ if (q !== '') {
486
+ if (c === '\\') { i++; continue; }
487
+ if (c === q) { q = ''; }
488
+ continue;
489
+ }
490
+ if (c === '"' || c === "'" || c === '`') { q = c; continue; }
491
+ if (c === '{' || c === '(' || c === '[') { d++; continue; }
492
+ if (c === '}' || c === ')' || c === ']') { d--; continue; }
493
+ }
494
+ depth[bodyMasked.length] = d;
495
+
496
+ const memberRe = /^[ \t]*(?:@[A-Za-z_$][\w$]*(?:\s*\((?:[^()\n]|\([^()\n]*\))*\))?[ \t]*)*(?:(?:private|public|protected|readonly|static|declare|abstract|async)\s+)*(?:get\s+|set\s+)?([A-Za-z_$][\w$]*)\s*(\??)\s*(?::\s*([^=;{\n]+))?\s*(\(|\{|;|=)/gm;
497
+ const fields = new Map();
498
+ const methods = new Map();
499
+ let m;
500
+ while ((m = memberRe.exec(bodyMasked)) !== null) {
501
+ if (depth[m.index] !== 0) { continue; }
502
+ const name = m[1];
503
+ if (name === 'constructor') {
504
+ // Constructors can contain writes; keep them as a method body for the write index.
505
+ }
506
+ const absIndex = open + 1 + m.index;
507
+ // Parse decorators from the original text: masked strings would turn @Monitor('a.b') into spaces.
508
+ const prefixOriginal = bodyCode.slice(m.index, m.index + m[0].length);
509
+ const decos = decoratorsInPrefix(prefixOriginal).concat(decoratorsAbove(code, absIndex));
510
+ const kind = m[4];
511
+ if (kind === '(') {
512
+ if (methods.has(name)) { continue; }
513
+ const openParen = open + 1 + m.index + m[0].length - 1;
514
+ const closeParen = matchBracket(masked, openParen);
515
+ if (closeParen < 0) { continue; }
516
+ let retType = (m[3] || '').trim();
517
+ let j = closeParen + 1;
518
+ while (j < masked.length && /\s/.test(masked[j])) { j++; }
519
+ if (masked[j] === ':') {
520
+ j++;
521
+ const retStart = j;
522
+ while (j < masked.length && masked[j] !== '{' && masked[j] !== ';' && masked[j] !== '\n') { j++; }
523
+ if (!retType) { retType = masked.slice(retStart, j).trim(); }
524
+ while (j < masked.length && /\s/.test(masked[j])) { j++; }
525
+ }
526
+ if (masked[j] !== '{') { continue; }
527
+ const bodyClose = matchBracket(masked, j);
528
+ if (bodyClose < 0) { continue; }
529
+ methods.set(name, {
530
+ name,
531
+ decos,
532
+ retType,
533
+ private: /\bprivate\s+/.test(m[0]),
534
+ accessor: /\b(?:get|set)\s+[A-Za-z_$][\w$]*\s*\(/.test(m[0]),
535
+ line: lineOfIndex(code, absIndex),
536
+ bodyStart: j + 1,
537
+ body: code.slice(j + 1, bodyClose),
538
+ masked: masked.slice(j + 1, bodyClose),
539
+ });
540
+ } else {
541
+ if (fields.has(name)) { continue; }
542
+ let typeName = (m[3] || '').trim();
543
+ let init = '';
544
+ if (kind === '=') {
545
+ const relStart = m.index + m[0].length;
546
+ const relEnd = readInitEnd(bodyMasked, relStart);
547
+ init = bodyCode.slice(relStart, relEnd).trim();
548
+ }
549
+ if (!typeName) { typeName = inferNewType(init); }
550
+ fields.set(name, {
551
+ name,
552
+ type: typeName,
553
+ init,
554
+ decos,
555
+ private: /\bprivate\s+/.test(m[0]),
556
+ readonly: /\breadonly\s+/.test(m[0]),
557
+ line: lineOfIndex(code, absIndex),
558
+ index: absIndex,
559
+ });
560
+ }
561
+ }
562
+ return { fields, methods };
563
+ }
564
+
565
+ function parseFile(filePath, raw) {
566
+ const code = stripComments(raw);
567
+ const masked = maskStrings(code);
568
+ const { imports, namespaces } = parseImports(filePath, code);
569
+ const classes = new Map();
570
+ const structs = new Map();
571
+ const interfaces = new Map();
572
+ const types = new Map();
573
+ const consts = new Map();
574
+ const reExports = new Map();
575
+ const starExports = [];
576
+ let m;
577
+
578
+ const typeRe = /((?:@[A-Za-z_$][\w$]*(?:\s*\([^)]*\))?\s*)*)(?:export\s+)?(?:default\s+)?(class|struct)\s+([A-Za-z_$][\w$]*)([^{]*)\{/g;
579
+ while ((m = typeRe.exec(masked)) !== null) {
580
+ const open = m.index + m[0].length - 1;
581
+ const close = matchBracket(masked, open);
582
+ if (close < 0) { continue; }
583
+ const decos = decoratorsInPrefix(m[1]);
584
+ const members = parseMembers(code, masked, open, close);
585
+ const decl = {
586
+ kind: m[2],
587
+ name: m[3],
588
+ filePath,
589
+ decos,
590
+ heritage: (m[4] || '').trim(),
591
+ open,
592
+ close,
593
+ line: lineOfIndex(code, m.index),
594
+ fields: members.fields,
595
+ methods: members.methods,
596
+ };
597
+ if (m[2] === 'class') { classes.set(m[3], decl); } else { structs.set(m[3], decl); }
598
+ }
599
+
600
+ const ifaceRe = /((?:@[A-Za-z_$][\w$]*(?:\s*\([^)]*\))?\s*)*)(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)(?:\s+extends\s+[^{]+)?\s*\{/g;
601
+ while ((m = ifaceRe.exec(masked)) !== null) {
602
+ const open = m.index + m[0].length - 1;
603
+ const close = matchBracket(masked, open);
604
+ if (close < 0) { continue; }
605
+ interfaces.set(m[2], {
606
+ kind: 'interface',
607
+ name: m[2],
608
+ filePath,
609
+ decos: decoratorsInPrefix(m[1]),
610
+ open,
611
+ close,
612
+ line: lineOfIndex(code, m.index),
613
+ fields: simpleFields(code, open, close),
614
+ methods: new Map(),
615
+ });
616
+ }
617
+
618
+ const aliasRe = /((?:@[A-Za-z_$][\w$]*(?:\s*\([^)]*\))?\s*)*)(?:export\s+)?type\s+([A-Za-z_$][\w$]*)\s*=\s*\{/g;
619
+ while ((m = aliasRe.exec(masked)) !== null) {
620
+ const open = m.index + m[0].length - 1;
621
+ const close = matchBracket(masked, open);
622
+ if (close < 0) { continue; }
623
+ types.set(m[2], {
624
+ kind: 'type',
625
+ name: m[2],
626
+ filePath,
627
+ decos: [],
628
+ open,
629
+ close,
630
+ line: lineOfIndex(code, m.index),
631
+ fields: simpleFields(code, open, close),
632
+ methods: new Map(),
633
+ });
634
+ }
635
+
636
+ // Top-level `const` (the singleton form). Local consts are indented and skipped by ^.
637
+ const constRe = /^(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*(?::\s*([^=;\n]+))?\s*=\s*([^;\n]*)/gm;
638
+ while ((m = constRe.exec(code)) !== null) {
639
+ if (insideAnyRange(m.index, classes, structs)) { continue; }
640
+ consts.set(m[1], {
641
+ kind: 'const',
642
+ name: m[1],
643
+ filePath,
644
+ typeName: (m[2] || '').trim() || inferNewType(m[3]),
645
+ init: (m[3] || '').trim(),
646
+ line: lineOfIndex(code, m.index),
647
+ });
648
+ }
649
+
650
+ const reExportRe = /export\s*\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g;
651
+ while ((m = reExportRe.exec(code)) !== null) {
652
+ for (const part of m[1].split(',')) {
653
+ const s = part.trim();
654
+ if (s === '') { continue; }
655
+ const alias = /^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/.exec(s);
656
+ if (alias) { reExports.set(alias[2] || alias[1], { fromSpec: m[2], importedName: alias[1] }); }
657
+ }
658
+ }
659
+ const starRe = /export\s*\*\s*from\s*['"]([^'"]+)['"]/g;
660
+ while ((m = starRe.exec(code)) !== null) { starExports.push(m[1]); }
661
+
662
+ return {
663
+ filePath,
664
+ code,
665
+ masked,
666
+ imports,
667
+ namespaces,
668
+ classes,
669
+ structs,
670
+ interfaces,
671
+ types,
672
+ consts,
673
+ reExports,
674
+ starExports,
675
+ };
676
+ }
677
+
678
+ function insideAnyRange(index, ...maps) {
679
+ for (const map of maps) {
680
+ for (const decl of map.values()) {
681
+ if (decl.open <= index && index <= decl.close) { return true; }
682
+ }
683
+ }
684
+ return false;
685
+ }
686
+
687
+ /* ------------------------------------------------------------------ */
688
+ /* Project model + resolution */
689
+ /* ------------------------------------------------------------------ */
690
+
691
+ function normalizeKey(p) {
692
+ return path.normalize(p).replace(/\\/g, '/').toLowerCase();
693
+ }
694
+
695
+ function findProjectRoot(filePaths) {
696
+ if (!filePaths.length) { return ''; }
697
+ let dir = path.dirname(filePaths[0]);
698
+ for (let i = 0; i < 12; i++) {
699
+ if (safe(() => fs.existsSync(path.join(dir, 'build-profile.json5')), false)) { return dir; }
700
+ const parent = path.dirname(dir);
701
+ if (parent === dir) { break; }
702
+ dir = parent;
703
+ }
704
+ return path.dirname(filePaths[0]);
705
+ }
706
+
707
+ function parseJson5Loose(text) {
708
+ const noComments = text
709
+ .replace(/\/\*[\s\S]*?\*\//g, '')
710
+ .replace(/(^|[^:])\/\/.*$/gm, '$1');
711
+ const noTrailing = noComments.replace(/,\s*([}\]])/g, '$1');
712
+ try { return JSON.parse(noTrailing); } catch (_err) { return null; }
713
+ }
714
+
715
+ function buildPackageMap(root) {
716
+ const map = new Map();
717
+ if (!root) { return map; }
718
+ const skip = new Set(['node_modules', 'oh_modules', 'build', '.hvigor', '.hometrans', '.git', 'dist', 'ohosSdk', 'hmsSdk']);
719
+ const stack = [root];
720
+ let visited = 0;
721
+ while (stack.length > 0 && visited < 20000) {
722
+ const dir = stack.pop();
723
+ visited++;
724
+ let entries = [];
725
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (_err) { continue; }
726
+ for (const entry of entries) {
727
+ if (entry.isDirectory()) {
728
+ if (!skip.has(entry.name)) { stack.push(path.join(dir, entry.name)); }
729
+ continue;
730
+ }
731
+ if (entry.name !== 'oh-package.json5' && entry.name !== 'oh-package.json') { continue; }
732
+ const pkgFile = path.join(dir, entry.name);
733
+ const parsed = safe(() => parseJson5Loose(fs.readFileSync(pkgFile, 'utf8')), null);
734
+ if (parsed && typeof parsed.name === 'string' && parsed.name !== '') {
735
+ map.set(parsed.name, { root: dir, main: parsed.main || 'Index.ets' });
736
+ }
737
+ }
738
+ }
739
+ return map;
740
+ }
741
+
742
+ function buildProject(scans, options) {
743
+ const files = [];
744
+ for (const scan of scans) {
745
+ if (!scan) { continue; }
746
+ const raw = typeof scan.raw === 'string' ? scan.raw : scan.code;
747
+ if (typeof raw !== 'string') { continue; }
748
+ files.push(parseFile(scan.filePath, raw));
749
+ }
750
+ const byPath = new Map(files.map((f) => [normalizeKey(f.filePath), f]));
751
+ const exports = new Map();
752
+ const add = (name, decl) => {
753
+ const list = exports.get(name) || [];
754
+ list.push(decl);
755
+ exports.set(name, list);
756
+ };
757
+ for (const f of files) {
758
+ for (const d of f.classes.values()) { add(d.name, d); }
759
+ for (const d of f.structs.values()) { add(d.name, d); }
760
+ for (const d of f.interfaces.values()) { add(d.name, d); }
761
+ for (const d of f.types.values()) { add(d.name, d); }
762
+ for (const d of f.consts.values()) { add(d.name, d); }
763
+ }
764
+ const root = options && options.projectRoot ? options.projectRoot : findProjectRoot(files.map((f) => f.filePath));
765
+ return {
766
+ files, byPath, exports, packageMap: buildPackageMap(root), root,
767
+ specCache: new Map(), symbolCache: new Map(),
768
+ };
769
+ }
770
+
771
+ function findDeclared(file, name) {
772
+ return file.classes.get(name) || file.structs.get(name) ||
773
+ file.interfaces.get(name) || file.types.get(name) || file.consts.get(name) || null;
774
+ }
775
+
776
+ function resolveSpecFile(project, fromFile, spec, resolved) {
777
+ const key = `${normalizeKey(fromFile.filePath)}|${spec}|${resolved || ''}`;
778
+ if (project.specCache.has(key)) { return project.specCache.get(key); }
779
+ const result = resolveSpecFileUncached(project, fromFile, spec, resolved);
780
+ project.specCache.set(key, result);
781
+ return result;
782
+ }
783
+
784
+ function resolveSpecFileUncached(project, fromFile, spec, resolved) {
785
+ if (resolved) {
786
+ const hit = project.byPath.get(normalizeKey(resolved));
787
+ if (hit) { return hit; }
788
+ }
789
+ if (typeof spec !== 'string' || spec === '') { return null; }
790
+ if (!spec.startsWith('.')) {
791
+ const parts = spec.split('/');
792
+ const pkgName = spec.startsWith('@') && parts.length >= 2 ? `${parts[0]}/${parts[1]}` : parts[0];
793
+ const rest = spec.startsWith('@') && parts.length >= 2 ? parts.slice(2) : parts.slice(1);
794
+ const info = project.packageMap.get(pkgName);
795
+ if (info) {
796
+ const target = rest.length === 0 ? info.main : rest.join('/');
797
+ const dir = rest.length === 0 ? info.root : path.join(info.root, target);
798
+ const candidates = rest.length === 0
799
+ ? [path.join(info.root, target), path.join(info.root, target, 'Index.ets'), path.join(info.root, 'src', 'main', 'ets', target)]
800
+ : [dir, `${dir}.ets`, `${dir}.ts`, path.join(dir, 'Index.ets')];
801
+ for (const c of candidates) {
802
+ const hit = project.byPath.get(normalizeKey(c));
803
+ if (hit) { return hit; }
804
+ }
805
+ }
806
+ // Fallback: a module directory named like the spec.
807
+ for (const f of project.files) {
808
+ const p = normalizeKey(f.filePath);
809
+ if (p.endsWith(`/${normalizeKey(spec)}/index.ets`) || p.endsWith(`/${normalizeKey(spec)}/index.ts`)) {
810
+ return f;
811
+ }
812
+ }
813
+ }
814
+ return null;
815
+ }
816
+
817
+ function findExported(project, file, name, seen) {
818
+ const visited = seen || new Set();
819
+ if (visited.has(normalizeKey(file.filePath))) { return null; }
820
+ visited.add(normalizeKey(file.filePath));
821
+ const local = findDeclared(file, name);
822
+ if (local) { return local; }
823
+ const re = file.reExports.get(name);
824
+ if (re) {
825
+ const target = resolveSpecFile(project, file, re.fromSpec, resolveRelativeImport(file.filePath, re.fromSpec));
826
+ if (target) { return findExported(project, target, re.importedName, visited); }
827
+ }
828
+ for (const spec of file.starExports) {
829
+ const target = resolveSpecFile(project, file, spec, resolveRelativeImport(file.filePath, spec));
830
+ if (target) {
831
+ const found = findExported(project, target, name, visited);
832
+ if (found) { return found; }
833
+ }
834
+ }
835
+ return null;
836
+ }
837
+
838
+ function resolveSymbol(project, file, name, options) {
839
+ const strict = !!(options && options.strictLocal);
840
+ const key = `${normalizeKey(file.filePath)}|${name}|${strict}`;
841
+ if (project.symbolCache.has(key)) { return project.symbolCache.get(key); }
842
+ const result = resolveSymbolUncached(project, file, name, strict);
843
+ project.symbolCache.set(key, result);
844
+ return result;
845
+ }
846
+
847
+ function resolveSymbolUncached(project, file, name, strict) {
848
+ if (name.indexOf('.') >= 0) {
849
+ const [ns, member] = name.split('.');
850
+ const nsImp = file.namespaces.get(ns);
851
+ if (!nsImp) { return null; }
852
+ const target = resolveSpecFile(project, file, nsImp.spec, nsImp.resolved);
853
+ return target ? findExported(project, target, member) : null;
854
+ }
855
+ const imp = file.imports.get(name);
856
+ if (imp) {
857
+ const target = resolveSpecFile(project, file, imp.spec, imp.resolved);
858
+ if (target) {
859
+ const found = findExported(project, target, imp.name);
860
+ if (found) { return found; }
861
+ }
862
+ }
863
+ const local = findDeclared(file, name);
864
+ if (local) { return local; }
865
+ // A render receiver that is a local variable / callback parameter may share a name with a
866
+ // unique top-level declaration; only an explicit import may fall back to the project-wide
867
+ // unique name. Everything else is a guess and stays silent.
868
+ if (strict && !file.imports.has(name)) { return null; }
869
+ const unique = project.exports.get(name);
870
+ if (unique && unique.length === 1) { return unique[0]; }
871
+ return null;
872
+ }
873
+
874
+ function resolveType(project, file, type) {
875
+ for (const cand of typeCandidates(type)) {
876
+ const sym = resolveSymbol(project, file, cand);
877
+ if (sym && (sym.kind === 'class' || sym.kind === 'struct' || sym.kind === 'interface' || sym.kind === 'type')) {
878
+ return sym;
879
+ }
880
+ }
881
+ return null;
882
+ }
883
+
884
+ function resolveConstType(project, file, name) {
885
+ const sym = resolveSymbol(project, file, name);
886
+ if (!sym || sym.kind !== 'const') { return null; }
887
+ const typeName = sym.typeName || inferNewType(sym.init);
888
+ return resolveType(project, project.byPath.get(normalizeKey(sym.filePath)) || file, typeName);
889
+ }
890
+
891
+ function fieldOf(decl, name) {
892
+ if (!decl) { return null; }
893
+ if (decl.fields instanceof Map) { return decl.fields.get(name) || null; }
894
+ if (Array.isArray(decl.fields)) { return decl.fields.find((f) => f.name === name) || null; }
895
+ return null;
896
+ }
897
+
898
+ function methodOf(decl, name) {
899
+ if (!decl || !(decl.methods instanceof Map)) { return null; }
900
+ return decl.methods.get(name) || null;
901
+ }
902
+
903
+ function declFile(project, decl) {
904
+ return project.byPath.get(normalizeKey(decl.filePath)) || null;
905
+ }
906
+
907
+ function isObservedV2(decl) {
908
+ return !!decl && decl.kind === 'class' && hasDeco(decl.decos, OBSERVED_V2_DECO);
909
+ }
910
+
911
+ /** A data model may declare a constructor / accessors; only real methods make it a service/handle. */
912
+ function hasBehaviorMethods(decl) {
913
+ if (!decl || !(decl.methods instanceof Map)) { return false; }
914
+ for (const method of decl.methods.values()) {
915
+ if (method.name !== 'constructor' && !method.accessor) { return true; }
916
+ }
917
+ return false;
918
+ }
919
+
920
+ function isComponentV2(decl) {
921
+ return !!decl && decl.kind === 'struct' && hasDeco(decl.decos, COMPONENT_V2_DECO);
922
+ }
923
+
924
+ function fieldIsTraced(decl, field) {
925
+ return !!field && hasDeco(field.decos, TRACE_DECO);
926
+ }
927
+
928
+ function stateRootKind(decl, field) {
929
+ for (const d of field.decos || []) {
930
+ if (d.name === 'Local') { return 'Local'; }
931
+ if (d.name === 'Param' || d.name === 'Once') { return 'Param'; }
932
+ if (d.name === 'Provider') { return 'Provider'; }
933
+ if (d.name === 'Consumer') { return 'Consumer'; }
934
+ if (d.name === 'State') { return 'State'; }
935
+ if (d.name === 'Link') { return 'Link'; }
936
+ if (d.name === 'Prop') { return 'Prop'; }
937
+ }
938
+ return '';
939
+ }
940
+
941
+ /* ------------------------------------------------------------------ */
942
+ /* Write index + render-read collection */
943
+ /* ------------------------------------------------------------------ */
944
+
945
+ function declKey(decl) {
946
+ return `${normalizeKey(decl.filePath)}#${decl.kind}:${decl.name}`;
947
+ }
948
+
949
+ function buildWriteIndex(project) {
950
+ const fields = new Map(); // declKey -> Set(fieldName)
951
+ const nested = []; // { decl, root, path: [..], line, mutator }
952
+ const addField = (decl, name) => {
953
+ if (!decl || !name) { return; }
954
+ const key = declKey(decl);
955
+ const set = fields.get(key) || new Set();
956
+ set.add(name);
957
+ fields.set(key, set);
958
+ };
959
+ for (const file of project.files) {
960
+ for (const decl of [...file.classes.values(), ...file.structs.values()]) {
961
+ for (const method of decl.methods.values()) {
962
+ if (method.name === 'constructor') { continue; } // construction-time assignment is not a UI write
963
+ const body = method.masked;
964
+ const lineAt = (index) => lineOfIndex(file.code, method.bodyStart + index);
965
+ let m;
966
+
967
+ // this.<field> = / += / ++ / -- ...
968
+ for (const write of collectDirectWrites(body)) {
969
+ addField(decl, write.name);
970
+ nested.push({
971
+ decl,
972
+ filePath: file.filePath,
973
+ root: write.name,
974
+ path: [write.name],
975
+ line: lineAt(write.index),
976
+ mutator: false,
977
+ });
978
+ }
979
+
980
+ // this.<a>.<b>... = / += / ++ | this.<a>.<b>...<mutator>(...) — index expressions are
981
+ // skipped, the property names around them are kept
982
+ // (this.formData.sections[0].fields[0].value).
983
+ const chain = /\bthis\s*\.\s*([A-Za-z_$][\w$]*)((?:\s*(?:\.\s*[A-Za-z_$][\w$]*|\[[^\]]*\]))+)\s*(\(|(?:[+\-*/%&|^]|\*\*|<<|>>>?|\?\?|&&|\|\|)?=|(?:\+\+|--))?/g;
984
+ while ((m = chain.exec(body)) !== null) {
985
+ const root = m[1];
986
+ const rest = chainNames(m[2]);
987
+ const op = m[3];
988
+ const last = rest[rest.length - 1];
989
+ if (op === '=') {
990
+ const eqPos = m.index + m[0].length - 1;
991
+ const prev = body[eqPos - 1];
992
+ const next = body[eqPos + 1];
993
+ if (prev === '=' || prev === '!' || prev === '<' || prev === '>' || next === '=') {
994
+ continue; // ==, ===, !=, <=, >= are reads, not writes
995
+ }
996
+ const path = [root, ...rest];
997
+ addField(decl, root);
998
+ const leafOwner = resolveChainDecl(project, declFile(project, decl), decl, path.slice(0, -1));
999
+ if (leafOwner) { addField(leafOwner, path[path.length - 1]); }
1000
+ nested.push({
1001
+ decl, filePath: file.filePath, root, path,
1002
+ line: lineAt(m.index), mutator: false,
1003
+ });
1004
+ } else if (op === '++' || op === '--' || (op && op !== '(' && op.endsWith('='))) {
1005
+ const path = [root, ...rest];
1006
+ addField(decl, root);
1007
+ const leafOwner = resolveChainDecl(project, declFile(project, decl), decl, path.slice(0, -1));
1008
+ if (leafOwner) { addField(leafOwner, path[path.length - 1]); }
1009
+ nested.push({
1010
+ decl, filePath: file.filePath, root, path,
1011
+ line: lineAt(m.index), mutator: false,
1012
+ });
1013
+ } else if (op === '(' && MUTATORS.has(last)) {
1014
+ const path = rest.length > 1 ? [root, ...rest.slice(0, -1)] : [root];
1015
+ addField(decl, root);
1016
+ const leafOwner = resolveChainDecl(project, declFile(project, decl), decl, path.slice(0, -1));
1017
+ if (leafOwner) { addField(leafOwner, path[path.length - 1]); }
1018
+ nested.push({
1019
+ decl, filePath: file.filePath, root, path,
1020
+ line: lineAt(m.index), mutator: true,
1021
+ });
1022
+ }
1023
+ }
1024
+ }
1025
+ }
1026
+ }
1027
+ return { fields, nested };
1028
+ }
1029
+
1030
+ /** Resolve the class that declares the last element of a field path, starting at `startDecl`. */
1031
+ function resolveChainDecl(project, file, startDecl, pathParts) {
1032
+ let owner = startDecl;
1033
+ let ownerFile = file;
1034
+ for (let i = 0; i < pathParts.length; i++) {
1035
+ const field = fieldOf(owner, pathParts[i]);
1036
+ if (!field) { return null; }
1037
+ const next = resolveType(project, ownerFile, field.type);
1038
+ if (!next) { return null; }
1039
+ owner = next;
1040
+ ownerFile = declFile(project, next);
1041
+ }
1042
+ return owner;
1043
+ }
1044
+
1045
+ /** Ranges of `.onXxx(() => { ... })` event callbacks — reads there are not render reads. */
1046
+ function eventHandlerRanges(text) {
1047
+ const ranges = [];
1048
+ const re = /\.\s*on[A-Z][A-Za-z0-9]*\s*\(/g;
1049
+ let m;
1050
+ while ((m = re.exec(text)) !== null) {
1051
+ const open = m.index + m[0].length - 1;
1052
+ const close = matchBracket(text, open);
1053
+ if (close > open) { ranges.push({ start: m.index, end: close }); }
1054
+ }
1055
+ return ranges;
1056
+ }
1057
+
1058
+ function insideRanges(ranges, index) {
1059
+ return ranges.some((r) => r.start <= index && index <= r.end);
1060
+ }
1061
+
1062
+ /** Ranges guarded by `if (...) { ... }` / `if (...) statement` — used to ignore idempotent clamp writes. */
1063
+ function ifRanges(text) {
1064
+ const ranges = [];
1065
+ const re = /\bif\s*\(/g;
1066
+ let m;
1067
+ while ((m = re.exec(text)) !== null) {
1068
+ const open = m.index + m[0].length - 1;
1069
+ const close = matchBracket(text, open);
1070
+ if (close < 0) { continue; }
1071
+ let j = close + 1;
1072
+ while (j < text.length && /\s/.test(text[j])) { j++; }
1073
+ if (text[j] === '{') {
1074
+ const end = matchBracket(text, j);
1075
+ if (end > j) { ranges.push({ start: j, end }); }
1076
+ } else {
1077
+ const start = j;
1078
+ while (j < text.length && text[j] !== ';') { j++; }
1079
+ ranges.push({ start, end: j });
1080
+ }
1081
+ }
1082
+ return ranges;
1083
+ }
1084
+
1085
+ /** A value-returning method whose body contains no write: safe to inline as a render read. */
1086
+ function isReadOnlyMethod(method) {
1087
+ if (!method) { return false; }
1088
+ const ret = String(method.retType || '').replace(/\s+/g, '');
1089
+ if (ret === '') { return false; } // unknown return type: do not inline (matches the documented "non-void" rule)
1090
+ if (/^(?:void|Promise<void>|undefined|null)$/.test(ret)) { return false; }
1091
+ const body = method.masked || '';
1092
+ if (collectDirectWrites(body).length > 0) { return false; }
1093
+ if (/\bthis\s*\.\s*[A-Za-z_$][\w$]*\s*\.\s*(?:push|pop|shift|unshift|splice|sort|reverse|fill|copyWithin|set|add|delete|clear)\s*\(/.test(body)) {
1094
+ return false;
1095
+ }
1096
+ if (/\bawait\b/.test(body)) { return false; }
1097
+ return true;
1098
+ }
1099
+
1100
+ /**
1101
+ * Collect reads in a render fragment.
1102
+ * Returns { fields: [{owner, field, viaMethod, line}], methods: [{owner, method}] }.
1103
+ *
1104
+ * builderDepth tracks @Builder expansion (render content); methodDepth tracks one-level
1105
+ * value-method inlining. They are separate on purpose: a @Builder that calls
1106
+ * appRouter.currentRoute() must still allow the one-level method inline.
1107
+ */
1108
+ function collectReads(project, file, struct, text, options) {
1109
+ const opts = options || {};
1110
+ const owner = opts.owner || struct;
1111
+ const allowBuilders = opts.allowBuilders !== false;
1112
+ const builderDepth = opts.builderDepth || 0;
1113
+ const methodDepth = opts.methodDepth || 0;
1114
+ const render = opts.render || 'build';
1115
+ const fields = [];
1116
+ const methods = [];
1117
+ const handlers = eventHandlerRanges(text);
1118
+ let m;
1119
+
1120
+ // this.<field> / this.<method>( / this.<field>.<member>
1121
+ const thisRe = /\bthis\s*\.\s*([A-Za-z_$][\w$]*)\s*(\(|\.)?/g;
1122
+ while ((m = thisRe.exec(text)) !== null) {
1123
+ if (insideRanges(handlers, m.index)) { continue; }
1124
+ const name = m[1];
1125
+ const next = m[2];
1126
+ const tail = tailAt(text, m.index + m[0].length);
1127
+ if (next === '(') {
1128
+ const meth = methodOf(owner, name);
1129
+ if (meth) {
1130
+ methods.push({ owner, method: name });
1131
+ if (allowBuilders && hasDeco(meth.decos, BUILDER_DECO) && builderDepth < MAX_WALK_DEPTH) {
1132
+ fields.push(...collectReads(project, file, struct, meth.masked, {
1133
+ owner: struct, allowBuilders, builderDepth: builderDepth + 1, methodDepth,
1134
+ }).fields);
1135
+ } else if (methodDepth < 1 && isReadOnlyMethod(meth)) {
1136
+ fields.push(...readsInMethod(project, file, owner, meth, 'this', render));
1137
+ }
1138
+ }
1139
+ continue;
1140
+ }
1141
+ if (next === '.') {
1142
+ // this.<field>.<member> — record the root field; resolve a method on its type.
1143
+ const mm = /^([A-Za-z_$][\w$]*)\s*(\(|\.)?/.exec(tail);
1144
+ if (!mm) { continue; }
1145
+ const memberTail = tail.slice(mm[0].length).replace(/^\s*/, '');
1146
+ if (/^=(?!=)/.test(memberTail) || /^\+\+|^--/.test(memberTail)) {
1147
+ continue; // this.<field>.<member> = ... is a write, not a render read
1148
+ }
1149
+ const rootField = fieldOf(owner, name);
1150
+ if (rootField) {
1151
+ fields.push({ owner, field: name, viaMethod: false, line: 0 });
1152
+ const typeDecl = resolveType(project, file, rootField.type);
1153
+ if (typeDecl) {
1154
+ if (mm[2] === '(') {
1155
+ const meth = methodOf(typeDecl, mm[1]);
1156
+ if (meth && methodDepth < 1 && isReadOnlyMethod(meth)) {
1157
+ fields.push(...readsInMethod(project, file, typeDecl, meth, `this.${name}`, render));
1158
+ }
1159
+ } else {
1160
+ const getter = methodOf(typeDecl, mm[1]);
1161
+ if (getter && methodDepth < 1 && isReadOnlyMethod(getter)) {
1162
+ fields.push(...readsInMethod(project, file, typeDecl, getter, `this.${name}`, render));
1163
+ } else {
1164
+ fields.push({ owner: typeDecl, field: mm[1], viaMethod: false, line: 0 });
1165
+ }
1166
+ }
1167
+ }
1168
+ }
1169
+ continue;
1170
+ }
1171
+ if (/^=(?!=)/.test(tail) || /^\+\+|^--/.test(tail)) { continue; } // this.x = / this.x++
1172
+ const field = fieldOf(owner, name);
1173
+ if (field) {
1174
+ fields.push({ owner, field: name, viaMethod: false, line: 0 });
1175
+ } else {
1176
+ const getter = methodOf(owner, name);
1177
+ if (getter && methodDepth < 1 && isReadOnlyMethod(getter)) {
1178
+ fields.push(...readsInMethod(project, file, owner, getter, 'this', render));
1179
+ }
1180
+ }
1181
+ }
1182
+
1183
+ // this.<root>.<a>[i].<b> — record every owner#field along the chain (nested leaf reads).
1184
+ const chainReadRe = /\bthis\s*\.\s*([A-Za-z_$][\w$]*)((?:\s*(?:\.\s*[A-Za-z_$][\w$]*|\[[^\]]*\]))+)/g;
1185
+ while ((m = chainReadRe.exec(text)) !== null) {
1186
+ if (insideRanges(handlers, m.index)) { continue; }
1187
+ const after = tailAt(text, m.index + m[0].length);
1188
+ if (/^=(?!=)/.test(after) || /^\+\+|^--/.test(after)) { continue; } // write, not read
1189
+ const names = chainNames(m[2]);
1190
+ if (names.length === 0) { continue; }
1191
+ const rootField = fieldOf(owner, m[1]);
1192
+ if (!rootField) { continue; }
1193
+ fields.push({ owner, field: m[1], viaMethod: false, line: 0 });
1194
+ let typeDecl = resolveType(project, file, rootField.type);
1195
+ let typeFile = typeDecl ? declFile(project, typeDecl) : file;
1196
+ for (const name of names) {
1197
+ if (!typeDecl) { break; }
1198
+ const f = fieldOf(typeDecl, name);
1199
+ if (!f) { break; }
1200
+ fields.push({ owner: typeDecl, field: name, viaMethod: false, line: 0 });
1201
+ const next = resolveType(project, typeFile || file, f.type);
1202
+ typeDecl = next;
1203
+ typeFile = next ? declFile(project, next) : typeFile;
1204
+ }
1205
+ }
1206
+
1207
+ // <ident>.<field> / <ident>.<method>( — imported singleton / namespace / class name.
1208
+ const recvRe = /\b([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)\s*(\(|\.)?/g;
1209
+ while ((m = recvRe.exec(text)) !== null) {
1210
+ if (insideRanges(handlers, m.index)) { continue; }
1211
+ const recv = m[1];
1212
+ if (recv === 'this' || GLOBAL_OBJECTS.has(recv)) { continue; }
1213
+ const member = m[2];
1214
+ const tail = tailAt(text, m.index + m[0].length);
1215
+ if (m[3] !== '(' && (/^=(?!=)/.test(tail) || /^\+\+|^--/.test(tail))) { continue; } // write
1216
+ // Only imports / this-file declarations: a local variable or ForEach parameter must not
1217
+ // borrow a same-named top-level declaration.
1218
+ let target = resolveSymbol(project, file, recv, { strictLocal: true });
1219
+ if (!target) { continue; }
1220
+ if (target.kind === 'const') {
1221
+ target = resolveConstType(project, file, recv);
1222
+ }
1223
+ if (!target) { continue; }
1224
+ if (m[3] === '(') {
1225
+ const meth = methodOf(target, member);
1226
+ if (meth && methodDepth < 1 && isReadOnlyMethod(meth)) {
1227
+ fields.push(...readsInMethod(project, file, target, meth, recv, render));
1228
+ }
1229
+ } else {
1230
+ // Field or getter on the singleton / imported class.
1231
+ const field = fieldOf(target, member);
1232
+ if (field) {
1233
+ fields.push({ owner: target, field: member, viaMethod: false, line: 0, receiver: recv });
1234
+ } else {
1235
+ const getter = methodOf(target, member);
1236
+ if (getter && methodDepth < 1 && isReadOnlyMethod(getter)) {
1237
+ fields.push(...readsInMethod(project, file, target, getter, recv, render));
1238
+ }
1239
+ }
1240
+ }
1241
+ }
1242
+ for (const f of fields) {
1243
+ if (!f.render) { f.render = render; }
1244
+ if (!f.receiver) { f.receiver = 'this'; }
1245
+ }
1246
+ return { fields, methods };
1247
+ }
1248
+
1249
+ function readsInMethod(project, file, owner, method, receiver, render) {
1250
+ const out = [];
1251
+ let m;
1252
+ const re = /\bthis\s*\.\s*([A-Za-z_$][\w$]*)/g;
1253
+ while ((m = re.exec(method.masked)) !== null) {
1254
+ const field = fieldOf(owner, m[1]);
1255
+ if (field) {
1256
+ out.push({
1257
+ owner, field: m[1], viaMethod: true, line: 0,
1258
+ receiver: receiver || 'this', render: render || 'build',
1259
+ });
1260
+ }
1261
+ }
1262
+ return out;
1263
+ }
1264
+
1265
+ /* ------------------------------------------------------------------ */
1266
+ /* Sub-checks */
1267
+ /* ------------------------------------------------------------------ */
1268
+
1269
+ function issue(subCode, severity, filePath, line, values) {
1270
+ return {
1271
+ subCode,
1272
+ severity,
1273
+ filePath,
1274
+ line: line > 0 ? line : 1,
1275
+ values: values || [],
1276
+ };
1277
+ }
1278
+
1279
+ /** All render text of a @ComponentV2 struct: build + @Builder members. */
1280
+ function renderTexts(struct) {
1281
+ const out = [];
1282
+ const build = methodOf(struct, 'build');
1283
+ if (build) { out.push(build); }
1284
+ for (const method of struct.methods.values()) {
1285
+ if (hasDeco(method.decos, BUILDER_DECO)) { out.push(method); }
1286
+ }
1287
+ return out;
1288
+ }
1289
+
1290
+ /** Project-wide set of `declKey(owner)#field` for every field read on a render path. */
1291
+ function buildRenderReadSet(project) {
1292
+ const set = new Set();
1293
+ const reads = [];
1294
+ for (const file of project.files) {
1295
+ for (const struct of file.structs.values()) {
1296
+ if (!isComponentV2(struct)) { continue; }
1297
+ for (const method of renderTexts(struct)) {
1298
+ const render = hasDeco(method.decos, BUILDER_DECO) ? '@Builder' : 'build';
1299
+ // build() expands builders through their own pass below; do not inline them twice.
1300
+ const result = collectReads(project, file, struct, method.masked, {
1301
+ owner: struct, render, allowBuilders: render === '@Builder',
1302
+ });
1303
+ for (const f of result.fields) {
1304
+ set.add(`${declKey(f.owner)}#${f.field}`);
1305
+ reads.push(f);
1306
+ }
1307
+ }
1308
+ }
1309
+ }
1310
+ return { set, reads };
1311
+ }
1312
+
1313
+ function isFieldRead(renderReadSet, owner, fieldName) {
1314
+ return !!owner && !!fieldName && renderReadSet.has(`${declKey(owner)}#${fieldName}`);
1315
+ }
1316
+
1317
+ /** B1 general: render reads an @ObservedV2 bare field through a one-level method. */
1318
+ function checkRenderReads(writeIndex, shadowContainers, renderReads) {
1319
+ const issues = [];
1320
+ const seen = new Set();
1321
+ for (const read of renderReads) {
1322
+ const owner = read.owner;
1323
+ const field = fieldOf(owner, read.field);
1324
+ if (!owner || !isObservedV2(owner) || !field) { continue; }
1325
+ if (field.private || field.readonly) { continue; }
1326
+ if (fieldIsTraced(owner, field)) { continue; }
1327
+ if (shadowContainers.has(`${declKey(owner)}#${read.field}`)) { continue; }
1328
+ const written = writeIndex.fields.get(declKey(owner));
1329
+ if (!written || !written.has(read.field)) { continue; }
1330
+ const key = `${declKey(owner)}#${read.field}`;
1331
+ if (seen.has(key)) { continue; }
1332
+ seen.add(key);
1333
+ const context = read.viaMethod ? `${read.render || 'build'} -> method` : (read.render || 'build');
1334
+ issues.push(issue(
1335
+ 'renderRead', AlertLevel.WARN, owner.filePath,
1336
+ field.line || owner.line,
1337
+ [context, `${owner.name}.${read.field}`],
1338
+ ));
1339
+ }
1340
+ return issues;
1341
+ }
1342
+
1343
+ /** B1 shadow: @Trace D = plain C.length used as a branch condition while the branch reads C. */
1344
+ function checkShadowState(project) {
1345
+ const issues = [];
1346
+ const seen = new Set();
1347
+ const shadows = []; // { owner, D, C, line }
1348
+ for (const file of project.files) {
1349
+ for (const decl of file.classes.values()) {
1350
+ if (!isObservedV2(decl)) { continue; }
1351
+ const bare = [...decl.fields.values()].filter((f) => !fieldIsTraced(decl, f));
1352
+ const traced = [...decl.fields.values()].filter((f) => fieldIsTraced(decl, f));
1353
+ if (!bare.length || !traced.length) { continue; }
1354
+ for (const method of decl.methods.values()) {
1355
+ let m;
1356
+ const re = /\bthis\s*\.\s*([A-Za-z_$][\w$]*)\s*=\s*this\s*\.\s*([A-Za-z_$][\w$]*)\s*\.\s*(?:length|size)\b/g;
1357
+ while ((m = re.exec(method.masked)) !== null) {
1358
+ const D = m[1];
1359
+ const C = m[2];
1360
+ if (D === C) { continue; }
1361
+ if (!traced.some((f) => f.name === D)) { continue; }
1362
+ if (!bare.some((f) => f.name === C)) { continue; }
1363
+ shadows.push({ owner: decl, D, C, line: lineOfIndex(file.code, method.bodyStart + m.index) });
1364
+ }
1365
+ }
1366
+ }
1367
+ }
1368
+ if (!shadows.length) { return { issues, containers: new Set() }; }
1369
+
1370
+ const containers = new Set();
1371
+
1372
+ for (const file of project.files) {
1373
+ for (const struct of file.structs.values()) {
1374
+ if (!isComponentV2(struct)) { continue; }
1375
+ for (const method of renderTexts(struct)) {
1376
+ const text = method.masked;
1377
+ let m;
1378
+ const ifRe = /\bif\s*\(/g;
1379
+ while ((m = ifRe.exec(text)) !== null) {
1380
+ const open = m.index + m[0].length - 1;
1381
+ const close = matchBracket(text, open);
1382
+ if (close < 0) { continue; }
1383
+ const cond = text.slice(open + 1, close);
1384
+ let j = close + 1;
1385
+ while (j < text.length && /\s/.test(text[j])) { j++; }
1386
+ let thenText = '';
1387
+ let thenEnd = j;
1388
+ if (text[j] === '{') {
1389
+ const thenClose = matchBracket(text, j);
1390
+ if (thenClose < 0) { continue; }
1391
+ thenText = text.slice(j + 1, thenClose);
1392
+ thenEnd = thenClose;
1393
+ } else {
1394
+ while (thenEnd < text.length && text[thenEnd] !== ';') { thenEnd++; }
1395
+ thenText = text.slice(j, thenEnd);
1396
+ }
1397
+ let elseText = '';
1398
+ let k = thenEnd + 1;
1399
+ while (k < text.length && /\s/.test(text[k])) { k++; }
1400
+ if (text.startsWith('else', k)) {
1401
+ let e = k + 4;
1402
+ while (e < text.length && /\s/.test(text[e])) { e++; }
1403
+ if (text[e] === '{') {
1404
+ const elseClose = matchBracket(text, e);
1405
+ if (elseClose > e) { elseText = text.slice(e + 1, elseClose); }
1406
+ } else if (text.startsWith('if', e)) {
1407
+ // the nested if is visited by the outer loop as well
1408
+ }
1409
+ }
1410
+ const condReads = collectReads(project, file, struct, cond, { owner: struct });
1411
+ const thenReads = collectReads(project, file, struct, thenText, { owner: struct, allowBuilders: true });
1412
+ const elseReads = elseText ? collectReads(project, file, struct, elseText, { owner: struct, allowBuilders: true }) : { fields: [] };
1413
+ const branchFields = [...thenReads.fields, ...elseReads.fields];
1414
+ for (const shadow of shadows) {
1415
+ const condHit = condReads.fields.find((r) => r.owner === shadow.owner && r.field === shadow.D);
1416
+ if (!condHit) { continue; }
1417
+ const sameInstance = (r) => !condHit.receiver || !r.receiver || r.receiver === condHit.receiver;
1418
+ const branchHit = branchFields.some((r) => r.owner === shadow.owner && r.field === shadow.C && sameInstance(r));
1419
+ if (!branchHit) { continue; }
1420
+ // If the branch also reads the shadow, push/pop refresh through D; only a write that
1421
+ // changes C without changing D (replaceTop / pop+push) is still stale. Do not hard-block.
1422
+ const branchReadsD = branchFields.some((r) => r.owner === shadow.owner && r.field === shadow.D && sameInstance(r));
1423
+ const key = `${normalizeKey(file.filePath)}#${shadow.owner.name}#${shadow.D}#${shadow.C}#${m.index}`;
1424
+ if (seen.has(key)) { continue; }
1425
+ seen.add(key);
1426
+ containers.add(`${declKey(shadow.owner)}#${shadow.C}`);
1427
+ issues.push(issue(
1428
+ branchReadsD ? 'shadowSoft' : 'shadow',
1429
+ branchReadsD ? AlertLevel.WARN : AlertLevel.ERROR,
1430
+ file.filePath,
1431
+ lineOfIndex(file.code, method.bodyStart + m.index),
1432
+ [`${shadow.owner.name}.${shadow.D}`, `${shadow.owner.name}.${shadow.C}`, `${shadow.owner.name}.${shadow.D} = ${shadow.owner.name}.${shadow.C}.length`],
1433
+ ));
1434
+ }
1435
+ }
1436
+ }
1437
+ }
1438
+ }
1439
+ return { issues, containers };
1440
+ }
1441
+
1442
+ /** B2: nested custom class in a @Param/@Provider/@Consumer (or @ObservedV2 field) tree is not @ObservedV2. */
1443
+ function checkNestedClass(project, writeIndex, renderReadSet) {
1444
+ const issues = [];
1445
+ const seen = new Set();
1446
+ for (const file of project.files) {
1447
+ for (const struct of file.structs.values()) {
1448
+ if (!isComponentV2(struct)) { continue; }
1449
+ for (const field of struct.fields.values()) {
1450
+ if (field.private) { continue; }
1451
+ const kind = stateRootKind(struct, field);
1452
+ if (kind !== 'Local' && kind !== 'Param' && kind !== 'Provider' && kind !== 'Consumer') { continue; }
1453
+ const rootType = resolveType(project, file, field.type);
1454
+ if (!rootType || rootType.kind === 'interface' || rootType.kind === 'type') { continue; }
1455
+ if (!hasPropertyWrite(writeIndex, struct, field.name)) { continue; }
1456
+ if (!isFieldRead(renderReadSet, struct, field.name)) { continue; }
1457
+ const candidate = firstUnobservedOnWrites(project, file, rootType, writeIndex, struct, field.name);
1458
+ if (!candidate) { continue; }
1459
+ const key = `${declKey(candidate)}`;
1460
+ if (seen.has(key)) { continue; }
1461
+ seen.add(key);
1462
+ issues.push(issue(
1463
+ 'nestedClass', AlertLevel.WARN, candidate.filePath,
1464
+ candidate.line,
1465
+ [candidate.name, `${struct.name}.${field.name}`, field.type],
1466
+ ));
1467
+ }
1468
+ }
1469
+ }
1470
+ // @ObservedV2 fields whose nested type is not @ObservedV2.
1471
+ for (const file of project.files) {
1472
+ for (const decl of file.classes.values()) {
1473
+ if (!isObservedV2(decl)) { continue; }
1474
+ for (const field of decl.fields.values()) {
1475
+ if (field.private) { continue; }
1476
+ const nested = resolveType(project, file, field.type);
1477
+ if (!nested || nested === decl || nested.kind === 'interface' || nested.kind === 'type') { continue; }
1478
+ if (isObservedV2(nested)) { continue; }
1479
+ if (hasBehaviorMethods(nested)) { continue; }
1480
+ // A whole-array reassignment does not need @ObservedV2 on the element; only a
1481
+ // property write below the first level does.
1482
+ if (!hasPropertyWrite(writeIndex, decl, field.name)) { continue; }
1483
+ if (!isFieldRead(renderReadSet, decl, field.name)) { continue; }
1484
+ const key = `${declKey(nested)}`;
1485
+ if (seen.has(key)) { continue; }
1486
+ seen.add(key);
1487
+ issues.push(issue(
1488
+ 'nestedClass', AlertLevel.WARN, nested.filePath, nested.line,
1489
+ [nested.name, `${decl.name}.${field.name}`, field.type],
1490
+ ));
1491
+ }
1492
+ }
1493
+ }
1494
+ return issues;
1495
+ }
1496
+
1497
+ function hasNestedWrite(writeIndex, decl, root) {
1498
+ return writeIndex.nested.some((w) => w.decl === decl && w.root === root && w.path.length >= 2);
1499
+ }
1500
+
1501
+ /** A property write below the first level (not a collection mutator) — the shape that needs a nested observed class. */
1502
+ function hasPropertyWrite(writeIndex, decl, root) {
1503
+ return writeIndex.nested.some((w) => w.decl === decl && w.root === root && w.path.length >= 2 && !w.mutator);
1504
+ }
1505
+
1506
+ /** Walk the first property-write path and return the first data-model class without @ObservedV2. */
1507
+ function firstUnobservedOnWrites(project, file, rootType, writeIndex, struct, root) {
1508
+ const write = writeIndex.nested.find((w) => w.decl === struct && w.root === root && w.path.length >= 2 && !w.mutator);
1509
+ if (!write) { return null; }
1510
+ let owner = rootType;
1511
+ let ownerFile = file;
1512
+ for (let i = 0; i < write.path.length; i++) {
1513
+ if (owner && owner.kind === 'class' && !isObservedV2(owner) && !hasBehaviorMethods(owner)) {
1514
+ return owner;
1515
+ }
1516
+ if (i === 0) { continue; } // path[0] is the root field name, already resolved as rootType
1517
+ const field = fieldOf(owner, write.path[i]);
1518
+ if (!field) { return null; }
1519
+ const next = resolveType(project, ownerFile, field.type);
1520
+ if (!next) { return null; }
1521
+ owner = next;
1522
+ ownerFile = declFile(project, next);
1523
+ }
1524
+ return null;
1525
+ }
1526
+
1527
+ /** B3: @Param/@Provider/@Consumer deep write into an @ObservedV2 class field without @Trace. */
1528
+ function checkDeepWrite(project, writeIndex, renderReadSet) {
1529
+ const issues = [];
1530
+ const seen = new Set();
1531
+ for (const file of project.files) {
1532
+ for (const struct of file.structs.values()) {
1533
+ if (!isComponentV2(struct)) { continue; }
1534
+ for (const field of struct.fields.values()) {
1535
+ if (field.private) { continue; }
1536
+ const kind = stateRootKind(struct, field);
1537
+ if (kind !== 'Param' && kind !== 'Provider' && kind !== 'Consumer') { continue; }
1538
+ const rootType = resolveType(project, file, field.type);
1539
+ if (!rootType) { continue; }
1540
+ for (const write of writeIndex.nested) {
1541
+ if (write.decl !== struct || write.root !== field.name) { continue; }
1542
+ if (write.path.length < 2) { continue; }
1543
+ let owner = rootType;
1544
+ let ownerFile = declFile(project, rootType);
1545
+ let ok = true;
1546
+ for (let i = 1; i < write.path.length - 1; i++) {
1547
+ const f = fieldOf(owner, write.path[i]);
1548
+ const next = f ? resolveType(project, ownerFile, f.type) : null;
1549
+ if (!next) { ok = false; break; }
1550
+ owner = next;
1551
+ ownerFile = declFile(project, next);
1552
+ }
1553
+ if (!ok) { continue; }
1554
+ const leaf = write.path[write.path.length - 1];
1555
+ const leafField = fieldOf(owner, leaf);
1556
+ if (!leafField || leafField.private || leafField.readonly) { continue; }
1557
+ if (!isObservedV2(owner)) { continue; } // B2 owns the unobserved-class case
1558
+ if (fieldIsTraced(owner, leafField)) { continue; }
1559
+ if (!isFieldRead(renderReadSet, owner, leaf)) { continue; } // internal flags do not need a refresh
1560
+ const key = `${declKey(owner)}#${leaf}`;
1561
+ if (seen.has(key)) { continue; }
1562
+ seen.add(key);
1563
+ issues.push(issue(
1564
+ 'deepWrite', AlertLevel.ERROR, owner.filePath, leafField.line || owner.line,
1565
+ [`${owner.name}.${leaf}`, write.path.join('.'), `${struct.name}.${field.name}`],
1566
+ ));
1567
+ }
1568
+ }
1569
+ }
1570
+ }
1571
+ return issues;
1572
+ }
1573
+
1574
+ /** B4: @Monitor('a.b') where a.b is a collection mutated element-by-element. */
1575
+ function checkMonitorDeepCollection(project) {
1576
+ const issues = [];
1577
+ for (const file of project.files) {
1578
+ for (const decl of [...file.classes.values(), ...file.structs.values()]) {
1579
+ const methods = [...decl.methods.values()];
1580
+ for (const method of methods) {
1581
+ for (const pathArg of decoArgs(method.decos, MONITOR_DECO)) {
1582
+ if (!pathArg || pathArg.indexOf('.') < 0) { continue; }
1583
+ const segments = pathArg.split('.').map((s) => s.trim()).filter(Boolean);
1584
+ if (segments.length < 2) { continue; }
1585
+ let owner = decl;
1586
+ let ownerFile = file;
1587
+ let ok = true;
1588
+ for (let i = 0; i < segments.length - 1; i++) {
1589
+ const f = fieldOf(owner, segments[i]);
1590
+ const next = f ? resolveType(project, ownerFile, f.type) : null;
1591
+ if (!next) { ok = false; break; }
1592
+ owner = next;
1593
+ ownerFile = declFile(project, next);
1594
+ }
1595
+ if (!ok) { continue; }
1596
+ const last = segments[segments.length - 1];
1597
+ const lastField = fieldOf(owner, last);
1598
+ if (!lastField || !isCollectionType(lastField.type)) { continue; }
1599
+ const dotted = segments.map(escapeRegExp).join('\\.');
1600
+ let mutator = false;
1601
+ let whole = false;
1602
+ for (const m of methods) {
1603
+ if (new RegExp(`\\bthis\\s*\\.\\s*${dotted}\\s*=(?!=)`).test(m.masked)) { whole = true; }
1604
+ if (new RegExp(`\\bthis\\s*\\.\\s*${dotted}\\s*\\.\\s*(?:push|pop|shift|unshift|splice|sort|reverse|fill|copyWithin|set|add|delete|clear)\\s*\\(`).test(m.masked)) {
1605
+ mutator = true;
1606
+ }
1607
+ }
1608
+ if (!mutator || whole) { continue; }
1609
+ issues.push(issue(
1610
+ 'monitorDeepCollection', AlertLevel.WARN, file.filePath, method.line,
1611
+ [pathArg, `${owner.name}.${last}`, lastField.type],
1612
+ ));
1613
+ }
1614
+ }
1615
+ }
1616
+ }
1617
+ return issues;
1618
+ }
1619
+
1620
+ /** B5: interface/object-typed state field assigned a plain object, then nested-written. */
1621
+ function checkPlainObjectState(project, writeIndex, renderReadSet) {
1622
+ const issues = [];
1623
+ for (const file of project.files) {
1624
+ for (const struct of file.structs.values()) {
1625
+ if (!isComponentV2(struct)) { continue; }
1626
+ for (const field of struct.fields.values()) {
1627
+ if (field.private) { continue; }
1628
+ const kind = stateRootKind(struct, field);
1629
+ if (kind !== 'Local' && kind !== 'Param') { continue; }
1630
+ const typeDecl = resolveType(project, file, field.type);
1631
+ if (!typeDecl || (typeDecl.kind !== 'interface' && typeDecl.kind !== 'type')) { continue; }
1632
+ if (!hasNestedWrite(writeIndex, struct, field.name)) { continue; }
1633
+ if (!isFieldRead(renderReadSet, struct, field.name)) { continue; }
1634
+ let line = 0;
1635
+ for (const method of struct.methods.values()) {
1636
+ const re = new RegExp(`\\bthis\\s*\\.\\s*${escapeRegExp(field.name)}\\s*=\\s*([\\s\\S]*?)(?:;|\\n)`, 'g');
1637
+ let m;
1638
+ while ((m = re.exec(method.masked)) !== null) {
1639
+ const rhs = m[1].trim();
1640
+ if (rhs === '') { continue; }
1641
+ if (/^new\s/.test(rhs) || /^UIUtils\s*\.\s*makeObserved\s*\(/.test(rhs) || /^makeObserved\s*\(/.test(rhs)) { continue; }
1642
+ if (rhs.startsWith('{') || /^Object\s*\.\s*assign\s*\(/.test(rhs)) {
1643
+ line = lineOfIndex(file.code, method.bodyStart + m.index);
1644
+ break;
1645
+ }
1646
+ }
1647
+ if (line) { break; }
1648
+ }
1649
+ if (!line) { continue; }
1650
+ issues.push(issue(
1651
+ 'plainObjectState', AlertLevel.WARN, file.filePath, line,
1652
+ [`${struct.name}.${field.name}`, field.type, typeDecl.name],
1653
+ ));
1654
+ }
1655
+ }
1656
+ }
1657
+ return issues;
1658
+ }
1659
+
1660
+ /** B6: V2 @Monitor loop (A writes what B watches, B writes what A watches). */
1661
+ function checkMonitorCycle(project) {
1662
+ const issues = [];
1663
+ for (const file of project.files) {
1664
+ for (const decl of [...file.classes.values(), ...file.structs.values()]) {
1665
+ const monitors = [];
1666
+ for (const method of decl.methods.values()) {
1667
+ const paths = decoArgs(method.decos, MONITOR_DECO);
1668
+ if (paths.length === 0) { continue; }
1669
+ const guarded = ifRanges(method.masked);
1670
+ const writes = new Set(
1671
+ collectDirectWrites(method.masked)
1672
+ .filter((w) => !insideRanges(guarded, w.index))
1673
+ .map((w) => w.name),
1674
+ );
1675
+ for (const path of paths) {
1676
+ const segments = path.split('.').map((s) => s.trim()).filter(Boolean);
1677
+ // Only a single-segment path can be compared with this.<field> writes; a dot path
1678
+ // (profile.name) writing this.name is a mirror, not a self-loop.
1679
+ const watches = segments.length === 1 ? segments[0] : '';
1680
+ monitors.push({ method, path, watches, writes });
1681
+ }
1682
+ }
1683
+ if (monitors.length === 0) { continue; }
1684
+ const edges = new Map();
1685
+ for (const a of monitors) {
1686
+ const targets = [];
1687
+ for (const b of monitors) {
1688
+ if (a.writes.has(b.watches)) { targets.push(b); }
1689
+ }
1690
+ edges.set(a, targets);
1691
+ }
1692
+ const state = new Map();
1693
+ const stack = [];
1694
+ const reported = new Set();
1695
+ const visit = (node) => {
1696
+ state.set(node, 1);
1697
+ stack.push(node);
1698
+ for (const next of edges.get(node) || []) {
1699
+ if (state.get(next) === 1) {
1700
+ const at = stack.indexOf(next);
1701
+ const cycle = stack.slice(at);
1702
+ for (const n of cycle) {
1703
+ if (reported.has(n)) { continue; }
1704
+ reported.add(n);
1705
+ issues.push(issue(
1706
+ 'monitorCycle', AlertLevel.WARN, file.filePath, n.method.line,
1707
+ [decl.name, n.path, cycle.map((x) => x.path).join(' -> ')],
1708
+ ));
1709
+ }
1710
+ } else if (!state.has(next)) {
1711
+ visit(next);
1712
+ }
1713
+ }
1714
+ stack.pop();
1715
+ state.set(node, 2);
1716
+ };
1717
+ for (const node of monitors) {
1718
+ if (!state.has(node)) { visit(node); }
1719
+ }
1720
+ }
1721
+ }
1722
+ return issues;
1723
+ }
1724
+
1725
+ /* ------------------------------------------------------------------ */
1726
+ /* Public analysis entry */
1727
+ /* ------------------------------------------------------------------ */
1728
+
1729
+ function analyzeV2Observation(scans, options) {
1730
+ const project = buildProject(scans, options);
1731
+ const writeIndex = buildWriteIndex(project);
1732
+ const renderIndex = buildRenderReadSet(project);
1733
+ const shadow = checkShadowState(project);
1734
+ const issues = [
1735
+ ...shadow.issues,
1736
+ ...checkRenderReads(writeIndex, shadow.containers, renderIndex.reads),
1737
+ ...checkNestedClass(project, writeIndex, renderIndex.set),
1738
+ ...checkDeepWrite(project, writeIndex, renderIndex.set),
1739
+ ...checkMonitorDeepCollection(project),
1740
+ ...checkPlainObjectState(project, writeIndex, renderIndex.set),
1741
+ ...checkMonitorCycle(project),
1742
+ ];
1743
+ // Stable output order (file, line) helps replay diffs and the gate's report.
1744
+ issues.sort((a, b) => {
1745
+ const fa = normalizeKey(a.filePath);
1746
+ const fb = normalizeKey(b.filePath);
1747
+ if (fa !== fb) { return fa < fb ? -1 : 1; }
1748
+ return a.line - b.line;
1749
+ });
1750
+ return issues;
1751
+ }
1752
+
1753
+ /* ------------------------------------------------------------------ */
1754
+ /* HomeCheck checker */
1755
+ /* ------------------------------------------------------------------ */
1756
+
1757
+ const MESSAGES = {
1758
+ renderRead: {
1759
+ en: '[v2-render-read-unobserved] the render path (%s) reaches `%s`, which has no @Trace. V2 only observes @Trace fields; the write does not re-render this path. Add @Trace to the field (or derive it with @Computed over @Trace fields).',
1760
+ cn: '[v2-render-read-unobserved] 渲染路径(%s)读到 `%s`,该字段没有 @Trace。V2 只观测 @Trace 字段,写入不会刷新这条路径。请给该字段加 @Trace,或改为基于 @Trace 字段的 @Computed 派生。',
1761
+ },
1762
+ shadow: {
1763
+ en: '[v2-render-shadow-state] `%s` is a @Trace shadow of the unobserved container `%s` (`%s`), and the render layer uses the shadow as a branch condition while the branch body reads the container. The condition only flips 0<->non-zero, so a second push (1->2) or replaceTop (depth unchanged) never rebuilds the branch. Make the container observable (@Trace on the stack / @Computed currentRoute), or select content from a value that actually changes.',
1764
+ cn: '[v2-render-shadow-state] `%s` 是未观测容器 `%s` 的 @Trace 影子信号(`%s`),渲染层用影子做分支条件、分支体却读容器。条件只会 0<->非 0 翻转,第二次 push(1->2)或 replaceTop(深度不变)都不会重建该分支。请让容器可观察(给栈加 @Trace / 用 @Computed 派生 currentRoute),或用真正会变的值选择内容。',
1765
+ },
1766
+ shadowSoft: {
1767
+ en: '[v2-render-shadow-state] `%s` is a @Trace shadow of the plain container `%s` (`%s`), and the branch body also reads the shadow. Push/pop changes the shadow, but a write that changes the container without changing the shadow (e.g. replaceTop / pop+push) still leaves the branch stale. Make the container observable, or verify every container write also changes the shadow.',
1768
+ cn: '[v2-render-shadow-state] `%s` 是未观测容器 `%s` 的 @Trace 影子信号(`%s`),而分支体也读了这个影子。push/pop 会改变影子,但「改了容器却没改影子」的写(如 replaceTop / pop+push)仍会让分支停在旧内容。请让容器可观察,或确认每个容器写都会同时改变影子。',
1769
+ },
1770
+ nestedClass: {
1771
+ en: '[v2-nested-class-unobserved] nested class `%s` is reached from `%s` (`%s`) and is written/read on the UI path, but it has no @ObservedV2. The observation chain stops at that layer; deeper writes never refresh the UI. Add @ObservedV2 to the class and @Trace to the fields the UI reads.',
1772
+ cn: '[v2-nested-class-unobserved] 嵌套类 `%s` 由 `%s`(`%s`)进入状态树并被 UI 读写,但它没有 @ObservedV2。观测链在该层断开,更深的写入不会刷新 UI。请给该类加 @ObservedV2,并给 UI 读取的字段加 @Trace。',
1773
+ },
1774
+ deepWrite: {
1775
+ en: '[v2-deep-write-unobserved] `%s` is written at a nested path (`%s`) under `%s`, but the field has no @Trace. @Param/@Provider/@Consumer observation is per-field; this write does not refresh. Add @Trace, or reassign the whole state object.',
1776
+ cn: '[v2-deep-write-unobserved] `%s` 在 `%s` 深层路径被写入(根 `%s`),但该字段没有 @Trace。@Param/@Provider/@Consumer 按字段观测,这次写入不会刷新。请加 @Trace,或整体重新赋值状态对象。',
1777
+ },
1778
+ monitorDeepCollection: {
1779
+ en: '[v2-monitor-deep-collection] @Monitor(\'%s\') watches the dot path ending in collection `%s` (`%s`), but the class mutates the collection element-by-element. Element-level mutators do not trigger a dot-path @Monitor; reassign the whole collection or watch the element field.',
1780
+ cn: '[v2-monitor-deep-collection] @Monitor(\'%s\') 监听的 dot 路径末段是集合 `%s`(`%s`),而类内对集合做元素级突变。元素级 mutator 不会触发 dot-path @Monitor;请整体重赋值集合,或改为监听元素字段。',
1781
+ },
1782
+ plainObjectState: {
1783
+ en: '[v2-plain-object-state] `%s` is typed as `%s` (`%s`, not a class) and is assigned a plain object, then written below the first level. Interfaces cannot carry @ObservedV2, so the raw object has no observation. Use an @ObservedV2 class + new, or UIUtils.makeObserved(...).',
1784
+ cn: '[v2-plain-object-state] `%s` 的类型是 `%s`(`%s`,不是 class),却用普通对象赋值后又做深层写入。接口无法承载 @ObservedV2,原始对象没有观测能力。请改用 @ObservedV2 class + new,或用 UIUtils.makeObserved(...) 包装。',
1785
+ },
1786
+ monitorCycle: {
1787
+ en: '[v2-monitor-cycle] `%s`: @Monitor(\'%s\') participates in a monitor loop (%s): its callback writes a field another @Monitor watches, which writes back. Give the link a single write direction and make the callback idempotent.',
1788
+ cn: '[v2-monitor-cycle] `%s` 上的 @Monitor(\'%s\') 参与了监听环(%s):回调写入另一个 @Monitor 监听的字段,后者又写回来。请只保留一个写入方向,并在回调里做幂等校验。',
1789
+ },
1790
+ };
1791
+
1792
+ function fill(template, values) {
1793
+ let out = String(template);
1794
+ for (const value of values || []) {
1795
+ out = out.replace('%s', String(value));
1796
+ }
1797
+ return out;
1798
+ }
1799
+
1800
+ function formatMessage(subCode, values) {
1801
+ const message = MESSAGES[subCode];
1802
+ if (!message) { return null; }
1803
+ return { en: fill(message.en, values), cn: fill(message.cn, values) };
1804
+ }
1805
+
1806
+ function isGeneratedFile(filePath) {
1807
+ const p = String(filePath || '').replace(/\\/g, '/');
1808
+ return /\/oh_modules\//.test(p) || /\/node_modules\//.test(p) ||
1809
+ /\/build\//.test(p) || /\.d\.ts$/i.test(p) ||
1810
+ /\/(ohosSdk|hmsSdk)\//.test(p);
1811
+ }
1812
+
1813
+ class ArkUIV2ObservationCheck extends GlobalChecker {
1814
+ constructor() {
1815
+ super();
1816
+ this.reported = new Set();
1817
+ }
1818
+
1819
+ reset() {
1820
+ super.reset();
1821
+ this.reported = new Set();
1822
+ }
1823
+
1824
+ checkScene(scene) {
1825
+ const files = safe(() => scene.getFiles(), []) || [];
1826
+ if (!Array.isArray(files) || files.length === 0) { return; }
1827
+ const scans = [];
1828
+ for (const arkFile of files) {
1829
+ const filePath = safe(() => arkFile.getFilePath(), '');
1830
+ if (!filePath || isGeneratedFile(filePath)) { continue; }
1831
+ let raw = '';
1832
+ try { raw = fs.readFileSync(filePath, 'utf8'); } catch (_err) { continue; }
1833
+ scans.push({ filePath, raw });
1834
+ }
1835
+ if (scans.length === 0) { return; }
1836
+ const issues = safe(() => analyzeV2Observation(scans), []);
1837
+ for (const found of issues) {
1838
+ const key = `${found.subCode}|${normalizeKey(found.filePath)}|${found.line}|${(found.values || []).join('§')}`;
1839
+ if (this.reported.has(key)) { continue; }
1840
+ this.reported.add(key);
1841
+ const message = formatMessage(found.subCode, found.values);
1842
+ if (!message) { continue; }
1843
+ this.addIssue({
1844
+ filePath: found.filePath,
1845
+ line: found.line,
1846
+ colStart: 0,
1847
+ colEnd: 0,
1848
+ severity: found.severity,
1849
+ message,
1850
+ });
1851
+ }
1852
+ }
1853
+ }
1854
+
1855
+ Rule({
1856
+ ruleId: RULE_ID,
1857
+ severity: AlertLevel.WARN,
1858
+ isGlobal: true,
1859
+ fileExtensions: ['.ets', '.ts'],
1860
+ })(ArkUIV2ObservationCheck);
1861
+
1862
+ module.exports = { ArkUIV2ObservationCheck, analyzeV2Observation, formatMessage };