@boyingliu01/xp-gate 0.36.1 → 0.37.1

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 (123) hide show
  1. package/adapters/cpp.sh +78 -10
  2. package/adapters/csharp.sh +58 -3
  3. package/adapters/gate-3.sh +15 -5
  4. package/adapters/gate-8.sh +131 -9
  5. package/adapters/typescript.sh +32 -8
  6. package/build-integrity/__tests__/import-resolver.test.ts +257 -0
  7. package/build-integrity/__tests__/quote-masker.test.ts +177 -0
  8. package/build-integrity/gate-10.ts +127 -9
  9. package/build-integrity/quote-masker.ts +266 -0
  10. package/gate-10.sh +66 -0
  11. package/gate-12-file-hygiene.sh +15 -7
  12. package/gate-13-compiler-strictness.sh +81 -1
  13. package/gate-3.sh +15 -5
  14. package/gate-6-layers.sh +375 -0
  15. package/gate-8.sh +131 -9
  16. package/hooks/gate-10.sh +66 -0
  17. package/hooks/gate-12-file-hygiene.sh +15 -7
  18. package/hooks/gate-13-compiler-strictness.sh +81 -1
  19. package/hooks/gate-3.sh +15 -5
  20. package/hooks/gate-6-layers.sh +375 -0
  21. package/hooks/gate-8.sh +131 -9
  22. package/hooks/gate-registry.sh +2 -2
  23. package/hooks/hook-module-resolution.sh +1 -1
  24. package/hooks/lib/assertion-quality.sh +8 -2
  25. package/hooks/lib/ccn-ratchet.sh +10 -0
  26. package/hooks/lib/layer-baseline.cjs +88 -0
  27. package/hooks/lib/typecheck.sh +28 -5
  28. package/hooks/pre-commit +376 -53
  29. package/hooks/pre-push +46 -13
  30. package/lib/__tests__/agent-runtime-journal.test.js +1 -1
  31. package/lib/__tests__/arch.test.js +9 -0
  32. package/lib/__tests__/audit-cli-contract.test.ts +1 -1
  33. package/lib/__tests__/check-alignment-reasons.test.mjs +11 -1
  34. package/lib/__tests__/check-all-skip-accounting.test.js +1 -1
  35. package/lib/__tests__/detect-deps-gate-identity.test.js +135 -0
  36. package/lib/__tests__/detect-deps.test.js +2 -1
  37. package/lib/__tests__/doctor-469-hook-env.test.js +7 -1
  38. package/lib/__tests__/doctor-arch-tools.test.js +169 -0
  39. package/lib/__tests__/doctor-delphi.test.js +1 -1
  40. package/lib/__tests__/doctor-drift-round2.test.js +4 -1
  41. package/lib/__tests__/doctor-executed-surface.test.js +45 -24
  42. package/lib/__tests__/doctor-module-drift.test.js +13 -7
  43. package/lib/__tests__/doctor-module-resolution-parity.test.js +74 -2
  44. package/lib/__tests__/doctor-tui-skill-freshness.test.js +21 -6
  45. package/lib/__tests__/doctor.test.js +17 -0
  46. package/lib/__tests__/gate-runner-tsx-invocation.test.js +149 -0
  47. package/lib/__tests__/gate-runner.test.js +23 -7
  48. package/lib/__tests__/init-gitignore.test.js +204 -0
  49. package/lib/__tests__/init.test.js +24 -3
  50. package/lib/__tests__/language-tools-build-file-install.test.js +82 -0
  51. package/lib/__tests__/language-tools-detect.test.js +61 -0
  52. package/lib/__tests__/mirror-sync.test.js +2 -0
  53. package/lib/__tests__/phase-transition.test.js +19 -1
  54. package/lib/__tests__/sprint-status-rework.test.js +32 -12
  55. package/lib/__tests__/test-alignment-range-guard.test.ts +82 -0
  56. package/lib/__tests__/test-alignment.test.ts +13 -3
  57. package/lib/__tests__/update-skill.test.js +2 -2
  58. package/lib/detect-deps.js +7 -1
  59. package/lib/doctor.js +81 -17
  60. package/lib/gate-runner.js +101 -7
  61. package/lib/hook-module-resolution.js +18 -6
  62. package/lib/init.js +136 -1
  63. package/lib/language-tools.js +217 -1
  64. package/lib/layer-baseline.cjs +88 -0
  65. package/lib/mattpocock-license-verdict.json +1 -1
  66. package/lib/principles.js +21 -6
  67. package/lib/test-alignment.ts +452 -55
  68. package/mock-policy/AGENTS.md +1 -1
  69. package/mutation/AGENTS.md +1 -1
  70. package/package.json +2 -1
  71. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  72. package/plugins/claude-code/skills/delphi-review/.delphi-config.json.example +34 -24
  73. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  74. package/plugins/claude-code/skills/delphi-review/INSTALL.md +29 -1
  75. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  76. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  77. package/plugins/dsh/package.json +1 -1
  78. package/plugins/dsh/skills/delphi-review/.delphi-config.json.example +34 -24
  79. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  80. package/plugins/dsh/skills/delphi-review/INSTALL.md +29 -1
  81. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  82. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  83. package/plugins/dsh/src/client.test.ts +1 -1
  84. package/plugins/dsh/src/command.test.ts +1 -1
  85. package/plugins/dsh/src/contract.test.ts +1 -1
  86. package/plugins/dsh/src/credentials.test.ts +1 -1
  87. package/plugins/opencode/package.json +1 -1
  88. package/plugins/opencode/skills/delphi-review/.delphi-config.json.example +34 -24
  89. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  90. package/plugins/opencode/skills/delphi-review/INSTALL.md +29 -1
  91. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  92. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  93. package/plugins/qoder/plugin.json +1 -1
  94. package/plugins/qoder/skills/delphi-review/.delphi-config.json.example +34 -24
  95. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  96. package/plugins/qoder/skills/delphi-review/INSTALL.md +29 -1
  97. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  98. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  99. package/principles/AGENTS.md +1 -1
  100. package/principles/__tests__/config-arch-group.test.ts +106 -0
  101. package/principles/__tests__/config-enforcement.test.ts +1 -1
  102. package/principles/adapters/control-nesting.ts +572 -0
  103. package/principles/adapters/csharp.ts +73 -42
  104. package/principles/adapters/java.ts +9 -5
  105. package/principles/adapters/typescript.ts +138 -176
  106. package/principles/config.ts +37 -2
  107. package/principles/index.ts +57 -4
  108. package/principles/reporter.ts +99 -65
  109. package/principles/rules/arch/__tests__/dependency.test.ts +180 -0
  110. package/principles/rules/arch/__tests__/naming.test.ts +133 -0
  111. package/principles/rules/arch/__tests__/shared.test.ts +113 -0
  112. package/principles/rules/arch/dependency.ts +264 -0
  113. package/principles/rules/arch/naming.ts +188 -0
  114. package/principles/rules/arch/shared.ts +169 -0
  115. package/principles/rules/exports.ts +26 -0
  116. package/principles/rules/index.ts +11 -18
  117. package/scripts/__tests__/sync-package-content.test.js +23 -1
  118. package/scripts/sync-package-content.js +8 -2
  119. package/skills/delphi-review/.delphi-config.json.example +34 -24
  120. package/skills/delphi-review/AGENTS.md +1 -1
  121. package/skills/delphi-review/INSTALL.md +29 -1
  122. package/skills/sprint-flow/AGENTS.md +1 -1
  123. package/skills/test-specification-alignment/AGENTS.md +1 -1
