neuroplex 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/brain/build.js +6 -4
  2. package/dist/brain/build.js.map +1 -1
  3. package/dist/brain/local.d.ts +2 -0
  4. package/dist/brain/local.js.map +1 -1
  5. package/dist/brain/obsidian.js +5 -0
  6. package/dist/brain/obsidian.js.map +1 -1
  7. package/dist/cli/index.js +97 -22
  8. package/dist/cli/index.js.map +1 -1
  9. package/dist/config/config.d.ts +24 -0
  10. package/dist/config/config.js +61 -1
  11. package/dist/config/config.js.map +1 -1
  12. package/dist/enrich/tasks.js +2 -0
  13. package/dist/enrich/tasks.js.map +1 -1
  14. package/dist/enrich/write.js +2 -2
  15. package/dist/enrich/write.js.map +1 -1
  16. package/dist/graph/schema.d.ts +3 -1
  17. package/dist/graph/schema.js +3 -0
  18. package/dist/graph/schema.js.map +1 -1
  19. package/dist/mcp/http.js +6 -2
  20. package/dist/mcp/http.js.map +1 -1
  21. package/dist/mcp/server.d.ts +1 -1
  22. package/dist/mcp/server.js +24 -2
  23. package/dist/mcp/server.js.map +1 -1
  24. package/dist/query/cli.d.ts +1 -0
  25. package/dist/query/cli.js +16 -2
  26. package/dist/query/cli.js.map +1 -1
  27. package/dist/query/queries.d.ts +4 -0
  28. package/dist/query/queries.js +5 -3
  29. package/dist/query/queries.js.map +1 -1
  30. package/dist/query/search.js +1 -1
  31. package/dist/query/search.js.map +1 -1
  32. package/dist/query/source.d.ts +36 -0
  33. package/dist/query/source.js +94 -0
  34. package/dist/query/source.js.map +1 -0
  35. package/dist/scan/assemble.d.ts +15 -0
  36. package/dist/scan/assemble.js +243 -15
  37. package/dist/scan/assemble.js.map +1 -1
  38. package/dist/scan/discover.js +3 -0
  39. package/dist/scan/discover.js.map +1 -1
  40. package/dist/scan/docs.d.ts +20 -0
  41. package/dist/scan/docs.js +198 -0
  42. package/dist/scan/docs.js.map +1 -0
  43. package/dist/scan/extract.d.ts +1 -1
  44. package/dist/scan/extract.js +13 -3
  45. package/dist/scan/extract.js.map +1 -1
  46. package/dist/scan/extractors/csharp.d.ts +4 -0
  47. package/dist/scan/extractors/csharp.js +604 -0
  48. package/dist/scan/extractors/csharp.js.map +1 -0
  49. package/dist/scan/extractors/python.js +170 -15
  50. package/dist/scan/extractors/python.js.map +1 -1
  51. package/dist/scan/extractors/typescript.js +405 -23
  52. package/dist/scan/extractors/typescript.js.map +1 -1
  53. package/dist/scan/parser.js +1 -0
  54. package/dist/scan/parser.js.map +1 -1
  55. package/dist/scan/repos.d.ts +38 -0
  56. package/dist/scan/repos.js +155 -0
  57. package/dist/scan/repos.js.map +1 -0
  58. package/dist/scan/scan.d.ts +15 -0
  59. package/dist/scan/scan.js +26 -16
  60. package/dist/scan/scan.js.map +1 -1
  61. package/dist/scan/types.d.ts +40 -1
  62. package/dist/scan/types.js +2 -1
  63. package/dist/scan/types.js.map +1 -1
  64. package/dist/sync/sync.js +37 -16
  65. package/dist/sync/sync.js.map +1 -1
  66. package/package.json +1 -1
  67. package/skills/neuroplex/SKILL.md +10 -0
@@ -16,6 +16,23 @@ const MCP_REGISTRATIONS = new Map([
16
16
  ['prompt', 'prompt'],
17
17
  ]);
18
18
  const HTTP_VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'all', 'options', 'head']);
