carrick 0.3.155 → 0.3.157

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 (125) hide show
  1. package/dist/contract.d.ts +22 -23
  2. package/dist/contract.js.map +1 -1
  3. package/dist/facts/enabled.d.ts +28 -0
  4. package/dist/facts/enabled.js +36 -0
  5. package/dist/facts/enabled.js.map +1 -1
  6. package/dist/facts/fetch.js +20 -8
  7. package/dist/facts/fetch.js.map +1 -1
  8. package/dist/facts/lines.d.ts +75 -2
  9. package/dist/facts/lines.js +302 -46
  10. package/dist/facts/lines.js.map +1 -1
  11. package/dist/facts/match.d.ts +2 -0
  12. package/dist/facts/match.js +189 -28
  13. package/dist/facts/match.js.map +1 -1
  14. package/dist/facts/peers.d.ts +2 -0
  15. package/dist/facts/peers.js +7 -2
  16. package/dist/facts/peers.js.map +1 -1
  17. package/dist/facts/store.d.ts +98 -2
  18. package/dist/facts/store.js +110 -12
  19. package/dist/facts/store.js.map +1 -1
  20. package/dist/held/client.d.ts +34 -0
  21. package/dist/held/client.js +85 -0
  22. package/dist/held/client.js.map +1 -0
  23. package/dist/held/daemon.d.ts +106 -0
  24. package/dist/held/daemon.js +307 -0
  25. package/dist/held/daemon.js.map +1 -0
  26. package/dist/held/engine.d.ts +50 -0
  27. package/dist/held/engine.js +166 -0
  28. package/dist/held/engine.js.map +1 -0
  29. package/dist/held/paths.d.ts +9 -0
  30. package/dist/held/paths.js +27 -0
  31. package/dist/held/paths.js.map +1 -0
  32. package/dist/held/place.d.ts +84 -0
  33. package/dist/held/place.js +198 -0
  34. package/dist/held/place.js.map +1 -0
  35. package/dist/held/registry.d.ts +22 -0
  36. package/dist/held/registry.js +72 -0
  37. package/dist/held/registry.js.map +1 -0
  38. package/dist/held/run.d.ts +2 -0
  39. package/dist/held/run.js +60 -0
  40. package/dist/held/run.js.map +1 -0
  41. package/dist/hook/bash-targets.d.ts +7 -2
  42. package/dist/hook/bash-targets.js +82 -27
  43. package/dist/hook/bash-targets.js.map +1 -1
  44. package/dist/hook/edit-flow.js +11 -7
  45. package/dist/hook/edit-flow.js.map +1 -1
  46. package/dist/hook/late.d.ts +1 -1
  47. package/dist/hook/late.js +3 -3
  48. package/dist/hook/late.js.map +1 -1
  49. package/dist/hook/lock.d.ts +26 -0
  50. package/dist/hook/lock.js +122 -0
  51. package/dist/hook/lock.js.map +1 -0
  52. package/dist/hook/post-bash.js +22 -7
  53. package/dist/hook/post-bash.js.map +1 -1
  54. package/dist/hook/post-read.js +9 -4
  55. package/dist/hook/post-read.js.map +1 -1
  56. package/dist/hook/probe.js +4 -2
  57. package/dist/hook/probe.js.map +1 -1
  58. package/dist/hook/read-answer.d.ts +23 -4
  59. package/dist/hook/read-answer.js +74 -19
  60. package/dist/hook/read-answer.js.map +1 -1
  61. package/dist/hook/rechecks.d.ts +2 -5
  62. package/dist/hook/rechecks.js +23 -130
  63. package/dist/hook/rechecks.js.map +1 -1
  64. package/dist/hook/similar.d.ts +13 -0
  65. package/dist/hook/similar.js +60 -0
  66. package/dist/hook/similar.js.map +1 -0
  67. package/dist/hook/stop-wait.d.ts +1 -0
  68. package/dist/hook/stop-wait.js +19 -24
  69. package/dist/hook/stop-wait.js.map +1 -1
  70. package/dist/hook/timings.d.ts +17 -3
  71. package/dist/hook/timings.js +10 -2
  72. package/dist/hook/timings.js.map +1 -1
  73. package/dist/lsp-frame.d.ts +20 -0
  74. package/dist/lsp-frame.js +47 -0
  75. package/dist/lsp-frame.js.map +1 -0
  76. package/dist/render.js +9 -3
  77. package/dist/render.js.map +1 -1
  78. package/dist/scan.d.ts +9 -0
  79. package/dist/scan.js +39 -8
  80. package/dist/scan.js.map +1 -1
  81. package/dist/server.js +4 -28
  82. package/dist/server.js.map +1 -1
  83. package/package.json +6 -6
  84. package/plugin/.claude-plugin/plugin.json +1 -1
  85. package/sidecar/dist/src/bundler.d.ts +5 -0
  86. package/sidecar/dist/src/bundler.js +20 -0
  87. package/sidecar/dist/src/capture/anchors.js +19 -4
  88. package/sidecar/dist/src/capture/api.d.ts +52 -4
  89. package/sidecar/dist/src/capture/check-probe.d.ts +17 -1
  90. package/sidecar/dist/src/capture/check-probe.js +39 -2
  91. package/sidecar/dist/src/capture/index.d.ts +12 -4
  92. package/sidecar/dist/src/capture/index.js +19 -3
  93. package/sidecar/dist/src/capture/result-label.js +3 -1
  94. package/sidecar/dist/src/capture/self-check.js +12 -31
  95. package/sidecar/dist/src/capture/serialised-arms.d.ts +27 -0
  96. package/sidecar/dist/src/capture/serialised-arms.js +76 -0
  97. package/sidecar/dist/src/capture/site-node.d.ts +17 -0
  98. package/sidecar/dist/src/capture/site-node.js +36 -0
  99. package/sidecar/dist/src/capture/stub-resolution.d.ts +63 -0
  100. package/sidecar/dist/src/capture/stub-resolution.js +102 -0
  101. package/sidecar/dist/src/capture/type-reasons.json +78 -0
  102. package/sidecar/dist/src/capture/unresolved.js +8 -1
  103. package/sidecar/dist/src/definition-resolver.d.ts +18 -9
  104. package/sidecar/dist/src/definition-resolver.js +66 -42
  105. package/sidecar/dist/src/engine-stamp.json +1 -0
  106. package/sidecar/dist/src/held-shadow.d.ts +60 -0
  107. package/sidecar/dist/src/held-shadow.js +222 -0
  108. package/sidecar/dist/src/index.js +47 -1
  109. package/sidecar/dist/src/library-claims.d.ts +3 -1
  110. package/sidecar/dist/src/library-claims.js +79 -3
  111. package/sidecar/dist/src/retype.js +1 -61
  112. package/sidecar/dist/src/type-home.d.ts +42 -0
  113. package/sidecar/dist/src/type-home.js +94 -0
  114. package/sidecar/dist/src/type-inferrer.d.ts +245 -28
  115. package/sidecar/dist/src/type-inferrer.js +938 -192
  116. package/sidecar/dist/src/type-parameters.d.ts +41 -0
  117. package/sidecar/dist/src/type-parameters.js +126 -0
  118. package/sidecar/dist/src/type-structural-expander.d.ts +1 -11
  119. package/sidecar/dist/src/type-structural-expander.js +9 -1
  120. package/sidecar/dist/src/types.d.ts +132 -20
  121. package/sidecar/dist/src/validators.d.ts +450 -244
  122. package/sidecar/dist/src/validators.js +27 -1
  123. package/dist/hook/lead.d.ts +0 -13
  124. package/dist/hook/lead.js +0 -39
  125. package/dist/hook/lead.js.map +0 -1
@@ -33,15 +33,17 @@ import { callInto, calledFunction, narrowByArguments } from './argument-modes.js
33
33
  import { functionAtLine } from './function-line-index.js';
34
34
  import { attributedDeclaration, installedPackageOf } from './declaration-attribution.js';
35
35
  import { endLineOf, startLineOf } from './line-index.js';
36
+ import { declaredTypeName, homeOfSchemaValue, homeOfTypeDeclaration, isTypeSpaceDeclaration } from './type-home.js';
36
37
  import { callsOf, descendantsOf, descendantsOnLine, descendantsOnLines, wrap, wrapCompilerNode, } from './node-index.js';
37
38
  import { elapsedMs, inferTiming, phaseClock, timedPhase } from './infer-timing.js';
38
39
  import { importedNameOf, packageNameOf } from './library-claims.js';
39
- import { constituentsOf, isFrameworkMachinery, nodeByLocatorText, normalizeLocatorText, symbolDeclaredOutside, typeIsOrContainsMachinery, } from './capture/index.js';
40
+ import { callNamedBy, callResultNamesNoCall, constituentsOf, isFrameworkMachinery, nodeByLocatorText, serialisedConditionalType, normalizeLocatorText, symbolDeclaredOutside, typeIsOrContainsMachinery, wrapsValueTransparently, } from './capture/index.js';
40
41
  import { StatedParams } from './stated-params.js';
41
42
  import { bindingToleratesAbsence, handlerToleratesAbsentBody } from './absent-body.js';
42
43
  import { replaceFileText } from './program-files.js';
43
- import { loopElementPick } from './loop-element.js';
44
- import { classifyStatusCodes, httpStatus, statesNoBody, statesNoShape, statusKeyCode, statusTableOf, successEntries, } from './capture/index.js';
44
+ import { enclosingTypeParameterIn, instantiatedAtCall } from './type-parameters.js';
45
+ import { endsWithPath, loopElementPick } from './loop-element.js';
46
+ import { classifyStatusCodes, httpStatus, statesNoBody, statesNoShape, statusKeyCode, statusTableOf, successEntries, TYPE_REASONS, } from './capture/index.js';
45
47
  import { addedDiagnostics, applyInsertions, fileDiagnostics, literalInsertions, mapBack, mapForward, normalise, pathOf, } from './unwidened.js';
46
48
  import { expandTypeStructural, jsonWireType, } from './type-structural-expander.js';
47
49
  /**
@@ -158,18 +160,14 @@ const STATUS_MEMBER_NAMES = ['status', 'statusCode'];
158
160
  /** An error or redirect send carries no body the route's contract describes. */
159
161
  const isDroppedResponseStatus = (status) => status === 'error' || status === 'redirect';
160
162
  /**
161
- * The reasons an `unknown` answer is a decision, not a failure to read: the
162
- * list `DECIDED_ABSTAIN_REASONS` in `src/engine/type_compat_v2.rs` holds
163
- * final. A stated reply never replaces one (carrick#2674).
163
+ * The reasons an `unknown` answer is a decision, not a failure to read, on the
164
+ * response path that reads this set: the words `capture/type-reasons.json`
165
+ * marks `always` (carrick#4231). A stated reply never replaces one
166
+ * (carrick#2674).
164
167
  */
165
- const DECIDED_ABSTAIN_REASONS = new Set([
166
- 'no_success_payload',
167
- 'no_request_body',
168
- 'projected_value_only',
169
- 'serialised_body_unread',
170
- 'body_built_by_callee',
171
- 'reshaped_by_callback',
172
- ]);
168
+ export const DECIDED_ABSTAIN_REASONS = new Set(Object.entries(TYPE_REASONS)
169
+ .filter(([, reason]) => reason.decided === 'always')
170
+ .map(([word]) => word));
173
171
  /** The provenance sentence for each reason a branch was not read. */
