carrick 0.3.153 → 0.3.155

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/bin/carrick.mjs +26 -4
  2. package/dist/cli.d.ts +6 -0
  3. package/dist/cli.js +1 -0
  4. package/dist/cli.js.map +1 -1
  5. package/dist/contract.d.ts +37 -3
  6. package/dist/contract.js +8 -0
  7. package/dist/contract.js.map +1 -1
  8. package/dist/facts/diff.d.ts +27 -0
  9. package/dist/facts/diff.js +134 -0
  10. package/dist/facts/diff.js.map +1 -0
  11. package/dist/facts/enabled.d.ts +2 -0
  12. package/dist/facts/enabled.js +9 -0
  13. package/dist/facts/enabled.js.map +1 -0
  14. package/dist/facts/fetch.d.ts +48 -0
  15. package/dist/facts/fetch.js +235 -0
  16. package/dist/facts/fetch.js.map +1 -0
  17. package/dist/facts/files.d.ts +21 -0
  18. package/dist/facts/files.js +58 -0
  19. package/dist/facts/files.js.map +1 -0
  20. package/dist/facts/lines.d.ts +70 -0
  21. package/dist/facts/lines.js +335 -0
  22. package/dist/facts/lines.js.map +1 -0
  23. package/dist/facts/match.d.ts +91 -0
  24. package/dist/facts/match.js +1122 -0
  25. package/dist/facts/match.js.map +1 -0
  26. package/dist/facts/peers.d.ts +48 -0
  27. package/dist/facts/peers.js +143 -0
  28. package/dist/facts/peers.js.map +1 -0
  29. package/dist/facts/refresh-run.d.ts +2 -0
  30. package/dist/facts/refresh-run.js +18 -0
  31. package/dist/facts/refresh-run.js.map +1 -0
  32. package/dist/facts/rules/packages.d.ts +16 -0
  33. package/dist/facts/rules/packages.js +157 -0
  34. package/dist/facts/rules/packages.js.map +1 -0
  35. package/dist/facts/rules/same-name.d.ts +28 -0
  36. package/dist/facts/rules/same-name.js +131 -0
  37. package/dist/facts/rules/same-name.js.map +1 -0
  38. package/dist/facts/store.d.ts +119 -0
  39. package/dist/facts/store.js +341 -0
  40. package/dist/facts/store.js.map +1 -0
  41. package/dist/git-remote.d.ts +6 -0
  42. package/dist/git-remote.js +37 -0
  43. package/dist/git-remote.js.map +1 -0
  44. package/dist/hook/apply-patch.d.ts +23 -0
  45. package/dist/hook/apply-patch.js +92 -0
  46. package/dist/hook/apply-patch.js.map +1 -1
  47. package/dist/hook/bash-targets.d.ts +8 -0
  48. package/dist/hook/bash-targets.js +23 -11
  49. package/dist/hook/bash-targets.js.map +1 -1
  50. package/dist/hook/edit-flow.d.ts +29 -2
  51. package/dist/hook/edit-flow.js +80 -29
  52. package/dist/hook/edit-flow.js.map +1 -1
  53. package/dist/hook/late.d.ts +29 -0
  54. package/dist/hook/late.js +121 -26
  55. package/dist/hook/late.js.map +1 -1
  56. package/dist/hook/post-bash.js +45 -22
  57. package/dist/hook/post-bash.js.map +1 -1
  58. package/dist/hook/post-edit.d.ts +16 -1
  59. package/dist/hook/post-edit.js +177 -13
  60. package/dist/hook/post-edit.js.map +1 -1
  61. package/dist/hook/post-read.js +8 -12
  62. package/dist/hook/post-read.js.map +1 -1
  63. package/dist/hook/post-search.d.ts +2 -0
  64. package/dist/hook/post-search.js +25 -0
  65. package/dist/hook/post-search.js.map +1 -0
  66. package/dist/hook/probe.d.ts +18 -3
  67. package/dist/hook/probe.js +30 -6
  68. package/dist/hook/probe.js.map +1 -1
  69. package/dist/hook/rechecks.d.ts +66 -11
  70. package/dist/hook/rechecks.js +115 -29
  71. package/dist/hook/rechecks.js.map +1 -1
  72. package/dist/hook/refresh.d.ts +9 -0
  73. package/dist/hook/refresh.js +10 -0
  74. package/dist/hook/refresh.js.map +1 -1
  75. package/dist/hook/reuse.d.ts +16 -2
  76. package/dist/hook/reuse.js +49 -6
  77. package/dist/hook/reuse.js.map +1 -1
  78. package/dist/hook/session-key.d.ts +12 -0
  79. package/dist/hook/session-key.js +30 -0
  80. package/dist/hook/session-key.js.map +1 -0
  81. package/dist/hook/session-start.js +14 -7
  82. package/dist/hook/session-start.js.map +1 -1
  83. package/dist/hook/stop-wait.d.ts +2 -9
  84. package/dist/hook/stop-wait.js +96 -113
  85. package/dist/hook/stop-wait.js.map +1 -1
  86. package/dist/hook/stop.js +13 -8
  87. package/dist/hook/stop.js.map +1 -1
  88. package/dist/hook/subagent-stop.d.ts +2 -0
  89. package/dist/hook/subagent-stop.js +45 -0
  90. package/dist/hook/subagent-stop.js.map +1 -0
  91. package/dist/hook/timings.d.ts +72 -0
  92. package/dist/hook/timings.js +175 -0
  93. package/dist/hook/timings.js.map +1 -0
  94. package/dist/hook/user-prompt.js +17 -13
  95. package/dist/hook/user-prompt.js.map +1 -1
  96. package/dist/hook/worktree.d.ts +11 -0
  97. package/dist/hook/worktree.js +27 -1
  98. package/dist/hook/worktree.js.map +1 -1
  99. package/dist/init/repo-copies.d.ts +6 -0
  100. package/dist/init/repo-copies.js +7 -3
  101. package/dist/init/repo-copies.js.map +1 -1
  102. package/dist/init/repos.d.ts +2 -2
  103. package/dist/init/repos.js +1 -34
  104. package/dist/init/repos.js.map +1 -1
  105. package/dist/init/settings.js +25 -13
  106. package/dist/init/settings.js.map +1 -1
  107. package/dist/render.d.ts +8 -33
  108. package/dist/render.js +42 -120
  109. package/dist/render.js.map +1 -1
  110. package/package.json +6 -6
  111. package/plugin/.claude-plugin/plugin.json +1 -1
  112. package/plugin/hooks/hooks.json +44 -3
  113. package/scripts/install-scanned-deps.sh +25 -2
  114. package/sidecar/dist/src/capture/anchors.d.ts +12 -1
  115. package/sidecar/dist/src/capture/anchors.js +28 -47
  116. package/sidecar/dist/src/capture/api.d.ts +41 -1
  117. package/sidecar/dist/src/capture/augmentations.d.ts +2 -0
  118. package/sidecar/dist/src/capture/augmentations.js +1 -1
  119. package/sidecar/dist/src/capture/check-classify.d.ts +12 -1
  120. package/sidecar/dist/src/capture/check-classify.js +43 -0
  121. package/sidecar/dist/src/capture/check-deep.d.ts +44 -1
  122. package/sidecar/dist/src/capture/check-deep.js +161 -2
  123. package/sidecar/dist/src/capture/check.js +23 -2
  124. package/sidecar/dist/src/capture/checkout.d.ts +9 -3
  125. package/sidecar/dist/src/capture/checkout.js +12 -5
  126. package/sidecar/dist/src/capture/deep-walk.d.ts +25 -0
  127. package/sidecar/dist/src/capture/deep-walk.js +41 -0
  128. package/sidecar/dist/src/capture/deno-project.d.ts +22 -0
  129. package/sidecar/dist/src/capture/deno-project.js +48 -1
  130. package/sidecar/dist/src/capture/index.d.ts +3 -1
  131. package/sidecar/dist/src/capture/index.js +14 -4
  132. package/sidecar/dist/src/capture/machinery.d.ts +8 -53
  133. package/sidecar/dist/src/capture/machinery.js +10 -157
  134. package/sidecar/dist/src/capture/node-builder.d.ts +6 -0
  135. package/sidecar/dist/src/capture/self-check.d.ts +7 -0
  136. package/sidecar/dist/src/capture/self-check.js +44 -1
  137. package/sidecar/dist/src/capture/site-node.d.ts +166 -0
  138. package/sidecar/dist/src/capture/site-node.js +570 -0
  139. package/sidecar/dist/src/capture/tool-env.d.ts +12 -0
  140. package/sidecar/dist/src/capture/tool-env.js +26 -0
  141. package/sidecar/dist/src/default-library.d.ts +39 -0
  142. package/sidecar/dist/src/default-library.js +132 -0
  143. package/sidecar/dist/src/definition-resolver.js +2 -0
  144. package/sidecar/dist/src/index.js +1 -1
  145. package/sidecar/dist/src/library-claims.d.ts +2 -0
  146. package/sidecar/dist/src/library-claims.js +387 -37
  147. package/sidecar/dist/src/node-index.d.ts +2 -0
  148. package/sidecar/dist/src/node-index.js +5 -1
  149. package/sidecar/dist/src/position-rows.d.ts +78 -7
  150. package/sidecar/dist/src/position-rows.js +343 -18
  151. package/sidecar/dist/src/project-loader.d.ts +3 -3
  152. package/sidecar/dist/src/project-loader.js +18 -9
  153. package/sidecar/dist/src/retype.d.ts +13 -0
  154. package/sidecar/dist/src/retype.js +126 -0
  155. package/sidecar/dist/src/type-inferrer.d.ts +47 -145
  156. package/sidecar/dist/src/type-inferrer.js +102 -529
  157. package/sidecar/dist/src/types.d.ts +64 -2
  158. package/sidecar/dist/src/validators.d.ts +806 -142
  159. package/sidecar/dist/src/validators.js +12 -1