19
+ /** NestJS method decorators → HTTP method. */
20
+ const NEST_VERBS = new Map([
21
+ ['Get', 'GET'],
22
+ ['Post', 'POST'],
23
+ ['Put', 'PUT'],
24
+ ['Patch', 'PATCH'],
25
+ ['Delete', 'DELETE'],
26
+ ['Options', 'OPTIONS'],
27
+ ['Head', 'HEAD'],
28
+ ['All', 'ANY'],
29
+ ]);
30
+ /** Methods of HTTP-client-looking receivers (`http.get(url)`, `this.api.post(url, body)`). */
31
+ const CLIENT_VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options']);
32
+ /** Receivers known to be HTTP clients: any literal first argument is a URL. */
33
+ const KNOWN_CLIENTS = new Set(['axios', 'ky', 'got', 'superagent']);
34
+ /** Receivers that register server routes (`router.get('/x', controller.list)`), never clients. */
35
+ const SERVER_RECEIVER = /^(app|server)$|[rR]outer$/;
19
36
  /** Parents that continue a method chain (`a.b().c()`, `await a.b()`). */
20
37
  const CHAIN_PARENTS = new Set(['call_expression', 'member_expression', 'await_expression', 'parenthesized_expression']);
21
38
  /** Extracts symbols, imports, calls and heritage from a TypeScript/TSX/JavaScript tree. */