@@ -0,0 +1,572 @@
1
+ /**
2
+ * Control-structure nesting measurement for TypeScript (#749).
3
+ *
4
+ * `clean-code.deep-nesting` asks how deeply a reader must nest to follow a
5
+ * function. Counting braces answers a different question: a config literal such
6
+ * as `{ db: { pool: { retry: { max: 3 } } } }` nests five braces but zero
7
+ * control structures, while `if > try > for > if` nests four. The former
8
+ * `maxNesting` scored both 5, so the rule could not tell a configuration object
9
+ * from logic.
10
+ *
11
+ * Semantics follow lizard's `-ENS` (`cognitive_brace.py`): a level is pushed by
12
+ * the structure that owns a body, `case`/`default` labels are not structures,
13
+ * and a nested function's body belongs to that function's own score.
14
+ *
15
+ * Extracted from `adapters/typescript.ts` to keep that file under the
16
+ * `large-file` budget.
17
+ */
18
+
19
+ /** The lexical states the scan tracks while counting control structures. */
20
+ interface NestingScanState {
21
+ inSingle: boolean;
22
+ inDouble: boolean;
23
+ inTemplate: boolean;
24
+ inLineComment: boolean;
25
+ inBlockComment: boolean;
26
+ }
27
+
28
+ /**
29
+ * Control-structure keywords whose body adds one nesting level.
30
+ *
31
+ * `else` is included because `else if` opens another conditional level: a reader
32
+ * tracks it as nesting, and `-ENS` counts it the same way. `case`/`default` are
33
+ * deliberately absent -- they label arms of a switch, not new levels.
34
+ */
35
+ const NESTING_KEYWORDS = new Set(['if', 'for', 'while', 'switch', 'catch', 'do', 'try', 'else', 'finally']);
36
+
37
+ /**
38
+ * True when the string/template/comment contents still contain unbalanced
39
+ * braces -- evidence that `maskLiterals` was skipped. A masked body cannot have
40
+ * a `{` or `}` inside a literal, so any imbalance is a masking gap.
41
+ *
42
+ * Braces are checked rather than parens because they are what the scanner's
43
+ * block pairing depends on. A paren check would additionally fire on
44
+ * `maskLiterals`' own gaps (it misses regex literals inside array literals, whose
45
+ * escaped `\(` reads as an open paren), which is a separate defect: widening the
46
+ * assertion here would turn that gap into a crash on valid code.
47
+ */
48
+ function hasUnbalancedBraces(body: string): boolean {
49
+ let depth = 0;
50
+ for (let i = 0; i < body.length; i++) {
51
+ if (body[i] === '{') depth++;
52
+ else if (body[i] === '}') {
53
+ depth--;
54
+ if (depth < 0) return true;
55
+ }
56
+ }
57
+ return depth !== 0;
58
+ }
59
+
60
+ /**
61
+ * Max control-structure nesting in a function body (0 = flat).
62
+ *
63
+ * The brace pairing below (`skipBalancedBrace`, `skipBalancedParen`) counts raw
64
+ * characters, so a `}` or `)` inside a string literal unbalances it. Callers
65
+ * MUST pass a source whose string/template/comment contents are already blanked
66
+ * (`maskLiterals`). The keyword state machine does skip comments and literals on
67
+ * its own, but that does not rescue the brace pairing -- masking is required,
68
+ * not optional.
69
+ *
70
+ * Unbalanced braces are rejected rather than scored: `skipBalancedBrace` returns
71
+ * the end of input when it never finds the close, so an unmasked body would
72
+ * silently swallow every following control structure and report an artificially
73
+ * low nesting score. A wrong number that looks like a clean result is the worst
74
+ * possible outcome for a quality gate, so this fails loudly instead.
75
+ *
76
+ * @param body The function body from `maskLiterals`.
77
+ * @returns The deepest control-structure nesting observed.
78
+ * @throws RangeError when `body` still contains unbalanced braces (unmasked).
79
+ */
80
+ export function maxControlNesting(body: string): number {
81
+ if (hasUnbalancedBraces(body)) {
82
+ throw new RangeError(
83
+ 'maxControlNesting requires masked input: unbalanced braces, so a literal '
84
+ + 'was not blanked. Pass maskLiterals(body) instead of raw source.',
85
+ );
86
+ }
87
+ return nestingOfRange(body, 0, body.length, 0);
88
+ }
89
+
90
+ /**
91
+ * Max nesting found while scanning `body[from, to)`, where `depth` is the number
92
+ * of enclosing control structures already open.
93
+ */
94
+ function nestingOfRange(body: string, from: number, to: number, depth: number): number {
95
+ let max = depth;
96
+ const setMax = (value: number): void => { if (value > max) max = value; };
97
+ const state: NestingScanState = {
98
+ inSingle: false,
99
+ inDouble: false,
100
+ inTemplate: false,
101
+ inLineComment: false,
102
+ inBlockComment: false,
103
+ };
104
+
105
+ for (let i = from; i < to;) {
106
+ const consumed = advanceNestingState(body, i, state);
107
+ if (consumed === PAIR_CONSUMED) {
108
+ // The pair (escape, comment close, comment open) is consumed whole. A
109
+ // comment opener must not also be read as a brace-less character below.
110
+ i += 2;
111
+ continue;
112
+ }
113
+ if (!isStructuralAt(state)) { i += 1; continue; }
114
+ i = consumeStructure(body, i, to, depth, setMax);
115
+ }
116
+ return max;
117
+ }
118
+
119
+ /**
120
+ * Consume one structural position during a nesting scan.
121
+ *
122
+ * Three things can start here: a control structure (whose body is scanned one
123
+ * level deeper), a nested function (whose body belongs to that function's own
124
+ * score), or an ordinary token. Each returns where the scan resumes.
125
+ */
126
+ function consumeStructure(
127
+ body: string, i: number, to: number, depth: number, setMax: (v: number) => void,
128
+ ): number {
129
+ // Anonymous arrow with a parenthesized parameter list: `items.map((x) => {`.
130
+ // The scan reaches `(` before any word, so this has to be checked here rather
131
+ // than in isNestedFunctionIntro. Without it the parenthesized form is charged
132
+ // to the enclosing function while `x => {` is not -- the same construct scored
133
+ // two different ways (#749 walkthrough).
134
+ if (body[i] === '(') {
135
+ const close = skipBalancedParen(body, i);
136
+ // A return-type annotation may sit between the parameter list and `=>`
137
+ // (`items.map((x): { ok: boolean } => { ... })`). Skip past it so the arrow
138
+ // is still recognized and its body is not charged to the enclosing function.
139
+ const afterParams = skipArrowReturnType(body, close, to);
140
+ if (body.startsWith('=>', afterParams)) {
141
+ const brace = findFunctionBodyBrace(body, afterParams, to);
142
+ return brace < 0 ? afterParams : skipBalancedBrace(body, brace);
143
+ }
144
+ }
145
+ const word = readWord(body, i);
146
+ if (!word) return i + 1;
147
+ if (NESTING_KEYWORDS.has(word.word) && !isMemberAccess(body, i) && !isKeyOrLabel(body, word.end)) {
148
+ // A control structure owns a nested region: count whatever nests inside it
149
+ // one level deeper, then resume past that region so its braces cannot be
150
+ // mistaken for the enclosing level's.
151
+ const scope = locateControlBody(body, word.end, to);
152
+ setMax(nestingOfRange(body, scope.bodyStart, scope.bodyEnd, depth + 1));
153
+ return scope.bodyEnd;
154
+ }
155
+ if (isNestedFunctionIntro(body, i, word.end)) {
156
+ // A nested function -- named or anonymous -- owns the structures in its own
157
+ // body: the adapter already reports it as its own function, scored there.
158
+ // Skipping it here keeps this function's score from being charged for
159
+ // nesting a reader never sees at this level, and matches lizard's `-ENS`,
160
+ // which attributes a callback's nesting to the callback.
161
+ const brace = findFunctionBodyBrace(body, word.end, to);
162
+ // Expression-bodied (`const f = () => 1;`): no body to skip, so drop only
163
+ // the intro. Skipping a range here would swallow the rest of the function.
164
+ if (brace < 0) return word.end;
165
+ return skipBalancedBrace(body, brace);
166
+ }
167
+ return word.end;
168
+ }
169
+
170
+ /**
171
+ * Locate the payload of a control body starting at `from`.
172
+ *
173
+ * `from` is the position just past the keyword (`consumeStructure` already
174
+ * consumed it), so for `else if (...) {` this starts at the `if` word rather
175
+ * than at `(`. The condition scan below is therefore skipped and the brace-less
176
+ * branch would mis-time the body -- except that `consumeStructure` recurses into
177
+ * the `if` keyword itself and reaches this function again from its own `)`.
178
+ * The body returned here is only the fallback for a structure with no condition.
179
+ *
180
+ * @returns the half-open range to scan at the deeper level.
181
+ */
182
+ function locateControlBody(body: string, from: number, to: number): { bodyStart: number; bodyEnd: number } {
183
+ let i = skipSpaces(body, from, to);
184
+ // `for await (...)` puts the `await` modifier between the keyword and the
185
+ // condition. Without skipping it the loop body looked brace-less and was cut
186
+ // at the newline, losing a level.
187
+ if (body.startsWith('await', i) && !/[\w$]/.test(body[i + 5] ?? '')) {
188
+ i = skipSpaces(body, i + 5, to);
189
+ }
190
+ if (body[i] === '(') {
191
+ let parens = 0;
192
+ for (; i < to; i++) {
193
+ if (body[i] === '(') parens++;
194
+ else if (body[i] === ')') {
195
+ parens--;
196
+ if (parens === 0) { i++; break; }
197
+ }
198
+ }
199
+ i = skipSpaces(body, i, to);
200
+ }
201
+ if (body[i] === '{') {
202
+ return { bodyStart: i + 1, bodyEnd: skipBalancedBrace(body, i) - 1 };
203
+ }
204
+ // Brace-less body. When the body is itself a control structure, the region to
205
+ // scan starts at that structure's keyword and ends where its own body ends --
206
+ // each level then adds its own +1 as the scan descends, so `if (a)\n if (b)\n
207
+ // if (c) { }` nests three deep. Returning the innermost range directly would
208
+ // skip the intermediate levels. A trailing `else` belongs to that inner `if`
209
+ // (`if (a) if (b) { } else { }`), so it is included or the `else` body would be
210
+ // rescanned at the outer depth.
211
+ const head = readWord(body, i);
212
+ if (head && NESTING_KEYWORDS.has(head.word) && !isMemberAccess(body, i) && !isKeyOrLabel(body, head.end)) {
213
+ const inner = locateControlBody(body, head.end, to);
214
+ // `inner.bodyEnd` is inclusive of the closing `}`, so step past it before
215
+ // looking for a trailing `else`/`catch`/`finally`.
216
+ let afterInner = inner.bodyEnd;
217
+ if (body[afterInner] === '}') afterInner++;
218
+ afterInner = skipSpaces(body, afterInner, to);
219
+ const tail = readWord(body, afterInner);
220
+ if (tail && (tail.word === 'else' || tail.word === 'catch' || tail.word === 'finally')) {
221
+ return { bodyStart: i, bodyEnd: locateControlBody(body, tail.end, to).bodyEnd };
222
+ }
223
+ return { bodyStart: i, bodyEnd: inner.bodyEnd };
224
+ }
225
+ // Otherwise it ends at the statement end, which for JavaScript is a newline as
226
+ // much as a `;`. Stopping only at `;` would swallow every following statement
227
+ // and score sequential guard clauses as nesting.
228
+ let end = i;
229
+ while (end < to && body[end] !== ';' && body[end] !== '\n') end++;
230
+ if (end < to && body[end] === ';') end++;
231
+ return { bodyStart: i, bodyEnd: end };
232
+ }
233
+
234
+ /**
235
+ * True when the parameter list starting at `open` is followed by a method body
236
+ * or return-type annotation -- i.e. method shorthand rather than a call.
237
+ */
238
+ function isMethodSignature(body: string, open: number): boolean {
239
+ const close = skipSpaces(body, skipBalancedParen(body, open), body.length);
240
+ return body[close] === '{' || body[close] === ':';
241
+ }
242
+
243
+ /** Index just past the balanced `<...>` at `open`, or `open` when unbalanced. */
244
+ function skipBalancedAngle(body: string, open: number): number {
245
+ let depth = 0;
246
+ for (let i = open; i < body.length; i++) {
247
+ if (body[i] === '<') depth++;
248
+ else if (body[i] === '>') {
249
+ depth--;
250
+ if (depth === 0) return i + 1;
251
+ }
252
+ }
253
+ return open;
254
+ }
255
+
256
+ /**
257
+ * True when the word at `wordStart` declares a nested function
258
+ * (`function name(...)`, `const name = async (...) =>`, `= function (...)`).
259
+ *
260
+ * Named functions are scored on their own; the enclosing function is not charged
261
+ * for structures a reader sees inside that separate definition.
262
+ */
263
+ function isNestedFunctionIntro(body: string, wordStart: number, wordEnd: number): boolean {
264
+ const current = body.slice(wordStart, wordEnd);
265
+ if (current === 'function') return true;
266
+ const afterWord = skipSpaces(body, wordEnd, body.length);
267
+ // Unparenthesized single-parameter arrow: `items.map(x => { ... })`,
268
+ // `async x => { ... }`. Without this the callback's nesting is charged to the
269
+ // enclosing function, while the parenthesized form is skipped correctly -- the
270
+ // same construct scored two different ways.
271
+ if (body.startsWith('=>', afterWord)) return true;
272
+ // Method shorthand: `{ m() { } }`, `m(): void { }`, `m<T>() { }`. lizard -ENS
273
+ // reports the method as its own function and the enclosing body as 0.
274
+ if (body[afterWord] === '(' && isMethodSignature(body, afterWord)) return true;
275
+ if (body[afterWord] === '<') {
276
+ const afterGeneric = skipSpaces(body, skipBalancedAngle(body, afterWord), body.length);
277
+ if (body[afterGeneric] === '(' && isMethodSignature(body, afterGeneric)) return true;
278
+ }
279
+ return isAssignedFunctionIntro(body, current, wordEnd);
280
+ }
281
+
282
+ /**
283
+ * True for `const name = (...) => {` / `let name = function (...) {` /
284
+ * `x = async () => {`, where the value assigned at `wordEnd` is a function.
285
+ */
286
+ function isAssignedFunctionIntro(body: string, current: string, wordEnd: number): boolean {
287
+ let k = wordEnd;
288
+ if (current === 'const' || current === 'let' || current === 'var') {
289
+ const name = readWord(body, skipSpaces(body, k, body.length));
290
+ if (!name) return false;
291
+ k = name.end;
292
+ } else if (!/^[A-Za-z_$][\w$]*$/.test(current)) {
293
+ return false;
294
+ }
295
+ k = skipSpaces(body, k, body.length);
296
+ if (body[k] !== '=') return false;
297
+ k = skipSpaces(body, k + 1, body.length);
298
+ // `const name = async (...) => {` -- the async modifier precedes the params.
299
+ if (body.startsWith('async', k) && !/[\w$]/.test(body[k + 5] ?? '')) {
300
+ k = skipSpaces(body, k + 5, body.length);
301
+ }
302
+ if (body.startsWith('function', k)) return true;
303
+ if (body[k] !== '(') return false;
304
+ const close = skipBalancedParen(body, k);
305
+ return body.startsWith('=>', skipArrowReturnType(body, close, body.length));
306
+ }
307
+
308
+ /**
309
+ * Locate the `{` that opens the body of a nested function whose intro ends at
310
+ * `from`.
311
+ *
312
+ * A destructured or defaulted parameter carries braces of its own
313
+ * (`const h = ({id}) => {`, `function f(a = {}) {`), so the parameter list is
314
+ * skipped first -- otherwise the parameter's brace is mistaken for the body and
315
+ * the real body is charged to the enclosing function.
316
+ *
317
+ * @returns the index of the body's `{`, or `-1` when the body is an expression
318
+ * with no braces (`const f = () => 1;`). The two cases must be distinguished:
319
+ * a caller that treated `-1` as `from` would hand a non-brace position to
320
+ * `skipBalancedBrace`, which then scans to the end of the enclosing function
321
+ * and silently drops every control structure after the arrow.
322
+ */
323
+ function findFunctionBodyBrace(body: string, from: number, to: number): number {
324
+ // Walk to the parameters (if any) and step over the whole list, including
325
+ // nested braces inside it.
326
+ let start = from;
327
+ for (; start < to; start++) {
328
+ if (body[start] === '(' || body[start] === '{' || body[start] === ';') break;
329
+ }
330
+ let i = start;
331
+ if (body[i] === '(') i = skipSpaces(body, skipBalancedParen(body, i), to);
332
+ // A return-type annotation sits between the parameter list and the body
333
+ // (`function inner(): { a: number } { ... }`), and braces inside it are not
334
+ // the body. When an annotation is present the body brace is located directly.
335
+ if (body[skipSpaces(body, i, to)] === ':') {
336
+ return findBraceAfterReturnType(body, i, to);
337
+ }
338
+ for (; i < to; i++) {
339
+ if (body[i] === '{') return i;
340
+ // No braced body before the statement ends: an expression-bodied arrow or a
341
+ // `function` whose `{` never appears. Report -1 so the caller resumes the
342
+ // scan instead of skipping a bogus range.
343
+ if (body[i] === ';' || body[i] === '}') return -1;
344
+ }
345
+ return -1;
346
+ }
347
+
348
+ /**
349
+ * Count the braces opened between `open` and the matching `}`, returning the
350
+ * index just past the close. `open` must point at a `{`.
351
+ *
352
+ * Braces inside strings, templates and comments are data by then: the caller
353
+ * passes a source that `maskLiterals` has already blanked.
354
+ */
355
+ function skipBalancedBrace(body: string, open: number): number {
356
+ let depth = 0;
357
+ for (let i = open; i < body.length; i++) {
358
+ if (body[i] === '{') depth++;
359
+ else if (body[i] === '}') {
360
+ depth--;
361
+ if (depth === 0) return i + 1;
362
+ }
363
+ }
364
+ return body.length;
365
+ }
366
+
367
+ /**
368
+ * Index just past an arrow's return-type annotation, when one is present.
369
+ *
370
+ * `(x): number =>` and `(x): { ok: boolean } =>` both put a type between the
371
+ * parameter list and `=>`. Skips a `:`-introduced type (walking balanced `{}`
372
+ * and `<>` inside it) so the arrow is still recognized.
373
+ */
374
+ function skipArrowReturnType(body: string, from: number, to: number): number {
375
+ const start = skipSpaces(body, from, to);
376
+ if (body[start] !== ':') return start;
377
+ // An arrow's return type may be an object literal, so inner braces are part of
378
+ // the type.
379
+ return scanTypeTo(body, start + 1, to);
380
+ }
381
+
382
+ /**
383
+ * Index of the `{` that opens a function/method body, given a position just
384
+ * after the parameter list.
385
+ *
386
+ * The return-type annotation may nest braces arbitrarily --
387
+ * `m(): Promise<{ ok: boolean }>`, `m(): { a: number } | null`, `m(): void`.
388
+ * So every balanced `{...}` that is part of the type is skipped, and the first
389
+ * brace that is followed by anything other than a continuation of the type is
390
+ * taken as the body. Walking the type token by token is what tells the two
391
+ * apart: a body brace is preceded by a complete type and is not inside `<>`.
392
+ *
393
+ * @returns the index of the body's `{`, or -1 when none is found before the
394
+ * statement ends.
395
+ */
396
+ function findBraceAfterReturnType(body: string, from: number, to: number): number {
397
+ let i = skipSpaces(body, from, to);
398
+ if (body[i] !== ':') return i;
399
+ i = skipSpaces(body, i + 1, to);
400
+ let angles = 0;
401
+ for (; i < to; i++) {
402
+ const c = body[i];
403
+ if (c === ';' || c === '\n') return -1;
404
+ if (c === '<') { angles++; continue; }
405
+ if (c === '>' && angles > 0) { angles--; continue; }
406
+ if (c !== '{') continue;
407
+ const afterBrace = skipBalancedBrace(body, i);
408
+ // Inside `<>` the braces are type arguments (`Promise<{ok:boolean}>`).
409
+ if (angles > 0) { i = afterBrace - 1; continue; }
410
+ const rest = skipSpaces(body, afterBrace, to);
411
+ if (rest >= to) return i;
412
+ // A `|`/`&`/`[` continues the type; another `{` means this brace was an
413
+ // object type and the real body follows (`m(): {a:number} { ... }`).
414
+ if ('|&'.includes(body[rest]) || body[rest] === '[') { i = afterBrace - 1; continue; }
415
+ return body[rest] === '{' ? rest : i;
416
+ }
417
+ return -1;
418
+ }
419
+
420
+ /** One classified step of an arrow return-type scan. */
421
+ type TypeScanStep = 'stop' | 'open-brace' | 'close-brace' | 'open-angle' | 'close-angle' | 'skip';
422
+
423
+ /**
424
+ * Classify one character of an arrow's return type. An arrow's return type may
425
+ * itself be an object literal (`(x): { ok: boolean } =>`), so a `{` opens a type
426
+ * brace.
427
+ */
428
+ function classifyTypeChar(body: string, i: number, braces: number, angles: number): TypeScanStep {
429
+ const c = body[i];
430
+ if (c === '{') return 'open-brace';
431
+ // A `}` at depth 0 closes the enclosing block, so the type cannot extend past it.
432
+ if (c === '}') return braces === 0 ? 'stop' : 'close-brace';
433
+ if (c === '<') return 'open-angle';
434
+ if (c === '>' && angles > 0) return 'close-angle';
435
+ const flat = braces === 0 && angles === 0;
436
+ if (flat && c === '=' && body[i + 1] === '>') return 'stop';
437
+ if (flat && (c === ';' || c === '\n')) return 'stop';
438
+ return 'skip';
439
+ }
440
+
441
+ /** Depth adjustment for one step of a type scan. */
442
+ function typeDepthDelta(step: TypeScanStep): { braces: number; angles: number } {
443
+ if (step === 'open-brace') return { braces: 1, angles: 0 };
444
+ if (step === 'close-brace') return { braces: -1, angles: 0 };
445
+ if (step === 'open-angle') return { braces: 0, angles: 1 };
446
+ if (step === 'close-angle') return { braces: 0, angles: -1 };
447
+ return { braces: 0, angles: 0 };
448
+ }
449
+
450
+ /** Scan a type annotation, returning the index of the `=>` (or terminator). */
451
+ function scanTypeTo(body: string, from: number, to: number): number {
452
+ let braces = 0;
453
+ let angles = 0;
454
+ for (let i = from; i < to; i++) {
455
+ const step = classifyTypeChar(body, i, braces, angles);
456
+ if (step === 'stop') return i;
457
+ const delta = typeDepthDelta(step);
458
+ braces += delta.braces;
459
+ angles += delta.angles;
460
+ }
461
+ return to;
462
+ }
463
+
464
+ /** Index just past the `)` matching the `(` at `open`. */
465
+ function skipBalancedParen(body: string, open: number): number {
466
+ let depth = 0;
467
+ for (let i = open; i < body.length; i++) {
468
+ if (body[i] === '(') depth++;
469
+ else if (body[i] === ')') {
470
+ depth--;
471
+ if (depth === 0) return i + 1;
472
+ }
473
+ }
474
+ return body.length;
475
+ }
476
+
477
+ /** First index at or after `from` that is not whitespace, clamped to `to`. */
478
+ function skipSpaces(body: string, from: number, to: number): number {
479
+ let i = from;
480
+ while (i < to && /\s/.test(body[i])) i++;
481
+ return i;
482
+ }
483
+
484
+ /** Read an identifier/keyword token starting at `i`; null when not an identifier. */
485
+ function readWord(body: string, i: number): { word: string; end: number } | null {
486
+ const c = body[i];
487
+ if (!/[A-Za-z_$]/.test(c)) return null;
488
+ let j = i + 1;
489
+ while (j < body.length && /[\w$]/.test(body[j])) j++;
490
+ return { word: body.slice(i, j), end: j };
491
+ }
492
+
493
+ /** True when the word at `i` is preceded by `.` (member access, not a keyword). */
494
+ function isMemberAccess(body: string, i: number): boolean {
495
+ let k = i - 1;
496
+ while (k >= 0 && /\s/.test(body[k])) k--;
497
+ return k >= 0 && body[k] === '.';
498
+ }
499
+
500
+ /**
501
+ * True when the word spanning `[start, end)` is an object key or a labeled
502
+ * statement rather than a control keyword: `{ for: 1 }`, `{ try: t }`, `o = { if: 1 }`.
503
+ *
504
+ * A control keyword is followed by `(` or `{` (`else` by `{` or `if`), never by
505
+ * `:`. The colon has to be checked immediately after the word so a real ternary
506
+ * or a typed arrow body is not caught, and the word must end a token so `forEach`
507
+ * is unaffected.
508
+ */
509
+ function isKeyOrLabel(body: string, end: number): boolean {
510
+ const next = skipSpaces(body, end, body.length);
511
+ return body[next] === ':';
512
+ }
513
+
514
+ /**
515
+ * Characters consumed when `advanceNestingState` reads a two-character pair:
516
+ * an escaped backslash, a comment open, or a comment close.
517
+ *
518
+ * Named so the scan below cannot silently treat a future three-character
519
+ * consumption as one -- only this value is special-cased.
520
+ */
521
+ const PAIR_CONSUMED = 2;
522
+
523
+ /**
524
+ * Advance the quoting/commenting state machine by one character.
525
+ *
526
+ * Pure with respect to depth: it only updates `state` and reports how many
527
+ * characters were consumed, so the counting and the lexing can be reasoned about
528
+ * separately (#602).
529
+ *
530
+ * @returns `PAIR_CONSUMED` when a two-character pair was consumed whole, else 1.
531
+ */
532
+ function advanceNestingState(body: string, i: number, state: NestingScanState): number {
533
+ const c = body[i];
534
+ const next = body[i + 1];
535
+
536
+ if (state.inLineComment) {
537
+ if (c === '\n') state.inLineComment = false;
538
+ return 1;
539
+ }
540
+ if (state.inBlockComment) {
541
+ if (c === '*' && next === '/') { state.inBlockComment = false; return 2; }
542
+ return 1;
543
+ }
544
+ if (state.inSingle) {
545
+ if (c === '\\') return 2;
546
+ if (c === "'") state.inSingle = false;
547
+ return 1;
548
+ }
549
+ if (state.inDouble) {
550
+ if (c === '\\') return 2;
551
+ if (c === '"') state.inDouble = false;
552
+ return 1;
553
+ }
554
+ if (state.inTemplate) {
555
+ if (c === '\\') return 2;
556
+ if (c === '`') state.inTemplate = false;
557
+ return 1;
558
+ }
559
+
560
+ if (c === '/' && next === '/') { state.inLineComment = true; return 2; }
561
+ if (c === '/' && next === '*') { state.inBlockComment = true; return 2; }
562
+ if (c === "'") state.inSingle = true;
563
+ else if (c === '"') state.inDouble = true;
564
+ else if (c === '`') state.inTemplate = true;
565
+ return 1;
566
+ }
567
+
568
+ /** True when the current state's character carries structure, not data. */
569
+ function isStructuralAt(state: NestingScanState): boolean {
570
+ return !state.inSingle && !state.inDouble && !state.inTemplate
571
+ && !state.inLineComment && !state.inBlockComment;
572
+ }