@trackunit/eslint-plugin-trackunit 0.6.190 → 0.7.3

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.
@@ -1,16 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.requireComponentPropContracts = exports.checkerTypeHasRequiredInterface = void 0;
3
+ exports.requireComponentPropContracts = exports.getMissingContractsForCheckerTypes = exports.getMissingContractsForCheckerType = exports.checkerTypeHasRequiredInterface = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const utils_1 = require("@typescript-eslint/utils");
6
- const fs = tslib_1.__importStar(require("fs"));
7
6
  const path = tslib_1.__importStar(require("path"));
8
7
  const ts = tslib_1.__importStar(require("typescript"));
9
8
  const ast_utils_1 = require("../../utils/ast-utils");
10
9
  const nx_utils_1 = require("../../utils/nx-utils");
10
+ const entrypoint_exports_1 = require("./entrypoint-exports");
11
11
  const createRule = utils_1.ESLintUtils.RuleCreator(name => `https://github.com/trackunit/manager/blob/main/libs/eslint/plugin-trackunit/src/lib/rules/${name}/${name}.ts`);
12
+ const { DefinitionType } = utils_1.TSESLint.Scope;
12
13
  const componentWrapperNames = new Set(["forwardRef", "memo"]);
13
- const publicEntrypointFileNames = ["index.ts", "index.tsx"];
14
14
  const getTypeSymbolInfo = (type) => {
15
15
  try {
16
16
  return {
@@ -34,104 +34,109 @@ const getTypeReferenceName = (typeName) => {
34
34
  }
35
35
  return null;
36
36
  };
37
+ /**
38
+ * The statically known member name of `obj.name` or `obj["name"]`. A non-literal computed member (`obj[name]`)
39
+ * has no syntactically known name and yields `null`.
40
+ */
41
+ const getMemberExpressionPropertyName = (node) => {
42
+ const { property } = node;
43
+ if (!node.computed && property.type === utils_1.AST_NODE_TYPES.Identifier) {
44
+ return property.name;
45
+ }
46
+ // Bug fix (SDK-565): `React["memo"](...)` is the same wrapper as `React.memo(...)`, so a string-literal computed
47
+ // callee is resolved to its literal value instead of being silently skipped.
48
+ if (node.computed && property.type === utils_1.AST_NODE_TYPES.Literal && typeof property.value === "string") {
49
+ return property.value;
50
+ }
51
+ return null;
52
+ };
37
53
  const getCallExpressionName = (node) => {
38
54
  const { callee } = node;
39
55
  if (callee.type === utils_1.AST_NODE_TYPES.Identifier) {
40
56
  return callee.name;
41
57
  }
42
- if (callee.type === utils_1.AST_NODE_TYPES.MemberExpression && callee.property.type === utils_1.AST_NODE_TYPES.Identifier) {
43
- return callee.property.name;
58
+ if (callee.type === utils_1.AST_NODE_TYPES.MemberExpression) {
59
+ return getMemberExpressionPropertyName(callee);
44
60
  }
45
61
  return null;
46
62
  };
47
63
  const isPascalCaseName = (name) => /^[A-Z]/.test(name);
48
- const normalizeFilePath = (filePath) => path.normalize(filePath);
49
64
  const getProjectRoot = (projectJsonPath) => path.dirname(projectJsonPath);
50
- const getPublicEntrypointPaths = (projectRoot) => publicEntrypointFileNames.map(fileName => path.join(projectRoot, "src", fileName));
51
- const getModulePathCandidates = (fromFilePath, moduleSpecifier) => {
52
- const modulePath = path.resolve(path.dirname(fromFilePath), moduleSpecifier);
53
- return [
54
- modulePath,
55
- `${modulePath}.ts`,
56
- `${modulePath}.tsx`,
57
- path.join(modulePath, "index.ts"),
58
- path.join(modulePath, "index.tsx"),
59
- ];
60
- };
61
- const moduleSpecifierTargetsFile = (fromFilePath, moduleSpecifier, targetFilePath) => {
62
- if (!moduleSpecifier.startsWith(".")) {
63
- return false;
64
- }
65
- const normalizedTargetFilePath = normalizeFilePath(targetFilePath);
66
- return getModulePathCandidates(fromFilePath, moduleSpecifier).some(candidatePath => normalizeFilePath(candidatePath) === normalizedTargetFilePath);
67
- };
68
- const getSourceExportName = (specifier) => {
69
- if (specifier.propertyName?.text === "default") {
70
- return specifier.name.text;
71
- }
72
- return specifier.propertyName?.text ?? specifier.name.text;
65
+ const isComponentWrapperCallExpression = (node) => {
66
+ const callExpressionName = getCallExpressionName(node);
67
+ return callExpressionName !== null && componentWrapperNames.has(callExpressionName);
73
68
  };
74
- const getPublicExportedNamesForFile = (projectRoot, filePath) => {
75
- const result = {
76
- exportsAll: false,
77
- names: new Set(),
78
- };
79
- for (const entrypointPath of getPublicEntrypointPaths(projectRoot)) {
80
- let sourceText;
81
- try {
82
- sourceText = fs.readFileSync(entrypointPath, "utf8");
83
- }
84
- catch {
85
- continue;
86
- }
87
- const sourceFile = ts.createSourceFile(entrypointPath, sourceText, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
88
- for (const statement of sourceFile.statements) {
89
- if (!ts.isExportDeclaration(statement) || !statement.moduleSpecifier) {
90
- continue;
91
- }
92
- if (!ts.isStringLiteral(statement.moduleSpecifier)) {
93
- continue;
94
- }
95
- if (!moduleSpecifierTargetsFile(entrypointPath, statement.moduleSpecifier.text, filePath)) {
96
- continue;
97
- }
98
- if (!statement.exportClause) {
99
- result.exportsAll = true;
100
- continue;
101
- }
102
- if (ts.isNamedExports(statement.exportClause)) {
103
- statement.exportClause.elements.forEach(specifier => {
104
- result.names.add(getSourceExportName(specifier));
105
- });
69
+ const isInlineFunctionNode = (node) => node?.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression || node?.type === utils_1.AST_NODE_TYPES.FunctionExpression;
70
+ const NOT_A_WRAPPED_COMPONENT = { kind: "none" };
71
+ /**
72
+ * The function a referenced variable's wrapper-call initialiser resolved to, as a `local` resolution named after the
73
+ * variable (`const RefButton = forwardRef(Base)` → `RefButton`); `imported` and `none` pass through.
74
+ */
75
+ const asLocalResolution = (resolution, name) => resolution.kind === "inline" || resolution.kind === "nestedInline" || resolution.kind === "local"
76
+ ? { kind: "local", functionNode: resolution.functionNode, name }
77
+ : resolution;
78
+ /** An inline function found one wrapper call deeper (`memo(forwardRef(() => …))`); other kinds pass through. */
79
+ const asNestedInlineResolution = (resolution) => resolution.kind === "inline" ? { kind: "nestedInline", functionNode: resolution.functionNode } : resolution;
80
+ /**
81
+ * Resolves a wrapped identifier (`memo(ButtonBase)`) to the function it names.
82
+ *
83
+ * Bug fix (SDK-565): the wrapper check used to accept only inline arrow/function arguments, so a component wrapped
84
+ * by reference was never checked. The identifier is resolved through the scope manager, which already knows every
85
+ * module-level binding regardless of declaration order, so `ButtonBase` may be declared after the export.
86
+ * `visitedVariables` stops mutually referencing wrapper chains (`const A = memo(B); const B = memo(A)`).
87
+ */
88
+ const resolveWrappedIdentifier = (identifier, sourceCode, visitedVariables) => {
89
+ const variable = utils_1.ASTUtils.findVariable(sourceCode.getScope(identifier), identifier);
90
+ if (!variable || visitedVariables.has(variable)) {
91
+ return NOT_A_WRAPPED_COMPONENT;
92
+ }
93
+ visitedVariables.add(variable);
94
+ const definition = variable.defs[0];
95
+ switch (definition?.type) {
96
+ case DefinitionType.FunctionName:
97
+ return definition.node.type === utils_1.AST_NODE_TYPES.FunctionDeclaration
98
+ ? { kind: "local", functionNode: definition.node, name: identifier.name }
99
+ : NOT_A_WRAPPED_COMPONENT;
100
+ case DefinitionType.Variable: {
101
+ const { init } = definition.node;
102
+ if (isInlineFunctionNode(init)) {
103
+ return { kind: "local", functionNode: init, name: identifier.name };
106
104
  }
105
+ // `const RefButton = forwardRef(Base); export const Button = memo(RefButton);`
106
+ return init?.type === utils_1.AST_NODE_TYPES.CallExpression
107
+ ? asLocalResolution(resolveWrappedComponent(init, sourceCode, visitedVariables), identifier.name)
108
+ : NOT_A_WRAPPED_COMPONENT;
107
109
  }
110
+ case DefinitionType.ImportBinding:
111
+ return { kind: "imported", identifier };
112
+ default:
113
+ return NOT_A_WRAPPED_COMPONENT;
108
114
  }
109
- return result;
110
- };
111
- const isEntrypointFile = (projectRoot, filePath) => {
112
- const normalizedFilePath = normalizeFilePath(filePath);
113
- return getPublicEntrypointPaths(projectRoot).some(entrypointPath => normalizeFilePath(entrypointPath) === normalizedFilePath);
114
- };
115
- const isComponentWrapperCallExpression = (node) => {
116
- const firstArgument = node.arguments[0];
117
- const callExpressionName = getCallExpressionName(node);
118
- if (!callExpressionName || !componentWrapperNames.has(callExpressionName)) {
119
- return false;
120
- }
121
- return (firstArgument?.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression ||
122
- firstArgument?.type === utils_1.AST_NODE_TYPES.FunctionExpression);
123
115
  };
124
- const getWrappedComponentFunction = (node) => {
116
+ const resolveWrappedComponent = (node, sourceCode, visitedVariables = new Set()) => {
125
117
  if (!isComponentWrapperCallExpression(node)) {
126
- return null;
118
+ return NOT_A_WRAPPED_COMPONENT;
127
119
  }
128
120
  const firstArgument = node.arguments[0];
129
- return firstArgument &&
130
- (firstArgument.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression ||
131
- firstArgument.type === utils_1.AST_NODE_TYPES.FunctionExpression)
132
- ? firstArgument
133
- : null;
121
+ if (isInlineFunctionNode(firstArgument)) {
122
+ return { kind: "inline", functionNode: firstArgument };
123
+ }
124
+ if (firstArgument?.type === utils_1.AST_NODE_TYPES.Identifier) {
125
+ return resolveWrappedIdentifier(firstArgument, sourceCode, visitedVariables);
126
+ }
127
+ // Nested wrappers (`memo(forwardRef(Base))`) follow the inner call.
128
+ if (firstArgument?.type === utils_1.AST_NODE_TYPES.CallExpression) {
129
+ return asNestedInlineResolution(resolveWrappedComponent(firstArgument, sourceCode, visitedVariables));
130
+ }
131
+ return NOT_A_WRAPPED_COMPONENT;
134
132
  };
133
+ /**
134
+ * Whether a resolved wrapped function is a component. A function declaration follows `isReactComponent` (PascalCase
135
+ * name or JSX return); an anonymous arrow/function expression can only be judged by what it returns.
136
+ */
137
+ const isComponentFunction = (node) => node.type === utils_1.AST_NODE_TYPES.FunctionDeclaration ? (0, ast_utils_1.isReactComponent)(node) : (0, ast_utils_1.functionReturnsJSX)(node);
138
+ /** The name a function carries itself: `function Base() {}` → `Base`; arrow functions have none. */
139
+ const getOwnFunctionName = (node) => node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression ? null : (node.id?.name ?? null);
135
140
  const getHeritageName = (heritage) => {
136
141
  const { expression } = heritage;
137
142
  if (expression.type === utils_1.AST_NODE_TYPES.Identifier) {
@@ -158,41 +163,117 @@ const getParameterTypeAnnotation = (parameter) => {
158
163
  return null;
159
164
  };
160
165
  const getFunctionPropsType = (node) => getParameterTypeAnnotation(node.params[0]);
161
- const getPropsTypeFromCallExpression = (node) => {
166
+ /**
167
+ * The props type named by a wrapper call's explicit type arguments: `forwardRef<E, P>(…)` → `P`, `memo<P>(…)` → `P`.
168
+ * A nested wrapper (`memo(forwardRef<E, P>(Base))`) falls through to the inner call's type arguments.
169
+ */
170
+ const getPropsTypeFromWrapperTypeArguments = (node) => {
162
171
  const typeArguments = node.typeArguments?.params ?? [];
163
- const firstArgument = node.arguments[0];
164
- if (firstArgument?.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression ||
165
- firstArgument?.type === utils_1.AST_NODE_TYPES.FunctionExpression) {
166
- const parameterType = getParameterTypeAnnotation(firstArgument.params[0]);
167
- if (parameterType) {
168
- return parameterType;
169
- }
172
+ const propsType = getCallExpressionName(node) === "forwardRef" ? typeArguments[1] : typeArguments[0];
173
+ if (propsType) {
174
+ return propsType;
170
175
  }
171
- if (getCallExpressionName(node) === "forwardRef") {
172
- return typeArguments[1] ?? null;
176
+ const firstArgument = node.arguments[0];
177
+ return firstArgument?.type === utils_1.AST_NODE_TYPES.CallExpression
178
+ ? getPropsTypeFromWrapperTypeArguments(firstArgument)
179
+ : null;
180
+ };
181
+ /** The wrapped function's own props annotation wins; the wrapper call's type arguments are the fallback. */
182
+ const getWrappedComponentPropsType = (node, functionNode) => getFunctionPropsType(functionNode) ?? getPropsTypeFromWrapperTypeArguments(node);
183
+ /**
184
+ * The component a `memo`/`forwardRef` call wraps, or `null` when it wraps none: a function written inline (not
185
+ * component-gated), a same-file reference or nested inline function (gated through `isComponentFunction`), or an
186
+ * imported reference. An imported reference can only be judged by name here (PascalCase, like a function
187
+ * declaration); its props live in another module and are resolved by the caller through the type checker (SDK-565).
188
+ */
189
+ const getWrapperCallComponent = (call, sourceCode) => {
190
+ const resolution = resolveWrappedComponent(call, sourceCode);
191
+ switch (resolution.kind) {
192
+ case "inline":
193
+ return {
194
+ kind: "function",
195
+ functionNode: resolution.functionNode,
196
+ propsType: getWrappedComponentPropsType(call, resolution.functionNode),
197
+ name: getOwnFunctionName(resolution.functionNode),
198
+ };
199
+ case "nestedInline":
200
+ case "local":
201
+ return isComponentFunction(resolution.functionNode)
202
+ ? {
203
+ kind: "function",
204
+ functionNode: resolution.functionNode,
205
+ propsType: getWrappedComponentPropsType(call, resolution.functionNode),
206
+ name: resolution.kind === "local" ? resolution.name : getOwnFunctionName(resolution.functionNode),
207
+ }
208
+ : null;
209
+ case "imported":
210
+ return isPascalCaseName(resolution.identifier.name)
211
+ ? {
212
+ kind: "imported",
213
+ identifier: resolution.identifier,
214
+ propsType: getPropsTypeFromWrapperTypeArguments(call),
215
+ name: resolution.identifier.name,
216
+ }
217
+ : null;
218
+ default:
219
+ return null;
173
220
  }
174
- return typeArguments[0] ?? null;
175
221
  };
176
- const getPropsTypeFromVariableDeclarator = (node) => {
222
+ /**
223
+ * The component a variable initialiser declares, or `null` when the initialiser is not a component: an arrow
224
+ * function returning JSX, or a `memo`/`forwardRef` call wrapping one (see `getWrapperCallComponent`).
225
+ */
226
+ const getVariableComponent = (node, sourceCode) => {
177
227
  const { init } = node;
178
- if (!init) {
179
- return null;
228
+ if (init?.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression) {
229
+ return (0, ast_utils_1.isReactComponent)(init)
230
+ ? { kind: "function", functionNode: init, propsType: getFunctionPropsType(init), name: null }
231
+ : null;
180
232
  }
181
- if (init.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression) {
182
- return getFunctionPropsType(init);
183
- }
184
- if (init.type === utils_1.AST_NODE_TYPES.CallExpression) {
185
- return getPropsTypeFromCallExpression(init);
186
- }
187
- return null;
233
+ return init?.type === utils_1.AST_NODE_TYPES.CallExpression ? getWrapperCallComponent(init, sourceCode) : null;
188
234
  };
189
- const isExportedDeclaration = (node) => {
235
+ /**
236
+ * The props types of an imported component as the type checker sees them: the first parameter of each of the
237
+ * import's call signatures. Covers plain functions, `FC<P>` and `MemoExoticComponent<…>` alike, since all expose a
238
+ * `(props: P) => …` call signature; an overloaded component contributes one type per overload, so a contract counts
239
+ * as satisfied when any overload carries it rather than only the first one TypeScript lists (SDK-565). Empty when
240
+ * the import has no call signature (not a component) or none takes a parameter, so the caller skips it instead of
241
+ * reporting every contract.
242
+ */
243
+ const getImportedPropsCheckerTypes = (identifier, { checker, services }) => {
244
+ const tsNode = services.esTreeNodeToTSNodeMap.get(identifier);
245
+ return checker
246
+ .getTypeAtLocation(tsNode)
247
+ .getCallSignatures()
248
+ .flatMap(signature => {
249
+ const propsParameter = signature.getParameters()[0];
250
+ return propsParameter ? [checker.getTypeOfSymbolAtLocation(propsParameter, tsNode)] : [];
251
+ });
252
+ };
253
+ /** `export default function X() {}` */
254
+ const isDefaultExportedDeclaration = (node) => node.parent?.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration;
255
+ /** `export { X as default }`: a default export written as a specifier. */
256
+ const isDefaultExportSpecifier = (specifier) => specifier.exported.type === utils_1.AST_NODE_TYPES.Identifier && specifier.exported.name === "default";
257
+ const isModuleScopeParent = (node) => node?.type === utils_1.AST_NODE_TYPES.Program ||
258
+ node?.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration ||
259
+ node?.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration;
260
+ /**
261
+ * Whether a component declaration lives at module scope. Only module-scope declarations can be the target of
262
+ * `export { X }` / `export default X`; a same-named declaration nested in another function is unrelated (SDK-563).
263
+ */
264
+ const isModuleScopedDeclaration = (node) => {
265
+ if (node.type === utils_1.AST_NODE_TYPES.VariableDeclarator) {
266
+ return isModuleScopeParent(node.parent.parent);
267
+ }
268
+ return isModuleScopeParent(node.parent);
269
+ };
270
+ /** Inline named export forms: `export function X`, `export const X`. */
271
+ const isNamedExportedDeclaration = (node) => {
190
272
  const parent = node.parent;
191
273
  if (!parent) {
192
274
  return false;
193
275
  }
194
- if (parent.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration ||
195
- parent.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration) {
276
+ if (parent.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration) {
196
277
  return true;
197
278
  }
198
279
  const grandParent = parent.parent;
@@ -329,51 +410,198 @@ const getTypeCheckerContext = (context) => {
329
410
  return null;
330
411
  }
331
412
  };
332
- const checkerTypeHasRequiredInterface = (type, requiredInterface, checker, visitedTypeNames = new Set()) => {
413
+ /**
414
+ * Whether `type` exposes every property of `contractType`, compared by name only: `Partial<Contract>` keeps the
415
+ * members (optional) and still counts, while `Omit<Contract, "member">` or a `Wrapper<Contract>` that nests the
416
+ * contract does not. A zero-member marker contract passes trivially.
417
+ */
418
+ const typeExposesPropertiesOf = (type, contractType, checker) => {
419
+ const exposedPropertyNames = new Set(checker.getPropertiesOfType(type).map(property => property.getName()));
420
+ return checker.getPropertiesOfType(contractType).every(property => exposedPropertyNames.has(property.getName()));
421
+ };
422
+ /** Whether a type is the required interface itself, by interface symbol or by alias name. */
423
+ const isRequiredInterfaceType = (type, requiredInterface) => getTypeSymbolInfo(type).symbolName === requiredInterface || type.aliasSymbol?.getName() === requiredInterface;
424
+ /**
425
+ * Marks a type as being walked, or reports that it already is. The guard is keyed on the `ts.Type` object itself:
426
+ * TypeScript hands out one object per declared interface and per distinct alias instantiation, so a genuine cycle
427
+ * (`LoopA extends LoopB extends LoopA`) revisits the same object while two sibling bases built from the same alias
428
+ * (`Omit<Styleable, never>, Omit<CommonProps, never>`) do not.
429
+ *
430
+ * Bug fix (SDK-564): the guard used to be keyed on the alias/symbol *name* (`"Omit"`), so once the first `Omit<…>` or
431
+ * `Pick<…>` base had been visited every later sibling using the same alias was skipped as "already seen" and its
432
+ * contract reported as missing.
433
+ */
434
+ const markVisited = (type, visited) => {
435
+ if (visited.has(type)) {
436
+ return false;
437
+ }
438
+ visited.add(type);
439
+ return true;
440
+ };
441
+ /**
442
+ * The contract type(s) a type carries, as the checker sees them: the type itself when it *is* the contract, otherwise
443
+ * the contracts found in its intersection/union parts, its alias type arguments, or an interface's base types.
444
+ *
445
+ * Bug fix (SDK-564): the structural comparison used to be anchored on the whole alias type *argument*, so for
446
+ * `MappedOmit<ButtonCommonProps, "size">` with `ButtonCommonProps extends CommonProps` it demanded every member of
447
+ * `ButtonCommonProps` (including the dropped `size`) instead of only `CommonProps`'s own members. Finding the actual
448
+ * contract type lets the comparison ask the right question.
449
+ */
450
+ const findContractTypes = (type, requiredInterface, checker, visited = new Set()) => {
451
+ if (type.isUnionOrIntersection()) {
452
+ return type.types.flatMap(part => findContractTypes(part, requiredInterface, checker, new Set(visited)));
453
+ }
454
+ if (isRequiredInterfaceType(type, requiredInterface)) {
455
+ return [type];
456
+ }
457
+ if (!markVisited(type, visited)) {
458
+ return [];
459
+ }
460
+ const fromAliasTypeArguments = (type.aliasTypeArguments ?? []).flatMap(typeArgument => findContractTypes(typeArgument, requiredInterface, checker, visited));
461
+ const fromBaseTypes = type.isClassOrInterface()
462
+ ? checker.getBaseTypes(type).flatMap(baseType => findContractTypes(baseType, requiredInterface, checker, visited))
463
+ : [];
464
+ return [...fromAliasTypeArguments, ...fromBaseTypes];
465
+ };
466
+ /**
467
+ * Whether `type` satisfies `requiredInterface`. `exposureRoot` is the *resulting* props type the structural check
468
+ * compares against; it stays fixed while the walk descends into intersection parts, base types and heritage clauses,
469
+ * and defaults to the type the check started on.
470
+ *
471
+ * Bug fix (SDK-564): the comparison used to run against the alias-carrying member itself, so
472
+ * `interface Props extends Omit<CommonProps, "id">, … { id?: string }` was reported even though the resulting props
473
+ * type exposes every `CommonProps` member: the base alone does not, but the interface body re-adds `id`. A contract's
474
+ * members may come from any part of the props type, so the comparison always targets the whole of it.
475
+ */
476
+ const checkerTypeHasRequiredInterface = (type, requiredInterface, checker, visited = new Set(), exposureRoot = type) => {
477
+ // `getPropertiesOfType` on a union yields the members common to every constituent, which is exactly the resulting
478
+ // props type, so the root is kept for unions as well.
333
479
  if (type.isUnion()) {
334
- return type.types.every(part => (0, exports.checkerTypeHasRequiredInterface)(part, requiredInterface, checker, new Set()));
480
+ return type.types.every(part => (0, exports.checkerTypeHasRequiredInterface)(part, requiredInterface, checker, new Set(), exposureRoot));
335
481
  }
336
482
  if (type.isIntersection()) {
337
- return type.types.some(part => (0, exports.checkerTypeHasRequiredInterface)(part, requiredInterface, checker, new Set(visitedTypeNames)));
483
+ return type.types.some(part => (0, exports.checkerTypeHasRequiredInterface)(part, requiredInterface, checker, new Set(visited), exposureRoot));
338
484
  }
339
- const { symbolName, declarations } = getTypeSymbolInfo(type);
340
- const aliasSymbolName = type.aliasSymbol?.getName();
341
- if (symbolName === requiredInterface || aliasSymbolName === requiredInterface) {
485
+ if (isRequiredInterfaceType(type, requiredInterface)) {
342
486
  return true;
343
487
  }
344
- const visitKey = aliasSymbolName ?? symbolName;
345
- if (visitKey) {
346
- if (visitedTypeNames.has(visitKey)) {
347
- return false;
348
- }
349
- visitedTypeNames.add(visitKey);
488
+ if (!markVisited(type, visited)) {
489
+ return false;
350
490
  }
351
- if (type.aliasTypeArguments?.some(typeArgument => (0, exports.checkerTypeHasRequiredInterface)(typeArgument, requiredInterface, checker))) {
491
+ // Bug fix (SDK-564): a contract among `aliasTypeArguments` is only an anchor, not a match. `Omit<Refable, "ref">`
492
+ // or a `Wrapper<Refable>` that nests the contract names it while hiding its members, so the resulting props type
493
+ // must still expose every property of the contract type found in the argument.
494
+ if (type.aliasTypeArguments?.some(typeArgument => findContractTypes(typeArgument, requiredInterface, checker).some(contractType => typeExposesPropertiesOf(exposureRoot, contractType, checker)))) {
352
495
  return true;
353
496
  }
354
497
  if (type.isClassOrInterface()) {
355
498
  const baseTypes = checker.getBaseTypes(type);
356
- if (baseTypes.some(baseType => (0, exports.checkerTypeHasRequiredInterface)(baseType, requiredInterface, checker, visitedTypeNames))) {
499
+ if (baseTypes.some(baseType => (0, exports.checkerTypeHasRequiredInterface)(baseType, requiredInterface, checker, visited, exposureRoot))) {
357
500
  return true;
358
501
  }
359
502
  }
360
- return declarations.some(declaration => {
503
+ return getTypeSymbolInfo(type).declarations.some(declaration => {
361
504
  if (!ts.isInterfaceDeclaration(declaration) || !declaration.heritageClauses) {
362
505
  return false;
363
506
  }
364
507
  return declaration.heritageClauses.some(heritageClause => heritageClause.types.some(heritageType => {
365
508
  const heritageInterfaceType = checker.getTypeAtLocation(heritageType);
366
- return (0, exports.checkerTypeHasRequiredInterface)(heritageInterfaceType, requiredInterface, checker, visitedTypeNames);
509
+ return (0, exports.checkerTypeHasRequiredInterface)(heritageInterfaceType, requiredInterface, checker, visited, exposureRoot);
367
510
  }));
368
511
  });
369
512
  };
370
513
  exports.checkerTypeHasRequiredInterface = checkerTypeHasRequiredInterface;
514
+ /** The identifier a type reference is named by: `Foo` in both `Foo<T>` and `ns.Foo<T>`. */
515
+ const getTypeReferenceNameNode = (typeNode) => ts.isQualifiedName(typeNode.typeName) ? typeNode.typeName.right : typeNode.typeName;
516
+ /** The symbol a type reference points at, with import aliases followed to their target. */
517
+ const resolveTypeReferenceSymbol = (typeNode, checker) => {
518
+ const symbol = checker.getSymbolAtLocation(getTypeReferenceNameNode(typeNode));
519
+ if (!symbol) {
520
+ return undefined;
521
+ }
522
+ // An unresolvable import still has a local alias symbol; following it yields TypeScript's placeholder
523
+ // `unknownSymbol`, which has no declarations and is treated as "unresolvable" by the caller.
524
+ return symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
525
+ };
526
+ const getTypeAliasDeclaration = (symbol) => symbol?.getDeclarations()?.find(ts.isTypeAliasDeclaration);
527
+ /** `any`, including TypeScript's error type for an unresolvable reference. */
528
+ const isAnyType = (type) => (type.flags & ts.TypeFlags.Any) !== 0;
529
+ /**
530
+ * Type-aware contract check driven from the annotation's TS *node* rather than its resolved type.
531
+ *
532
+ * Bug fix (SDK-564): `checker.getTypeAtLocation` on a whole annotation lets TypeScript collapse `any & X` to `any`,
533
+ * so one unresolvable import (the error type) hid every sibling contract. Intersection (`some`) and union (`every`)
534
+ * constituents are therefore resolved individually, mirroring the syntactic `typeHasRequiredInterface`. A constituent
535
+ * that resolves to `any` is either an unresolvable reference, which counts by name since TypeScript already reports
536
+ * the broken import, or a type alias whose body is walked the same way; anything that resolves normally is handed to
537
+ * `checkerTypeHasRequiredInterface`.
538
+ *
539
+ * The whole annotation's type is resolved once up front as the exposure root for every constituent (SDK-564): a
540
+ * member such as `Omit<CommonProps, "id">` is judged on what the *resulting* props type exposes, since its siblings
541
+ * may contribute the members it drops. When the whole annotation collapses to `any` (a broken import) there is no
542
+ * usable root, and each constituent is its own.
543
+ */
544
+ const checkerTypeNodeHasRequiredInterface = (typeNode, requiredInterface, checker) => {
545
+ const annotationType = checker.getTypeAtLocation(typeNode);
546
+ const exposureRoot = isAnyType(annotationType) ? undefined : annotationType;
547
+ return typeNodeConstituentHasRequiredInterface(typeNode, requiredInterface, checker, exposureRoot, new Set());
548
+ };
549
+ const typeNodeConstituentHasRequiredInterface = (typeNode, requiredInterface, checker, exposureRoot, visitedAliases) => {
550
+ const checkConstituent = (part, aliases) => typeNodeConstituentHasRequiredInterface(part, requiredInterface, checker, exposureRoot, aliases);
551
+ if (ts.isParenthesizedTypeNode(typeNode)) {
552
+ return checkConstituent(typeNode.type, visitedAliases);
553
+ }
554
+ if (ts.isIntersectionTypeNode(typeNode)) {
555
+ return typeNode.types.some(part => checkConstituent(part, new Set(visitedAliases)));
556
+ }
557
+ if (ts.isUnionTypeNode(typeNode)) {
558
+ return typeNode.types.every(part => checkConstituent(part, new Set(visitedAliases)));
559
+ }
560
+ const type = checker.getTypeAtLocation(typeNode);
561
+ if (!isAnyType(type) || !ts.isTypeReferenceNode(typeNode)) {
562
+ return (0, exports.checkerTypeHasRequiredInterface)(type, requiredInterface, checker, new Set(), exposureRoot ?? type);
563
+ }
564
+ const symbol = resolveTypeReferenceSymbol(typeNode, checker);
565
+ const aliasDeclaration = getTypeAliasDeclaration(symbol);
566
+ if (aliasDeclaration) {
567
+ if (visitedAliases.has(aliasDeclaration)) {
568
+ return false;
569
+ }
570
+ visitedAliases.add(aliasDeclaration);
571
+ return checkConstituent(aliasDeclaration.type, visitedAliases);
572
+ }
573
+ const isUnresolvable = (symbol?.getDeclarations()?.length ?? 0) === 0;
574
+ return isUnresolvable && getTypeReferenceNameNode(typeNode).text === requiredInterface;
575
+ };
371
576
  const checkerTypeHasRequiredProp = (type, requiredProp, checker) => {
372
577
  if (type.isUnion()) {
373
578
  return type.types.every(part => checkerTypeHasRequiredProp(part, requiredProp, checker));
374
579
  }
375
580
  return Boolean(type.getProperty(requiredProp));
376
581
  };
582
+ /**
583
+ * The contract names a resolved props type is missing, required props first, then required interfaces, in the
584
+ * configured order. Exported so checker-backed candidates can be judged without an annotation node (SDK-565).
585
+ */
586
+ const getMissingContractsForCheckerType = (type, { requiredProps, requiredInterfaces }, checker) => [
587
+ ...requiredProps.filter(requiredProp => !checkerTypeHasRequiredProp(type, requiredProp, checker)),
588
+ ...requiredInterfaces.filter(requiredInterface => !(0, exports.checkerTypeHasRequiredInterface)(type, requiredInterface, checker)),
589
+ ];
590
+ exports.getMissingContractsForCheckerType = getMissingContractsForCheckerType;
591
+ /**
592
+ * The contracts missing from *every* one of several props types, in the configured order: for an overloaded
593
+ * component each overload's props type is a candidate, and a contract carried by any of them is satisfied
594
+ * (SDK-565). An empty list of types misses nothing; callers skip such candidates before getting here.
595
+ */
596
+ const getMissingContractsForCheckerTypes = (types, contractOptions, checker) => {
597
+ const [firstMissing = [], ...otherMissing] = types.map(type => (0, exports.getMissingContractsForCheckerType)(type, contractOptions, checker));
598
+ return firstMissing.filter(contract => otherMissing.every(missing => missing.includes(contract)));
599
+ };
600
+ exports.getMissingContractsForCheckerTypes = getMissingContractsForCheckerTypes;
601
+ const getTsTypeNode = (typeNode, typeCheckerContext) => {
602
+ const tsNode = typeCheckerContext?.services.esTreeNodeToTSNodeMap.get(typeNode);
603
+ return tsNode && ts.isTypeNode(tsNode) ? tsNode : null;
604
+ };
377
605
  const getCheckerType = (typeNode, typeCheckerContext) => {
378
606
  if (!typeCheckerContext) {
379
607
  return null;
@@ -430,10 +658,12 @@ exports.requireComponentPropContracts = createRule({
430
658
  if (!projectMetadata) {
431
659
  return {};
432
660
  }
433
- const requiredProps = options.requiredProps ?? [];
434
- const requiredInterfaces = options.requiredInterfaces ?? [];
661
+ const contractOptions = {
662
+ requiredProps: options.requiredProps ?? [],
663
+ requiredInterfaces: options.requiredInterfaces ?? [],
664
+ };
435
665
  const restrictToComponentsWithJsxReturn = options.restrictToComponentsWithJsxReturn ?? false;
436
- if (requiredProps.length === 0 && requiredInterfaces.length === 0) {
666
+ if (contractOptions.requiredProps.length === 0 && contractOptions.requiredInterfaces.length === 0) {
437
667
  return {};
438
668
  }
439
669
  const declarations = {
@@ -441,30 +671,109 @@ exports.requireComponentPropContracts = createRule({
441
671
  typeAliases: new Map(),
442
672
  };
443
673
  const typeCheckerContext = getTypeCheckerContext(context);
674
+ /** Local names exported via module-local `export { X }` specifiers anywhere in the file. */
444
675
  const exportedIdentifiers = new Set();
445
- const componentCandidates = [];
676
+ /** Local name exported via `export default X` or `export { X as default }`, if any. */
677
+ let defaultExportedIdentifier = null;
678
+ const componentDeclarations = [];
446
679
  const projectRoot = getProjectRoot(projectMetadata.projectJsonPath);
447
- const publicExports = getPublicExportedNamesForFile(projectRoot, filename);
448
- const isCurrentFileEntrypoint = isEntrypointFile(projectRoot, filename);
449
- const isExportedComponentName = (componentName, node) => {
450
- if (!isPascalCaseName(componentName) ||
451
- (!isExportedDeclaration(node) && !exportedIdentifiers.has(componentName))) {
452
- return false;
680
+ const publicExports = (0, entrypoint_exports_1.getPublicExportedNamesForFile)(projectRoot, filename);
681
+ const isCurrentFileEntrypoint = (0, entrypoint_exports_1.isEntrypointFile)(projectRoot, filename);
682
+ /** `export const X`, `export function X`, or a module-local `export { X }` naming the declaration. */
683
+ const isNamedExportedComponent = ({ componentName, node }) => isNamedExportedDeclaration(node) || (isModuleScopedDeclaration(node) && exportedIdentifiers.has(componentName));
684
+ /** `export default function X`, `export default X`, or `export { X as default }`. */
685
+ const isDefaultExportedComponent = ({ componentName, node }) => isDefaultExportedDeclaration(node) ||
686
+ (isModuleScopedDeclaration(node) && defaultExportedIdentifier === componentName);
687
+ /**
688
+ * Whether an entrypoint exposes this exported component. A named export is reachable through `export *` or a
689
+ * re-export of its local declaration name. The default export is reachable only through a `default` re-export
690
+ * (`exportsDefault`), regardless of its local name, since the entrypoint's alias (`export { default as X }`)
691
+ * says nothing about what the declaration is called and `export *` never forwards `default` (SDK-563).
692
+ * A declaration can be both named- and default-exported, so either path makes it public.
693
+ */
694
+ const isPublicComponent = ({ componentName, isNamedExport, isDefaultExport }) => isCurrentFileEntrypoint ||
695
+ (isNamedExport && (publicExports.exportsAll || publicExports.names.has(componentName))) ||
696
+ (isDefaultExport && publicExports.exportsDefault);
697
+ /**
698
+ * Resolves a collected declaration to a checkable candidate, or `null` when it is not a public export.
699
+ * Only valid once the whole file has been visited (see `Program:exit`).
700
+ */
701
+ const toComponentCandidate = (declaration) => {
702
+ const candidate = {
703
+ ...declaration,
704
+ isNamedExport: isNamedExportedComponent(declaration),
705
+ isDefaultExport: isDefaultExportedComponent(declaration),
706
+ };
707
+ if (!candidate.isNamedExport && !candidate.isDefaultExport) {
708
+ return null;
453
709
  }
454
- return isCurrentFileEntrypoint || publicExports.exportsAll || publicExports.names.has(componentName);
710
+ return isPublicComponent(candidate) ? candidate : null;
455
711
  };
456
- const checkCandidate = (candidate) => {
457
- const checkerType = candidate.propsType ? getCheckerType(candidate.propsType, typeCheckerContext) : null;
458
- const missingProps = requiredProps.filter(requiredProp => !candidate.propsType ||
712
+ /**
713
+ * With type information the interface check starts from the annotation's TS node, not its resolved type, so an
714
+ * unresolvable member cannot collapse its siblings to `any` (SDK-564). Without it, the syntactic walk applies.
715
+ */
716
+ const propsTypeHasRequiredInterface = (propsType, requiredInterface) => {
717
+ const propsTsTypeNode = getTsTypeNode(propsType, typeCheckerContext);
718
+ return propsTsTypeNode && typeCheckerContext
719
+ ? checkerTypeNodeHasRequiredInterface(propsTsTypeNode, requiredInterface, typeCheckerContext.checker)
720
+ : typeHasRequiredInterface(propsType, requiredInterface, declarations, new Set());
721
+ };
722
+ /** Contracts missing from a candidate's props annotation (`propsType`); a missing annotation misses them all. */
723
+ const getMissingContractsForPropsType = (propsType, { requiredProps, requiredInterfaces }) => {
724
+ const checkerType = propsType ? getCheckerType(propsType, typeCheckerContext) : null;
725
+ const missingProps = requiredProps.filter(requiredProp => !propsType ||
459
726
  (checkerType && typeCheckerContext
460
727
  ? !checkerTypeHasRequiredProp(checkerType, requiredProp, typeCheckerContext.checker)
461
- : !typeHasRequiredProp(candidate.propsType, requiredProp, declarations, new Set())));
462
- const missingInterfaces = requiredInterfaces.filter(requiredInterface => !candidate.propsType ||
463
- (checkerType && typeCheckerContext
464
- ? !(0, exports.checkerTypeHasRequiredInterface)(checkerType, requiredInterface, typeCheckerContext.checker)
465
- : !typeHasRequiredInterface(candidate.propsType, requiredInterface, declarations, new Set())));
466
- const missingContracts = [...missingProps, ...missingInterfaces];
467
- if (missingContracts.length === 0) {
728
+ : !typeHasRequiredProp(propsType, requiredProp, declarations, new Set())));
729
+ const missingInterfaces = requiredInterfaces.filter(requiredInterface => !propsType || !propsTypeHasRequiredInterface(propsType, requiredInterface));
730
+ return [...missingProps, ...missingInterfaces];
731
+ };
732
+ /**
733
+ * Contracts a candidate is missing, or `null` when it cannot be judged. A checker-backed candidate
734
+ * (`propsCheckerTypes`, SDK-565) is judged on those types alone, never on `propsType`; one whose props types
735
+ * could not be resolved is skipped instead of being reported for every contract.
736
+ */
737
+ const getMissingContracts = (candidate) => {
738
+ if (candidate.propsCheckerTypes === undefined) {
739
+ return getMissingContractsForPropsType(candidate.propsType, contractOptions);
740
+ }
741
+ return candidate.propsCheckerTypes.length > 0 && typeCheckerContext
742
+ ? (0, exports.getMissingContractsForCheckerTypes)(candidate.propsCheckerTypes, contractOptions, typeCheckerContext.checker)
743
+ : null;
744
+ };
745
+ /**
746
+ * Records a resolved component under `componentName`, with `node` as the declaration the export decision and
747
+ * the report are made on: the declarator for `export const Button = memo(Base)`, the wrapper call itself for
748
+ * `export default memo(Base)` (SDK-565).
749
+ */
750
+ const collectComponent = (componentName, node, component) => {
751
+ if (component.kind === "imported") {
752
+ // Bug fix (SDK-565): an imported wrapped reference used to be skipped unconditionally. Its props are only
753
+ // reachable through the type checker, and whether it returns intrinsic JSX is not visible at all, so it
754
+ // is checked only with type information and without `restrictToComponentsWithJsxReturn`. Explicit wrapper
755
+ // type arguments (`forwardRef<E, P>(Imported)`) are an annotation in this file and take precedence.
756
+ if (!typeCheckerContext || restrictToComponentsWithJsxReturn) {
757
+ return;
758
+ }
759
+ componentDeclarations.push(component.propsType
760
+ ? { componentName, node, propsType: component.propsType }
761
+ : {
762
+ componentName,
763
+ node,
764
+ propsType: null,
765
+ propsCheckerTypes: getImportedPropsCheckerTypes(component.identifier, typeCheckerContext),
766
+ });
767
+ return;
768
+ }
769
+ if (restrictToComponentsWithJsxReturn && !(0, ast_utils_1.functionReturnsIntrinsicJSX)(component.functionNode)) {
770
+ return;
771
+ }
772
+ componentDeclarations.push({ componentName, node, propsType: component.propsType });
773
+ };
774
+ const checkCandidate = (candidate) => {
775
+ const missingContracts = getMissingContracts(candidate);
776
+ if (!missingContracts || missingContracts.length === 0) {
468
777
  return;
469
778
  }
470
779
  context.report({
@@ -478,15 +787,36 @@ exports.requireComponentPropContracts = createRule({
478
787
  };
479
788
  return {
480
789
  ExportNamedDeclaration(node) {
790
+ // `export { X } from "./other"` re-exports another module's binding, not a local declaration.
791
+ if (node.source) {
792
+ return;
793
+ }
794
+ // Without a `source`, every specifier's `local` is an identifier naming a module-local binding.
481
795
  for (const specifier of node.specifiers) {
482
- if (specifier.local.type === utils_1.AST_NODE_TYPES.Identifier) {
483
- exportedIdentifiers.add(specifier.local.name);
796
+ if (isDefaultExportSpecifier(specifier)) {
797
+ defaultExportedIdentifier = specifier.local.name;
798
+ continue;
484
799
  }
800
+ exportedIdentifiers.add(specifier.local.name);
485
801
  }
486
802
  },
487
803
  ExportDefaultDeclaration(node) {
488
- if (node.declaration.type === utils_1.AST_NODE_TYPES.Identifier) {
489
- exportedIdentifiers.add(node.declaration.name);
804
+ const { declaration } = node;
805
+ if (declaration.type === utils_1.AST_NODE_TYPES.Identifier) {
806
+ defaultExportedIdentifier = declaration.name;
807
+ return;
808
+ }
809
+ // Bug fix (SDK-565): `export default memo(Base)` used to be dropped because only identifier declarations
810
+ // were tracked here. The wrapper call is resolved like a declarator initialiser; the statement has no name
811
+ // of its own, so the component is reported under the wrapped function's name (`Base`), and an anonymous
812
+ // inline argument is skipped like `export default () => …`. The call node is the declaration: it sits
813
+ // directly under the `ExportDefaultDeclaration`, so it is default-exported and module-scoped.
814
+ if (declaration.type !== utils_1.AST_NODE_TYPES.CallExpression) {
815
+ return;
816
+ }
817
+ const component = getWrapperCallComponent(declaration, context.sourceCode);
818
+ if (component?.name && isPascalCaseName(component.name)) {
819
+ collectComponent(component.name, declaration, component);
490
820
  }
491
821
  },
492
822
  TSInterfaceDeclaration(node) {
@@ -497,14 +827,14 @@ exports.requireComponentPropContracts = createRule({
497
827
  },
498
828
  FunctionDeclaration(node) {
499
829
  const componentName = node.id?.name;
500
- const returnsIntrinsicJsx = (0, ast_utils_1.functionReturnsIntrinsicJSX)(node) === true;
830
+ const returnsIntrinsicJsx = (0, ast_utils_1.functionReturnsIntrinsicJSX)(node);
501
831
  if (!componentName ||
832
+ !isPascalCaseName(componentName) ||
502
833
  !(0, ast_utils_1.isReactComponent)(node) ||
503
- (restrictToComponentsWithJsxReturn && !returnsIntrinsicJsx) ||
504
- !isExportedComponentName(componentName, node)) {
834
+ (restrictToComponentsWithJsxReturn && !returnsIntrinsicJsx)) {
505
835
  return;
506
836
  }
507
- componentCandidates.push({
837
+ componentDeclarations.push({
508
838
  componentName,
509
839
  node,
510
840
  propsType: getFunctionPropsType(node),
@@ -514,27 +844,27 @@ exports.requireComponentPropContracts = createRule({
514
844
  if (node.id.type !== utils_1.AST_NODE_TYPES.Identifier) {
515
845
  return;
516
846
  }
517
- const { init } = node;
518
- const wrappedComponentFunction = init?.type === utils_1.AST_NODE_TYPES.CallExpression ? getWrappedComponentFunction(init) : null;
519
- const isComponent = init?.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression
520
- ? (0, ast_utils_1.isReactComponent)(init)
521
- : wrappedComponentFunction !== null;
522
- const returnsJsx = init?.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression
523
- ? (0, ast_utils_1.functionReturnsIntrinsicJSX)(init) === true
524
- : wrappedComponentFunction !== null && (0, ast_utils_1.functionReturnsIntrinsicJSX)(wrappedComponentFunction) === true;
525
- if (!isComponent ||
526
- (restrictToComponentsWithJsxReturn && !returnsJsx) ||
527
- !isExportedComponentName(node.id.name, node)) {
847
+ if (!isPascalCaseName(node.id.name)) {
528
848
  return;
529
849
  }
530
- componentCandidates.push({
531
- componentName: node.id.name,
532
- node,
533
- propsType: getPropsTypeFromVariableDeclarator(node),
534
- });
850
+ // The component checks and the props annotation apply to the *resolved* function (inline or a same-file
851
+ // reference), while the declaration keeps the exported declarator so the report lands on `Button` for
852
+ // `export const Button = memo(ButtonBase)` (SDK-565).
853
+ const component = getVariableComponent(node, context.sourceCode);
854
+ if (component) {
855
+ collectComponent(node.id.name, node, component);
856
+ }
535
857
  },
536
858
  "Program:exit"() {
537
- componentCandidates.forEach(checkCandidate);
859
+ // The export decision is deferred until here: `export { X }` / `export default X` may appear after the
860
+ // declaration, so `exportedIdentifiers` / `defaultExportedIdentifier` are only complete once the whole
861
+ // file has been visited (SDK-563).
862
+ for (const declaration of componentDeclarations) {
863
+ const candidate = toComponentCandidate(declaration);
864
+ if (candidate) {
865
+ checkCandidate(candidate);
866
+ }
867
+ }
538
868
  },
539
869
  };
540
870
  },