@@ -32,6 +49,9 @@ class TsExtractor {
32
49
  /** Names exported through a local `export { a, b as c }` or `export default a`. */
33
50
  clauseExports = new Set();
34
51
  seenCalls = new Set();
52
+ seenRequests = new Set();
53
+ /** Class members reported as `route` (NestJS handlers), exported with their class. */
54
+ memberRoutes = new Set();
35
55
  constructor(root, lang) {
36
56
  this.root = root;
37
57
  this.lang = lang;
@@ -127,6 +147,7 @@ class TsExtractor {
127
147
  const body = node.childForFieldName('body');
128
148
  if (!body)
129
149
  return;
150
+ const prefix = controllerPrefix(classDecorators(node));
130
151
  for (const member of namedChildren(body)) {
131
152
  const memberName = member.childForFieldName('name') ?? member.childForFieldName('property');
132
153
  if (!memberName || memberName.text === 'constructor')
@@ -134,17 +155,22 @@ class TsExtractor {
134
155
  const value = member.childForFieldName('value');
135
156
  const isMethod = METHOD_MEMBERS.has(member.type) ||
136
157
  (FIELD_MEMBERS.has(member.type) && value !== null && FUNCTION_VALUES.has(value.type));
137
- if (isMethod)
138
- this.addSymbol(`${name}.${memberName.text}`, 'method', member, exported, member);
158
+ if (!isMethod)
159
+ continue;
160
+ const qualified = `${name}.${memberName.text}`;
161
+ const http = prefix === undefined ? undefined : nestEndpoint(prefix, memberDecorators(member));
162
+ if (http)
163
+ this.memberRoutes.add(qualified);
164
+ this.addSymbol(qualified, http ? 'route' : 'method', member, exported, member, http);
139
165
  }
140
166
  }
141
- addSymbol(name, kind, rangeNode, exported, owner) {
167
+ addSymbol(name, kind, rangeNode, exported, owner, http) {
142
168
  // Calls inside a repeated declaration (e.g. an overload's implementation) still belong to `name`.
143
169
  this.owners.set(owner.id, name);
144
170
  if (this.names.has(name))
145
171
  return;
146
172
  this.names.add(name);
147
- this.out.symbols.push({ name, kind, range: lineRange(rangeNode), exported });
173
+ this.out.symbols.push({ name, kind, range: lineRange(rangeNode), exported, ...(http ? { http } : {}) });
148
174
  }
149
175
  isComponent(name, fn) {
150
176
  if (this.lang === 'typescript' || !/^[A-Z]/.test(name))
@@ -181,7 +207,8 @@ class TsExtractor {
181
207
  }
182
208
  for (const symbol of this.out.symbols) {
183
209
  const owner = symbol.name.split('.')[0] ?? '';
184
- if (symbol.kind === 'method' && exportedClasses.has(owner))
210
+ const isMember = symbol.kind === 'method' || this.memberRoutes.has(symbol.name);
211
+ if (isMember && exportedClasses.has(owner))
185
212
  symbol.exported = true;
186
213
  }
187
214
  }
@@ -282,19 +309,22 @@ class TsExtractor {
282
309
  this.out.imports.push(entry);
283
310
  }
284
311
  // ---- calls ----
285
- walk(node, caller) {
312
+ walk(node, caller, scopes = []) {
286
313
  const owner = this.owners.get(node.id) ?? caller;
314
+ const inner = enterScope(node, scopes);
287
315
  if (node.type === 'call_expression') {
288
316
  this.addRouteHandler(node);
289
317
  const isImport = this.addDynamicImport(node);
290
- if (!isImport && owner)
291
- this.addCall(owner, node.childForFieldName('function'), node);
318
+ if (!isImport && owner) {
319
+ this.addCall(owner, unwrapAwait(node.childForFieldName('function')), node, inner);
320
+ this.addRequest(owner, node);
321
+ }
292
322
  }
293
323
  else if (node.type === 'new_expression' && owner) {
294
- this.addCall(owner, node.childForFieldName('constructor'), node);
324
+ this.addCall(owner, node.childForFieldName('constructor'), node, inner);
295
325
  }
296
326
  for (const child of namedChildren(node))
297
- this.walk(child, owner);
327
+ this.walk(child, owner, inner);
298
328
  }
299
329
  /**
300
330
  * Anonymous entry-point callbacks (CLI commands, MCP tools, HTTP routes) become
@@ -304,7 +334,17 @@ class TsExtractor {
304
334
  const route = routeOf(call);
305
335
  if (!route)
306
336
  return;
307
- this.addSymbol(this.uniqueName(route.name), 'route', statementOf(call), false, route.handler);
337
+ this.addSymbol(this.uniqueName(route.name), 'route', statementOf(call), false, route.handler, route.http);
338
+ }
339
+ addRequest(caller, call) {
340
+ const request = requestOf(call);
341
+ if (!request)
342
+ return;
343
+ const key = `${caller}\0${request.method}\0${request.url}`;
344
+ if (this.seenRequests.has(key))
345
+ return;
346
+ this.seenRequests.add(key);
347
+ this.out.requests.push({ caller, ...request, line: line(call) });
308
348
  }
309
349
  /** `name`, or `name (2)`, `name (3)`... when already taken in this file. */
310
350
  uniqueName(name) {
@@ -315,30 +355,52 @@ class TsExtractor {
315
355
  n++;
316
356
  return `${name} (${n})`;
317
357
  }
318
- addCall(caller, target, node) {
358
+ addCall(caller, target, node, scopes) {
319
359
  if (!target)
320
360
  return;
321
361
  let callee;
322
362
  let object;
363
+ let objectType;
323
364
  if (target.type === 'identifier') {
324
365
  callee = target.text;
325
366
  }
326
367
  else if (target.type === 'member_expression') {
327
368
  const receiver = target.childForFieldName('object');
328
369
  const property = target.childForFieldName('property');
329
- if (!receiver || !property || (receiver.type !== 'identifier' && receiver.type !== 'this'))
370
+ if (!receiver || !property)
330
371
  return;
372
+ const field = thisField(receiver);
373
+ if (receiver.type === 'identifier') {
374
+ object = receiver.text;
375
+ objectType = lookupType(scopes, object, false);
376
+ }
377
+ else if (receiver.type === 'this') {
378
+ object = 'this';
379
+ }
380
+ else if (field) {
381
+ // `this.svc.find()` is reported as a call on `svc`, typed from the class fields.
382
+ object = field;
383
+ objectType = lookupType(scopes, field, true);
384
+ }
385
+ else {
386
+ return; // a.b.c(), f().g()...
387
+ }
331
388
  callee = property.text;
332
- object = receiver.text;
333
389
  }
334
390
  else {
335
- return; // super(), f().g(), arr[0]()...
391
+ return; // super(), arr[0]()...
336
392
  }
337
393
  const key = `${caller}\0${callee}\0${object ?? ''}`;
338
394
  if (this.seenCalls.has(key))
339
395
  return;
340
396
  this.seenCalls.add(key);
341
- this.out.calls.push({ caller, callee, ...(object !== undefined ? { object } : {}), line: line(node) });
397
+ this.out.calls.push({
398
+ caller,
399
+ callee,
400
+ ...(object !== undefined ? { object } : {}),
401
+ ...(objectType !== undefined ? { objectType } : {}),
402
+ line: line(node),
403
+ });
342
404
  }
343
405
  // ---- heritage ----
344
406
  addClassHeritage(symbol, node) {
@@ -386,12 +448,7 @@ function stringContent(node) {
386
448
  }
387
449
  /** True when `node` has an anonymous `type` keyword child (`import type`, `type a` specifiers). */
388
450
  function hasTypeKeyword(node) {
389
- for (let i = 0; i < node.childCount; i++) {
390
- const child = node.child(i);
391
- if (child && !child.isNamed && child.type === 'type')
392
- return true;
393
- }
394
- return false;
451
+ return hasKeyword(node, 'type');
395
452
  }
396
453
  function specifierBinding(spec, nameField, aliasField) {
397
454
  const name = spec.childForFieldName(nameField)?.text;
@@ -445,7 +502,8 @@ function routeOf(call) {
445
502
  if (mcpKind)
446
503
  return { name: `${mcpKind}:${first}`, handler };
447
504
  if (HTTP_VERBS.has(method) && receiver.type === 'identifier' && first.startsWith('/')) {
448
- return { name: `${method.toUpperCase()} ${first}`, handler };
505
+ const verb = method === 'all' ? 'ANY' : method.toUpperCase();
506
+ return { name: `${method.toUpperCase()} ${first}`, handler, http: { method: verb, path: first } };
449
507
  }
450
508
  return undefined;
451
509
  }
@@ -506,4 +564,328 @@ function heritageTarget(node) {
506
564
  return undefined;
507
565
  return base.text;
508
566
  }
567
+ // ---- NestJS controllers ----
568
+ /** Decorators of a class, including those written before `export`. */
569
+ function classDecorators(node) {
570
+ const outer = node.parent?.type === 'export_statement' ? namedChildren(node.parent) : [];
571
+ return [...outer, ...namedChildren(node)].filter((c) => c.type === 'decorator');
572
+ }
573
+ /**
574
+ * Decorators of a class member: its children in the JavaScript grammar, the
575
+ * preceding siblings in the class body in the TypeScript grammar.
576
+ */
577
+ function memberDecorators(member) {
578
+ const result = namedChildren(member).filter((c) => c.type === 'decorator');
579
+ for (let prev = member.previousNamedSibling; prev?.type === 'decorator'; prev = prev.previousNamedSibling) {
580
+ result.push(prev);
581
+ }
582
+ return result;
583
+ }
584
+ /** Name and arguments of `@Name(...)` or `@Name`. */
585
+ function decoratorCall(decorator) {
586
+ const expr = namedChildren(decorator)[0];
587
+ if (expr?.type === 'identifier')
588
+ return { name: expr.text, args: [] };
589
+ if (expr?.type !== 'call_expression')
590
+ return undefined;
591
+ const fn = expr.childForFieldName('function');
592
+ return fn?.type === 'identifier' ? { name: fn.text, args: callArguments(expr) } : undefined;
593
+ }
594
+ /** Path of `@Controller('users')`, `@Controller({ path: 'users' })` or `@Controller()` (''); undefined without one. */
595
+ function controllerPrefix(decorators) {
596
+ for (const decorator of decorators) {
597
+ const call = decoratorCall(decorator);
598
+ if (call?.name === 'Controller')
599
+ return decoratorPath(call.args[0]);
600
+ }
601
+ return undefined;
602
+ }
603
+ function nestEndpoint(prefix, decorators) {
604
+ for (const decorator of decorators) {
605
+ const call = decoratorCall(decorator);
606
+ const method = call ? NEST_VERBS.get(call.name) : undefined;
607
+ if (call && method)
608
+ return { method, path: joinPaths(prefix, decoratorPath(call.args[0])) };
609
+ }
610
+ return undefined;
611
+ }
612
+ /** A decorator path argument: a literal, the first entry of an array, or an object's `path`. */
613
+ function decoratorPath(arg) {
614
+ if (!arg)
615
+ return '';
616
+ if (arg.type === 'array')
617
+ return decoratorPath(namedChildren(arg)[0]);
618
+ if (arg.type === 'object')
619
+ return decoratorPath(objectProperty(arg, 'path'));
620
+ return literalText(arg) ?? '';
621
+ }
622
+ /** `/` + parts joined with `/`, repeated and trailing slashes removed. */
623
+ function joinPaths(...parts) {
624
+ const joined = `/${parts.join('/')}`.replace(/\/{2,}/g, '/');
625
+ return joined.length > 1 ? joined.replace(/\/$/, '') : joined;
626
+ }
627
+ /**
628
+ * Recognises `fetch(url, opts)`, `axios(...)`, `axios.get(url)`, `$.ajax({...})` and
629
+ * `<client>.get(url, ...)` / `this.<client>.get(url, ...)` with a URL-like first argument.
630
+ * Calls with a function argument are route registrations, not requests.
631
+ */
632
+ function requestOf(call) {
633
+ const fn = unwrapAwait(call.childForFieldName('function'));
634
+ const args = callArguments(call);
635
+ const [first, second] = args;
636
+ if (!fn || !first || args.some((a) => FUNCTION_VALUES.has(a.type)))
637
+ return undefined;
638
+ if (fn.type === 'identifier') {
639
+ if (fn.text === 'axios' && first.type === 'object')
640
+ return configRequest(first);
641
+ if (fn.text === 'fetch' || fn.text === 'axios')
642
+ return withUrl(urlText(first), optionMethod(second, 'method'));
643
+ return undefined;
644
+ }
645
+ if (fn.type !== 'member_expression')
646
+ return undefined;
647
+ const method = fn.childForFieldName('property')?.text;
648
+ const receiver = clientName(fn.childForFieldName('object'));
649
+ if (!method || receiver === undefined)
650
+ return undefined;
651
+ if (receiver === 'axios' && method === 'request')
652
+ return configRequest(first);
653
+ if (receiver === '$' && method === 'ajax')
654
+ return configRequest(first);
655
+ if (!CLIENT_VERBS.has(method) || SERVER_RECEIVER.test(receiver))
656
+ return undefined;
657
+ const url = urlText(first);
658
+ if (url === undefined || (!KNOWN_CLIENTS.has(receiver) && !isUrlLike(url)))
659
+ return undefined;
660
+ return { method: method.toUpperCase(), url };
661
+ }
662
+ /** `http` for receivers `http` and `this.http`; undefined for other receivers. */
663
+ function clientName(receiver) {
664
+ if (receiver?.type === 'identifier')
665
+ return receiver.text;
666
+ if (receiver?.type !== 'member_expression' || receiver.childForFieldName('object')?.type !== 'this')
667
+ return undefined;
668
+ return receiver.childForFieldName('property')?.text;
669
+ }
670
+ function withUrl(url, method) {
671
+ return url === undefined ? undefined : { method, url };
672
+ }
673
+ /** `{ url, method }` (axios) or `{ url, type }` (jQuery) config objects. */
674
+ function configRequest(config) {
675
+ if (config.type !== 'object')
676
+ return undefined;
677
+ const urlNode = objectProperty(config, 'url');
678
+ const method = optionMethod(config, objectProperty(config, 'method') ? 'method' : 'type');
679
+ return withUrl(urlNode ? urlText(urlNode) : undefined, method);
680
+ }
681
+ /** Uppercased string value of `key` in an options object literal; `GET` otherwise. */
682
+ function optionMethod(options, key) {
683
+ const value = options?.type === 'object' ? objectProperty(options, key) : undefined;
684
+ const text = value ? literalText(value) : undefined;
685
+ return text ? text.toUpperCase() : 'GET';
686
+ }
687
+ /** Value of a `key: value` pair in an object literal. */
688
+ function objectProperty(object, key) {
689
+ for (const pair of namedChildren(object)) {
690
+ if (pair.type !== 'pair')
691
+ continue;
692
+ const name = pair.childForFieldName('key');
693
+ const text = name?.type === 'string' ? stringContent(name) : name?.text;
694
+ if (text === key)
695
+ return pair.childForFieldName('value') ?? undefined;
696
+ }
697
+ return undefined;
698
+ }
699
+ const isStringNode = (node) => node.type === 'string' || node.type === 'template_string';
700
+ /**
701
+ * URL of a string literal, a template literal (substitutions become `{}`) or a
702
+ * concatenation starting with a literal (`'/a/' + id` → `/a/{}`); undefined otherwise.
703
+ */
704
+ function urlText(node) {
705
+ if (node.type === 'string')
706
+ return stringContent(node);
707
+ if (node.type === 'template_string')
708
+ return templateText(node);
709
+ if (!isConcatenation(node))
710
+ return undefined;
711
+ const parts = concatParts(node);
712
+ if (!parts[0] || !isStringNode(parts[0]))
713
+ return undefined;
714
+ return parts.map((p) => (isStringNode(p) ? urlText(p) : '{}')).join('');
715
+ }
716
+ function isConcatenation(node) {
717
+ return node.type === 'binary_expression' && node.childForFieldName('operator')?.text === '+';
718
+ }
719
+ /** Operands of a `+` chain, left to right. */
720
+ function concatParts(node) {
721
+ if (!isConcatenation(node))
722
+ return [node];
723
+ const left = node.childForFieldName('left');
724
+ const right = node.childForFieldName('right');
725
+ return left && right ? [...concatParts(left), ...concatParts(right)] : [node];
726
+ }
727
+ /** Template literal text as written, without backticks, each `${...}` replaced by `{}`. */
728
+ function templateText(node) {
729
+ let result = '';
730
+ for (const part of node.children) {
731
+ if (!part || part.type === '`')
732
+ continue;
733
+ result += part.type === 'template_substitution' ? '{}' : part.text;
734
+ }
735
+ return result;
736
+ }
737
+ /** Starts with `/`, `http(s)://`, or an interpolation followed by `/` (`${API}/users`). */
738
+ function isUrlLike(url) {
739
+ return /^(\/|https?:\/\/|\{\}\/)/.test(url);
740
+ }
741
+ /** Scopes inside `node`: `scopes` plus the one `node` opens, if any. */
742
+ function enterScope(node, scopes) {
743
+ if (node.type === 'program') {
744
+ return [{ fields: false, types: collectBindings(node, new Map()) }, ...scopes];
745
+ }
746
+ if (CLASS_DECLARATIONS.has(node.type)) {
747
+ const body = node.childForFieldName('body');
748
+ return body ? [{ fields: true, types: fieldTypes(body) }, ...scopes] : scopes;
749
+ }
750
+ const isFunction = FUNCTION_VALUES.has(node.type) || FUNCTION_DECLARATIONS.has(node.type) || node.type === 'method_definition';
751
+ if (!isFunction)
752
+ return scopes;
753
+ const types = new Map();
754
+ for (const param of parameters(node))
755
+ types.set(param.name, param.type ?? null);
756
+ const body = node.childForFieldName('body');
757
+ if (body)
758
+ collectBindings(body, types);
759
+ return [{ fields: false, types }, ...scopes];
760
+ }
761
+ /** Type of `name`: from the nearest class fields for `this.x`, else the nearest binding outside classes. */
762
+ function lookupType(scopes, name, fieldsOnly) {
763
+ for (const scope of scopes) {
764
+ if (scope.fields !== fieldsOnly)
765
+ continue;
766
+ if (fieldsOnly || scope.types.has(name))
767
+ return scope.types.get(name) ?? undefined;
768
+ }
769
+ return undefined;
770
+ }
771
+ /** Variables declared under `node`, without entering nested functions or classes. */
772
+ function collectBindings(node, types) {
773
+ for (const child of namedChildren(node)) {
774
+ if (FUNCTION_VALUES.has(child.type) || FUNCTION_DECLARATIONS.has(child.type) || CLASS_DECLARATIONS.has(child.type)) {
775
+ continue;
776
+ }
777
+ if (child.type === 'variable_declarator') {
778
+ const name = child.childForFieldName('name');
779
+ if (name?.type === 'identifier')
780
+ bind(types, name.text, declaredType(child));
781
+ }
782
+ else if (child.type === 'for_in_statement') {
783
+ const left = child.childForFieldName('left');
784
+ if (left?.type === 'identifier')
785
+ bind(types, left.text, undefined);
786
+ }
787
+ collectBindings(child, types);
788
+ }
789
+ return types;
790
+ }
791
+ /** A name declared twice with different types has no knowable type. */
792
+ function bind(types, name, type) {
793
+ const previous = types.get(name);
794
+ types.set(name, previous === undefined || previous === type ? (type ?? null) : null);
795
+ }
796
+ /** `const s: T = …`, `const s = new T()`, `const s = useMemo(() => new T(), [])`. */
797
+ function declaredType(node) {
798
+ const annotation = node.childForFieldName('type');
799
+ if (annotation)
800
+ return annotatedType(annotation);
801
+ const value = node.childForFieldName('value');
802
+ return value ? constructedType(value) ?? memoizedType(value) : undefined;
803
+ }
804
+ function constructedType(node) {
805
+ const inner = node.type === 'parenthesized_expression' ? namedChildren(node)[0] : node;
806
+ if (inner?.type !== 'new_expression')
807
+ return undefined;
808
+ const ctor = inner.childForFieldName('constructor');
809
+ return ctor ? simpleTypeName(ctor.text) : undefined;
810
+ }
811
+ function memoizedType(call) {
812
+ if (call.type !== 'call_expression' || call.childForFieldName('function')?.text !== 'useMemo')
813
+ return undefined;
814
+ const factory = callArguments(call)[0];
815
+ const body = factory?.type === 'arrow_function' ? factory.childForFieldName('body') : null;
816
+ return body ? constructedType(body) : undefined;
817
+ }
818
+ /** Field types of a class body, including TS parameter properties of its constructor. */
819
+ function fieldTypes(body) {
820
+ const types = new Map();
821
+ for (const member of namedChildren(body)) {
822
+ if (FIELD_MEMBERS.has(member.type)) {
823
+ const name = member.childForFieldName('name') ?? member.childForFieldName('property');
824
+ if (name)
825
+ bind(types, name.text, declaredType(member));
826
+ }
827
+ else if (member.type === 'method_definition' && nameOf(member) === 'constructor') {
828
+ for (const param of parameters(member)) {
829
+ if (param.property)
830
+ bind(types, param.name, param.type);
831
+ }
832
+ }
833
+ }
834
+ return types;
835
+ }
836
+ /** Simple identifier parameters of a function; destructured ones are skipped. */
837
+ function parameters(fn) {
838
+ const params = fn.childForFieldName('parameters') ?? fn.childForFieldName('parameter');
839
+ if (!params)
840
+ return [];
841
+ const list = params.type === 'formal_parameters' ? namedChildren(params) : [params];
842
+ const result = [];
843
+ for (const param of list) {
844
+ const pattern = param.childForFieldName('pattern') ?? param.childForFieldName('left') ?? param;
845
+ if (pattern.type !== 'identifier')
846
+ continue;
847
+ const annotation = param.childForFieldName('type');
848
+ const type = annotation ? annotatedType(annotation) : undefined;
849
+ const property = namedChildren(param).some((c) => c.type === 'accessibility_modifier') || hasKeyword(param, 'readonly');
850
+ result.push({ name: pattern.text, ...(type !== undefined ? { type } : {}), property });
851
+ }
852
+ return result;
853
+ }
854
+ /** `: ns.Repo<User> | null` → `Repo`; undefined for unions, arrays, literals... */
855
+ function annotatedType(annotation) {
856
+ const type = annotation.type === 'type_annotation' ? namedChildren(annotation)[0] : annotation;
857
+ if (!type)
858
+ return undefined;
859
+ const members = type.text
860
+ .split('|')
861
+ .map((t) => t.trim())
862
+ .filter((t) => t !== '' && t !== 'null' && t !== 'undefined');
863
+ return members.length === 1 && members[0] ? simpleTypeName(members[0]) : undefined;
864
+ }
865
+ /** `ns.Repo<User>` → `Repo`; undefined when not a (dotted) type name. */
866
+ function simpleTypeName(text) {
867
+ const base = text.replace(/<[\s\S]*>$/, '').trim();
868
+ if (!DOTTED_NAME.test(base))
869
+ return undefined;
870
+ return base.slice(base.lastIndexOf('.') + 1);
871
+ }
872
+ /** `svc` for `this.svc`; undefined for other expressions. */
873
+ function thisField(node) {
874
+ if (node.type !== 'member_expression' || node.childForFieldName('object')?.type !== 'this')
875
+ return undefined;
876
+ const property = node.childForFieldName('property');
877
+ return property?.type === 'property_identifier' ? property.text : undefined;
878
+ }
879
+ /** tree-sitter reads `await a.b<T>(x)` as a call of `await a.b`; returns `a.b`. */
880
+ function unwrapAwait(fn) {
881
+ return fn?.type === 'await_expression' ? (namedChildren(fn)[0] ?? null) : fn;
882
+ }
883
+ function hasKeyword(node, keyword) {
884
+ for (let i = 0; i < node.childCount; i++) {
885
+ const child = node.child(i);
886
+ if (child && !child.isNamed && child.type === keyword)
887
+ return true;
888
+ }
889
+ return false;
890
+ }
509
891
  //# sourceMappingURL=typescript.js.map