174
172
  const SERIALISED_BODY_UNREAD_DETAIL = {
175
173
  prebuilt: 'A return hands back a status and body built somewhere else, such as a variable or a field of another result, so the value in its body was not read.',
@@ -273,6 +271,17 @@ function isBareStringText(text) {
273
271
  return (members.includes('string') &&
274
272
  members.every((member) => member === 'string' || member === 'null' || member === 'undefined'));
275
273
  }
274
+ /**
275
+ * carrick#1842: `string` cannot tell a body read as raw text from a JSON body
276
+ * that is a string, and raw text states no structural contract. The row says
277
+ * which it is, so the check phase reads the pair unverifiable instead of
278
+ * comparing `string` with the other side's body. `rawText` is the caller's
279
+ * decision that this body is a bare string filled by a text read.
280
+ */
281
+ function markRawTextRead(inferred, rawText) {
282
+ if (rawText)
283
+ inferred.raw_text_read = true;
284
+ }
276
285
  /**
277
286
  * How many readings one batch may make (carrick#2629). A count, not a time,
278
287
  * so whether a reading is made never depends on the machine's load: a reading
@@ -313,6 +322,11 @@ export class TypeInferrer {
313
322
  * unwidened reading re-reads from here (carrick#1516).
314
323
  */
315
324
  readNodes = new WeakMap();
325
+ /**
326
+ * The type each inferred type's text was printed from, where the builder
327
+ * named one. The open-parameter check (carrick#4201) reads it.
328
+ */
329
+ printedTypes = new WeakMap();
316
330
  unwidenedLimits;
317
331
  now;
318
332
  /**
@@ -617,7 +631,7 @@ export class TypeInferrer {
617
631
  isTheRowsOwnFunction(request, func) {
618
632
  if (startLineOf(func) === request.line_number)
619
633
  return true;
620
- return this.registrationAtLine(func.getSourceFile(), request.line_number)?.handler === func;
634
+ return this.registrationAtLine(func.getSourceFile(), request.line_number, request.route_path)?.handler === func;
621
635
  }
622
636
  /**
623
637
  * The declared type of a symbol the model named, found as the bundle finds
@@ -697,6 +711,24 @@ export class TypeInferrer {
697
711
  replaceFileText(pick.file, original.slice(0, pick.start) + pick.text + original.slice(pick.end));
698
712
  try {
699
713
  const result = this.inferRecordingNames(mapped, extractionConfig);
714
+ // carrick#4244: the spans were read in the rewritten file. Past the
715
+ // list they move back by `delta`; inside the list they name text the
716
+ // file as written does not hold, so they are dropped.
717
+ if (result?.read_spans) {
718
+ const file = pick.file.getFilePath();
719
+ const listEnd = pick.start + pick.text.length;
720
+ const kept = result.read_spans.flatMap((span) => {
721
+ if (span.file_path !== file || span.end <= pick.start)
722
+ return [span];
723
+ if (span.start >= listEnd)
724
+ return [{ ...span, start: span.start - delta, end: span.end - delta }];
725
+ return [];
726
+ });
727
+ if (kept.length > 0)
728
+ result.read_spans = kept;
729
+ else
730
+ delete result.read_spans;
731
+ }
700
732
  this.log(`Typed ${request.file_path}:${request.line_number} (${request.infer_kind}) for loop element ` +
701
733
  `${pick.index + 1} of ${pick.of}: ${request.route_path}`);
702
734
  return result;
@@ -952,13 +984,15 @@ export class TypeInferrer {
952
984
  }
953
985
  switch (request.infer_kind) {
954
986
  case 'function_return':
955
- return this.inferFunctionReturn(sourceFile, request, extractionConfig);
987
+ return this.withoutOpenTypeParameter(request, this.inferFunctionReturn(sourceFile, request, extractionConfig));
956
988
  case 'response_body':
957
- return this.withStatedReply(sourceFile, request, this.inferResponseBody(sourceFile, request, extractionConfig));
989
+ // Checked before a stated reply is weighed: the decided answer stands
990
+ // against one (`DECIDED_ABSTAIN_REASONS`).
991
+ return this.withStatedReply(sourceFile, request, this.withoutOpenTypeParameter(request, this.inferResponseBody(sourceFile, request, extractionConfig)));
958
992
  case 'call_result':
959
- return this.inferCallResult(sourceFile, request, extractionConfig);
993
+ return this.withoutOpenTypeParameter(request, this.inferCallResult(sourceFile, request, extractionConfig));
960
994
  case 'variable':
961
- return this.inferVariable(sourceFile, request, extractionConfig);
995
+ return this.withoutOpenTypeParameter(request, this.inferVariable(sourceFile, request, extractionConfig));
962
996
  case 'expression':
963
997
  return this.inferExpression(sourceFile, request, extractionConfig);
964
998
  case 'request_body':
@@ -976,6 +1010,55 @@ export class TypeInferrer {
976
1010
  return null;
977
1011
  }
978
1012
  }
1013
+ /**
1014
+ * carrick#4201: a response, call result, return or variable read inside a
1015
+ * generic function whose type still holds that function's (or its class's)
1016
+ * type parameter states no type of its own: only the function's callers set
1017
+ * it. The answer is a decided `unknown` with `bound_by_callers`, never a
1018
+ * type naming the parameter. The kinds that describe the generic function
1019
+ * itself (`function_param`, `signature_return`, `receiver_type`) never come
1020
+ * here: `T` belongs there.
1021
+ *
1022
+ * The read is anchored inside the node the answer was read from, so a
1023
+ * return read at the function finds the function's own parameters
1024
+ * (`enclosingTypeParameterIn` starts from the anchor's parent).
1025
+ */
1026
+ withoutOpenTypeParameter(request, inferred) {
1027
+ if (!inferred)
1028
+ return inferred;
1029
+ const printed = this.printedTypes.get(inferred);
1030
+ const node = this.readNodes.get(inferred.source_location);
1031
+ if (!printed || !node)
1032
+ return inferred;
1033
+ const open = this.openTypeParameterAt(printed, node);
1034
+ return open === undefined ? inferred : this.boundByCallers(request, inferred.source_location, open);
1035
+ }
1036
+ /**
1037
+ * The name of a type parameter `type` holds that a declaration around
1038
+ * `node`, or `node` itself, declares. A function or class read at itself is
1039
+ * anchored inside it: `enclosingTypeParameterIn` starts from the anchor's
1040
+ * parent, so it would miss the declaration's own parameters.
1041
+ */
1042
+ openTypeParameterAt(type, node) {
1043
+ const read = node.compilerNode;
1044
+ const inside = ts.isFunctionLike(read) || ts.isClassLike(read)
1045
+ ? (ts.forEachChild(read, (child) => child) ?? read)
1046
+ : read;
1047
+ const open = openAt(this.project.getTypeChecker().compilerObject, type.compilerType, inside);
1048
+ return open.kind === 'open' ? open.name : undefined;
1049
+ }
1050
+ /** The decided answer for a read holding the open type parameter `name` (carrick#4201). */
1051
+ boundByCallers(request, location, name) {
1052
+ this.log(`Read at ${request.file_path}:${request.line_number} holds the type parameter '${name}', ` +
1053
+ 'which only the callers of the function declaring it set; leaving it unknown');
1054
+ return this.decidedAbstain(request, location, {
1055
+ path: '',
1056
+ kind: 'unknown',
1057
+ reason: 'bound_by_callers',
1058
+ detail: `the type read here is the type parameter '${name}' of the generic function ` +
1059
+ `it sits in, which only that function's callers set, so this site states no type`,
1060
+ });
1061
+ }
979
1062
  /**
980
1063
  * The call a `call_result` locator names, located exactly as `infer` locates
981
1064
  * it (span, else expression text near a line). The retype check
@@ -1026,7 +1109,7 @@ export class TypeInferrer {
1026
1109
  const node = this.resolveTargetNode(sourceFile, request);
1027
1110
  if (!node)
1028
1111
  return request;
1029
- const atLine = this.registrationAtLine(sourceFile, request.line_number);
1112
+ const atLine = this.registrationAtLine(sourceFile, request.line_number, request.route_path);
1030
1113
  if (!atLine)
1031
1114
  return request;
1032
1115
  const within = (inner, outer) => inner.getPos() >= outer.getPos() && inner.getEnd() <= outer.getEnd();
@@ -1073,7 +1156,7 @@ export class TypeInferrer {
1073
1156
  // function at its line; the handler follows the options object. Where a
1074
1157
  // registration sits on the line, read the handler it hands in, as the
1075
1158
  // line-only `response_body` path does.
1076
- const atLine = this.registrationAtLine(sourceFile, request.line_number);
1159
+ const atLine = this.registrationAtLine(sourceFile, request.line_number, request.route_path);
1077
1160
  if (atLine) {
1078
1161
  this.log(`Line ${request.line_number} is a route registration; following handler return`);
1079
1162
  return this.buildFunctionReturnInferredType(request, atLine.handler, extractionConfig, true);
@@ -1175,9 +1258,14 @@ export class TypeInferrer {
1175
1258
  // response. There the recovery is restricted to an argument the SOURCE
1176
1259
  // annotates (`satisfies` / `as` / `<T>`): the developer stated the
1177
1260
  // contract, so it is a claim rather than a guess.
1261
+ // carrick#4269: a send that returns the reply it was called on
1262
+ // (`reply.send(x)`, `res.json(x)`) hands back the framework's own
1263
+ // parameter, which is transport whatever members it declares.
1264
+ const handsBackParameter = this.returnsHandlerParameterType(request, func, awaitedType);
1178
1265
  const machinery = unwrapResult.verifiedMachinery === true ||
1179
1266
  this.typeIsOrContainsResponseMachinery(awaitedType) ||
1180
- this.returnsLabelledSend(func);
1267
+ this.returnsLabelledSend(func) ||
1268
+ handsBackParameter;
1181
1269
  const unresolvable = awaitedType.isAny() || awaitedType.isUnknown();
1182
1270
  if (machinery || unresolvable) {
1183
1271
  const recovered = this.recoverPayloadFromReturnStatements(func, !machinery, this.wireFormatFor(request));
@@ -1186,6 +1274,23 @@ export class TypeInferrer {
1186
1274
  "contract; recovered the payload from the response helper's argument");
1187
1275
  return this.inferredFromRecoveredPayload(request, recovered);
1188
1276
  }
1277
+ if (handsBackParameter) {
1278
+ const declaredTop = this.sentValuesDeclaredTop(func);
1279
+ if (declaredTop) {
1280
+ this.log(`Return at ${request.file_path}:${request.line_number} sends a value its ` +
1281
+ `code declares \`${declaredTop}\`; that is the body's type`);
1282
+ const inferred = this.createInferredType(request, declaredTop, false, this.getNodeLocation(func));
1283
+ inferred.any_provenance = [
1284
+ {
1285
+ path: '',
1286
+ kind: declaredTop,
1287
+ reason: 'declared',
1288
+ detail: `the handler sends a value its code declares \`${declaredTop}\``,
1289
+ },
1290
+ ];
1291
+ return inferred;
1292
+ }
1293
+ }
1189
1294
  // Nothing recoverable. Reject a wrapper envelope that IS or CONTAINS
1190
1295
  // framework machinery (carrick#371): `withApiWrapper({ handler: () =>
1191
1296
  // ({ response: Response, error })})` resolves the handler's return to
@@ -1196,6 +1301,17 @@ export class TypeInferrer {
1196
1301
  this.log(`Return type at ${request.file_path}:${request.line_number} is or contains ` +
1197
1302
  'framework machinery (Response/Request-shaped); abstaining rather than ' +
1198
1303
  'capturing the wrapper envelope as a response contract');
1304
+ // carrick#4148: when every returned branch states an error or
1305
+ // redirect status, the handler has no success body: a decided
1306
+ // answer with its reason, not a blind unknown.
1307
+ if (this.everyReturnStatesDroppedStatus(func)) {
1308
+ return this.decidedAbstain(request, this.getNodeLocation(func), {
1309
+ path: '',
1310
+ kind: 'unknown',
1311
+ reason: 'no_success_payload',
1312
+ detail: 'every response this handler returns states an error or redirect status, so it publishes no success body',
1313
+ });
1314
+ }
1199
1315
  return null;
1200
1316
  }
1201
1317
  this.log(`Return type at ${request.file_path}:${request.line_number} resolved to ` +
@@ -1237,7 +1353,7 @@ export class TypeInferrer {
1237
1353
  return null;
1238
1354
  }
1239
1355
  const anchor = this.unwrapArrayLevels(awaitedType);
1240
- const inferred = this.createInferredType(request, typeString, isExplicit, this.getNodeLocation(func), unwrapResult.wasUnwrapped ? unwrapResult.typeString : undefined, this.primaryTypeSymbol(anchor.element), anchor.depth, this.primaryTypeSymbolSource(anchor.element), unwrapResult.wasUnwrapped ? unwrapResult.payloadType : awaitedType, anchor.element);
1356
+ const inferred = this.createInferredType(request, typeString, isExplicit, this.getNodeLocation(func), unwrapResult.wasUnwrapped ? unwrapResult.typeString : undefined, this.primaryTypeSymbol(anchor.element), anchor.depth, undefined, unwrapResult.wasUnwrapped ? unwrapResult.payloadType : awaitedType, anchor.element);
1241
1357
  if (provenance && provenance.length > 0) {
1242
1358
  inferred.any_provenance = provenance;
1243
1359
  }
@@ -1254,7 +1370,11 @@ export class TypeInferrer {
1254
1370
  unwrapResult.wasUnwrapped ? unwrapResult.payloadType : awaitedType,
1255
1371
  ]);
1256
1372
  }
1257
- return inferred;
1373
+ // carrick#4244: the annotation is what an annotated function's text was
1374
+ // read from; otherwise its returned expressions. A generator's contract
1375
+ // is what it yields, which no return statement holds: no reads.
1376
+ const generator = 'isGenerator' in func && typeof func.isGenerator === 'function' && func.isGenerator();
1377
+ return this.withReads(inferred, returnTypeNode ? [returnTypeNode] : generator ? [] : returned);
1258
1378
  }
1259
1379
  /**
1260
1380
  * Infer a function's return type for the signature hint. Unlike
@@ -1308,7 +1428,7 @@ export class TypeInferrer {
1308
1428
  // scanner re-aims the explicit bundle at the root symbol instead of
1309
1429
  // pasting this string, so the alias's definition stays self-contained.
1310
1430
  const anchor = this.unwrapArrayLevels(this.unwrapPromiseType(paramType));
1311
- const inferred = this.createInferredType(request, typeString, isExplicit, this.getNodeLocation(target.node), undefined, this.primaryTypeSymbol(anchor.element), anchor.depth, this.primaryTypeSymbolSource(anchor.element), paramType, anchor.element);
1431
+ const inferred = this.createInferredType(request, typeString, isExplicit, this.getNodeLocation(target.node), undefined, this.primaryTypeSymbol(anchor.element), anchor.depth, undefined, paramType, anchor.element);
1312
1432
  // carrick#2814: a subscriber that defaults its payload, or reads it only
1313
1433
  // in ways `undefined` survives, still works when none is sent.
1314
1434
  const binding = Node.isBindingElement(target.node) ? target.node : target.param;
@@ -1331,7 +1451,7 @@ export class TypeInferrer {
1331
1451
  withAbsentBodyMark(sourceFile, request, inferred) {
1332
1452
  if (!inferred)
1333
1453
  return inferred;
1334
- const atLine = this.registrationAtLine(sourceFile, request.line_number);
1454
+ const atLine = this.registrationAtLine(sourceFile, request.line_number, request.route_path);
1335
1455
  let registration = atLine?.registration;
1336
1456
  let handler = atLine?.handler;
1337
1457
  if (!handler) {
@@ -1410,14 +1530,10 @@ export class TypeInferrer {
1410
1530
  // away from the registration line. Follow the handler at that line before
1411
1531
  // the generic function-return fallback, which can't reach a handler more
1412
1532
  // than a couple of lines from the registration.
1413
- const atLine = this.registrationAtLine(sourceFile, request.line_number);
1533
+ const atLine = this.registrationAtLine(sourceFile, request.line_number, request.route_path);
1414
1534
  if (atLine) {
1415
- const declared = this.declaredResponseInferredType(request, atLine.registration);
1416
- if (declared) {
1417
- return declared;
1418
- }
1419
1535
  this.log(`Line ${request.line_number} is a route registration; following handler return`);
1420
- return (this.buildFunctionReturnInferredType(request, atLine.handler, extractionConfig, true) ?? this.labelledSendBodies(request, atLine.handler));
1536
+ return this.responseAtRegistration(request, atLine.registration, atLine.handler, extractionConfig);
1421
1537
  }
1422
1538
  // carrick#807: the request named an expression and the file holds none
1423
1539
  // that matches. Where its line declares the handler, that handler is
@@ -1471,12 +1587,8 @@ export class TypeInferrer {
1471
1587
  if (!Node.isCallExpression(node)) {
1472
1588
  const registryHandler = this.resolveRegisteredHandler(node);
1473
1589
  if (registryHandler) {
1474
- const declared = this.declaredResponseInferredType(request, node);
1475
- if (declared) {
1476
- return declared;
1477
- }
1478
1590
  this.log(`Span resolves to a route-registry object literal at ${request.file_path}:${request.line_number}; following handler return`);
1479
- return this.buildFunctionReturnInferredType(request, registryHandler, extractionConfig, true);
1591
+ return this.responseAtRegistration(request, node, registryHandler, extractionConfig);
1480
1592
  }
1481
1593
  }
1482
1594
  // carrick#1161: the locator anchors the HANDLER, not the response. When it
@@ -1520,39 +1632,35 @@ export class TypeInferrer {
1520
1632
  let payloadNode = node;
1521
1633
  if (Node.isCallExpression(node)) {
1522
1634
  const args = node.getArguments();
1523
- // A call that receives a function is a callback registration (e.g. an
1524
- // endpoint registration like `app.get('/path', handler)`) — its first
1525
- // argument is the route path, not a payload. The span locator falls
1526
- // back to exactly this shape when no payload expression was reported,
1527
- // so drilling here would put the path literal's type in the manifest.
1528
- // A call handed a function whose result is plain data is not a
1529
- // registration but the payload: `rows.map((r) => ({ ... }))` sends the
1530
- // list, not the callback's return (carrick#2055).
1531
- const registersCallback = args.some((arg) => Node.isArrowFunction(arg) || Node.isFunctionExpression(arg)) &&
1532
- !this.callResultIsPlainData(node);
1533
- if (registersCallback) {
1534
- // A registration that DECLARES its response contract in a schema needs
1535
- // no indirection: the declaration is the contract the framework
1536
- // serializes against, so it wins over whatever the handler happens to
1537
- // return.
1538
- const declared = this.declaredResponseInferredType(request, node);
1539
- if (declared) {
1540
- return declared;
1541
- }
1542
- // The locator lands on a route registration whose handler carries the
1543
- // response contract in its RETURN type — one indirection away. Follow
1544
- // the handler and infer its return instead of dropping the payload.
1635
+ // A registration is not a payload: its first argument is the route
1636
+ // path, and the span locator falls back to exactly this shape when no
1637
+ // payload expression was reported, so drilling would put the path
1638
+ // literal's type in the manifest. The route's response is what its
1639
+ // handler returns, read through the one registration reader, or
1640
+ // nothing where no handler can be followed.
1641
+ if (this.registersHandlerAt(node, request)) {
1545
1642
  const handler = this.resolveRegisteredHandler(node);
1546
1643
  if (handler) {
1547
1644
  this.log(`Span resolves to a callback-registration call at ${request.file_path}:${request.line_number}; following handler return`);
1548
- return this.buildFunctionReturnInferredType(request, handler, extractionConfig, true);
1645
+ return this.responseAtRegistration(request, node, handler, extractionConfig);
1549
1646
  }
1550
1647
  this.log(`Span resolves to a callback-registration call at ${request.file_path}:${request.line_number}; no payload to infer`);
1551
1648
  return null;
1552
1649
  }
1553
1650
  // A call whose result is a value the repo shapes is not a send: it is
1554
1651
  // the payload (carrick#1732), and drilling would publish its input.
1555
- if (args.length > 0 && !this.callResultIsPayload(node)) {
1652
+ // carrick#4283: a send that hands back a registration handler's own
1653
+ // reply is drilled whoever declares the reply.
1654
+ // carrick#4300, carrick#4341: a call that hands back the handler's
1655
+ // reply and is handed only a status (`reply.code(204)`) names no body,
1656
+ // whoever declares the reply, so it is decided before the drill guard.
1657
+ if (args.length > 0 && this.locatedStatusHandsBackReply(node, request)) {
1658
+ this.log(`Response payload at ${request.file_path}:${request.line_number} is a call that ` +
1659
+ 'hands back the reply and states only a status; it names no body');
1660
+ return null;
1661
+ }
1662
+ if (args.length > 0 &&
1663
+ (!this.callResultIsPayload(node) || this.locatedSendHandsBackReply(node, request))) {
1556
1664
  payloadNode = args[0];
1557
1665
  }
1558
1666
  }
@@ -1600,14 +1708,27 @@ export class TypeInferrer {
1600
1708
  typeString = this.expandResolvedTypeStructural(resolved, typeText(resolved, payloadNode), this.wireFormatFor(request));
1601
1709
  }
1602
1710
  const anchor = this.unwrapArrayLevels(this.unwrapPromiseType(payloadType));
1603
- const inferred = this.createInferredType(request, typeString, false, this.getNodeLocation(payloadNode), unwrapResult.wasUnwrapped ? unwrapResult.typeString : undefined, this.primaryTypeSymbol(anchor.element), anchor.depth, this.primaryTypeSymbolSource(anchor.element), unwrapResult.wasUnwrapped ? unwrapResult.payloadType : this.unwrapPromiseType(payloadType), anchor.element);
1604
- this.relateModelSymbol(request, inferred, [
1605
- unwrapResult.wasUnwrapped ? unwrapResult.payloadType : this.unwrapPromiseType(payloadType),
1606
- ]);
1711
+ const inferred = this.createInferredType(request, typeString, false, this.getNodeLocation(payloadNode), unwrapResult.wasUnwrapped ? unwrapResult.typeString : undefined, this.primaryTypeSymbol(anchor.element), anchor.depth, undefined, unwrapResult.wasUnwrapped ? unwrapResult.payloadType : this.unwrapPromiseType(payloadType), anchor.element);
1712
+ // carrick#2111: a located expression inside a callback an array or a
1713
+ // promise is handed (`row` in `rows.find((row) => …)`) reads the callback,
1714
+ // not the route, and a read of the wrong function must never displace the
1715
+ // symbol the model named. Such a callback was once read as a registration,
1716
+ // which decided the answer before this point (carrick#4379); it is asked
1717
+ // only where the callback is the function the row's line names.
1718
+ const owner = this.findContainingFunctionForNode(payloadNode);
1719
+ const ownerCall = owner?.getParent();
1720
+ const inIteration = owner !== undefined &&
1721
+ Node.isCallExpression(ownerCall) &&
1722
+ this.calledOnCollectionOrPromise(ownerCall);
1723
+ if (!inIteration || this.isTheRowsOwnFunction(request, owner)) {
1724
+ this.relateModelSymbol(request, inferred, [
1725
+ unwrapResult.wasUnwrapped ? unwrapResult.payloadType : this.unwrapPromiseType(payloadType),
1726
+ ]);
1727
+ }
1607
1728
  if (byArguments && !byArguments.type && byArguments.tested.length > 0) {
1608
1729
  this.addArgumentReads(inferred, byArguments.tested);
1609
1730
  }
1610
- return inferred;
1731
+ return this.withReads(inferred, [payloadNode]);
1611
1732
  }
1612
1733
  /**
1613
1734
  * The handler a module exports on `line`: a function that opens on exactly
@@ -1773,9 +1894,37 @@ export class TypeInferrer {
1773
1894
  const sourceFile = this.project.getSourceFile(request.file_path);
1774
1895
  if (!sourceFile)
1775
1896
  return false;
1776
- const handler = this.registrationAtLine(sourceFile, request.line_number)?.handler;
1897
+ const handler = this.registrationAtLine(sourceFile, request.line_number, request.route_path)?.handler;
1777
1898
  return handler !== undefined && owners.includes(handler.compilerNode);
1778
1899
  }
1900
+ /**
1901
+ * True when a located call hands back the reply of the registration handler
1902
+ * it sits in (`handsBackHandlerParameter`, `isRegisteredHandler`), is
1903
+ * handed a status-shaped value, read as a chain's status call is read
1904
+ * (`statusOfValue`, as `chainStatus` reads it), and does not take any
1905
+ * value in that slot (`takesAnyValue`): `reply.code(204)`,
1906
+ * `res.status(204)`. Such a call states a status and names no body
1907
+ * (carrick#4300); a send of a number (`reply.send(count)`) keeps its
1908
+ * reading. No method name is read.
1909
+ */
1910
+ locatedStatusHandsBackReply(call, request) {
1911
+ const handler = this.findContainingFunctionForNode(call);
1912
+ return (handler !== undefined &&
1913
+ this.statesOnlyStatus(call, handler) &&
1914
+ this.isRegisteredHandler(request, handler));
1915
+ }
1916
+ /**
1917
+ * The one status-only shape: a call that hands one of the handler's
1918
+ * parameters back, is handed a status-shaped value (`statusOfValue`), and
1919
+ * does not take any value in that slot (`takesAnyValue`). Read by the
1920
+ * located-call check and by `returnsHandlerParameterType` (carrick#4341).
1921
+ */
1922
+ statesOnlyStatus(call, handler) {
1923
+ return (Node.isCallExpression(call) &&
1924
+ this.statusOfValue(call.getArguments()[0]) !== 'undecided' &&
1925
+ !this.takesAnyValue(call) &&
1926
+ this.handsBackHandlerParameter(call, handler));
1927
+ }
1779
1928
  /**
1780
1929
  * True when a located call's own result is the route's payload, so the
1781
1930
  * transitional drill into its first argument must not run (carrick#1732).
@@ -1887,16 +2036,11 @@ export class TypeInferrer {
1887
2036
  // resolved symbol is the better answer and keeps its precedence.
1888
2037
  const stated = recovered.statedTypeNode;
1889
2038
  const writtenAnchor = resolvedSymbol === undefined && stated ? this.writtenAnchorOf(stated) : undefined;
1890
- // carrick#1819: a symbol the resolved type carries has a declaration file
1891
- // as much as one read off the annotation does.
1892
- const resolvedSource = resolvedSymbol !== undefined && recoveredAnchor
1893
- ? this.primaryTypeSymbolSource(recoveredAnchor.element)
1894
- : undefined;
1895
- const inferred = this.createInferredType(request, recovered.typeString, recovered.isExplicit, this.getNodeLocation(recovered.node), undefined, resolvedSymbol ?? writtenAnchor?.symbol, writtenAnchor ? writtenAnchor.depth : recoveredAnchor?.depth, writtenAnchor ? writtenAnchor.source : resolvedSource, recovered.anchorType, resolvedSymbol !== undefined ? recoveredAnchor?.element : undefined);
2039
+ const inferred = this.createInferredType(request, recovered.typeString, recovered.isExplicit, this.getNodeLocation(recovered.node), undefined, resolvedSymbol ?? writtenAnchor?.symbol, writtenAnchor ? writtenAnchor.depth : recoveredAnchor?.depth, writtenAnchor?.home, recovered.anchorType, resolvedSymbol !== undefined ? recoveredAnchor?.element : undefined);
1896
2040
  if (recovered.responseModes)
1897
2041
  inferred.response_modes = recovered.responseModes;
1898
2042
  this.relateModelSymbol(request, inferred, recovered.readTypes);
1899
- return inferred;
2043
+ return this.withReads(inferred, recovered.nodes);
1900
2044
  }
1901
2045
  /**
1902
2046
  * carrick#1161: type a route response from every send in the handler the
@@ -1940,7 +2084,7 @@ export class TypeInferrer {
1940
2084
  // line is outside that function says nothing about the function, so it
1941
2085
  // is "untied" (carrick#2463): only a located error or redirect send is
1942
2086
  // walked then, and only when a send survives the drop.
1943
- const tied = !!this.registrationAtLine(sourceFile, request.line_number) ||
2087
+ const tied = !!this.registrationAtLine(sourceFile, request.line_number, request.route_path) ||
1944
2088
  (func.getStartLineNumber() <= request.line_number &&
1945
2089
  request.line_number <= func.getEndLineNumber());
1946
2090
  const returnedBranches = this.responseReturnedExpressions(func).flatMap((expression) => this.expandResponseBranches(expression, 0));
@@ -2012,7 +2156,7 @@ export class TypeInferrer {
2012
2156
  // carrick#2372: the sends sit in an executor the route's handler calls,
2013
2157
  // and other routes may call it with other arguments. Keep only the sends
2014
2158
  // this route's arguments leave reachable.
2015
- const registered = this.registrationAtLine(sourceFile, request.line_number)?.handler;
2159
+ const registered = this.registrationAtLine(sourceFile, request.line_number, request.route_path)?.handler;
2016
2160
  const routeCall = registered && registered !== func ? callInto(registered, func) : undefined;
2017
2161
  let argumentReads = [];
2018
2162
  let narrowed = false;
@@ -2249,6 +2393,131 @@ export class TypeInferrer {
2249
2393
  * keys. Its result is transport whatever its type looks like, so the body
2250
2394
  * is read from the send's argument.
2251
2395
  */
2396
+ /**
2397
+ * True when the handler's awaited return is the type of one of its own
2398
+ * parameters: the reply a fluent send hands back (`reply.send(x)` returns
2399
+ * `reply`). That value is the object the framework passed in, never the
2400
+ * body.
2401
+ *
2402
+ * A type declared outside the repository is read this way whatever the
2403
+ * function returns it from (carrick#4269). A type the repository declares
2404
+ * is read this way only by its shape (carrick#4283): the function is a
2405
+ * route registration's handler, every return is a call that hands one of
2406
+ * its parameters back (`handsBackHandlerParameter`), and at least one of
2407
+ * them is given a value of any type (`takesAnyValue`) or states only a
2408
+ * status (`statesOnlyStatus`, carrick#4341). A function returning
2409
+ * its own options type, or a callback returning a builder's typed setter,
2410
+ * returns data.
2411
+ */
2412
+ returnsHandlerParameterType(request, func, awaitedType) {
2413
+ if (awaitedType.isAny() || awaitedType.isUnknown())
2414
+ return false;
2415
+ const symbol = awaitedType.getSymbol() ?? awaitedType.getAliasSymbol();
2416
+ if (this.symbolIsLibOrExternalOrigin(symbol)) {
2417
+ return func
2418
+ .getParameters()
2419
+ .some((parameter) => parameter.getType().compilerType === awaitedType.compilerType);
2420
+ }
2421
+ if (!this.isRegisteredHandler(request, func))
2422
+ return false;
2423
+ const branches = this.responseReturnedExpressions(func).flatMap((expression) => this.expandResponseBranches(expression, 0));
2424
+ const calls = branches.map((branch) => this.peelTransparentExpression(branch));
2425
+ return (calls.length > 0 &&
2426
+ calls.every((call) => this.handsBackHandlerParameter(call, func)) &&
2427
+ calls.some((call) => Node.isCallExpression(call) &&
2428
+ (this.takesAnyValue(call) || this.statesOnlyStatus(call, func))));
2429
+ }
2430
+ /**
2431
+ * True when `node` is a method call on a handler's own parameter that hands
2432
+ * that parameter back (carrick#4283): given at least one argument, its
2433
+ * result is the type of the object it was called on, and that type is one
2434
+ * of the handler's parameters (`reply.send(x)`, `reply.code(201)`).
2435
+ */
2436
+ handsBackHandlerParameter(node, handler) {
2437
+ if (!Node.isCallExpression(node) || node.getArguments().length === 0)
2438
+ return false;
2439
+ const callee = node.getExpression();
2440
+ if (!Node.isPropertyAccessExpression(callee))
2441
+ return false;
2442
+ const result = node.getType().compilerType;
2443
+ if (callee.getExpression().getType().compilerType !== result)
2444
+ return false;
2445
+ return handler.getParameters().some((parameter) => parameter.getType().compilerType === result);
2446
+ }
2447
+ /**
2448
+ * True when the first parameter of the signature `call` resolves to is
2449
+ * declared as taking any value (`typeNodeStatesNothing`): the slot of a
2450
+ * send (`send(payload?: unknown)`), never a typed setter (`set(v: string)`,
2451
+ * `code(status: number)`).
2452
+ */
2453
+ takesAnyValue(call) {
2454
+ const declaration = this.project.getTypeChecker().getResolvedSignature(call)?.getDeclaration();
2455
+ if (!declaration || !Node.isParametered(declaration))
2456
+ return false;
2457
+ const typeNode = declaration.getParameters()[0]?.getTypeNode();
2458
+ return typeNode !== undefined && this.typeNodeStatesNothing(typeNode);
2459
+ }
2460
+ /**
2461
+ * True when a located call is a send that hands back the reply of the
2462
+ * registration handler it sits in (carrick#4283), read by the same shape
2463
+ * `returnsHandlerParameterType` reads a returned send with.
2464
+ */
2465
+ locatedSendHandsBackReply(call, request) {
2466
+ const handler = this.findContainingFunctionForNode(call);
2467
+ return (handler !== undefined &&
2468
+ this.isRegisteredHandler(request, handler) &&
2469
+ this.handsBackHandlerParameter(call, handler) &&
2470
+ this.takesAnyValue(call));
2471
+ }
2472
+ /**
2473
+ * True when `func` is a route registration's handler: the one the
2474
+ * registration on the request's line hands in (found as
2475
+ * `registrationAtLine` finds it), or an inline function a registration
2476
+ * call is handed, for a request on a line inside it.
2477
+ */
2478
+ isRegisteredHandler(request, func) {
2479
+ const sourceFile = this.project.getSourceFile(request.file_path);
2480
+ if (sourceFile) {
2481
+ // carrick#4309: a line can register several routes (a chain); any of
2482
+ // their handlers is a registered handler.
2483
+ for (const { handler } of this.registrationsOnLine(sourceFile, request.line_number)) {
2484
+ if (handler === func)
2485
+ return true;
2486
+ }
2487
+ }
2488
+ const parent = func.getParent();
2489
+ return Node.isCallExpression(parent) && this.registrationHandlerAt(parent) === func;
2490
+ }
2491
+ /**
2492
+ * `any` or `unknown` when every returned send hands over a value whose code
2493
+ * declares that top type (`reply.send(request.body)` with `body: unknown`),
2494
+ * else `undefined`. The body is read where a send reads it: the slot a
2495
+ * label states, else the first argument.
2496
+ */
2497
+ sentValuesDeclaredTop(func) {
2498
+ const kinds = new Set();
2499
+ const branches = this.responseReturnedExpressions(func).flatMap((expression) => this.expandResponseBranches(expression, 0));
2500
+ if (branches.length === 0)
2501
+ return undefined;
2502
+ for (const branch of branches) {
2503
+ const call = this.peelTransparentExpression(branch);
2504
+ if (!Node.isCallExpression(call))
2505
+ return undefined;
2506
+ const labelled = this.statedParams.sendAt(call);
2507
+ const slot = labelled !== undefined && labelled !== 'setter' ? labelled.arg : 0;
2508
+ const arg = call.getArguments()[slot];
2509
+ if (!arg || Node.isSpreadElement(arg))
2510
+ return undefined;
2511
+ const sent = this.unwrapPromiseType(this.unwrapJsonStringifyArg(this.peelTransparentExpression(arg)).getType());
2512
+ if (sent.isAny())
2513
+ kinds.add('any');
2514
+ else if (sent.isUnknown())
2515
+ kinds.add('unknown');
2516
+ else
2517
+ return undefined;
2518
+ }
2519
+ return kinds.size === 1 ? [...kinds][0] : 'any';
2520
+ }
2252
2521
  returnsLabelledSend(func) {
2253
2522
  if (!this.statedParams.readsReplies)
2254
2523
  return false;
@@ -2312,9 +2581,9 @@ export class TypeInferrer {
2312
2581
  * A part the type lacks is a decided abstain, so the capture's own re-read
2313
2582
  * of the raw call does not publish the envelope in its place.
2314
2583
  */
2315
- labelledCallResult(request, callExpr, label) {
2584
+ labelledCallResult(request, callExpr, label, instantiated) {
2316
2585
  const location = this.getNodeLocation(callExpr);
2317
- const raw = callExpr.getType();
2586
+ const raw = instantiated ?? callExpr.getType();
2318
2587
  const awaited = this.awaitedBeyondPromise(raw) ?? this.unwrapPromiseType(raw);
2319
2588
  const missing = (what) => this.decidedAbstain(request, location, {
2320
2589
  path: '',
@@ -2374,28 +2643,56 @@ export class TypeInferrer {
2374
2643
  texts.push(text);
2375
2644
  }
2376
2645
  const anchor = read.length === 1 ? this.unwrapArrayLevels(this.unwrapPromiseType(read[0])) : undefined;
2377
- return this.createInferredType(request, texts.join(' | '), false, location, undefined, anchor ? this.primaryTypeSymbol(anchor.element) : undefined, anchor?.depth, anchor ? this.primaryTypeSymbolSource(anchor.element) : undefined, read.length === 1 ? this.unwrapPromiseType(read[0]) : undefined, anchor?.element);
2646
+ return this.createInferredType(request, texts.join(' | '), false, location, undefined, anchor ? this.primaryTypeSymbol(anchor.element) : undefined, anchor?.depth, undefined, read.length === 1 ? this.unwrapPromiseType(read[0]) : undefined, anchor?.element);
2647
+ }
2648
+ /**
2649
+ * The type of a call result read inside a maker, as the call `through_call`
2650
+ * names instantiates it (carrick#4375): the same read a built body takes,
2651
+ * `typeAtThroughCall`. Only a request that names a call is read this way; a
2652
+ * result with none keeps the reading it has. `undefined` where the read
2653
+ * holds nothing the call binds.
2654
+ */
2655
+ callResultAtThroughCall(node, request) {
2656
+ if (!request.through_call)
2657
+ return undefined;
2658
+ const atCaller = this.typeAtThroughCall(node, request);
2659
+ if (atCaller.kind === 'open')
2660
+ return { abstain: atCaller.abstain };
2661
+ if (atCaller.kind === 'as_read')
2662
+ return undefined;
2663
+ // The read is made inside the maker, where the parameter is open again.
2664
+ this.readNodes.delete(this.getNodeLocation(node));
2665
+ return { type: atCaller.type };
2378
2666
  }
2379
2667
  inferCallResult(sourceFile, request, extractionConfig) {
2380
2668
  const callExpr = this.resolveTargetCallExpression(sourceFile, request);
2381
2669
  // A call's result is read off the call. A locator that finds no call names
2382
2670
  // nothing this can read, and whatever other node its text overlaps is not
2383
- // the call's result (carrick#2056); the retype abstains on the same miss.
2384
- if (!callExpr) {
2385
- this.log(`Call-result locator at ${request.file_path}:${request.line_number} finds no call; leaving unresolved`);
2671
+ // the call's result (carrick#2056); the retype abstains on the same miss,
2672
+ // and the capture on the same rule (`callNamedBy`, carrick#4232).
2673
+ if (!callExpr || !callNamedBy(callExpr.compilerNode)) {
2674
+ this.log(`${callResultNamesNoCall(`${request.file_path}:${request.line_number}`)}; leaving unresolved`);
2386
2675
  return null;
2387
2676
  }
2388
2677
  // carrick#2818: the library store labels which part of this call's result
2389
2678
  // holds the response body. The label is the library's own statement, so it
2390
2679
  // is read before any wrapper rule of the service's extraction config.
2391
2680
  if (request.result) {
2392
- return this.labelledCallResult(request, callExpr, request.result);
2681
+ // carrick#4375: a result generic in a maker is read as the maker call
2682
+ // named in `through_call` instantiates it, by the path a built body takes.
2683
+ const labelled = this.callResultAtThroughCall(callExpr, request);
2684
+ if (labelled && 'abstain' in labelled)
2685
+ return labelled.abstain;
2686
+ return this.labelledCallResult(request, callExpr, request.result, labelled?.type);
2393
2687
  }
2394
2688
  // Walk up from the already-found call expression instead of re-searching
2395
2689
  const func = this.findContainingFunctionForNode(callExpr);
2396
2690
  const use = this.resolveCallResultTerminalNode(callExpr, func);
2397
2691
  const terminalNode = use.terminal;
2398
- const returnType = terminalNode.getType();
2692
+ const atCaller = this.callResultAtThroughCall(terminalNode, request);
2693
+ if (atCaller && 'abstain' in atCaller)
2694
+ return atCaller.abstain;
2695
+ const returnType = atCaller?.type ?? terminalNode.getType();
2399
2696
  let typeString = typeText(returnType, terminalNode);
2400
2697
  // Blueprint row N8: the type `typeString` prints, while it prints one.
2401
2698
  let printedType = this.unwrapPromiseType(returnType);
@@ -2600,6 +2897,48 @@ export class TypeInferrer {
2600
2897
  'payload a caller receives',
2601
2898
  });
2602
2899
  }
2900
+ // carrick#4185: the value is an object that holds transport machinery as
2901
+ // a member (`{ res: Response; json: Reply }`), a function's hand-back of
2902
+ // the response beside its parsed body. Judged against a producer's body,
2903
+ // every member of it reads as one the producer does not send, so it is
2904
+ // never published whole. The body is the member the function the call
2905
+ // makes fills from the response's body read, read off that function's
2906
+ // own returns and through the library-label reader, so one reader answers
2907
+ // which part of a call's value holds the body. A value it cannot decide
2908
+ // states no response contract.
2909
+ if (!unwrapResult.wasUnwrapped && !carrierPayload) {
2910
+ const published = printedType ?? this.unwrapPromiseType(returnType);
2911
+ if (this.typeIsOrContainsResponseMachinery(published) &&
2912
+ !this.typeIsFrameworkMachinery(published)) {
2913
+ const callValue = this.unwrapPromiseType(callExpr.getType());
2914
+ const member = published.compilerType === callValue.compilerType
2915
+ ? this.handBackBodyMember(callExpr)
2916
+ : undefined;
2917
+ if (member) {
2918
+ this.log(`Call result at ${where} is a hand-back object around the response; ` +
2919
+ `its body is the member '${member.name}' the called function fills from the body read`);
2920
+ const read = this.labelledCallResult(request, callExpr, { member: [member.name] });
2921
+ // carrick#4288: a member filled from a text read is raw text, as a
2922
+ // direct text read of the response is.
2923
+ markRawTextRead(read, member.textRead && isBareStringText(read.type_string));
2924
+ // carrick#4196: the answer names the member it read, so a caller
2925
+ // row whose owner never asked for a body reads this answer and no
2926
+ // other reading of the call.
2927
+ const decided = !(read.any_provenance ?? []).some((finding) => finding.path === '' && finding.reason === 'result_member_missing');
2928
+ return decided ? { ...read, body_member: member.name } : read;
2929
+ }
2930
+ this.log(`Call result at ${where} holds transport machinery as a member and no member of ` +
2931
+ 'it is decided as the body; this site states no response contract');
2932
+ return this.decidedAbstain(request, this.getNodeLocation(callExpr), {
2933
+ path: '',
2934
+ kind: 'unknown',
2935
+ reason: 'body_member_undecided',
2936
+ detail: "this call's result is an object that holds the transport response as one of its " +
2937
+ "members, and the called function's code does not decide which member holds the " +
2938
+ 'parsed body, so this site states no response contract',
2939
+ });
2940
+ }
2941
+ }
2603
2942
  typeString = this.unwrapPromise(typeString, returnType);
2604
2943
  // carrick#2594: the call's value is untyped (`Promise<any>`,
2605
2944
  // `Promise<unknown>`), and the function it is made in states its type:
@@ -2739,7 +3078,10 @@ export class TypeInferrer {
2739
3078
  }
2740
3079
  }
2741
3080
  }
2742
- const inferred = this.createInferredType(request, typeString, isExplicit, this.getNodeLocation(terminalNode), unwrapResult.wasUnwrapped ? unwrapResult.typeString : undefined, anchor ? this.primaryTypeSymbol(anchor.element) : undefined, anchor?.depth, anchor ? this.primaryTypeSymbolSource(anchor.element) : undefined, printedType, anchor?.element);
3081
+ const inferred = this.createInferredType(request, typeString, isExplicit, this.getNodeLocation(terminalNode), unwrapResult.wasUnwrapped ? unwrapResult.typeString : undefined, anchor ? this.primaryTypeSymbol(anchor.element) : undefined, anchor?.depth, undefined, printedType, anchor?.element,
3082
+ // carrick#2148: a carrier the call's reading left (carrick#1376) is the
3083
+ // transport's bookkeeping, not the body, so it has no home either.
3084
+ leftCarrier && !anchor ? null : undefined);
2743
3085
  // carrick#1749: say when the text is the source's own statement of the
2744
3086
  // body, and what that statement is rooted at, so the scanner can tell a
2745
3087
  // model symbol that names the body from one that names a part of it.
@@ -2754,14 +3096,8 @@ export class TypeInferrer {
2754
3096
  else {
2755
3097
  this.relateModelSymbolToArguments(request, inferred, callExpr, printedType);
2756
3098
  }
2757
- // carrick#1842: `string` cannot tell a body read as raw text from a JSON
2758
- // body that is a string, and raw text states no structural contract. The
2759
- // row says which it is, so the check phase can read the pair unverifiable
2760
- // instead of comparing `string` with the other side's body.
2761
- if (isBareStringText(typeString) &&
2762
- (this.textReadAtTerminal(callExpr, terminalNode) || this.callChoosesTextBody(callExpr))) {
2763
- inferred.raw_text_read = true;
2764
- }
3099
+ markRawTextRead(inferred, isBareStringText(typeString) &&
3100
+ (this.textReadAtTerminal(callExpr, terminalNode) || this.callChoosesTextBody(callExpr)));
2765
3101
  return inferred;
2766
3102
  }
2767
3103
  /**
@@ -2913,12 +3249,7 @@ export class TypeInferrer {
2913
3249
  * the read's value as it is: `await`, parentheses, `!`, a cast, `satisfies`.
2914
3250
  */
2915
3251
  wrapsReadTransparently(node) {
2916
- return (Node.isParenthesizedExpression(node) ||
2917
- Node.isAwaitExpression(node) ||
2918
- Node.isNonNullExpression(node) ||
2919
- Node.isAsExpression(node) ||
2920
- Node.isTypeAssertion(node) ||
2921
- Node.isSatisfiesExpression(node));
3252
+ return wrapsValueTransparently(node.compilerNode);
2922
3253
  }
2923
3254
  /**
2924
3255
  * A stated type with `any` or `unknown` written anywhere in it (`unknown`,
@@ -2992,16 +3323,17 @@ export class TypeInferrer {
2992
3323
  if (symbol?.isAlias()) {
2993
3324
  symbol = symbol.getAliasedSymbol() ?? symbol;
2994
3325
  }
2995
- const source = symbol?.getDeclarations()[0]?.getSourceFile().getFilePath();
3326
+ const machinery = this.isFrameworkMachinery(node.getType());
3327
+ const home = symbol && !machinery ? this.homeOfSymbol(nameNode.getText(), symbol) : undefined;
2996
3328
  const typeArguments = node.getTypeArguments().length;
2997
3329
  const rootRelation = symbol ? this.statedRootRelation(symbol, typeNode) : undefined;
2998
3330
  return {
2999
3331
  root: nameNode.getText(),
3000
- ...(source ? { root_source: source } : {}),
3332
+ ...(home ? { root_home: home } : {}),
3001
3333
  ...depthField,
3002
3334
  ...(typeArguments > 0 ? { root_type_arguments: typeArguments } : {}),
3003
3335
  ...(rootRelation ? { root_relation: rootRelation } : {}),
3004
- ...(this.isFrameworkMachinery(node.getType()) ? { machinery: true } : {}),
3336
+ ...(machinery ? { machinery: true } : {}),
3005
3337
  };
3006
3338
  }
3007
3339
  /**
@@ -3049,7 +3381,10 @@ export class TypeInferrer {
3049
3381
  if (!node) {
3050
3382
  return null;
3051
3383
  }
3052
- const type = node.getType();
3384
+ const atCaller = this.typeAtThroughCall(node, request);
3385
+ if (atCaller.kind === 'open')
3386
+ return atCaller.abstain;
3387
+ const type = atCaller.type;
3053
3388
  let typeString = typeText(type, node);
3054
3389
  // Apply extraction config
3055
3390
  const unwrapResult = this.unwrapTypeWithConfig(type, node, extractionConfig);
@@ -3066,7 +3401,96 @@ export class TypeInferrer {
3066
3401
  ? unwrapResult.payloadType
3067
3402
  : type;
3068
3403
  const anchor = this.unwrapArrayLevels(this.unwrapPromiseType(anchorSource));
3069
- return this.createInferredType(request, typeString, false, this.getNodeLocation(node), unwrapResult.wasUnwrapped ? unwrapResult.typeString : undefined, this.primaryTypeSymbol(anchor.element), anchor.depth, this.primaryTypeSymbolSource(anchor.element), this.unwrapPromiseType(anchorSource), anchor.element);
3404
+ return this.unwidenedAtCaller(node, atCaller, this.createInferredType(request, typeString, false, this.locationOfRead(node, atCaller), unwrapResult.wasUnwrapped ? unwrapResult.typeString : undefined, this.primaryTypeSymbol(anchor.element), anchor.depth, undefined, this.unwrapPromiseType(anchorSource), anchor.element));
3405
+ }
3406
+ /**
3407
+ * The type of `node`, a payload the scanner reads inside the wrapper that
3408
+ * builds it (carrick#4128), as the call it names in `through_call`
3409
+ * instantiates that wrapper: `{ body: item }` in `place<T>(item: T)` reads
3410
+ * `{ body: Book }` at `place(book)`. A type parameter the call leaves open
3411
+ * is never published: the answer is a decided `unknown`. A request with no
3412
+ * `through_call` (the wrapper's own row) names no call to bind one, so a
3413
+ * type parameter its read holds stays open and is never published either
3414
+ * (carrick#4164); a read that holds none is the type at `node` as it stands.
3415
+ */
3416
+ typeAtThroughCall(node, request) {
3417
+ const read = node.getType();
3418
+ const through = request.through_call;
3419
+ const checker = this.project.getTypeChecker();
3420
+ if (!through) {
3421
+ const open = openAt(checker.compilerObject, read.compilerType, node.compilerNode);
3422
+ if (open.kind === 'as_read')
3423
+ return { kind: 'as_read', type: read };
3424
+ this.log(`Payload at ${request.file_path}:${request.line_number} holds the type parameter '${open.name}' ` +
3425
+ 'and names no call that binds it; leaving it unknown');
3426
+ return {
3427
+ kind: 'open',
3428
+ abstain: this.decidedAbstain(request, this.getNodeLocation(node), {
3429
+ path: '',
3430
+ kind: 'unknown',
3431
+ reason: 'bound_by_callers',
3432
+ detail: `the body is built inside a generic function from its type parameter '${open.name}', ` +
3433
+ `which only that function's callers bind, so this site states no body type`,
3434
+ }),
3435
+ };
3436
+ }
3437
+ const callerFile = this.getSourceFile(through.file_path);
3438
+ const call = callerFile
3439
+ ? this.findCallExpressionAtSpan(callerFile, through.span_start, through.span_end)
3440
+ : undefined;
3441
+ // A call the span does not find reaches nothing: whatever the read holds
3442
+ // open stays open.
3443
+ const outcome = call
3444
+ ? instantiatedAtCall(checker.compilerObject, read.compilerType, node.compilerNode, call.compilerNode)
3445
+ : openAt(checker.compilerObject, read.compilerType, node.compilerNode);
3446
+ if (outcome.kind === 'as_read')
3447
+ return { kind: 'as_read', type: read };
3448
+ if (outcome.kind === 'instantiated' && call) {
3449
+ return {
3450
+ kind: 'instantiated',
3451
+ // Read through ts-morph's own checker, so the type is the wrapper the
3452
+ // rest of the inferrer reads.
3453
+ type: checker.getTypeOfSymbolAtLocation({ compilerSymbol: outcome.symbol }, call),
3454
+ };
3455
+ }
3456
+ const open = outcome.kind === 'open' ? outcome.name : '';
3457
+ this.log(`Payload at ${request.file_path}:${request.line_number} holds the type parameter '${open}', ` +
3458
+ 'which the call that reaches it does not bind; leaving it unknown');
3459
+ return {
3460
+ kind: 'open',
3461
+ abstain: this.decidedAbstain(request, this.getNodeLocation(node), {
3462
+ path: '',
3463
+ kind: 'unknown',
3464
+ reason: 'bound_by_callers',
3465
+ detail: `the body is built inside a generic function, and the call that reaches it leaves ` +
3466
+ `its type parameter '${open}' unset, so the call states no body type`,
3467
+ }),
3468
+ };
3469
+ }
3470
+ /**
3471
+ * Where a read's answer points. An instantiated read is not re-read
3472
+ * unwidened: that reading is made at the node, inside the generic
3473
+ * function, where the type parameter is open again (carrick#4128).
3474
+ */
3475
+ locationOfRead(node, read) {
3476
+ const location = this.getNodeLocation(node);
3477
+ if (read.kind === 'instantiated')
3478
+ this.readNodes.delete(location);
3479
+ return location;
3480
+ }
3481
+ /**
3482
+ * An instantiated read whose function writes a literal on its path is
3483
+ * marked as the unwidened reading not made: that reading is the one that
3484
+ * keeps such a literal (`kind: 'order'`) at its literal type, and without
3485
+ * it the body is judged on the widened type alone, so its pair abstains on
3486
+ * a mismatch rather than report one (carrick#2011).
3487
+ */
3488
+ unwidenedAtCaller(node, read, result) {
3489
+ if (read.kind === 'instantiated' &&
3490
+ pathOf(node).some((fn) => literalInsertions(fn, node).length > 0)) {
3491
+ result.unwidened_out_of_budget = true;
3492
+ }
3493
+ return result;
3070
3494
  }
3071
3495
  inferRequestBody(sourceFile, request, extractionConfig) {
3072
3496
  let located = this.resolveTargetNode(sourceFile, request);
@@ -3076,7 +3500,7 @@ export class TypeInferrer {
3076
3500
  // read the route's declared request contract — the handler's parameter
3077
3501
  // annotation, the registration's schema, or the first typed request
3078
3502
  // expression in the body (`c.req.json<T>()`, `req.body as T`).
3079
- const atLine = this.registrationAtLine(sourceFile, request.line_number);
3503
+ const atLine = this.registrationAtLine(sourceFile, request.line_number, request.route_path);
3080
3504
  if (atLine) {
3081
3505
  const declared = this.declaredRequestContract(atLine.registration, atLine.handler);
3082
3506
  if (declared) {
@@ -3101,7 +3525,7 @@ export class TypeInferrer {
3101
3525
  // is kept only where a registration already had it.
3102
3526
  const typedRead = atLine ? this.inferRequestReadFromHandler(atLine.handler) : null;
3103
3527
  return typedRead
3104
- ? this.declaredRequestInferredType(request, { text: typedRead }, this.getNodeLocation(handler))
3528
+ ? this.declaredRequestInferredType(request, typedRead, this.getNodeLocation(handler))
3105
3529
  : null;
3106
3530
  }
3107
3531
  // Inline-handler registration (`app.post('/x', async (c) => { … })`) or a
@@ -3141,6 +3565,15 @@ export class TypeInferrer {
3141
3565
  this.log(`Route registration at ${request.file_path}:${request.line_number} has no typed request read; leaving unresolved`);
3142
3566
  return null;
3143
3567
  }
3568
+ // A span at a registration whose handler cannot be followed (a wrapper
3569
+ // call, a member reference) names no request expression either: reading
3570
+ // the call's own value would publish the server instance as the body.
3571
+ const locatedCall = this.unwrapExpressionNode(located);
3572
+ if (Node.isCallExpression(locatedCall) && this.registersHandlerAt(locatedCall, request)) {
3573
+ this.log(`Route registration at ${request.file_path}:${request.line_number}: no handler to follow; ` +
3574
+ 'leaving the request unresolved');
3575
+ return null;
3576
+ }
3144
3577
  // The locator resolved to an expression that is NOT the registration, but
3145
3578
  // the request's line still is one: this is the live producer shape, where
3146
3579
  // the analyzer reported a payload expression and the scanner sends it as a
@@ -3160,7 +3593,7 @@ export class TypeInferrer {
3160
3593
  // the typed request READ inside the handler body — is deliberately not
3161
3594
  // consulted here: that one is itself an expression, so the locator's own
3162
3595
  // expression stays authoritative when nothing is declared.
3163
- const declaredAt = this.registrationAtLine(sourceFile, request.line_number);
3596
+ const declaredAt = this.registrationAtLine(sourceFile, request.line_number, request.route_path);
3164
3597
  if (declaredAt) {
3165
3598
  const declared = this.declaredRequestContract(declaredAt.registration, declaredAt.handler);
3166
3599
  if (declared) {
@@ -3251,7 +3684,7 @@ export class TypeInferrer {
3251
3684
  else if (inCall.kind === 'body_type') {
3252
3685
  this.log(`Request locator at ${request.file_path}:${request.line_number} names ${inCall.from}; ` +
3253
3686
  "reading the body off the config variable's type");
3254
- return this.createInferredType(request, this.expandResolvedTypeStructural(inCall.type, typeText(inCall.type, inCall.at)), false, this.getNodeLocation(inCall.at), undefined, undefined, undefined, undefined, inCall.type);
3687
+ return this.withReads(this.createInferredType(request, this.expandResolvedTypeStructural(inCall.type, typeText(inCall.type, inCall.at)), false, this.getNodeLocation(inCall.at), undefined, undefined, undefined, undefined, inCall.type), [inCall.at]);
3255
3688
  }
3256
3689
  else if (inCall.kind === 'abstain') {
3257
3690
  this.log(`Request locator at ${request.file_path}:${request.line_number}: ${inCall.why}; leaving unresolved`);
@@ -3309,7 +3742,7 @@ export class TypeInferrer {
3309
3742
  if (validatedRead) {
3310
3743
  this.log(`Request locator at ${request.file_path}:${request.line_number} is a validated read ` +
3311
3744
  "of its registration's body schema; publishing the schema's input");
3312
- return this.declaredRequestInferredType(request, validatedRead, this.getNodeLocation(node));
3745
+ return this.declaredRequestInferredType(request, validatedRead, this.getNodeLocation(node), [node]);
3313
3746
  }
3314
3747
  // carrick#1166: a validated read of a part the registration's validator
3315
3748
  // binds and which is not a body (`valid('param')`) is not what a caller
@@ -3330,7 +3763,12 @@ export class TypeInferrer {
3330
3763
  });
3331
3764
  }
3332
3765
  }
3333
- const payloadType = node.getType();
3766
+ const atCaller = this.typeAtThroughCall(node, request);
3767
+ if (atCaller.kind === 'open')
3768
+ return atCaller.abstain;
3769
+ // carrick#4285: a conditional body (`x ? JSON.stringify(x) : null`) is the
3770
+ // union of its arms read as a direct `JSON.stringify` body is.
3771
+ const payloadType = this.serialisedConditionalPayload(node) ?? atCaller.type;
3334
3772
  let typeString = typeText(payloadType, node);
3335
3773
  let isExplicit = false;
3336
3774
  // Apply extraction config
@@ -3363,7 +3801,8 @@ export class TypeInferrer {
3363
3801
  // so an ancestor walk from `located` would miss it. `node` is the inner
3364
3802
  // expression whose ancestors include the `as T`, so the cast is recovered;
3365
3803
  // the typed-binding and untyped-control cases are unaffected.
3366
- const explicitType = this.extractExplicitTypeFromAncestor(node);
3804
+ const explicitTypeNode = this.explicitTypeNodeFromAncestor(node);
3805
+ const explicitType = explicitTypeNode ? this.expandAnnotationTypeNode(explicitTypeNode) : null;
3367
3806
  if (explicitType) {
3368
3807
  typeString = explicitType;
3369
3808
  isExplicit = true;
@@ -3385,7 +3824,7 @@ export class TypeInferrer {
3385
3824
  if (parsedWith) {
3386
3825
  this.log(`Request locator at ${request.file_path}:${request.line_number} is an untyped read ` +
3387
3826
  `its handler states a type for (${parsedWith.how}); publishing that type`);
3388
- return this.declaredRequestInferredType(request, parsedWith, this.getNodeLocation(node));
3827
+ return this.declaredRequestInferredType(request, parsedWith, this.getNodeLocation(node), [node]);
3389
3828
  }
3390
3829
  }
3391
3830
  // Publication guard (carrick#964): the locator landed on machinery — a
@@ -3402,11 +3841,11 @@ export class TypeInferrer {
3402
3841
  return null;
3403
3842
  }
3404
3843
  typeString = this.unwrapPromise(typeString, payloadType);
3405
- return this.createInferredType(request, typeString, isExplicit, this.getNodeLocation(node), unwrapResult.wasUnwrapped ? unwrapResult.typeString : undefined, undefined, undefined, undefined, explicitType
3844
+ return this.unwidenedAtCaller(node, atCaller, this.withReads(this.createInferredType(request, typeString, isExplicit, this.locationOfRead(node, atCaller), unwrapResult.wasUnwrapped ? unwrapResult.typeString : undefined, undefined, undefined, undefined, explicitType
3406
3845
  ? undefined
3407
3846
  : unwrapResult.wasUnwrapped
3408
3847
  ? unwrapResult.payloadType
3409
- : this.unwrapPromiseType(payloadType));
3848
+ : this.unwrapPromiseType(payloadType), undefined, explicitType && explicitTypeNode ? this.unwrapPromiseType(explicitTypeNode.getType()) : undefined), [node]));
3410
3849
  }
3411
3850
  // ===========================================================================
3412
3851
  // Call Result Resolution
@@ -4278,7 +4717,7 @@ export class TypeInferrer {
4278
4717
  const anchor = stated.typeNode
4279
4718
  ? this.unwrapArrayLevels(this.unwrapPromiseType(stated.typeNode.getType()))
4280
4719
  : undefined;
4281
- const inferred = this.createInferredType(request, stated.text, true, this.getNodeLocation(stated.at), undefined, anchor ? this.primaryTypeSymbol(anchor.element) : undefined, anchor?.depth, anchor ? this.primaryTypeSymbolSource(anchor.element) : undefined, stated.typeNode ? this.unwrapPromiseType(stated.typeNode.getType()) : undefined, anchor?.element);
4720
+ const inferred = this.createInferredType(request, stated.text, true, this.getNodeLocation(stated.at), undefined, anchor ? this.primaryTypeSymbol(anchor.element) : undefined, anchor?.depth, undefined, stated.typeNode ? this.unwrapPromiseType(stated.typeNode.getType()) : undefined, anchor?.element);
4282
4721
  if (stated.typeNode) {
4283
4722
  inferred.stated_body = this.statedRoot(stated.typeNode);
4284
4723
  }
@@ -4357,6 +4796,69 @@ export class TypeInferrer {
4357
4796
  * re-reading the raw call (`inference_decided_no_contract`,
4358
4797
  * engine/type_compat_v2.rs).
4359
4798
  */
4799
+ /**
4800
+ * carrick#4185: the member of the object a call's function hands back that
4801
+ * holds the response's parsed body, decided from that function's code:
4802
+ * every `return` of it is an object literal, and in each exactly one member
4803
+ * is filled from a platform whole-body read (`json: (await res.json()) as
4804
+ * Reply`), itself or through a `const` it initialises, and every return
4805
+ * names the same member. The member's name never decides it. A function
4806
+ * the service does not declare (a library, a declaration with no body)
4807
+ * decides nothing. `textRead` says every return fills it from a text read
4808
+ * (carrick#4288).
4809
+ */
4810
+ handBackBodyMember(callExpr) {
4811
+ const callee = calledFunction(callExpr);
4812
+ if (!callee || this.runtimeFile(callee.getSourceFile().compilerNode))
4813
+ return undefined;
4814
+ const returned = this.returnedExpressions(callee);
4815
+ if (returned.length === 0)
4816
+ return undefined;
4817
+ let textRead = true;
4818
+ const readsBody = (value) => {
4819
+ let inner = this.unwrapExpressionNode(value);
4820
+ if (Node.isIdentifier(inner) || Node.isShorthandPropertyAssignment(inner)) {
4821
+ const symbol = Node.isShorthandPropertyAssignment(inner)
4822
+ ? inner.getValueSymbol()
4823
+ : inner.getSymbol();
4824
+ const local = symbol?.getDeclarations()?.[0];
4825
+ if (!local ||
4826
+ !Node.isVariableDeclaration(local) ||
4827
+ local.getVariableStatement()?.getDeclarationKind() !== VariableDeclarationKind.Const) {
4828
+ return false;
4829
+ }
4830
+ inner = this.unwrapExpressionNode(local.getInitializer());
4831
+ }
4832
+ if (!Node.isCallExpression(inner) ||
4833
+ !this.isPlatformBodyRead(inner, WHOLE_BODY_READS, 'platform_only')) {
4834
+ return false;
4835
+ }
4836
+ textRead &&= this.isPlatformBodyRead(inner, TEXT_READ, 'platform_only');
4837
+ return true;
4838
+ };
4839
+ let decided;
4840
+ for (const expression of returned) {
4841
+ const literal = this.unwrapExpressionNode(expression);
4842
+ if (!Node.isObjectLiteralExpression(literal))
4843
+ return undefined;
4844
+ const holding = literal.getProperties().flatMap((property) => {
4845
+ if (Node.isPropertyAssignment(property)) {
4846
+ const value = property.getInitializer();
4847
+ return value && readsBody(value) ? [property.getName()] : [];
4848
+ }
4849
+ if (Node.isShorthandPropertyAssignment(property)) {
4850
+ return readsBody(property) ? [property.getName()] : [];
4851
+ }
4852
+ return [];
4853
+ });
4854
+ if (holding.length !== 1)
4855
+ return undefined;
4856
+ if (decided !== undefined && decided !== holding[0])
4857
+ return undefined;
4858
+ decided = holding[0];
4859
+ }
4860
+ return decided === undefined ? undefined : { name: decided, textRead };
4861
+ }
4360
4862
  transportAbstain(request, callExpr, detail = "what this call's result carries is transport that the service's wrapper " +
4361
4863
  'rules verify and read no payload out of (a library response object around the body), ' +
4362
4864
  'so this site states no response contract') {
@@ -5478,6 +5980,21 @@ export class TypeInferrer {
5478
5980
  }
5479
5981
  return this.unwrapExpressionNode(args[0]);
5480
5982
  }
5983
+ /**
5984
+ * The union of a conditional serialised body's arms (carrick#4285), or
5985
+ * undefined where `node` is no such conditional or the union holds a type
5986
+ * parameter, which only a caller binds.
5987
+ */
5988
+ serialisedConditionalPayload(node) {
5989
+ const checker = this.project.getTypeChecker().compilerObject;
5990
+ const union = serialisedConditionalType(checker, node.compilerNode);
5991
+ if (!union || openAt(checker, union, node.compilerNode).kind !== 'as_read') {
5992
+ return undefined;
5993
+ }
5994
+ // ts-morph has no public wrapper for a compiler type it did not hand out.
5995
+ const factory = node.getSourceFile()._context.compilerFactory;
5996
+ return factory.getType(union);
5997
+ }
5481
5998
  extractExplicitTypeFromAncestor(node) {
5482
5999
  const typeNode = this.explicitTypeNodeFromAncestor(node);
5483
6000
  return typeNode ? this.expandAnnotationTypeNode(typeNode) : null;
@@ -5951,6 +6468,16 @@ export class TypeInferrer {
5951
6468
  'takes its body, so the call sends no request body',
5952
6469
  });
5953
6470
  }
6471
+ /**
6472
+ * carrick#4148: the handler returns at least one expression and every
6473
+ * branch of every return is a send stating an error or redirect status.
6474
+ * A branch that states no status (or a computed one) makes this false.
6475
+ */
6476
+ everyReturnStatesDroppedStatus(func) {
6477
+ const branches = this.returnedExpressions(func).flatMap((expression) => this.expandResponseBranches(expression, 0));
6478
+ return (branches.length > 0 &&
6479
+ branches.every((branch) => isDroppedResponseStatus(this.responseSiteStatus(branch, true))));
6480
+ }
5954
6481
  /** An `unknown` answer the inferrer decided, carrying its reason at the root. */
5955
6482
  decidedAbstain(request, location, reason) {
5956
6483
  const abstain = this.createInferredType(request, 'unknown', false, location);
@@ -6789,7 +7316,13 @@ export class TypeInferrer {
6789
7316
  * `primary_type_symbol` so the manifest anchor no longer depends on the LLM.
6790
7317
  */
6791
7318
  primaryTypeSymbol(type) {
6792
- const name = this.anchorSymbolOf(type)?.getName();
7319
+ const symbol = this.anchorSymbolOf(type);
7320
+ let name = symbol?.getName();
7321
+ // A default export is named by the name it declares (carrick#4359).
7322
+ if (symbol && name === 'default') {
7323
+ const declaration = symbol.getDeclarations().find(isTypeSpaceDeclaration);
7324
+ name = declaration ? declaredTypeName(name, declaration) : undefined;
7325
+ }
6793
7326
  // Reject the compiler's synthetic names for anonymous shapes (`__type`,
6794
7327
  // `__object`, `__function`, …). They are not user-facing type names, so
6795
7328
  // they would be a meaningless — and non-resolvable — anchor.
@@ -6799,44 +7332,63 @@ export class TypeInferrer {
6799
7332
  return name;
6800
7333
  }
6801
7334
  /**
6802
- * Declaration file (absolute path) of the anchor symbol
6803
- * `primaryTypeSymbol` reports for this type, or `undefined` when the type
6804
- * has no user-facing anchor or no source declaration. Every path that
6805
- * reports the symbol reports this beside it (carrick#1819): it is where a
6806
- * reader finds the type an anchor names. The scanner's pub/sub two-anchor
6807
- * arbitration (carrick#413) also uses it to re-aim a demoted explicit
6808
- * bundle request: the bundler resolves a `SymbolRequest` only against
6809
- * declarations IN its `source_file`, so the request must point at the file
6810
- * that actually declares the tsc-witnessed payload type.
6811
- *
6812
- * The declarations read are those of the symbol the anchor is named from
6813
- * (`anchorSymbolOf`: the type's own symbol, or its alias's), so a name
6814
- * imported through a barrel reports the file that declares it, and a name
6815
- * two files declare reports the one this type resolves to. A declaration in
6816
- * an installed package or a TypeScript lib is reported as it is found, as
6817
- * an absolute path; what a reader is shown for it is the scanner's call.
6818
- *
6819
- * Only declaration kinds the bundler's `validateSymbols` can resolve
6820
- * (interface, type alias, class, enum, function, variable) count. A
6821
- * symbol's declaration list can also contain re-export machinery — a
6822
- * barrel's `ExportSpecifier` (`export { Foo } from './foo'`) points at a
6823
- * file that does not DECLARE the type, and a request re-aimed there would
6824
- * fail validation, turning a resolvable explicit type into `unknown`.
6825
- * With no declaring node, no source is reported and the arbitration
6826
- * fails closed to the explicit anchor.
6827
- */
6828
- primaryTypeSymbolSource(type) {
6829
- if (this.primaryTypeSymbol(type) === undefined) {
7335
+ * carrick#2148: where `type` is declared, as a reader would open it: the
7336
+ * name, the declaring file (absolute) and the 1-based line of the
7337
+ * declaration's name. Every answer's `type_home` comes from here.
7338
+ *
7339
+ * The type read is the named one: array levels are peeled, and so is a
7340
+ * `| null`/`| undefined` around exactly one other type (`Invoice | null`
7341
+ * is homed at `Invoice`). A type that already has a name is not peeled, so
7342
+ * an alias of a union keeps its own home. A union of several types has no
7343
+ * one home.
7344
+ *
7345
+ * The symbol is the one `primaryTypeSymbol` names (`anchorSymbolOf`), so a
7346
+ * name imported through a barrel is homed at the file that declares it and
7347
+ * an instantiated generic alias (`Page<Order>`) at `Page`. There is no home
7348
+ * for framework machinery, a `BUILTIN_ANCHOR_SYMBOLS` name, or where
7349
+ * `homeOfDeclaration` gives none.
7350
+ */
7351
+ typeHomeOf(type) {
7352
+ if (!type)
6830
7353
  return undefined;
7354
+ const MAX_HOME_PEELS = 10;
7355
+ let current = type;
7356
+ for (let peeled = 0; peeled < MAX_HOME_PEELS; peeled++) {
7357
+ if (this.primaryTypeSymbol(current) !== undefined)
7358
+ break;
7359
+ const element = current.getArrayElementType();
7360
+ if (element) {
7361
+ current = element;
7362
+ continue;
7363
+ }
7364
+ if (current.isUnion()) {
7365
+ const members = current.getUnionTypes();
7366
+ const named = members.filter((member) => !member.isNull() && !member.isUndefined());
7367
+ if (named.length === 1 && named.length < members.length) {
7368
+ current = named[0];
7369
+ continue;
7370
+ }
7371
+ }
7372
+ break;
6831
7373
  }
6832
- const decls = this.anchorSymbolOf(type)?.getDeclarations() ?? [];
6833
- const declaring = decls.find((d) => Node.isInterfaceDeclaration(d) ||
6834
- Node.isTypeAliasDeclaration(d) ||
6835
- Node.isClassDeclaration(d) ||
6836
- Node.isEnumDeclaration(d) ||
6837
- Node.isFunctionDeclaration(d) ||
6838
- Node.isVariableDeclaration(d));
6839
- return declaring?.getSourceFile().getFilePath();
7374
+ const name = this.primaryTypeSymbol(current);
7375
+ const symbol = this.anchorSymbolOf(current);
7376
+ if (name === undefined || !symbol || this.isFrameworkMachinery(current))
7377
+ return undefined;
7378
+ return this.homeOfSymbol(name, symbol);
7379
+ }
7380
+ /**
7381
+ * The home of `symbol` under the name a reader knows it by: its first
7382
+ * type-space declaration (interface, type alias, class, enum), by
7383
+ * `homeOfDeclaration`'s rule. A symbol declared only as a value has none.
7384
+ */
7385
+ homeOfSymbol(name, symbol) {
7386
+ const declaration = symbol.getDeclarations().find(isTypeSpaceDeclaration);
7387
+ return declaration ? this.homeOfDeclaration(name, declaration) : undefined;
7388
+ }
7389
+ /** `homeOfTypeDeclaration` in this service's program. */
7390
+ homeOfDeclaration(name, declaration) {
7391
+ return homeOfTypeDeclaration(name, declaration, this.project.getProgram().compilerObject);
6840
7392
  }
6841
7393
  /**
6842
7394
  * The anchor a `satisfies X` / `as X` / `<X>` annotation states IN SOURCE:
@@ -6893,18 +7445,16 @@ export class TypeInferrer {
6893
7445
  if (!symbol)
6894
7446
  return undefined;
6895
7447
  const resolved = symbol.getAliasedSymbol() ?? symbol;
6896
- const declaration = resolved
6897
- .getDeclarations()
6898
- .find((d) => Node.isTypeAliasDeclaration(d) ||
6899
- Node.isInterfaceDeclaration(d) ||
6900
- Node.isClassDeclaration(d) ||
6901
- Node.isEnumDeclaration(d));
7448
+ const declaration = resolved.getDeclarations().find(isTypeSpaceDeclaration);
6902
7449
  if (!declaration)
6903
7450
  return undefined;
6904
7451
  const sourceFile = declaration.getSourceFile();
6905
7452
  if (sourceFile.compilerNode.hasNoDefaultLib)
6906
7453
  return undefined;
6907
- return { symbol: name, source: sourceFile.getFilePath(), depth };
7454
+ const home = this.isFrameworkMachinery(declaration.getType())
7455
+ ? undefined
7456
+ : this.homeOfDeclaration(name, declaration);
7457
+ return { symbol: name, home, depth };
6908
7458
  }
6909
7459
  /**
6910
7460
  * Peel array levels off a resolved type: `TimelineEvent[]` → element
@@ -7137,18 +7687,82 @@ export class TypeInferrer {
7137
7687
  * (a validation-schema object passed alongside the handler) lives on the
7138
7688
  * registration node itself, so the schema anchors need both halves.
7139
7689
  */
7140
- registrationAtLine(sourceFile, line) {
7690
+ registrationAtLine(sourceFile, line, routePath) {
7691
+ let first;
7692
+ for (const found of this.registrationsOnLine(sourceFile, line)) {
7693
+ first ??= found;
7694
+ if (routePath === undefined)
7695
+ break;
7696
+ // carrick#4381: a line that registers several routes serves the one
7697
+ // whose own path the row's path ends with (the row's path holds the
7698
+ // mounts' prefix), compared by `endsWithPath` as a loop's element is.
7699
+ // A line none of whose registrations states that path as a literal
7700
+ // keeps the first.
7701
+ if (this.registrationStatesPath(found.registration, routePath))
7702
+ return found;
7703
+ }
7704
+ return first;
7705
+ }
7706
+ /** Whether a registration call's first argument is a string literal the route path ends with. */
7707
+ registrationStatesPath(registration, routePath) {
7708
+ if (!Node.isCallExpression(registration))
7709
+ return false;
7710
+ const arg = registration.getArguments()[0];
7711
+ if (!arg)
7712
+ return false;
7713
+ const literal = peelValueWrappers(arg);
7714
+ return ((Node.isStringLiteral(literal) || Node.isNoSubstitutionTemplateLiteral(literal)) &&
7715
+ endsWithPath(routePath, literal.getLiteralValue()));
7716
+ }
7717
+ /** Every registration that starts on `line`, in source order. */
7718
+ *registrationsOnLine(sourceFile, line) {
7141
7719
  for (const entry of descendantsOnLine(sourceFile, line)) {
7142
7720
  if (entry.kind === SyntaxKind.CallExpression ||
7143
7721
  entry.kind === SyntaxKind.ObjectLiteralExpression) {
7144
7722
  const node = wrap(sourceFile, entry);
7145
7723
  const handler = this.resolveRegisteredHandler(node);
7146
7724
  if (handler) {
7147
- return { registration: node, handler };
7725
+ yield { registration: node, handler };
7148
7726
  }
7149
7727
  }
7150
7728
  }
7151
- return undefined;
7729
+ }
7730
+ /**
7731
+ * Whether a call is a route registration, by one test for both sides: it is
7732
+ * handed an inline function and its result is not plain data (`rows.map(fn)`
7733
+ * sends the list), or the ask is located by span alone and the call names a
7734
+ * handler or is handed a callable after its first argument. A model-located
7735
+ * ask keeps today's reading, so `rows.map(toView)` is still a payload. A
7736
+ * call whose own result is a primitive is a value, not a registration
7737
+ * (`JSON.stringify(body, this.replacer)`).
7738
+ */
7739
+ registersHandlerAt(call, request) {
7740
+ if (this.callResultIsPlainData(call))
7741
+ return false;
7742
+ const args = call.getArguments();
7743
+ if (args.some((arg) => Node.isArrowFunction(arg) || Node.isFunctionExpression(arg))) {
7744
+ return true;
7745
+ }
7746
+ if (request.span_start === undefined || request.expression_text)
7747
+ return false;
7748
+ const own = call.getType();
7749
+ if (own.isString() || own.isNumber() || own.isBoolean() || own.isStringLiteral() ||
7750
+ own.isNumberLiteral() || own.isBooleanLiteral()) {
7751
+ return false;
7752
+ }
7753
+ return (this.handlerFromRegistrationCall(call) !== undefined ||
7754
+ args.slice(1).some((arg) => this.isCallableType(arg.getType())));
7755
+ }
7756
+ /**
7757
+ * A registration's response, read only from its handler: the contract the
7758
+ * registration declares, else what the handler returns, else the bodies it
7759
+ * sends through labelled sends. Shared by a line ask, a registry object and
7760
+ * a registration call.
7761
+ */
7762
+ responseAtRegistration(request, registration, handler, extractionConfig) {
7763
+ return (this.declaredResponseInferredType(request, registration) ??
7764
+ this.buildFunctionReturnInferredType(request, handler, extractionConfig, true) ??
7765
+ this.labelledSendBodies(request, handler));
7152
7766
  }
7153
7767
  /**
7154
7768
  * Follow a route-registration locator ONE indirection to the handler function.
@@ -7229,9 +7843,29 @@ export class TypeInferrer {
7229
7843
  * reading the first function read a middleware as the route. The path
7230
7844
  * literal is not function-valued, so it is skipped naturally. No callee-name
7231
7845
  * check: a call whose argument resolves to a function is structurally a
7232
- * registration regardless of the framework.
7846
+ * registration regardless of the framework, unless it is called on an array
7847
+ * or a promise (carrick#4379).
7233
7848
  */
7849
+ /**
7850
+ * carrick#4379: whether a call is made on an array or a promise (`rows.map(cb)`,
7851
+ * `rows.filter(cb)`, `pending.then(cb)`). Such a call hands its function to
7852
+ * an iteration or a continuation, never to a server or router, so the
7853
+ * function is no route handler and the call's result is the value to read.
7854
+ * Decided by the receiver's compiler type, so it names no method.
7855
+ */
7856
+ calledOnCollectionOrPromise(call) {
7857
+ const callee = call.getExpression();
7858
+ if (!Node.isPropertyAccessExpression(callee))
7859
+ return false;
7860
+ const receiver = callee.getExpression().getType().getNonNullableType();
7861
+ if (receiver.isArray() || receiver.isTuple() || receiver.getArrayElementType())
7862
+ return true;
7863
+ const then = receiver.getProperty('then');
7864
+ return !!then && this.isCallableType(then.getTypeAtLocation(call));
7865
+ }
7234
7866
  handlerFromRegistrationCall(call) {
7867
+ if (this.calledOnCollectionOrPromise(call))
7868
+ return undefined;
7235
7869
  for (const arg of [...call.getArguments()].reverse()) {
7236
7870
  const handler = this.asHandlerFunction(arg);
7237
7871
  if (handler) {
@@ -7504,6 +8138,16 @@ export class TypeInferrer {
7504
8138
  * at the first body read" without assuming which framework produced it.
7505
8139
  * Returns null (not a spurious type) for a genuinely payload-less handler.
7506
8140
  */
8141
+ /** The property access that reads a member straight off `cast`, parentheses aside. */
8142
+ memberReadOffCast(cast) {
8143
+ let outer = cast;
8144
+ while (Node.isParenthesizedExpression(outer.getParent()))
8145
+ outer = outer.getParentOrThrow();
8146
+ const parent = outer.getParent();
8147
+ return parent && Node.isPropertyAccessExpression(parent) && parent.getExpression() === outer
8148
+ ? parent
8149
+ : undefined;
8150
+ }
7507
8151
  inferRequestReadFromHandler(func) {
7508
8152
  const body = func.getBody();
7509
8153
  if (!body) {
@@ -7521,7 +8165,7 @@ export class TypeInferrer {
7521
8165
  if (typeArgs.length > 0) {
7522
8166
  const resolved = this.structuralTextFromTypeNode(typeArgs[0]);
7523
8167
  if (resolved) {
7524
- found = resolved;
8168
+ found = { text: resolved, type: typeArgs[0].getType(), reads: [descendant] };
7525
8169
  traversal.stop();
7526
8170
  return;
7527
8171
  }
@@ -7530,12 +8174,18 @@ export class TypeInferrer {
7530
8174
  // B. an `as T` cast (`req.body as TrackRequest`) or a typed binding
7531
8175
  // (`const b: TrackRequest = …`). Read the annotation/cast target.
7532
8176
  if (Node.isAsExpression(descendant)) {
8177
+ // A member read off the cast (`(req as unknown as { body: T }).body`)
8178
+ // reads that member: the cast's whole object is one level too many
8179
+ // (carrick#4212). The checker types the member access itself.
8180
+ const member = this.memberReadOffCast(descendant);
7533
8181
  const typeNode = descendant.getTypeNode();
7534
- const resolved = typeNode
7535
- ? this.structuralTextFromTypeNode(typeNode)
7536
- : null;
8182
+ const resolved = member
8183
+ ? this.structuralTextFromType(member.getType(), member)
8184
+ : typeNode
8185
+ ? this.structuralTextFromTypeNode(typeNode)
8186
+ : null;
7537
8187
  if (resolved) {
7538
- found = resolved;
8188
+ found = { text: resolved, type: (member ?? typeNode)?.getType(), reads: [member ?? descendant] };
7539
8189
  traversal.stop();
7540
8190
  return;
7541
8191
  }
@@ -7677,7 +8327,7 @@ export class TypeInferrer {
7677
8327
  if (statedText) {
7678
8328
  this.log(`Request at ${request.file_path}:${request.line_number} is the body its handler ` +
7679
8329
  'reads off the platform request, as the source types that read');
7680
- return this.createInferredType(request, statedText, true, this.getNodeLocation(read));
8330
+ return this.withReads(this.createInferredType(request, statedText, true, this.getNodeLocation(read), undefined, undefined, undefined, undefined, undefined, undefined, statedNode?.getType()), [read]);
7681
8331
  }
7682
8332
  const func = this.findContainingFunctionForNode(read);
7683
8333
  const validated = func
@@ -7686,7 +8336,7 @@ export class TypeInferrer {
7686
8336
  if (validated) {
7687
8337
  this.log(`Request at ${request.file_path}:${request.line_number} is the body its handler ` +
7688
8338
  `reads off the platform request and states a type for (${validated.how}); publishing that type`);
7689
- return this.declaredRequestInferredType(request, validated, this.getNodeLocation(read));
8339
+ return this.declaredRequestInferredType(request, validated, this.getNodeLocation(read), [read]);
7690
8340
  }
7691
8341
  return null;
7692
8342
  }
@@ -7775,7 +8425,7 @@ export class TypeInferrer {
7775
8425
  const node = this.unwrapExpressionNode(located);
7776
8426
  return this.registrationHandlerAt(node) ? node : undefined;
7777
8427
  }
7778
- return this.registrationAtLine(sourceFile, request.line_number)?.registration;
8428
+ return this.registrationAtLine(sourceFile, request.line_number, request.route_path)?.registration;
7779
8429
  }
7780
8430
  /**
7781
8431
  * Anchor (b) on the response side: the success-status contract declared in the
@@ -7790,7 +8440,10 @@ export class TypeInferrer {
7790
8440
  }
7791
8441
  this.log(`Route registration at ${request.file_path}:${request.line_number} declares its ` +
7792
8442
  'response schema; using the declared contract');
7793
- return this.createInferredType(request, declared.text, true, this.getNodeLocation(registration), undefined, undefined);
8443
+ const inferred = this.createInferredType(request, declared.text, true, this.getNodeLocation(registration), undefined, undefined, undefined, undefined, undefined, undefined, declared.type);
8444
+ if (declared.home)
8445
+ inferred.type_home = declared.home;
8446
+ return this.withReads(inferred, declared.reads ?? []);
7794
8447
  }
7795
8448
  /**
7796
8449
  * The request contract of a route registration, in anchor order: the
@@ -7804,8 +8457,7 @@ export class TypeInferrer {
7804
8457
  if (declared) {
7805
8458
  return declared;
7806
8459
  }
7807
- const read = this.inferRequestReadFromHandler(handler);
7808
- return read ? { text: read } : null;
8460
+ return this.inferRequestReadFromHandler(handler);
7809
8461
  }
7810
8462
  /**
7811
8463
  * carrick-cloud#1366, shape 1: the request contract of a parameter a KEYED
@@ -7834,6 +8486,7 @@ export class TypeInferrer {
7834
8486
  return null;
7835
8487
  const siblings = func.getParameters();
7836
8488
  const members = [];
8489
+ const keyedParams = [];
7837
8490
  const seen = new Set();
7838
8491
  let wholeBody;
7839
8492
  for (const sibling of siblings) {
@@ -7848,6 +8501,7 @@ export class TypeInferrer {
7848
8501
  if (seen.has(keyed.key))
7849
8502
  continue;
7850
8503
  seen.add(keyed.key);
8504
+ keyedParams.push(sibling);
7851
8505
  const optional = sibling.hasQuestionToken() || sibling.hasInitializer();
7852
8506
  let type = sibling.getType();
7853
8507
  if (optional)
@@ -7862,11 +8516,11 @@ export class TypeInferrer {
7862
8516
  return null;
7863
8517
  const keyedText = `{ ${members.join(' ')} }`;
7864
8518
  if (!wholeBody)
7865
- return { text: keyedText };
8519
+ return { text: keyedText, reads: keyedParams };
7866
8520
  const wholeType = wholeBody.getType();
7867
8521
  const wholeText = this.expandResolvedTypeStructural(wholeType, typeText(wholeType, wholeBody));
7868
8522
  const operand = /^\{[\s\S]*\}$/.test(wholeText) ? wholeText : `(${wholeText})`;
7869
- return { text: `${operand} & ${keyedText}` };
8523
+ return { text: `${operand} & ${keyedText}`, reads: [wholeBody, ...keyedParams] };
7870
8524
  }
7871
8525
  /**
7872
8526
  * The handler parameter a request locator names: the parameter itself, its
@@ -8592,7 +9246,7 @@ export class TypeInferrer {
8592
9246
  * An explicit request `InferredType` for a contract the route declares,
8593
9247
  * carrying the provenance the reading recorded.
8594
9248
  */
8595
- declaredRequestInferredType(request, contract, location) {
9249
+ declaredRequestInferredType(request, contract, location, reads = contract.reads ?? []) {
8596
9250
  if (contract.noRequestBody !== undefined) {
8597
9251
  this.log(`Route at ${request.file_path}:${request.line_number} states no request body: ${contract.noRequestBody}`);
8598
9252
  return this.decidedAbstain(request, location, {
@@ -8602,11 +9256,13 @@ export class TypeInferrer {
8602
9256
  detail: contract.noRequestBody,
8603
9257
  });
8604
9258
  }
8605
- const inferred = this.createInferredType(request, contract.text, true, location, undefined, undefined);
9259
+ const inferred = this.createInferredType(request, contract.text, true, location, undefined, undefined, undefined, undefined, undefined, undefined, contract.type);
9260
+ if (contract.home)
9261
+ inferred.type_home = contract.home;
8606
9262
  if (contract.provenance && contract.provenance.length > 0) {
8607
9263
  inferred.any_provenance = contract.provenance;
8608
9264
  }
8609
- return inferred;
9265
+ return this.withReads(inferred, reads);
8610
9266
  }
8611
9267
  /**
8612
9268
  * The request contract a route DECLARES, in anchor order: the handler's
@@ -8627,12 +9283,12 @@ export class TypeInferrer {
8627
9283
  if (stated?.kind === 'body') {
8628
9284
  const text = this.structuralTextFromType(stated.type, stated.at);
8629
9285
  if (text) {
8630
- return { text };
9286
+ return { text, type: stated.type, reads: [stated.at] };
8631
9287
  }
8632
9288
  }
8633
9289
  const annotated = this.requestBodyFromHandlerParams(handler);
8634
9290
  if (annotated) {
8635
- return { text: annotated };
9291
+ return annotated;
8636
9292
  }
8637
9293
  const schema = this.routeSchemaContract(registration, 'body') ??
8638
9294
  this.validatedBodyContract(registration);
@@ -8670,7 +9326,7 @@ export class TypeInferrer {
8670
9326
  const empty = !today || this.isEmptyResponseReading(today);
8671
9327
  if (reads && !empty && !this.statedParams.readsReturns)
8672
9328
  return today;
8673
- const at = this.registrationAtLine(sourceFile, request.line_number);
9329
+ const at = this.registrationAtLine(sourceFile, request.line_number, request.route_path);
8674
9330
  const handler = at?.handler ?? this.exportedFunctionOpeningOn(sourceFile, request.line_number);
8675
9331
  if (!handler)
8676
9332
  return today;
@@ -8686,6 +9342,11 @@ export class TypeInferrer {
8686
9342
  publishStatedReply(request, handler, stated, today, why) {
8687
9343
  const texts = [];
8688
9344
  for (const variant of stated.variants) {
9345
+ // A generic handler's reply parameter that holds its own type
9346
+ // parameter states no reply: only its callers set it (carrick#4201).
9347
+ const open = this.openTypeParameterAt(variant, handler);
9348
+ if (open !== undefined)
9349
+ return this.boundByCallers(request, this.getNodeLocation(handler), open);
8689
9350
  const text = this.structuralTextFromType(variant, stated.at);
8690
9351
  // A variant holding `any` or `unknown` is one the check refuses as an
8691
9352
  // anchor (`usable_inferred_text`): publishing it would fall back to the
@@ -8698,7 +9359,7 @@ export class TypeInferrer {
8698
9359
  if (today && today.type_string === printed)
8699
9360
  return today;
8700
9361
  this.log(`Route at ${request.file_path}:${request.line_number}: ${why}`);
8701
- return this.createInferredType(request, printed, true, this.getNodeLocation(handler));
9362
+ return this.withReads(this.createInferredType(request, printed, true, this.getNodeLocation(handler), undefined, undefined, undefined, undefined, undefined, undefined, stated.variants.length === 1 ? stated.variants[0] : undefined), [stated.at]);
8702
9363
  }
8703
9364
  /** Nothing read: `void`, or an `unknown` with no decided reason at its root. */
8704
9365
  isEmptyResponseReading(inferred) {
@@ -8750,7 +9411,7 @@ export class TypeInferrer {
8750
9411
  }
8751
9412
  const text = this.structuralTextFromType(bodyType, param);
8752
9413
  if (text) {
8753
- return text;
9414
+ return { text, type: bodyType, reads: [param.getTypeNode() ?? param] };
8754
9415
  }
8755
9416
  }
8756
9417
  return null;
@@ -8816,7 +9477,7 @@ export class TypeInferrer {
8816
9477
  for (const candidate of this.middlewareBodySchemaValues(registration)) {
8817
9478
  const declared = this.schemaContract(candidate, 'input');
8818
9479
  if (declared) {
8819
- return declared;
9480
+ return { ...declared, reads: [this.unwrapExpressionNode(candidate)] };
8820
9481
  }
8821
9482
  }
8822
9483
  return null;
@@ -9006,7 +9667,17 @@ export class TypeInferrer {
9006
9667
  return null;
9007
9668
  }
9008
9669
  const [first] = decided;
9009
- return { text: first.text, provenance: first.provenance, at: first.at, how: first.how, typeNode: first.typeNode };
9670
+ // carrick#2148 H3: a home only where every deciding schema is the same one.
9671
+ const homes = new Set(decided.map(({ home }) => (home ? `${home.file_path}:${home.line}` : '')));
9672
+ return {
9673
+ text: first.text,
9674
+ type: first.typeNode?.getType(),
9675
+ provenance: first.provenance,
9676
+ ...(first.home && homes.size === 1 ? { home: first.home } : {}),
9677
+ at: first.at,
9678
+ how: first.how,
9679
+ typeNode: first.typeNode,
9680
+ };
9010
9681
  }
9011
9682
  /**
9012
9683
  * What a call that takes the value at argument `index` states for it:
@@ -9017,7 +9688,14 @@ export class TypeInferrer {
9017
9688
  stateAtReceivingCall(call, index, reads, found, stateNode) {
9018
9689
  const contract = this.schemaHandedArgument(call, index);
9019
9690
  if (contract) {
9020
- found.push({ rank: 1, text: contract.text, provenance: contract.provenance, at: call, how: 'a schema it is handed to' });
9691
+ found.push({
9692
+ rank: 1,
9693
+ text: contract.text,
9694
+ provenance: contract.provenance,
9695
+ home: contract.home,
9696
+ at: call,
9697
+ how: 'a schema it is handed to',
9698
+ });
9021
9699
  return;
9022
9700
  }
9023
9701
  const passThrough = this.passThroughFunction(call, index);
@@ -9222,7 +9900,8 @@ export class TypeInferrer {
9222
9900
  if (!value) {
9223
9901
  return null;
9224
9902
  }
9225
- return this.schemaContract(value, part === 'body' ? 'input' : 'output');
9903
+ const declared = this.schemaContract(value, part === 'body' ? 'input' : 'output');
9904
+ return declared ? { ...declared, reads: [this.unwrapExpressionNode(value)] } : null;
9226
9905
  }
9227
9906
  /**
9228
9907
  * The value a route `schema` object declares for `part`, as a zero- or
@@ -9337,6 +10016,16 @@ export class TypeInferrer {
9337
10016
  * `unknown`.
9338
10017
  */
9339
10018
  schemaContract(value, direction) {
10019
+ const contract = this.schemaContractText(value, direction);
10020
+ if (!contract)
10021
+ return null;
10022
+ const home = homeOfSchemaValue(this.unwrapExpressionNode(value));
10023
+ return home ? { ...contract, home } : contract;
10024
+ }
10025
+ /**
10026
+ * `schemaContract`'s text and provenance, read off the schema's types.
10027
+ */
10028
+ schemaContractText(value, direction) {
9340
10029
  const node = this.unwrapExpressionNode(value);
9341
10030
  let schemaType;
9342
10031
  if (Node.isCallExpression(node)) {
@@ -9891,6 +10580,39 @@ export class TypeInferrer {
9891
10580
  // ===========================================================================
9892
10581
  // Result Building
9893
10582
  // ===========================================================================
10583
+ /**
10584
+ * carrick#4244: stamp the nodes `inferred`'s text was built from on it, as
10585
+ * `read_spans`. Called at each builder's return with exactly those nodes.
10586
+ * Offsets are taken now, as numbers, so a later rewrite of the file (the
10587
+ * unwidened reading) cannot move them, and a spread of the answer keeps
10588
+ * them. An answer whose text is bare `any`/`unknown`, a no-value type
10589
+ * (`void`, `undefined`, `never`) or empty has no value to place and gets
10590
+ * none, annotated or not; a decided abstain is built by
10591
+ * `decidedAbstain` and never passes through here. Outer parentheses are
10592
+ * peeled: `({ ... })` is the literal.
10593
+ */
10594
+ withReads(inferred, nodes) {
10595
+ if (/^\s*(any|unknown|void|undefined|never)?\s*$/.test(inferred.type_string))
10596
+ return inferred;
10597
+ const seen = new Set();
10598
+ const spans = [];
10599
+ for (const read of nodes) {
10600
+ if (!read)
10601
+ continue;
10602
+ let node = read;
10603
+ while (Node.isParenthesizedExpression(node))
10604
+ node = node.getExpression();
10605
+ const span = { file_path: node.getSourceFile().getFilePath(), start: node.getStart(), end: node.getEnd() };
10606
+ const key = `${span.file_path}\u0000${span.start}\u0000${span.end}`;
10607
+ if (seen.has(key))
10608
+ continue;
10609
+ seen.add(key);
10610
+ spans.push(span);
10611
+ }
10612
+ if (spans.length > 0)
10613
+ inferred.read_spans = spans;
10614
+ return inferred;
10615
+ }
9894
10616
  getNodeLocation(node) {
9895
10617
  const startLinePos = startLineOf(node);
9896
10618
  const endLinePos = endLineOf(node);
@@ -9904,10 +10626,10 @@ export class TypeInferrer {
9904
10626
  this.readNodes.set(location, node);
9905
10627
  return location;
9906
10628
  }
9907
- createInferredType(request, typeString, isExplicit, sourceLocation, payloadTypeString, primaryTypeSymbol, arrayDepth, primaryTypeSymbolSource, printedType, anchorType) {
10629
+ createInferredType(request, typeString, isExplicit, sourceLocation, payloadTypeString, primaryTypeSymbol, arrayDepth, writtenHome, printedType, anchorType, homeType) {
9908
10630
  const alias = request.alias ||
9909
10631
  this.generateAlias(request.file_path, request.line_number, request.infer_kind);
9910
- return {
10632
+ const inferred = {
9911
10633
  alias,
9912
10634
  type_string: typeString,
9913
10635
  is_explicit: isExplicit,
@@ -9920,13 +10642,32 @@ export class TypeInferrer {
9920
10642
  // depth join copies it onto the model's symbol when the symbols agree,
9921
10643
  // or, at a handler's send, when the element has no symbol to disagree.
9922
10644
  array_depth: arrayDepth !== undefined && arrayDepth > 0 ? arrayDepth : undefined,
9923
- // Same gate: a declaration source without an anchor symbol is useless.
9924
- primary_type_symbol_source: primaryTypeSymbol !== undefined ? primaryTypeSymbolSource : undefined,
10645
+ ...this.homeField(primaryTypeSymbol, writtenHome, anchorType, homeType === undefined ? printedType : homeType),
9925
10646
  ...(printedType && this.isFrameworkMachinery(printedType) ? { machinery: true } : {}),
9926
10647
  ...(primaryTypeSymbol !== undefined && anchorType && this.isFrameworkMachinery(anchorType)
9927
10648
  ? { anchor_machinery: true }
9928
10649
  : {}),
9929
10650
  };
10651
+ if (printedType)
10652
+ this.printedTypes.set(inferred, printedType);
10653
+ return inferred;
10654
+ }
10655
+ /**
10656
+ * carrick#2148: the `type_home` of an answer. Where the builder reports
10657
+ * `primary_type_symbol`, the home is that symbol's: read off the anchor
10658
+ * type the symbol was named from, or the annotation it was read off as
10659
+ * written (`writtenHome`), so it is that symbol's declaration and never
10660
+ * another type's. Where no symbol is reported, the home is the printed
10661
+ * type's (`typeHomeOf`), unless the builder passes `null`: the printed type
10662
+ * is one it deliberately anchors nothing on.
10663
+ */
10664
+ homeField(primaryTypeSymbol, writtenHome, anchorType, printedType) {
10665
+ const home = primaryTypeSymbol === undefined
10666
+ ? this.typeHomeOf(printedType ?? undefined)
10667
+ : anchorType
10668
+ ? this.typeHomeOf(anchorType)
10669
+ : writtenHome;
10670
+ return home ? { type_home: home } : {};
9930
10671
  }
9931
10672
  generateAlias(filePath, lineNumber, inferKind) {
9932
10673
  const fileName = filePath
@@ -9989,3 +10730,8 @@ function nodeAtSpan(span) {
9989
10730
  function isNullishType(type) {
9990
10731
  return type.isUndefined() || type.isNull() || type.getText() === 'void';
9991
10732
  }
10733
+ /** {@link instantiatedAtCall} with no call to read: a parameter `type` holds open stays open. */
10734
+ function openAt(checker, type, at) {
10735
+ const name = enclosingTypeParameterIn(checker, type, at);
10736
+ return name === undefined ? { kind: 'as_read' } : { kind: 'open', name };
10737
+ }