@@ -0,0 +1,1122 @@
1
+ // A light declaration scanner: which named things an edit touched, read from
2
+ // the file's current text with no compiler.
3
+ //
4
+ // The fact file keys a function by the name the naming rule gives it (the
5
+ // seam doc in carrick-cloud, `docs/internal/reference/edit-facts-wire.md`,
6
+ // "Naming rule for `name`"): `f` for a declared or const-bound function,
7
+ // `Class.method` for a class member, `obj.Key.key` for a function inside an
8
+ // object literal bound to a const, and the nearest named encloser for an
9
+ // anonymous one. This finds the same names from the text as it is now, so a
10
+ // function that moved on the agent's branch is still found, and a renamed one
11
+ // is not.
12
+ //
13
+ // One tokenizer pass (strings, templates, comments and regex literals are
14
+ // skipped), then a walk over matched brackets. Whenever the text does not
15
+ // read cleanly (an unbalanced bracket, an unterminated string), the scan says
16
+ // so and the caller prints nothing for the file.
17
+ const OPEN = { "(": ")", "[": "]", "{": "}" };
18
+ const CLOSE = new Set([")", "]", "}"]);
19
+ /** After these a `/` starts a regex literal, not a division. */
20
+ const REGEX_AFTER_PUNC = new Set([
21
+ "(", ",", "=", ":", "[", "!", "&", "|", "?", "{", "}", ";", "+", "-", "*", "%", "<", ">", "~", "^", "=>",
22
+ "==", "===", "!=", "!==", "&&", "||", "??", "+=", "-=", "*=", "/=", "<=", ">=", "...",
23
+ ]);
24
+ const REGEX_AFTER_WORD = new Set([
25
+ "return", "typeof", "case", "do", "else", "in", "of", "new", "delete", "void", "throw", "yield", "await", "instanceof",
26
+ ]);
27
+ const PUNCS = ["...", "===", "!==", "**=", "??=", "&&=", "||=", "=>", "==", "!=", "<=", ">=", "&&", "||", "??", "?.", "+=", "-=", "*=", "/=", "%=", "++", "--"];
28
+ /** Words before a declaration that belong to its span. */
29
+ const DECLARATION_PREFIXES = new Set(["export", "default", "async", "declare"]);
30
+ /** Words after `class` that start its heritage, not its name. */
31
+ const HERITAGE = new Set(["extends", "implements"]);
32
+ /** Words in a type after which a `{` opens an object type, not a body. */
33
+ const TYPE_OPERATORS = new Set(["is", "asserts", "keyof", "typeof", "extends", "infer", "readonly", "unique"]);
34
+ const CLASS_MODIFIERS = new Set([
35
+ "static", "async", "get", "set", "public", "private", "protected", "readonly", "override", "abstract", "declare", "accessor",
36
+ ]);
37
+ function isIdStart(ch) {
38
+ return /[A-Za-z_$#]/.test(ch) || ch.charCodeAt(0) > 127;
39
+ }
40
+ function isIdPart(ch) {
41
+ return /[A-Za-z0-9_$]/.test(ch) || ch.charCodeAt(0) > 127;
42
+ }
43
+ /** After these a `<` in a `.tsx` or `.jsx` file opens an element. */
44
+ const JSX_AFTER_PUNC = new Set(["(", ",", "=", ":", "?", "&&", "||", "??", "=>", "{", "[", ";", "!"]);
45
+ const JSX_AFTER_WORD = new Set(["return", "yield", "await", "default"]);
46
+ /** A `<` that opens type parameters in a `.tsx` file: `<T,>` or `<T extends X>`. */
47
+ const TYPE_PARAMS_IN_JSX = /^<\s*[A-Za-z_$][\w$]*\s*(?:,|extends\s+[^=\s])/;
48
+ /**
49
+ * The tokens of `text`, or null when a string, template, comment, regex or
50
+ * (with `jsx`) element does not end. An element is one opaque token; the
51
+ * code in its `{...}` containers is tokenized after it.
52
+ */
53
+ export function tokenize(text, jsx = false) {
54
+ try {
55
+ return lexAll(text, jsx);
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ }
61
+ function lexAll(text, jsx) {
62
+ const BAIL = new Error("unreadable");
63
+ const tokens = [];
64
+ let i = 0;
65
+ let line = 1;
66
+ const n = text.length;
67
+ const prevSignificant = () => tokens[tokens.length - 1];
68
+ // Skips a template literal starting at the backtick at `at`; returns the
69
+ // index after it and whether it had substitutions, or null if unterminated.
70
+ const skipTemplate = (at) => {
71
+ let k = at + 1;
72
+ let plain = true;
73
+ while (k < n) {
74
+ const ch = text[k];
75
+ if (ch === "\\") {
76
+ k += 2;
77
+ continue;
78
+ }
79
+ if (ch === "\n")
80
+ line += 1;
81
+ if (ch === "`")
82
+ return { end: k + 1, plain };
83
+ if (ch === "$" && text[k + 1] === "{") {
84
+ plain = false;
85
+ // The substitution is code: read it with the main lexer so a `/` in
86
+ // operand position starts a regex here exactly as at top level. A
87
+ // `{` token stands in as the previous token (operand position) and
88
+ // the tokens it reads are dropped.
89
+ const mark = tokens.length;
90
+ tokens.push({ kind: "punc", value: "{", start: k, end: k + 2, line });
91
+ i = k + 2;
92
+ lex(true);
93
+ tokens.length = mark;
94
+ if (text[i] !== "}")
95
+ return null;
96
+ k = i + 1;
97
+ continue;
98
+ }
99
+ k += 1;
100
+ }
101
+ return null;
102
+ };
103
+ // The index after the quoted string starting at `at`, or null if unterminated.
104
+ const skipString = (at) => {
105
+ const quote = text[at];
106
+ let k = at + 1;
107
+ while (k < n) {
108
+ const ch = text[k];
109
+ if (ch === "\\") {
110
+ k += 2;
111
+ continue;
112
+ }
113
+ if (ch === quote)
114
+ return k + 1;
115
+ if (ch === "\n")
116
+ return null;
117
+ k += 1;
118
+ }
119
+ return null;
120
+ };
121
+ // Whether a `<` at `i` opens an element: in expression position, before a
122
+ // tag name or `>`, and not a generic arrow's type parameters (`<T,>`,
123
+ // `<T extends X>`), which a component file must spell that way.
124
+ const jsxStarts = () => {
125
+ if (!jsx || !/[A-Za-z>]/.test(text[i + 1] ?? ""))
126
+ return false;
127
+ if (TYPE_PARAMS_IN_JSX.test(text.slice(i, i + 200)))
128
+ return false;
129
+ const prev = prevSignificant();
130
+ return (prev === undefined ||
131
+ (prev.kind === "punc" && JSX_AFTER_PUNC.has(prev.value)) ||
132
+ (prev.kind === "id" && JSX_AFTER_WORD.has(prev.value)));
133
+ };
134
+ // A tag's inside, from after `<` to after its `>`; true when it closed itself (`/>`).
135
+ const jsxTag = () => {
136
+ while (i < n) {
137
+ const c = text[i];
138
+ if (c === "\n") {
139
+ line += 1;
140
+ i += 1;
141
+ continue;
142
+ }
143
+ if (c === '"' || c === "'") {
144
+ const close = skipString(i);
145
+ if (close === null)
146
+ throw BAIL;
147
+ i = close;
148
+ continue;
149
+ }
150
+ if (c === "{") {
151
+ i += 1;
152
+ lex(true);
153
+ i += 1;
154
+ continue;
155
+ }
156
+ if (c === "/" && text[i + 1] === ">") {
157
+ i += 2;
158
+ return true;
159
+ }
160
+ if (c === ">") {
161
+ i += 1;
162
+ return false;
163
+ }
164
+ i += 1;
165
+ }
166
+ throw BAIL;
167
+ };
168
+ // One element from its `<` to after its closing tag.
169
+ const jsxElement = () => {
170
+ i += 1;
171
+ if (jsxTag())
172
+ return;
173
+ let depth = 1;
174
+ while (i < n) {
175
+ const c = text[i];
176
+ if (c === "\n") {
177
+ line += 1;
178
+ i += 1;
179
+ continue;
180
+ }
181
+ if (c === "{") {
182
+ i += 1;
183
+ lex(true);
184
+ i += 1;
185
+ continue;
186
+ }
187
+ if (c === "<") {
188
+ if (text[i + 1] === "/") {
189
+ const close = text.indexOf(">", i);
190
+ if (close < 0)
191
+ throw BAIL;
192
+ i = close + 1;
193
+ depth -= 1;
194
+ if (depth === 0)
195
+ return;
196
+ continue;
197
+ }
198
+ i += 1;
199
+ if (!jsxTag())
200
+ depth += 1;
201
+ continue;
202
+ }
203
+ i += 1;
204
+ }
205
+ throw BAIL;
206
+ };
207
+ // Tokens from `i` to the end, or (with `untilBrace`) to the `}` that closes
208
+ // the container it started in, leaving `i` on that `}`.
209
+ function lex(untilBrace) {
210
+ let depth = 0;
211
+ while (i < n) {
212
+ const ch = text[i];
213
+ if (ch === "\n") {
214
+ line += 1;
215
+ i += 1;
216
+ continue;
217
+ }
218
+ if (ch === "}" && untilBrace && depth === 0)
219
+ return;
220
+ if (ch === "{")
221
+ depth += 1;
222
+ else if (ch === "}")
223
+ depth -= 1;
224
+ if (ch === "<" && jsxStarts()) {
225
+ const token = { kind: "tpl", value: "", start: i, end: i, line };
226
+ tokens.push(token);
227
+ jsxElement();
228
+ token.end = i;
229
+ continue;
230
+ }
231
+ if (ch === " " || ch === "\t" || ch === "\r" || ch === "\f" || ch === "\v" || ch === " " || ch === "") {
232
+ i += 1;
233
+ continue;
234
+ }
235
+ if (ch === "/" && text[i + 1] === "/") {
236
+ while (i < n && text[i] !== "\n")
237
+ i += 1;
238
+ continue;
239
+ }
240
+ if (ch === "/" && text[i + 1] === "*") {
241
+ const close = text.indexOf("*/", i + 2);
242
+ if (close < 0)
243
+ throw BAIL;
244
+ for (let k = i; k < close; k += 1)
245
+ if (text[k] === "\n")
246
+ line += 1;
247
+ i = close + 2;
248
+ continue;
249
+ }
250
+ const startLine = line;
251
+ if (ch === "'" || ch === '"') {
252
+ const close = skipString(i);
253
+ if (close === null)
254
+ throw BAIL;
255
+ tokens.push({ kind: "str", value: unquote(text.slice(i + 1, close - 1)), start: i, end: close, line: startLine });
256
+ i = close;
257
+ continue;
258
+ }
259
+ if (ch === "`") {
260
+ const done = skipTemplate(i);
261
+ if (done === null)
262
+ throw BAIL;
263
+ tokens.push({
264
+ kind: done.plain ? "str" : "tpl",
265
+ value: done.plain ? unquote(text.slice(i + 1, done.end - 1)) : "",
266
+ start: i,
267
+ end: done.end,
268
+ line: startLine,
269
+ });
270
+ i = done.end;
271
+ continue;
272
+ }
273
+ if (ch === "/") {
274
+ const prev = prevSignificant();
275
+ const regex = prev === undefined ||
276
+ (prev.kind === "punc" && REGEX_AFTER_PUNC.has(prev.value)) ||
277
+ (prev.kind === "id" && REGEX_AFTER_WORD.has(prev.value));
278
+ if (regex) {
279
+ let k = i + 1;
280
+ let inClass = false;
281
+ while (k < n) {
282
+ const c = text[k];
283
+ if (c === "\n")
284
+ throw BAIL;
285
+ if (c === "\\") {
286
+ k += 2;
287
+ continue;
288
+ }
289
+ if (c === "[")
290
+ inClass = true;
291
+ else if (c === "]")
292
+ inClass = false;
293
+ else if (c === "/" && !inClass)
294
+ break;
295
+ k += 1;
296
+ }
297
+ if (k >= n)
298
+ throw BAIL;
299
+ k += 1;
300
+ while (k < n && /[A-Za-z]/.test(text[k]))
301
+ k += 1;
302
+ tokens.push({ kind: "regex", value: "", start: i, end: k, line: startLine });
303
+ i = k;
304
+ continue;
305
+ }
306
+ }
307
+ if (isIdStart(ch)) {
308
+ let k = i + 1;
309
+ while (k < n && isIdPart(text[k]))
310
+ k += 1;
311
+ tokens.push({ kind: "id", value: text.slice(i, k), start: i, end: k, line: startLine });
312
+ i = k;
313
+ continue;
314
+ }
315
+ if (/[0-9]/.test(ch) || (ch === "." && /[0-9]/.test(text[i + 1] ?? ""))) {
316
+ let k = i + 1;
317
+ while (k < n && /[0-9A-Za-z_.]/.test(text[k]))
318
+ k += 1;
319
+ tokens.push({ kind: "num", value: text.slice(i, k), start: i, end: k, line: startLine });
320
+ i = k;
321
+ continue;
322
+ }
323
+ const multi = PUNCS.find((p) => text.startsWith(p, i));
324
+ const value = multi ?? ch;
325
+ tokens.push({ kind: "punc", value, start: i, end: i + value.length, line: startLine });
326
+ i += value.length;
327
+ }
328
+ if (untilBrace)
329
+ throw BAIL;
330
+ }
331
+ lex(false);
332
+ return tokens;
333
+ }
334
+ function unquote(body) {
335
+ return body.replace(/\\(.)/g, "$1");
336
+ }
337
+ /** For every bracket token, the index of its partner; null when they do not balance. */
338
+ function matchBrackets(tokens) {
339
+ const match = new Map();
340
+ const stack = [];
341
+ for (const [index, token] of tokens.entries()) {
342
+ if (token.kind !== "punc")
343
+ continue;
344
+ if (OPEN[token.value])
345
+ stack.push(index);
346
+ else if (CLOSE.has(token.value)) {
347
+ const open = stack.pop();
348
+ if (open === undefined || OPEN[tokens[open].value] !== token.value)
349
+ return null;
350
+ match.set(open, index);
351
+ match.set(index, open);
352
+ }
353
+ }
354
+ return stack.length === 0 ? match : null;
355
+ }
356
+ /**
357
+ * The token reads one scan may make. Past it the scan gives up (`ok: false`),
358
+ * so no file under `MAX_FACT_FILE_BYTES` keeps a hook waiting (about 10 ms
359
+ * of reads past the tokenizer). Measured 2026-11-12: a 2,000-line file takes
360
+ * about 31,000, a 12,000-line, 514 KB source file about 141,000.
361
+ */
362
+ export const SCAN_STEP_BUDGET = 1_000_000;
363
+ /** Scan `text` for named spans and calls; `jsx` for a `.tsx` or `.jsx` file. */
364
+ export function scanSource(text, jsx = false, budget = SCAN_STEP_BUDGET) {
365
+ const tokens = tokenize(text, jsx);
366
+ const match = tokens ? matchBrackets(tokens) : null;
367
+ if (!tokens || !match)
368
+ return { ok: false, spans: [], calls: [], steps: 0 };
369
+ // A name's line is 1 + the newlines before its token in the text (R40.1),
370
+ // never the lexer's running count, which a line continuation or a JSX
371
+ // closing tag can leave behind.
372
+ let starts;
373
+ const lineAt = (offset) => {
374
+ starts ??= lineStarts(text);
375
+ return lastBelow(starts.length, (index) => starts[index], offset, true) + 1;
376
+ };
377
+ try {
378
+ return scanTokens(tokens, match, budget, lineAt);
379
+ }
380
+ catch (error) {
381
+ if (error instanceof OverBudget)
382
+ return { ok: false, spans: [], calls: [], steps: budget };
383
+ throw error;
384
+ }
385
+ }
386
+ class OverBudget extends Error {
387
+ }
388
+ function scanTokens(tokens, match, budget, lineAt) {
389
+ const spans = [];
390
+ const calls = [];
391
+ let steps = 0;
392
+ // Every token read counts against the budget.
393
+ const t = (index) => {
394
+ steps += 1;
395
+ if (steps > budget)
396
+ throw new OverBudget();
397
+ return tokens[index];
398
+ };
399
+ const is = (index, kind, value) => {
400
+ const token = t(index);
401
+ return token !== undefined && token.kind === kind && (value === undefined || token.value === value);
402
+ };
403
+ const punc = (index, value) => is(index, "punc", value);
404
+ // Set when a declaration is seen that this scanner cannot place: the file is
405
+ // then not read at all, so an edit in it is never handed to an outer function.
406
+ let unplaced = false;
407
+ /** The index after the `>` closing a type parameter or argument list opened at `from`, or -1. */
408
+ // One scan answers every `<` it passes (`a < b` with no `;` after it would
409
+ // otherwise rescan to the end of its block once per `<`): `end` is the
410
+ // answer, `stop` the token the scan stopped at, `limited` when that was the limit.
411
+ const angles = new Map();
412
+ const angleEnd = (from, limit) => {
413
+ const known = angles.get(from);
414
+ if (known !== undefined) {
415
+ if (known.stop < limit && !known.limited)
416
+ return known.end;
417
+ if (known.stop >= limit)
418
+ return -1;
419
+ }
420
+ const open = [];
421
+ const settle = (end, stop, limited) => {
422
+ for (const at of open)
423
+ angles.set(at, { end, stop, limited });
424
+ };
425
+ for (let k = from; k < limit; k += 1) {
426
+ const token = t(k);
427
+ if (token.kind !== "punc")
428
+ continue;
429
+ if (OPEN[token.value]) {
430
+ k = match.get(k);
431
+ continue;
432
+ }
433
+ if (token.value === "<")
434
+ open.push(k);
435
+ else if (token.value === ">") {
436
+ const at = open.pop();
437
+ if (at === undefined)
438
+ return -1;
439
+ angles.set(at, { end: k + 1, stop: k, limited: false });
440
+ if (open.length === 0)
441
+ return k + 1;
442
+ }
443
+ else if (token.value === ";" || CLOSE.has(token.value)) {
444
+ settle(-1, k, false);
445
+ return -1;
446
+ }
447
+ }
448
+ settle(-1, limit, true);
449
+ return -1;
450
+ };
451
+ /**
452
+ * At the `<` of a call's type arguments (`new Map<string, T[]>(`), the
453
+ * index of the call's `(`, so their commas are not read as separators; else -1.
454
+ */
455
+ const typeArgsCall = (k, limit) => {
456
+ if (!punc(k, "<") || !is(k - 1, "id"))
457
+ return -1;
458
+ const after = angleEnd(k, limit);
459
+ return after > 0 && punc(after, "(") ? after : -1;
460
+ };
461
+ /** Past a type parameter list at `k` when there is one; -1 when it does not close. */
462
+ const pastTypeParams = (k, limit) => (punc(k, "<") ? angleEnd(k, limit) : k);
463
+ // Every call's direct string arguments.
464
+ for (const [index, token] of tokens.entries()) {
465
+ if (token.kind !== "punc" || token.value !== "(")
466
+ continue;
467
+ const prev = t(index - 1);
468
+ const callee = prev !== undefined &&
469
+ ((prev.kind === "id" && !REGEX_AFTER_WORD.has(prev.value) && prev.value !== "function" && prev.value !== "if" &&
470
+ prev.value !== "for" && prev.value !== "while" && prev.value !== "switch" && prev.value !== "catch") ||
471
+ (prev.kind === "punc" && (prev.value === ")" || prev.value === "]" || prev.value === "?.")) ||
472
+ prev.kind === "tpl");
473
+ if (!callee)
474
+ continue;
475
+ const close = match.get(index);
476
+ const literals = [];
477
+ let takesFunction = false;
478
+ for (let k = index + 1; k < close; k += 1) {
479
+ const inner = t(k);
480
+ if (inner.kind === "punc" && OPEN[inner.value]) {
481
+ k = match.get(k);
482
+ continue;
483
+ }
484
+ if (inner.kind === "str")
485
+ literals.push(inner.value);
486
+ else if ((inner.kind === "punc" && inner.value === "=>") || (inner.kind === "id" && inner.value === "function"))
487
+ takesFunction = true;
488
+ }
489
+ // The callee: its last name, and where its member chain starts.
490
+ let last = punc(index - 1, "?.") ? index - 2 : index - 1;
491
+ const member = is(last, "id") ? t(last).value : null;
492
+ while (is(last, "id") && (punc(last - 1, ".") || punc(last - 1, "?.")) && is(last - 2, "id"))
493
+ last -= 2;
494
+ const from = is(last, "id") ? t(last).start : t(index - 1).start;
495
+ calls.push({ from, start: token.start, end: tokens[close].end, member, literals, takesFunction });
496
+ }
497
+ /** Skips a type annotation after `:` up to the token where `stop` holds, jumping brackets. */
498
+ const skipType = (from, limit, stop) => {
499
+ let k = from;
500
+ while (k < limit && !stop(k)) {
501
+ const token = t(k);
502
+ if (token.kind === "punc" && OPEN[token.value]) {
503
+ k = match.get(k) + 1;
504
+ continue;
505
+ }
506
+ if (token.kind === "punc" && (token.value === ";" || CLOSE.has(token.value)))
507
+ return k;
508
+ k += 1;
509
+ }
510
+ return k;
511
+ };
512
+ /** The index of the body `{` after a parameter list closing at `close`, or -1. */
513
+ const bodyAfterParams = (close, limit) => {
514
+ let k = close + 1;
515
+ if (punc(k, ":")) {
516
+ k += 1;
517
+ while (k < limit) {
518
+ const token = t(k);
519
+ if (token.kind === "punc" && token.value === "{") {
520
+ // After a word or bracket that ends a type the `{` is the body; after
521
+ // one that opens a type (`v is {`, `T extends U ? {`) it is an object
522
+ // type. After anything else the return type did not read: the file is not read.
523
+ const before = t(k - 1);
524
+ const typeOpener = (before.kind === "punc" && [":", "|", "&", "<", ",", "(", "=>", "?"].includes(before.value)) ||
525
+ (before.kind === "id" && TYPE_OPERATORS.has(before.value));
526
+ const typeEnds = before.kind === "id" || before.kind === "str" || before.kind === "num" || before.kind === "tpl" ||
527
+ (before.kind === "punc" && [")", "]", "}", ">"].includes(before.value));
528
+ if (!typeOpener && !typeEnds) {
529
+ unplaced = true;
530
+ return -1;
531
+ }
532
+ if (!typeOpener)
533
+ return k;
534
+ k = match.get(k) + 1;
535
+ continue;
536
+ }
537
+ if (token.kind === "punc" && OPEN[token.value]) {
538
+ k = match.get(k) + 1;
539
+ continue;
540
+ }
541
+ if (token.kind === "punc" && (token.value === ";" || CLOSE.has(token.value)))
542
+ return -1;
543
+ k += 1;
544
+ }
545
+ return -1;
546
+ }
547
+ return punc(k, "{") ? k : -1;
548
+ };
549
+ /** The end (exclusive token index) of an expression starting at `from`. */
550
+ const exprEnd = (from, limit) => {
551
+ let k = from;
552
+ while (k < limit) {
553
+ const token = t(k);
554
+ if (token.kind === "punc" && OPEN[token.value]) {
555
+ k = match.get(k) + 1;
556
+ continue;
557
+ }
558
+ const call = typeArgsCall(k, limit);
559
+ if (call > 0) {
560
+ k = call;
561
+ continue;
562
+ }
563
+ if (token.kind === "punc" && (token.value === "," || token.value === ";" || CLOSE.has(token.value)))
564
+ return k;
565
+ if (k > from) {
566
+ const prev = t(k - 1);
567
+ const prevEnds = prev.kind === "str" || prev.kind === "num" || prev.kind === "tpl" || prev.kind === "regex" ||
568
+ (prev.kind === "id" && !REGEX_AFTER_WORD.has(prev.value)) ||
569
+ (prev.kind === "punc" && (prev.value === ")" || prev.value === "]" || prev.value === "}"));
570
+ const startsStatement = (token.kind === "id" && !["as", "satisfies", "instanceof", "in", "of"].includes(token.value)) ||
571
+ token.kind === "str";
572
+ if (token.line > prev.line && prevEnds && startsStatement)
573
+ return k;
574
+ }
575
+ k += 1;
576
+ }
577
+ return limit;
578
+ };
579
+ /**
580
+ * Whether a function expression starts at `at`; when it does, the token
581
+ * range of its body (`bodyOpen` set for a block body) and the index after it.
582
+ */
583
+ const functionAt = (at, limit) => {
584
+ let k = at;
585
+ if (is(k, "id", "async") && !punc(k + 1, "=>") && !punc(k + 1, "="))
586
+ k += 1;
587
+ if (is(k, "id", "function")) {
588
+ k += 1;
589
+ if (punc(k, "*"))
590
+ k += 1;
591
+ if (is(k, "id"))
592
+ k += 1;
593
+ k = pastTypeParams(k, limit);
594
+ if (k < 0 || !punc(k, "("))
595
+ return null;
596
+ const body = bodyAfterParams(match.get(k), limit);
597
+ if (body < 0)
598
+ return null;
599
+ return { bodyOpen: body, after: match.get(body) + 1, exprFrom: -1 };
600
+ }
601
+ let arrow = -1;
602
+ if (is(k, "id") && punc(k + 1, "=>"))
603
+ arrow = k + 1;
604
+ else if (punc(k, "(") || punc(k, "<")) {
605
+ k = pastTypeParams(k, limit);
606
+ if (k < 0 || !punc(k, "("))
607
+ return null;
608
+ const close = match.get(k);
609
+ if (punc(close + 1, "=>"))
610
+ arrow = close + 1;
611
+ else if (punc(close + 1, ":")) {
612
+ const at2 = skipType(close + 2, limit, (index) => punc(index, "=>"));
613
+ if (punc(at2, "=>"))
614
+ arrow = at2;
615
+ }
616
+ }
617
+ if (arrow < 0)
618
+ return null;
619
+ if (punc(arrow + 1, "{"))
620
+ return { bodyOpen: arrow + 1, after: match.get(arrow + 1) + 1, exprFrom: -1 };
621
+ const end = exprEnd(arrow + 1, limit);
622
+ return { bodyOpen: -1, after: end, exprFrom: arrow + 1 };
623
+ };
624
+ /** Records a named function whose name token is at `nameAt` and walks its body. Returns the index after it. */
625
+ const named = (name, declStart, fn, nameAt) => {
626
+ const last = t(fn.after - 1);
627
+ // The span starts at its modifiers: `export`, `export default`, `async`, `declare`.
628
+ let first = declStart;
629
+ while (first > 0 && is(first - 1, "id") && DECLARATION_PREFIXES.has(t(first - 1).value))
630
+ first -= 1;
631
+ spans.push({ name, start: tokens[first].start, end: last.end, nameLine: lineAt(tokens[nameAt].start) });
632
+ if (fn.bodyOpen >= 0)
633
+ walk(fn.bodyOpen + 1, match.get(fn.bodyOpen), { kind: "code" });
634
+ else
635
+ walk(fn.exprFrom, fn.after, { kind: "code" });
636
+ return fn.after;
637
+ };
638
+ /**
639
+ * Walks the class whose `class` keyword is at `at` as `name`, and records
640
+ * it as a span from `spanFrom` when that is set (a class expression), its
641
+ * name token at `nameAt`. Returns the index after its body; -1 when there
642
+ * is no body before `limit` or its heritage does not read (then `unplaced`
643
+ * is set).
644
+ */
645
+ const classAt = (at, limit, name, spanFrom, nameAt) => {
646
+ let k = at + 1;
647
+ if (is(k, "id") && !HERITAGE.has(t(k).value))
648
+ k += 1;
649
+ // The heritage clause up to the body; type arguments may hold `{`.
650
+ while (k >= 0 && k < limit && !punc(k, "{")) {
651
+ k = punc(k, "(") || punc(k, "[") ? match.get(k) + 1 : punc(k, "<") ? angleEnd(k, limit) : k + 1;
652
+ }
653
+ if (k < 0) {
654
+ unplaced = true;
655
+ return -1;
656
+ }
657
+ if (k >= limit)
658
+ return -1;
659
+ const close = match.get(k);
660
+ if (spanFrom >= 0) {
661
+ let first = spanFrom;
662
+ while (first > 0 && is(first - 1, "id") && DECLARATION_PREFIXES.has(t(first - 1).value))
663
+ first -= 1;
664
+ spans.push({ name, start: tokens[first].start, end: tokens[close].end, nameLine: lineAt(tokens[nameAt].start) });
665
+ }
666
+ walk(k + 1, close, { kind: "class", name });
667
+ return close + 1;
668
+ };
669
+ const walkCode = (from, limit) => {
670
+ let i = from;
671
+ while (i < limit) {
672
+ const token = t(i);
673
+ if (token.kind === "id" && token.value === "function") {
674
+ let k = i + 1;
675
+ if (punc(k, "*"))
676
+ k += 1;
677
+ if (is(k, "id")) {
678
+ const params = pastTypeParams(k + 1, limit);
679
+ if (params < 0 || !punc(params, "(")) {
680
+ unplaced = true;
681
+ return;
682
+ }
683
+ const fn = functionAt(i, limit);
684
+ if (fn) {
685
+ i = named(t(k).value, i, fn, k);
686
+ continue;
687
+ }
688
+ // An overload or `declare` signature: no body to place.
689
+ i = match.get(params) + 1;
690
+ continue;
691
+ }
692
+ }
693
+ if (token.kind === "id" && (token.value === "const" || token.value === "let" || token.value === "var") && is(i + 1, "id")) {
694
+ const name = t(i + 1).value;
695
+ let k = i + 2;
696
+ if (punc(k, ":"))
697
+ k = skipType(k + 1, limit, (index) => punc(index, "="));
698
+ if (punc(k, "=")) {
699
+ const value = k + 1;
700
+ if (punc(value, "{")) {
701
+ walk(value + 1, match.get(value), { kind: "object", path: name });
702
+ i = match.get(value) + 1;
703
+ continue;
704
+ }
705
+ if (is(value, "id", "class")) {
706
+ const after = classAt(value, limit, name, i, i + 1);
707
+ if (unplaced)
708
+ return;
709
+ if (after > 0) {
710
+ i = after;
711
+ continue;
712
+ }
713
+ }
714
+ const fn = functionAt(value, limit);
715
+ if (fn) {
716
+ i = named(name, i, fn, i + 1);
717
+ continue;
718
+ }
719
+ // A function this scanner did not read (a generic it cannot close, an
720
+ // `async` or `function` value it cannot follow): not read at all.
721
+ if (punc(value, "<") || is(value, "id", "function") || (is(value, "id", "async") && !punc(value + 1, "."))) {
722
+ unplaced = true;
723
+ return;
724
+ }
725
+ i = value;
726
+ continue;
727
+ }
728
+ }
729
+ if (token.kind === "id" && token.value === "class" && !punc(i - 1, ".") && !punc(i - 1, "?.") && !punc(i + 1, ":")) {
730
+ // A class with no name of its own (an expression) is its own thing,
731
+ // named by nothing a row can carry: an edit in it is never its encloser's.
732
+ const own = is(i + 1, "id") && !HERITAGE.has(t(i + 1).value);
733
+ const after = classAt(i, limit, own ? t(i + 1).value : "(class)", own ? -1 : i, own ? i + 1 : i);
734
+ if (unplaced)
735
+ return;
736
+ if (after > 0) {
737
+ i = after;
738
+ continue;
739
+ }
740
+ }
741
+ // An assignment of a function or class to a name or member
742
+ // (`obj.h = function () {}`, `Foo.prototype.m = () => {}`): its own
743
+ // thing, named by the target's last name.
744
+ if (token.kind === "id" && punc(i + 1, "=") && !is(i - 1, "id", "type")) {
745
+ let start = i;
746
+ while ((punc(start - 1, ".") || punc(start - 1, "?.")) && is(start - 2, "id"))
747
+ start -= 2;
748
+ if (is(i + 2, "id", "class")) {
749
+ const after = classAt(i + 2, limit, token.value, start, i);
750
+ if (unplaced)
751
+ return;
752
+ if (after > 0) {
753
+ i = after;
754
+ continue;
755
+ }
756
+ }
757
+ const fn = functionAt(i + 2, limit);
758
+ if (fn) {
759
+ i = named(token.value, start, fn, i);
760
+ continue;
761
+ }
762
+ }
763
+ if (token.kind === "punc" && OPEN[token.value]) {
764
+ walk(i + 1, match.get(i), { kind: "code" });
765
+ i = match.get(i) + 1;
766
+ continue;
767
+ }
768
+ i += 1;
769
+ }
770
+ };
771
+ /** The index of the next `,` (or `;` in a class) at this level, walking nested brackets as code. */
772
+ const nextEntry = (from, limit, separators) => {
773
+ let k = from;
774
+ while (k < limit) {
775
+ const token = t(k);
776
+ if (token.kind === "punc" && separators.includes(token.value))
777
+ return k + 1;
778
+ const call = typeArgsCall(k, limit);
779
+ if (call > 0) {
780
+ k = call;
781
+ continue;
782
+ }
783
+ if (token.kind === "punc" && OPEN[token.value]) {
784
+ walk(k + 1, match.get(k), { kind: "code" });
785
+ k = match.get(k) + 1;
786
+ continue;
787
+ }
788
+ k += 1;
789
+ }
790
+ return limit;
791
+ };
792
+ const walkObject = (from, limit, path) => {
793
+ let i = from;
794
+ while (i < limit) {
795
+ if (punc(i, "...")) {
796
+ i = nextEntry(i, limit, [","]);
797
+ continue;
798
+ }
799
+ let k = i;
800
+ while ((is(k, "id", "async") || is(k, "id", "get") || is(k, "id", "set")) && !punc(k + 1, ":") && !punc(k + 1, "(") && !punc(k + 1, ",")) {
801
+ k += 1;
802
+ }
803
+ if (punc(k, "*"))
804
+ k += 1;
805
+ let key = null;
806
+ const keyAt = k;
807
+ if (is(k, "id") || is(k, "str") || is(k, "num")) {
808
+ key = t(k).value;
809
+ k += 1;
810
+ }
811
+ else if (punc(k, "[")) {
812
+ k = match.get(k) + 1;
813
+ }
814
+ else {
815
+ i = nextEntry(i, limit, [","]);
816
+ continue;
817
+ }
818
+ if (punc(k, "?"))
819
+ k += 1;
820
+ if (punc(k, "<")) {
821
+ k = angleEnd(k, limit);
822
+ if (k < 0 || !punc(k, "(")) {
823
+ unplaced = true;
824
+ return;
825
+ }
826
+ }
827
+ if (punc(k, "(")) {
828
+ const body = bodyAfterParams(match.get(k), limit);
829
+ if (body >= 0) {
830
+ if (key !== null)
831
+ named(`${path}.${key}`, i, { bodyOpen: body, after: match.get(body) + 1, exprFrom: -1 }, keyAt);
832
+ else
833
+ walk(body + 1, match.get(body), { kind: "code" });
834
+ i = nextEntry(match.get(body) + 1, limit, [","]);
835
+ continue;
836
+ }
837
+ }
838
+ if (punc(k, ":")) {
839
+ const value = k + 1;
840
+ if (punc(value, "{") && key !== null) {
841
+ walk(value + 1, match.get(value), { kind: "object", path: `${path}.${key}` });
842
+ i = nextEntry(match.get(value) + 1, limit, [","]);
843
+ continue;
844
+ }
845
+ const fn = functionAt(value, limit);
846
+ if (fn && key !== null) {
847
+ const after = named(`${path}.${key}`, i, fn, keyAt);
848
+ i = nextEntry(after, limit, [","]);
849
+ continue;
850
+ }
851
+ i = nextEntry(value, limit, [","]);
852
+ continue;
853
+ }
854
+ i = nextEntry(k, limit, [","]);
855
+ }
856
+ };
857
+ const walkClass = (from, limit, className) => {
858
+ let i = from;
859
+ while (i < limit) {
860
+ if (punc(i, ";")) {
861
+ i += 1;
862
+ continue;
863
+ }
864
+ const memberStart = i;
865
+ let k = i;
866
+ // Decorators: `@name`, `@a.b`, `@name(...)`.
867
+ while (punc(k, "@")) {
868
+ k += 1;
869
+ while (is(k, "id") || punc(k, "."))
870
+ k += 1;
871
+ if (punc(k, "("))
872
+ k = match.get(k) + 1;
873
+ }
874
+ while (is(k, "id") && CLASS_MODIFIERS.has(t(k).value) && !punc(k + 1, "(") && !punc(k + 1, "=") && !punc(k + 1, ";") && !punc(k + 1, ":")) {
875
+ k += 1;
876
+ }
877
+ if (punc(k, "*"))
878
+ k += 1;
879
+ if (punc(k, "{")) {
880
+ // A static block.
881
+ walk(k + 1, match.get(k), { kind: "code" });
882
+ i = match.get(k) + 1;
883
+ continue;
884
+ }
885
+ let key = null;
886
+ const keyAt = k;
887
+ if (is(k, "id") || is(k, "str") || is(k, "num")) {
888
+ key = t(k).value;
889
+ k += 1;
890
+ }
891
+ else if (punc(k, "[")) {
892
+ k = match.get(k) + 1;
893
+ }
894
+ else {
895
+ // A member this scanner does not know how to read.
896
+ unplaced = true;
897
+ return;
898
+ }
899
+ if (punc(k, "?") || punc(k, "!"))
900
+ k += 1;
901
+ if (punc(k, "<")) {
902
+ k = angleEnd(k, limit);
903
+ if (k < 0 || !punc(k, "(")) {
904
+ unplaced = true;
905
+ return;
906
+ }
907
+ }
908
+ if (punc(k, "(")) {
909
+ const body = bodyAfterParams(match.get(k), limit);
910
+ if (body >= 0) {
911
+ if (key !== null)
912
+ named(`${className}.${key}`, memberStart, { bodyOpen: body, after: match.get(body) + 1, exprFrom: -1 }, keyAt);
913
+ else
914
+ walk(body + 1, match.get(body), { kind: "code" });
915
+ i = match.get(body) + 1;
916
+ continue;
917
+ }
918
+ // An overload or abstract signature.
919
+ i = nextEntry(match.get(k) + 1, limit, [";"]);
920
+ continue;
921
+ }
922
+ if (punc(k, ":"))
923
+ k = skipType(k + 1, limit, (index) => punc(index, "=") || punc(index, ";") || (t(index).line > t(index - 1).line && is(index, "id")));
924
+ if (punc(k, "=")) {
925
+ const fn = functionAt(k + 1, limit);
926
+ if (fn && key !== null) {
927
+ i = named(`${className}.${key}`, memberStart, fn, keyAt);
928
+ continue;
929
+ }
930
+ const end = exprEnd(k + 1, limit);
931
+ walk(k + 1, end, { kind: "code" });
932
+ i = end;
933
+ continue;
934
+ }
935
+ i = k;
936
+ }
937
+ };
938
+ function walk(from, limit, ctx) {
939
+ if (ctx.kind === "code")
940
+ walkCode(from, limit);
941
+ else if (ctx.kind === "object")
942
+ walkObject(from, limit, ctx.path);
943
+ else
944
+ walkClass(from, limit, ctx.name);
945
+ }
946
+ walk(0, tokens.length, { kind: "code" });
947
+ if (unplaced)
948
+ return { ok: false, spans: [], calls: [], steps };
949
+ return { ok: true, spans, calls, steps };
950
+ }
951
+ /**
952
+ * Where `snippets` sit in `text`. A snippet found nowhere, or in more than one
953
+ * place, gives no range: which copy the edit wrote is not known.
954
+ */
955
+ export function rangesOf(text, snippets) {
956
+ const ranges = [];
957
+ for (const snippet of snippets) {
958
+ if (snippet.trim().length === 0)
959
+ continue;
960
+ const at = text.indexOf(snippet);
961
+ if (at < 0 || text.indexOf(snippet, at + 1) >= 0)
962
+ continue;
963
+ ranges.push({ start: at, end: at + snippet.length });
964
+ }
965
+ return ranges;
966
+ }
967
+ function lineStarts(text) {
968
+ const starts = [0];
969
+ for (let at = text.indexOf("\n"); at >= 0; at = text.indexOf("\n", at + 1))
970
+ starts.push(at + 1);
971
+ return starts;
972
+ }
973
+ /**
974
+ * Where lines were removed, as offsets: a removal before the 1-based line N
975
+ * of the file as it is now sits at the start of line N (the end of the text
976
+ * when N is past the last line).
977
+ */
978
+ export function gapsOfLines(text, removedBefore) {
979
+ const starts = lineStarts(text);
980
+ return [...new Set(removedBefore)].map((line) => starts[line - 1] ?? text.length);
981
+ }
982
+ /** The ranges of the 1-based `lines` of `text`. */
983
+ export function rangesOfLines(text, lines) {
984
+ const starts = lineStarts(text);
985
+ const ranges = [];
986
+ for (const line of new Set(lines)) {
987
+ const start = starts[line - 1];
988
+ if (start === undefined)
989
+ continue;
990
+ const next = starts[line];
991
+ ranges.push({ start, end: next === undefined ? text.length : next - 1 });
992
+ }
993
+ return ranges;
994
+ }
995
+ /** The largest index in `0..length` whose `key` is below `bound` (or at it, with `orEqual`), else -1. */
996
+ function lastBelow(length, key, bound, orEqual) {
997
+ let low = 0;
998
+ let high = length - 1;
999
+ let found = -1;
1000
+ while (low <= high) {
1001
+ const mid = (low + high) >> 1;
1002
+ const value = key(mid);
1003
+ if (value < bound || (orEqual && value === bound)) {
1004
+ found = mid;
1005
+ low = mid + 1;
1006
+ }
1007
+ else
1008
+ high = mid - 1;
1009
+ }
1010
+ return found;
1011
+ }
1012
+ /**
1013
+ * The named spans in start order with each one's parent (they nest: the
1014
+ * walk records a thing before its body), so the innermost span holding an
1015
+ * offset is found by one binary search and a walk up, not a pass over all.
1016
+ */
1017
+ function spanIndex(spans) {
1018
+ const sorted = [...spans].sort((a, b) => a.start - b.start || b.end - a.end);
1019
+ const parent = [];
1020
+ const stack = [];
1021
+ for (const [index, span] of sorted.entries()) {
1022
+ while (stack.length > 0 && sorted[stack[stack.length - 1]].end <= span.start)
1023
+ stack.pop();
1024
+ parent.push(stack.length > 0 ? stack[stack.length - 1] : -1);
1025
+ stack.push(index);
1026
+ }
1027
+ return {
1028
+ /** The innermost span holding `offset` (`start < offset` with `strict`), or null. */
1029
+ at(offset, strict) {
1030
+ let index = lastBelow(sorted.length, (k) => sorted[k].start, offset, !strict);
1031
+ while (index >= 0 && sorted[index].end <= offset)
1032
+ index = parent[index];
1033
+ return index >= 0 ? sorted[index] : null;
1034
+ },
1035
+ /** Every span wholly inside `range`. */
1036
+ within(range) {
1037
+ const out = [];
1038
+ for (let k = lastBelow(sorted.length, (j) => sorted[j].start, range.start, false) + 1; k < sorted.length; k += 1) {
1039
+ const span = sorted[k];
1040
+ if (span.start >= range.end)
1041
+ break;
1042
+ if (span.end <= range.end)
1043
+ out.push(span);
1044
+ }
1045
+ return out;
1046
+ },
1047
+ };
1048
+ }
1049
+ /**
1050
+ * The names an edit over `ranges` touched (the innermost named encloser of
1051
+ * each changed line, and every named thing inside a changed range), and the
1052
+ * calls outside every named thing whose text (from the callee to the
1053
+ * closing `)`) covers part of a changed line. A removal at offset `gap`
1054
+ * (`gapsOfLines`) touches only the innermost thing, or top-level call, it
1055
+ * sits strictly inside: never one whose first line it is just above, and
1056
+ * never one it follows.
1057
+ */
1058
+ export function touched(text, scan, ranges, gaps = []) {
1059
+ const names = new Set();
1060
+ const calls = new Set();
1061
+ const index = spanIndex(scan.spans);
1062
+ // Removals and changed lines that no named thing holds, in offset order.
1063
+ const topGaps = [];
1064
+ for (const gap of gaps) {
1065
+ const span = index.at(gap, true);
1066
+ if (span)
1067
+ names.add(span.name);
1068
+ else
1069
+ topGaps.push(gap);
1070
+ }
1071
+ const topLines = [];
1072
+ const allLines = [];
1073
+ for (const range of ranges) {
1074
+ // Each changed line, by its first non-blank character.
1075
+ let at = range.start;
1076
+ while (at < range.end) {
1077
+ const lineEnd = text.indexOf("\n", at);
1078
+ const stop = lineEnd < 0 || lineEnd >= range.end ? range.end : lineEnd;
1079
+ let first = at;
1080
+ while (first < stop && /\s/.test(text[first]))
1081
+ first += 1;
1082
+ if (first < stop) {
1083
+ allLines.push({ first, stop });
1084
+ const span = index.at(first, false);
1085
+ if (span)
1086
+ names.add(span.name);
1087
+ else
1088
+ topLines.push({ first, stop });
1089
+ }
1090
+ at = stop + 1;
1091
+ }
1092
+ for (const span of index.within(range))
1093
+ names.add(span.name);
1094
+ }
1095
+ const reachedIn = (span) => {
1096
+ const inside = (offset) => offset > span.start && offset < span.end;
1097
+ const spanGaps = gaps.filter(inside).sort((a, b) => a - b);
1098
+ const spanLines = allLines.filter((line) => inside(line.first)).sort((a, b) => a.first - b.first);
1099
+ return scan.calls.filter((call) => call.from >= span.start && call.end <= span.end && hits(call, spanGaps, spanLines));
1100
+ };
1101
+ if (topGaps.length === 0 && topLines.length === 0)
1102
+ return { names: [...names], calls: [], reachedIn };
1103
+ topGaps.sort((a, b) => a - b);
1104
+ topLines.sort((a, b) => a.first - b.first);
1105
+ for (const call of scan.calls) {
1106
+ if (index.at(call.start, false) !== null)
1107
+ continue;
1108
+ if (hits(call, topGaps, topLines))
1109
+ calls.add(call);
1110
+ }
1111
+ return { names: [...names], calls: [...calls], reachedIn };
1112
+ }
1113
+ /** Whether a removal (sorted `gaps`) or a changed line (sorted `lines`) falls inside `call`, from its callee to its `)`. */
1114
+ function hits(call, gaps, lines) {
1115
+ // The first removal after the callee starts, and the first changed line ending after it.
1116
+ const gap = gaps[lastBelow(gaps.length, (k) => gaps[k], call.from, true) + 1];
1117
+ if (gap !== undefined && gap < call.end)
1118
+ return true;
1119
+ const k = lastBelow(lines.length, (j) => lines[j].stop, call.from, true) + 1;
1120
+ return k < lines.length && lines[k].first < call.end;
1121
+ }
1122
+ //# sourceMappingURL=match.js.map