carrick 0.3.147 → 0.3.148

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "carrick",
3
- "version": "0.3.147",
3
+ "version": "0.3.148",
4
4
  "carrickCache": {
5
5
  "cache_version": 22,
6
6
  "intent_cache_version": 2
@@ -115,11 +115,11 @@
115
115
  "zod": "^3.23.0"
116
116
  },
117
117
  "optionalDependencies": {
118
- "@carrick-tools/cli-darwin-arm64": "0.3.147",
119
- "@carrick-tools/cli-darwin-x64": "0.3.147",
120
- "@carrick-tools/cli-linux-arm64": "0.3.147",
121
- "@carrick-tools/cli-linux-x64": "0.3.147",
122
- "@carrick-tools/cli-win32-x64": "0.3.147"
118
+ "@carrick-tools/cli-darwin-arm64": "0.3.148",
119
+ "@carrick-tools/cli-darwin-x64": "0.3.148",
120
+ "@carrick-tools/cli-linux-arm64": "0.3.148",
121
+ "@carrick-tools/cli-linux-x64": "0.3.148",
122
+ "@carrick-tools/cli-win32-x64": "0.3.148"
123
123
  },
124
124
  "devDependencies": {
125
125
  "@types/node": "^24.13.3"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "carrick",
3
3
  "description": "Claude Code plugin for Carrick, which indexes TypeScript codebases across service and repository boundaries. After each edit it adds the file's routes, calls, and cross-service type mismatches to the session, and it registers Carrick's language server. It pairs with the Carrick MCP server, which lets agents search functions by intent rather than name.",
4
- "version": "0.3.147",
4
+ "version": "0.3.148",
5
5
  "author": {
6
6
  "name": "Carrick",
7
7
  "email": "hello@carrick.tools"
@@ -38,6 +38,7 @@
38
38
  * caller's answers. An executor only one call reaches, or whose callers all
39
39
  * pass the same value, has no such mode.
40
40
  */
41
+ import { functionBodyOf, peelValueWrappers } from './function-body.js';
41
42
  import { Node, SyntaxKind } from 'ts-morph';
42
43
  import { stepsOnPath } from './failure-path.js';
43
44
  /** The function a call runs, when it has one body in the program. */
@@ -45,24 +46,7 @@ export function calledFunction(call) {
45
46
  let symbol = call.getExpression().getSymbol();
46
47
  if (symbol?.isAlias())
47
48
  symbol = symbol.getAliasedSymbol();
48
- const declarations = symbol?.getDeclarations() ?? [];
49
- if (declarations.length !== 1)
50
- return undefined;
51
- const [declaration] = declarations;
52
- if ((Node.isFunctionDeclaration(declaration) || Node.isMethodDeclaration(declaration)) &&
53
- declaration.getBody()) {
54
- return declaration;
55
- }
56
- if (Node.isVariableDeclaration(declaration) || Node.isPropertyAssignment(declaration)) {
57
- let initializer = declaration.getInitializer();
58
- while (initializer && (Node.isParenthesizedExpression(initializer) || Node.isAsExpression(initializer))) {
59
- initializer = initializer.getExpression();
60
- }
61
- if (initializer && (Node.isArrowFunction(initializer) || Node.isFunctionExpression(initializer))) {
62
- return initializer;
63
- }
64
- }
65
- return undefined;
49
+ return functionBodyOf(symbol?.getDeclarations() ?? []);
66
50
  }
67
51
  /** The one call in `caller` that runs `callee`, or `undefined` for none or several. */
68
52
  export function callInto(caller, callee) {
@@ -196,7 +180,7 @@ function bindArguments(callee, call) {
196
180
  const UNDEFINED = { kind: 'value', value: undefined };
197
181
  /** What one argument expression states. */
198
182
  function statedBy(arg) {
199
- const expression = peel(arg);
183
+ const expression = peelValueWrappers(arg);
200
184
  if (Node.isStringLiteral(expression) || Node.isNoSubstitutionTemplateLiteral(expression)) {
201
185
  return { kind: 'value', value: expression.getLiteralValue() };
202
186
  }
@@ -220,7 +204,7 @@ function statedBy(arg) {
220
204
  }
221
205
  /** What an argument states about one of its members, when it is an object literal. */
222
206
  function statedMember(arg, member) {
223
- const literal = peel(arg);
207
+ const literal = peelValueWrappers(arg);
224
208
  if (!Node.isObjectLiteralExpression(literal))
225
209
  return undefined;
226
210
  let found;
@@ -309,25 +293,15 @@ function isWritten(node) {
309
293
  }
310
294
  return false;
311
295
  }
312
- function peel(node) {
313
- let current = node;
314
- while (Node.isParenthesizedExpression(current) ||
315
- Node.isAsExpression(current) ||
316
- Node.isNonNullExpression(current) ||
317
- Node.isSatisfiesExpression(current)) {
318
- current = current.getExpression();
319
- }
320
- return current;
321
- }
322
296
  /** The entry a test operand reads, when it reads a stated value. */
323
297
  function entryOf(node, binding) {
324
- const operand = peel(node);
298
+ const operand = peelValueWrappers(node);
325
299
  if (Node.isIdentifier(operand)) {
326
300
  const symbol = operand.getSymbol();
327
301
  return symbol ? binding.direct.get(symbol) : undefined;
328
302
  }
329
303
  if (Node.isPropertyAccessExpression(operand)) {
330
- const object = peel(operand.getExpression());
304
+ const object = peelValueWrappers(operand.getExpression());
331
305
  const symbol = Node.isIdentifier(object) ? object.getSymbol() : undefined;
332
306
  return symbol ? binding.members.get(symbol)?.get(operand.getName()) : undefined;
333
307
  }
@@ -338,7 +312,7 @@ function statedOperand(node, binding) {
338
312
  }
339
313
  /** The literal a test operand is, when it is one. */
340
314
  function literalOperand(node) {
341
- const operand = peel(node);
315
+ const operand = peelValueWrappers(node);
342
316
  if (Node.isVoidExpression(operand))
343
317
  return UNDEFINED;
344
318
  if (Node.isStringLiteral(operand) ||
@@ -367,7 +341,7 @@ function compare(stated, literal, loose) {
367
341
  }
368
342
  /** True, false, or `undefined` when the stated arguments do not decide `condition`. */
369
343
  function evaluate(condition, binding) {
370
- const test = peel(condition);
344
+ const test = peelValueWrappers(condition);
371
345
  if (Node.isPrefixUnaryExpression(test) && test.getOperatorToken() === SyntaxKind.ExclamationToken) {
372
346
  const inner = evaluate(test.getOperand(), binding);
373
347
  return inner === undefined ? undefined : !inner;
@@ -6,7 +6,7 @@ import { Node, ts, } from 'ts-morph';
6
6
  import * as path from 'node:path';
7
7
  import * as fs from 'node:fs';
8
8
  import { expandTypeStructural, } from './type-structural-expander.js';
9
- import { externalImportsOf, isExternalOrigin } from './origin.js';
9
+ import { expandOriginOf, isExternalOrigin } from './origin.js';
10
10
  import { statusTableBody } from './capture/index.js';
11
11
  /**
12
12
  * #248: upper bound on `SymbolRequest.array_depth`. SDL list nesting is
@@ -321,11 +321,7 @@ export class TypeBundler {
321
321
  * `ExpandOrigin`.
322
322
  */
323
323
  expandOrigin() {
324
- return {
325
- program: this.project.getProgram().compilerObject,
326
- repoRoot: this.repoRoot,
327
- imports: externalImportsOf(this.project),
328
- };
324
+ return expandOriginOf(this.project, this.repoRoot);
329
325
  }
330
326
  extractTypeDefinition(symbol) {
331
327
  const tableBody = symbol.consumer_response ? this.statusTableBodyText(symbol) : undefined;
@@ -39,6 +39,8 @@ export { findServiceTsconfig, fileConfigPath } from './service-config.js';
39
39
  export { WriteGuard } from './guarded-fs.js';
40
40
  export { installedPackageDirectory } from './installed-package-directory.js';
41
41
  export { isDeclarationFileName, packageNameOf } from './specifiers.js';
42
+ export { toPosix } from './installed-package.js';
43
+ export { constituentsOf } from './result-label.js';
42
44
  export { moduleExport } from './anchors.js';
43
45
  export { runCheck } from './check.js';
44
46
  export type { CheckProgress } from './check.js';
@@ -83,4 +85,4 @@ export declare function removeStaleSurfaceEntries(dir: string, guard: WriteGuard
83
85
  /** Same normalization intent as bundle_file_stems on the Rust side. */
84
86
  export declare function sanitizeServiceName(name: string): string;
85
87
  export declare function captureStub(opts: CaptureStubOptions): CaptureStubResult;
86
- export { classifyStatusCodes, constituents, httpStatus, statesNoBody, statesNoShape, statusKeyCode, statusTableBody, statusTableOf, successEntries, } from './status-table.js';
88
+ export { classifyStatusCodes, httpStatus, statesNoBody, statesNoShape, statusKeyCode, statusTableBody, statusTableOf, successEntries, } from './status-table.js';
@@ -60,6 +60,8 @@ export { findServiceTsconfig, fileConfigPath } from './service-config.js';
60
60
  export { WriteGuard } from './guarded-fs.js';
61
61
  export { installedPackageDirectory } from './installed-package-directory.js';
62
62
  export { isDeclarationFileName, packageNameOf } from './specifiers.js';
63
+ export { toPosix } from './installed-package.js';
64
+ export { constituentsOf } from './result-label.js';
63
65
  export { moduleExport } from './anchors.js';
64
66
  // v2 check core ("tsc as the judge"). Same bundle, same seam: the sidecar
65
67
  // reaches it only through this door (index.js).
@@ -1312,4 +1314,4 @@ function resolveAnchors(opts, parsed, ctx, deno, owner) {
1312
1314
  }
1313
1315
  // carrick#1841: the response-table reading the inferrer and the v1 bundle
1314
1316
  // share with the capture's symbol anchor.
1315
- export { classifyStatusCodes, constituents, httpStatus, statesNoBody, statesNoShape, statusKeyCode, statusTableBody, statusTableOf, successEntries, } from './status-table.js';
1317
+ export { classifyStatusCodes, httpStatus, statesNoBody, statesNoShape, statusKeyCode, statusTableBody, statusTableOf, successEntries, } from './status-table.js';
@@ -46,6 +46,7 @@ export interface InstalledPackageSpecifier {
46
46
  * deciding whether a runtime name is covered by a pinned types package.
47
47
  */
48
48
  export declare function typesPackageOf(name: string): string;
49
+ export declare function toPosix(p: string): string;
49
50
  /** A path or specifier without its script, source or declaration extension. */
50
51
  export declare function withoutExtension(subpath: string): string;
51
52
  /**
@@ -26,6 +26,7 @@ import * as fs from 'node:fs';
26
26
  import * as path from 'node:path';
27
27
  import { sidecarCompilerOptions } from './compiler-options.js';
28
28
  import { isPublishedSemver } from './lockfile.js';
29
+ import { packageNameOf } from './specifiers.js';
29
30
  const DECLARATION_SUFFIXES = ['', '.d.ts', '.d.mts', '.d.cts', '.ts', '.mts', '.cts', '/index.d.ts'];
30
31
  const RESOLUTION_OPTIONS = sidecarCompilerOptions({
31
32
  module: ts.ModuleKind.ESNext,
@@ -51,7 +52,7 @@ export function typesPackageOf(name) {
51
52
  const scoped = /^@([^/]+)\/(.+)$/.exec(name);
52
53
  return scoped ? `@types/${scoped[1]}__${scoped[2]}` : `@types/${name}`;
53
54
  }
54
- function toPosix(p) {
55
+ export function toPosix(p) {
55
56
  return p.split(path.sep).join('/');
56
57
  }
57
58
  function readManifest(dir) {
@@ -214,7 +215,7 @@ export function withInstalledPackages(options, installs, base = ts.createCompile
214
215
  : ts.resolveModuleName(name, containingFile, compilerOptions, base).resolvedModule;
215
216
  if (resolved || name.startsWith('.') || name.startsWith('/'))
216
217
  return resolved;
217
- const packageName = packageNameOfSpecifier(name);
218
+ const packageName = packageNameOf(name);
218
219
  for (const owner of [packageName, typesPackageOf(packageName)]) {
219
220
  const root = installs[owner];
220
221
  if (root) {
@@ -227,10 +228,6 @@ export function withInstalledPackages(options, installs, base = ts.createCompile
227
228
  });
228
229
  return base;
229
230
  }
230
- function packageNameOfSpecifier(spec) {
231
- const parts = spec.split('/');
232
- return spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
233
- }
234
231
  /** Entry subpaths of a package that a consumer can import. */
235
232
  function entrySubpaths(manifest) {
236
233
  const exportsField = manifest.exports;
@@ -15,7 +15,7 @@
15
15
  * A capture whose program stays inside rootDir is placed exactly as before.
16
16
  */
17
17
  import * as path from 'node:path';
18
- import { withoutExtension } from './installed-package.js';
18
+ import { toPosix, withoutExtension } from './installed-package.js';
19
19
  import { rewriteSpecifiers } from './specifiers.js';
20
20
  /** Tree directory holding declarations of sources outside rootDir. */
21
21
  export const OUTSIDE_DIR = '__outside__';
@@ -33,7 +33,7 @@ export function placeEmittedTree(args) {
33
33
  const outsideFiles = [];
34
34
  for (const fileName of args.emitted.keys()) {
35
35
  sourceSideOf.set(fileName, sourceSidePath(fileName, args.staging, args.entryDir));
36
- const rel = posix(path.relative(args.staging, fileName));
36
+ const rel = toPosix(path.relative(args.staging, fileName));
37
37
  if (escapes(rel)) {
38
38
  outsideFiles.push(fileName);
39
39
  continue;
@@ -45,7 +45,7 @@ export function placeEmittedTree(args) {
45
45
  return { relOf, textOf, outside, rewrites: 0 };
46
46
  const shared = commonDirectory([args.entryDir, ...outsideFiles.map((f) => path.dirname(path.resolve(f)))]);
47
47
  for (const fileName of outsideFiles) {
48
- const rel = path.posix.join(OUTSIDE_DIR, posix(path.relative(shared, path.resolve(fileName))));
48
+ const rel = path.posix.join(OUTSIDE_DIR, toPosix(path.relative(shared, path.resolve(fileName))));
49
49
  relOf.set(fileName, rel);
50
50
  outside.set(path.resolve(fileName).replace(DECLARATION_EXT, ''), rel);
51
51
  }
@@ -88,7 +88,7 @@ export function placeEmittedTree(args) {
88
88
  * source's own path.
89
89
  */
90
90
  function sourceSidePath(fileName, staging, entryDir) {
91
- const rel = posix(path.relative(staging, fileName));
91
+ const rel = toPosix(path.relative(staging, fileName));
92
92
  return escapes(rel) ? path.resolve(fileName) : path.join(entryDir, rel);
93
93
  }
94
94
  /**
@@ -119,9 +119,6 @@ export function surfaceModuleInTree(args) {
119
119
  return held.has(target) || held.has(path.join(target, 'index'));
120
120
  };
121
121
  }
122
- function posix(p) {
123
- return p.split(path.sep).join('/');
124
- }
125
122
  function escapes(rel) {
126
123
  return rel === '..' || rel.startsWith('../') || path.isAbsolute(rel);
127
124
  }
@@ -75,5 +75,3 @@ export declare function statusTableBody(checker: ts.TypeChecker, type: ts.Type,
75
75
  kind: 'no_body';
76
76
  entries: StatusTableEntry[];
77
77
  } | undefined;
78
- /** The members of a union, or the type itself: what a set comparison reads. */
79
- export declare function constituents(type: ts.Type): ts.Type[];
@@ -124,7 +124,3 @@ export function statusTableBody(checker, type, at) {
124
124
  }
125
125
  return { kind: 'body', entries: success, types };
126
126
  }
127
- /** The members of a union, or the type itself: what a set comparison reads. */
128
- export function constituents(type) {
129
- return type.isUnion() ? type.types : [type];
130
- }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The function body a call runs (carrick#3500). One answer for the helpers
3
+ * that ask it: a declaration that has a body is that body; an overloaded
4
+ * function is its one implementation (the signatures carry no body); a
5
+ * variable or property initialised with an arrow or function expression is
6
+ * that function, through the wrappers that leave a value as it is
7
+ * (parentheses, `as`, `<T>`, `!`, `satisfies`).
8
+ *
9
+ * A name with two bodies, or with none, has no one body and answers
10
+ * undefined.
11
+ */
12
+ import { Node, type ArrowFunction, type FunctionDeclaration, type FunctionExpression, type MethodDeclaration } from 'ts-morph';
13
+ export type PlainFunctionBody = FunctionDeclaration | ArrowFunction | FunctionExpression;
14
+ export type FunctionBody = PlainFunctionBody | MethodDeclaration;
15
+ /** An expression without the wrappers that leave its value as it is. */
16
+ export declare function peelValueWrappers(node: Node): Node;
17
+ /**
18
+ * The one function with a body among `declarations`, or undefined for none
19
+ * or several. `methods: false` leaves method declarations out.
20
+ */
21
+ export declare function functionBodyOf(declarations: readonly Node[], options: {
22
+ methods: false;
23
+ }): PlainFunctionBody | undefined;
24
+ export declare function functionBodyOf(declarations: readonly Node[], options?: {
25
+ methods?: boolean;
26
+ }): FunctionBody | undefined;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The function body a call runs (carrick#3500). One answer for the helpers
3
+ * that ask it: a declaration that has a body is that body; an overloaded
4
+ * function is its one implementation (the signatures carry no body); a
5
+ * variable or property initialised with an arrow or function expression is
6
+ * that function, through the wrappers that leave a value as it is
7
+ * (parentheses, `as`, `<T>`, `!`, `satisfies`).
8
+ *
9
+ * A name with two bodies, or with none, has no one body and answers
10
+ * undefined.
11
+ */
12
+ import { Node, } from 'ts-morph';
13
+ /** An expression without the wrappers that leave its value as it is. */
14
+ export function peelValueWrappers(node) {
15
+ let current = node;
16
+ while (Node.isParenthesizedExpression(current) ||
17
+ Node.isAsExpression(current) ||
18
+ Node.isTypeAssertion(current) ||
19
+ Node.isSatisfiesExpression(current) ||
20
+ Node.isNonNullExpression(current)) {
21
+ current = current.getExpression();
22
+ }
23
+ return current;
24
+ }
25
+ function bodyOfDeclaration(declaration, methods) {
26
+ if (Node.isFunctionDeclaration(declaration))
27
+ return declaration.getBody() ? declaration : undefined;
28
+ if (Node.isMethodDeclaration(declaration))
29
+ return methods && declaration.getBody() ? declaration : undefined;
30
+ if (Node.isArrowFunction(declaration) || Node.isFunctionExpression(declaration))
31
+ return declaration;
32
+ if (Node.isVariableDeclaration(declaration) || Node.isPropertyAssignment(declaration)) {
33
+ const initializer = declaration.getInitializer();
34
+ const value = initializer ? peelValueWrappers(initializer) : undefined;
35
+ if (value && (Node.isArrowFunction(value) || Node.isFunctionExpression(value)))
36
+ return value;
37
+ }
38
+ return undefined;
39
+ }
40
+ export function functionBodyOf(declarations, options = {}) {
41
+ const methods = options.methods ?? true;
42
+ const bodies = new Set();
43
+ for (const declaration of declarations) {
44
+ const body = bodyOfDeclaration(declaration, methods);
45
+ if (body)
46
+ bodies.add(body);
47
+ }
48
+ return bodies.size === 1 ? [...bodies][0] : undefined;
49
+ }
@@ -34,6 +34,7 @@
34
34
  * Anything else returns `undefined`, and the request is typed as before.
35
35
  */
36
36
  import { Node, SyntaxKind } from 'ts-morph';
37
+ import { peelValueWrappers } from './function-body.js';
37
38
  import { stringLiteral } from './response-modes.js';
38
39
  /** Methods of an array that change it in place. */
39
40
  const MUTATORS = new Set([
@@ -57,7 +58,7 @@ export function loopElementPick(registration, routePath) {
57
58
  const pathArg = registration.getArguments()[0];
58
59
  if (!pathArg)
59
60
  return undefined;
60
- const template = unwrap(pathArg);
61
+ const template = peelValueWrappers(pathArg);
61
62
  if (!Node.isTemplateExpression(template))
62
63
  return undefined;
63
64
  const holes = template.getTemplateSpans().map((span) => span.getExpression());
@@ -111,21 +112,6 @@ export function loopElementPick(registration, routePath) {
111
112
  of: elements.length,
112
113
  };
113
114
  }
114
- /** `node` through parentheses, `as` and `satisfies`. */
115
- function unwrap(node) {
116
- let at = node;
117
- for (;;) {
118
- if (Node.isParenthesizedExpression(at) ||
119
- Node.isAsExpression(at) ||
120
- Node.isSatisfiesExpression(at) ||
121
- Node.isTypeAssertion(at)) {
122
- at = at.getExpression();
123
- }
124
- else {
125
- return at;
126
- }
127
- }
128
- }
129
115
  /** The name node a declaration binds, for a name declared by a variable, a parameter or a binding element. */
130
116
  function declarationName(declared) {
131
117
  if (Node.isVariableDeclaration(declared) ||
@@ -199,7 +185,7 @@ function enclosingLoop(registration, holes) {
199
185
  * else, a spread included.
200
186
  */
201
187
  function listElements(list) {
202
- let literal = unwrap(list);
188
+ let literal = peelValueWrappers(list);
203
189
  if (Node.isIdentifier(literal)) {
204
190
  const declared = literal.getSymbol()?.getDeclarations()[0];
205
191
  if (!declared || !Node.isVariableDeclaration(declared))
@@ -216,7 +202,7 @@ function listElements(list) {
216
202
  return undefined;
217
203
  if (!readonly && declared.isExported())
218
204
  return undefined;
219
- literal = unwrap(initializer);
205
+ literal = peelValueWrappers(initializer);
220
206
  }
221
207
  if (!Node.isArrayLiteralExpression(literal))
222
208
  return undefined;
@@ -224,7 +210,7 @@ function listElements(list) {
224
210
  if (elements.some((element) => Node.isSpreadElement(element) || Node.isOmittedExpression(element))) {
225
211
  return undefined;
226
212
  }
227
- return elements.map(unwrap);
213
+ return elements.map((element) => peelValueWrappers(element));
228
214
  }
229
215
  function hasConstAssertion(node) {
230
216
  let at = node;
@@ -280,7 +266,7 @@ function elementValue(element, position) {
280
266
  if (items.some((item) => Node.isSpreadElement(item)))
281
267
  return undefined;
282
268
  const item = items[position];
283
- return item ? stringLiteral(unwrap(item)) : undefined;
269
+ return item ? stringLiteral(peelValueWrappers(item)) : undefined;
284
270
  }
285
271
  /** A path segment that is a parameter, in either spelling. */
286
272
  function isParam(segment) {
@@ -14,6 +14,7 @@
14
14
  * rather than by sharing this module.
15
15
  */
16
16
  import type { Project, ResolutionHostFactory, ts } from 'ts-morph';
17
+ import type { ExpandOrigin } from './type-structural-expander.js';
17
18
  /**
18
19
  * True when a declaration's source file is runtime/library origin rather than
19
20
  * user source. Four answers, in order:
@@ -87,3 +88,5 @@ export declare function registerExternalImports(project: Project, imports: Exter
87
88
  * `undefined` for any other project, which reads the compiler's flag alone.
88
89
  */
89
90
  export declare function externalImportsOf(project: Project): ExternalImports | undefined;
91
+ /** The program, service root and import record the printer decides library origin from. */
92
+ export declare function expandOriginOf(project: Project, repoRoot: string): ExpandOrigin;
@@ -132,3 +132,11 @@ export function registerExternalImports(project, imports) {
132
132
  export function externalImportsOf(project) {
133
133
  return externalImportsByProject.get(project);
134
134
  }
135
+ /** The program, service root and import record the printer decides library origin from. */
136
+ export function expandOriginOf(project, repoRoot) {
137
+ return {
138
+ program: project.getProgram().compilerObject,
139
+ repoRoot,
140
+ imports: externalImportsOf(project),
141
+ };
142
+ }
@@ -52,7 +52,7 @@ import * as fs from 'node:fs';
52
52
  import * as path from 'node:path';
53
53
  import * as zlib from 'node:zlib';
54
54
  import { ts } from 'ts-morph';
55
- import { WriteGuard, installedPackageDirectory, isDeclarationFileName, moduleExport } from './capture/index.js';
55
+ import { WriteGuard, installedPackageDirectory, isDeclarationFileName, moduleExport, toPosix } from './capture/index.js';
56
56
  import { attributedDeclaration, installedPackageOf, typeDeclaration } from './declaration-attribution.js';
57
57
  import { typeToStringAsDeclared } from './print-type.js';
58
58
  /** The format's version, written in the header. */
@@ -310,7 +310,7 @@ export class PathNames {
310
310
  /** A request file's name: relative to the root, which every file the scanner sends is inside. */
311
311
  relative(file) {
312
312
  const inside = this.inside(path.resolve(file));
313
- return toSlashes(inside ? inside.rel : path.basename(file));
313
+ return toPosix(inside ? inside.rel : path.basename(file));
314
314
  }
315
315
  /** What a declaring file is written as, or `null` when nothing names it. */
316
316
  declaringFile(fileName) {
@@ -324,10 +324,10 @@ export class PathNames {
324
324
  nameDeclaringFile(fileName) {
325
325
  const inside = this.inside(fileName);
326
326
  if (inside)
327
- return toSlashes(inside.rel);
327
+ return toPosix(inside.rel);
328
328
  const installed = installedPackageDirectory(this.roots[0], fileName) ?? this.packageDirectoryOf(fileName);
329
329
  if (installed && fs.existsSync(path.join(installed.directory, 'package.json'))) {
330
- return `pkg:${installed.name}/${toSlashes(path.relative(installed.directory, fileName))}`;
330
+ return `pkg:${installed.name}/${toPosix(path.relative(installed.directory, fileName))}`;
331
331
  }
332
332
  return null;
333
333
  }
@@ -397,9 +397,6 @@ export class PathNames {
397
397
  });
398
398
  }
399
399
  }
400
- function toSlashes(p) {
401
- return p.split(path.sep).join('/');
402
- }
403
400
  /**
404
401
  * The rows of one program's files. The `implementations` action
405
402
  * (`implementations.ts`, carrick#2432) reads a call's symbol and names its
@@ -15,6 +15,7 @@
15
15
  * type parameter of the reply type. A union of success and error bodies is
16
16
  * cut to the variants a success-status send through the parameter carries.
17
17
  */
18
+ import { functionBodyOf } from './function-body.js';
18
19
  import { Node, SyntaxKind, ts, } from 'ts-morph';
19
20
  import { declarationKey } from './library-claims.js';
20
21
  /** Type flags of a value that cannot hold a request body: a string, number, boolean and the like. */
@@ -283,23 +284,7 @@ export class StatedParams {
283
284
  let symbol = callee.getSymbol();
284
285
  if (symbol?.isAlias())
285
286
  symbol = symbol.getAliasedSymbol() ?? symbol;
286
- for (const declaration of symbol?.getDeclarations() ?? []) {
287
- if (!this.isRepoFile(declaration.getSourceFile()))
288
- continue;
289
- if (Node.isFunctionDeclaration(declaration) ||
290
- Node.isMethodDeclaration(declaration) ||
291
- Node.isArrowFunction(declaration) ||
292
- Node.isFunctionExpression(declaration)) {
293
- return declaration.getBody() ? declaration : undefined;
294
- }
295
- if (Node.isVariableDeclaration(declaration) || Node.isPropertyAssignment(declaration)) {
296
- const initializer = declaration.getInitializer();
297
- if (initializer && (Node.isArrowFunction(initializer) || Node.isFunctionExpression(initializer))) {
298
- return initializer;
299
- }
300
- }
301
- }
302
- return undefined;
287
+ return functionBodyOf((symbol?.getDeclarations() ?? []).filter((d) => this.isRepoFile(d.getSourceFile())));
303
288
  }
304
289
  // ===========================================================================
305
290
  // Reply
@@ -1584,6 +1584,16 @@ export declare class TypeInferrer {
1584
1584
  * annotates; see `recoverPayloadFromReturnStatements`.
1585
1585
  */
1586
1586
  private responseHelperPayloadNode;
1587
+ /**
1588
+ * True when a call's callee is a function this repository declares whose
1589
+ * every returned branch is a send stating an error or redirect status, or a
1590
+ * call to another such function (carrick#3523). `return failure(result)` is
1591
+ * then an error branch, as `json({ error }, { status: 400 })` written inline
1592
+ * is, and the value handed to it is never the success body. A callee that
1593
+ * returns anything else (a success send, a status the source does not fix,
1594
+ * a non-send) keeps the ordinary argument reading.
1595
+ */
1596
+ private callsFailureHelper;
1587
1597
  /**
1588
1598
  * True when a node's type reads as a response payload.
1589
1599
  *
@@ -20,11 +20,12 @@
20
20
  import * as path from 'node:path';
21
21
  import { Node, SyntaxKind, VariableDeclarationKind, ts, } from 'ts-morph';
22
22
  import { typeToStringAsDeclared } from './print-type.js';
23
+ import { functionBodyOf, peelValueWrappers } from './function-body.js';
23
24
  import { validateInferRequestItem } from './validators.js';
24
25
  import { declarationSite } from './bundler.js';
25
26
  import { printedTypeHoldsTopType, relateSymbolToRead } from './symbol-relation.js';
26
27
  import { notePrintedType, PrintedTypes } from './printed-names.js';
27
- import { externalImportsOf, isExternalOrigin } from './origin.js';
28
+ import { expandOriginOf, externalImportsOf, isExternalOrigin } from './origin.js';
28
29
  import { BINARY_BODY_READS, isPlatformBodyRead, JSON_READ, RAW_TEXT_FORMAT, WHOLE_BODY_READS, } from './platform-body-read.js';
29
30
  import { reachedOnlyOnFailure } from './failure-path.js';
30
31
  import { readResponseModes } from './response-modes.js';
@@ -35,11 +36,12 @@ import { endLineOf, startLineOf } from './line-index.js';
35
36
  import { callsOf, descendantsOf, descendantsOnLine, descendantsOnLines, wrap, } from './node-index.js';
36
37
  import { elapsedMs, inferTiming, phaseClock, timedPhase } from './infer-timing.js';
37
38
  import { importedNameOf, packageNameOf } from './library-claims.js';
39
+ import { constituentsOf } from './capture/index.js';
38
40
  import { StatedParams } from './stated-params.js';
39
41
  import { bindingToleratesAbsence, handlerToleratesAbsentBody } from './absent-body.js';
40
42
  import { replaceFileText } from './program-files.js';
41
43
  import { loopElementPick } from './loop-element.js';
42
- import { classifyStatusCodes, constituents, httpStatus, statesNoBody, statesNoShape, statusKeyCode, statusTableOf, successEntries, } from './capture/index.js';
44
+ import { classifyStatusCodes, httpStatus, statesNoBody, statesNoShape, statusKeyCode, statusTableOf, successEntries, } from './capture/index.js';
43
45
  import { addedDiagnostics, applyInsertions, fileDiagnostics, literalInsertions, mapBack, mapForward, normalise, pathOf, } from './unwidened.js';
44
46
  import { expandTypeStructural, jsonWireType, } from './type-structural-expander.js';
45
47
  /**
@@ -458,11 +460,7 @@ export class TypeInferrer {
458
460
  * classify one declaration two ways.
459
461
  */
460
462
  expandOrigin() {
461
- return {
462
- program: this.project.getProgram().compilerObject,
463
- repoRoot: this.repoRoot,
464
- imports: externalImportsOf(this.project),
465
- };
463
+ return expandOriginOf(this.project, this.repoRoot);
466
464
  }
467
465
  /**
468
466
  * Infer types for the given requests
@@ -4131,7 +4129,7 @@ export class TypeInferrer {
4131
4129
  for (const arg of args) {
4132
4130
  const entries = statusTableOf(checker, arg.compilerType);
4133
4131
  if (entries) {
4134
- tableValues.set(arg, new Set(entries.flatMap((entry) => constituents(checker.getTypeOfSymbolAtLocation(entry.symbol, at.compilerNode)))));
4132
+ tableValues.set(arg, new Set(entries.flatMap((entry) => constituentsOf(checker.getTypeOfSymbolAtLocation(entry.symbol, at.compilerNode)))));
4135
4133
  }
4136
4134
  }
4137
4135
  const bodies = new Map();
@@ -4145,7 +4143,7 @@ export class TypeInferrer {
4145
4143
  if (held.getText() === arg.getText())
4146
4144
  return true;
4147
4145
  const values = tableValues.get(arg);
4148
- const heldTypes = constituents(held.compilerType);
4146
+ const heldTypes = constituentsOf(held.compilerType);
4149
4147
  if (values &&
4150
4148
  heldTypes.length === values.size &&
4151
4149
  heldTypes.every((member) => values.has(member))) {
@@ -6367,19 +6365,7 @@ export class TypeInferrer {
6367
6365
  * expression.
6368
6366
  */
6369
6367
  builderFunctionOf(symbol) {
6370
- const bodies = [];
6371
- for (const declaration of symbol.getDeclarations()) {
6372
- if (Node.isFunctionDeclaration(declaration) && declaration.getBody()) {
6373
- bodies.push(declaration);
6374
- }
6375
- else if (Node.isVariableDeclaration(declaration)) {
6376
- const initializer = declaration.getInitializer();
6377
- const fn = initializer ? this.peelTransparentExpression(initializer) : undefined;
6378
- if (fn && (Node.isArrowFunction(fn) || Node.isFunctionExpression(fn)))
6379
- bodies.push(fn);
6380
- }
6381
- }
6382
- return bodies.length === 1 ? bodies[0] : undefined;
6368
+ return functionBodyOf(symbol.getDeclarations(), { methods: false });
6383
6369
  }
6384
6370
  /**
6385
6371
  * The payload a builder call serialises. The source states it, and the
@@ -6562,6 +6548,8 @@ export class TypeInferrer {
6562
6548
  const status = this.responseSiteStatus(call);
6563
6549
  if (status === 'error' || status === 'redirect')
6564
6550
  return undefined;
6551
+ if (Node.isCallExpression(call) && this.callsFailureHelper(call, depth))
6552
+ return undefined;
6565
6553
  // carrick#3053: a send the service's labels name carries its body in the
6566
6554
  // slot the label states, read as a labelled call send reads it.
6567
6555
  const labelled = this.statedParams.sendAt(call);
@@ -6590,6 +6578,37 @@ export class TypeInferrer {
6590
6578
  }
6591
6579
  return undefined;
6592
6580
  }
6581
+ /**
6582
+ * True when a call's callee is a function this repository declares whose
6583
+ * every returned branch is a send stating an error or redirect status, or a
6584
+ * call to another such function (carrick#3523). `return failure(result)` is
6585
+ * then an error branch, as `json({ error }, { status: 400 })` written inline
6586
+ * is, and the value handed to it is never the success body. A callee that
6587
+ * returns anything else (a success send, a status the source does not fix,
6588
+ * a non-send) keeps the ordinary argument reading.
6589
+ */
6590
+ callsFailureHelper(call, depth) {
6591
+ if (depth > RESPONSE_HELPER_MAX_DEPTH)
6592
+ return false;
6593
+ let symbol = call.getExpression().getSymbol();
6594
+ if (symbol?.isAlias())
6595
+ symbol = symbol.getAliasedSymbol() ?? symbol;
6596
+ if (!symbol || this.symbolIsLibOrExternalOrigin(symbol))
6597
+ return false;
6598
+ const helper = this.builderFunctionOf(symbol);
6599
+ if (!helper)
6600
+ return false;
6601
+ const branches = this.returnedExpressions(helper).flatMap((expression) => this.expandResponseBranches(expression, 0));
6602
+ if (branches.length === 0)
6603
+ return false;
6604
+ return branches.every((branch) => {
6605
+ const status = this.responseSiteStatus(branch);
6606
+ if (status === 'error' || status === 'redirect')
6607
+ return true;
6608
+ const inner = this.peelTransparentExpression(branch);
6609
+ return Node.isCallExpression(inner) && this.callsFailureHelper(inner, depth + 1);
6610
+ });
6611
+ }
6593
6612
  /**
6594
6613
  * True when a node's type reads as a response payload.
6595
6614
  *
@@ -7425,9 +7444,9 @@ export class TypeInferrer {
7425
7444
  */
7426
7445
  asHandlerFunction(node, followWrapperCalls = true) {
7427
7446
  const expr = this.unwrapExpressionNode(node);
7428
- if (Node.isArrowFunction(expr) || Node.isFunctionExpression(expr)) {
7429
- return expr;
7430
- }
7447
+ const inline = functionBodyOf([peelValueWrappers(expr)], { methods: false });
7448
+ if (inline)
7449
+ return inline;
7431
7450
  if (Node.isIdentifier(expr)) {
7432
7451
  for (const def of expr.getDefinitionNodes()) {
7433
7452
  const func = this.functionFromDeclaration(def, followWrapperCalls);
@@ -7450,7 +7469,9 @@ export class TypeInferrer {
7450
7469
  */
7451
7470
  functionFromDeclaration(decl, followWrapperCalls = true) {
7452
7471
  if (Node.isFunctionDeclaration(decl)) {
7453
- return decl;
7472
+ // A declaration with no body anywhere (`declare function`) is still the
7473
+ // handler's function; its body is out of reach, which callers read.
7474
+ return functionBodyOf(decl.getSymbol()?.getDeclarations() ?? [decl], { methods: false }) ?? decl;
7454
7475
  }
7455
7476
  if (Node.isArrowFunction(decl) || Node.isFunctionExpression(decl)) {
7456
7477
  return decl;
@@ -7469,10 +7490,10 @@ export class TypeInferrer {
7469
7490
  if (varDecl) {
7470
7491
  const initializer = varDecl.getInitializer();
7471
7492
  if (initializer) {
7493
+ const direct = functionBodyOf([varDecl], { methods: false });
7494
+ if (direct)
7495
+ return direct;
7472
7496
  const inner = this.unwrapExpressionNode(initializer);
7473
- if (Node.isArrowFunction(inner) || Node.isFunctionExpression(inner)) {
7474
- return inner;
7475
- }
7476
7497
  if (followWrapperCalls && Node.isCallExpression(inner)) {
7477
7498
  return this.functionWrappedBy(inner, 0);
7478
7499
  }
@@ -9245,47 +9266,24 @@ export class TypeInferrer {
9245
9266
  let symbol = call.getExpression().getSymbol();
9246
9267
  if (symbol?.isAlias())
9247
9268
  symbol = symbol.getAliasedSymbol() ?? symbol;
9248
- for (const declaration of symbol?.getDeclarations() ?? []) {
9249
- const fn = Node.isFunctionDeclaration(declaration) || Node.isMethodDeclaration(declaration)
9250
- ? declaration
9251
- : Node.isVariableDeclaration(declaration)
9252
- ? this.unwrapExpressionNode(declaration.getInitializer())
9253
- : undefined;
9254
- if (!fn ||
9255
- !(Node.isFunctionDeclaration(fn) ||
9256
- Node.isMethodDeclaration(fn) ||
9257
- Node.isArrowFunction(fn) ||
9258
- Node.isFunctionExpression(fn)) ||
9259
- !fn.getBody() ||
9260
- fn.getSourceFile().isDeclarationFile() ||
9261
- fn.getSourceFile().isInNodeModules()) {
9262
- continue;
9263
- }
9264
- const parameter = fn.getParameters()[index];
9265
- const parameterSymbol = parameter?.getNameNode().getSymbol()?.compilerSymbol;
9266
- if (!parameter || parameter.isRestParameter() || !parameterSymbol)
9267
- continue;
9268
- const returned = this.returnedExpressions(fn);
9269
- let returnsArgument = false;
9270
- const everyReturnPasses = returned.every((expression) => {
9271
- let node = expression;
9272
- while (Node.isParenthesizedExpression(node) ||
9273
- Node.isAsExpression(node) ||
9274
- Node.isTypeAssertion(node) ||
9275
- Node.isSatisfiesExpression(node) ||
9276
- Node.isNonNullExpression(node)) {
9277
- node = node.getExpression();
9278
- }
9279
- if (Node.isIdentifier(node) && node.getSymbol()?.compilerSymbol === parameterSymbol) {
9280
- returnsArgument = true;
9281
- return true;
9282
- }
9283
- return this.isEmptyDefault(node);
9284
- });
9285
- if (everyReturnPasses && returnsArgument)
9286
- return fn;
9269
+ const fn = functionBodyOf(symbol?.getDeclarations() ?? []);
9270
+ if (!fn || fn.getSourceFile().isDeclarationFile() || fn.getSourceFile().isInNodeModules()) {
9271
+ return undefined;
9287
9272
  }
9288
- return undefined;
9273
+ const parameter = fn.getParameters()[index];
9274
+ const parameterSymbol = parameter?.getNameNode().getSymbol()?.compilerSymbol;
9275
+ if (!parameter || parameter.isRestParameter() || !parameterSymbol)
9276
+ return undefined;
9277
+ let returnsArgument = false;
9278
+ const everyReturnPasses = this.returnedExpressions(fn).every((expression) => {
9279
+ const node = peelValueWrappers(expression);
9280
+ if (Node.isIdentifier(node) && node.getSymbol()?.compilerSymbol === parameterSymbol) {
9281
+ returnsArgument = true;
9282
+ return true;
9283
+ }
9284
+ return this.isEmptyDefault(node);
9285
+ });
9286
+ return everyReturnPasses && returnsArgument ? fn : undefined;
9289
9287
  }
9290
9288
  /** `{}`, `[]`, `null` or `undefined`: a default that states no member. */
9291
9289
  isEmptyDefault(node) {