@starci/eslint-canon-be 3.18.4 → 3.19.1

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 (211) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -1
  3. package/dist/comments.js +1 -1
  4. package/dist/explicit-surface.js +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/jwt-alg.js +1 -1
  7. package/dist/lib/edition.d.ts +1 -1
  8. package/dist/lib/edition.js +1 -1
  9. package/dist/lib/hfs-view.d.ts +5 -0
  10. package/dist/lib/hfs.d.ts +0 -6
  11. package/dist/lib/hfs.js +7 -5
  12. package/dist/lib/runtime-root.d.ts +6 -1
  13. package/dist/lib/runtime-root.js +8 -2
  14. package/dist/lib/subject-values.js +1 -1
  15. package/dist/module-layering.js +2 -2
  16. package/dist/project-graph.js +1 -1
  17. package/dist/schema-authority.js +66 -2
  18. package/dist/third-party-owner.js +1 -1
  19. package/package.json +3 -1
  20. package/runtime/bundle.json +1 -190
  21. package/runtime/scripts/api/git/recorded-lines.mjs +5 -5
  22. package/runtime/scripts/hfs/project-graph.mjs +6 -6
  23. package/runtime/scripts/hfs/project-rule.mjs +3 -3
  24. package/runtime/config.example.yaml +0 -194
  25. package/runtime/engine/by-code-unit.mjs +0 -12
  26. package/runtime/engine/config.mjs +0 -461
  27. package/runtime/engine/invalid-config.mjs +0 -15
  28. package/runtime/engine/model-config.mjs +0 -112
  29. package/runtime/engine/orca-config.mjs +0 -34
  30. package/runtime/engine/plain-object.mjs +0 -5
  31. package/runtime/engine/release-config.mjs +0 -32
  32. package/runtime/engine/removed-vocabulary.mjs +0 -27
  33. package/runtime/engine/resources-config.mjs +0 -59
  34. package/runtime/engine/runtime-root.mjs +0 -138
  35. package/runtime/engine/secrets.mjs +0 -202
  36. package/runtime/engine/sonar-config.mjs +0 -24
  37. package/runtime/engine/temp-root.mjs +0 -26
  38. package/runtime/engine/yaml.mjs +0 -161
  39. package/runtime/knowledge/grammars/index.yaml +0 -114
  40. package/runtime/knowledge/hfs/canon-pins.yaml +0 -720
  41. package/runtime/knowledge/hfs/fe-stack.yaml +0 -272
  42. package/runtime/knowledge/hfs/rules.yaml +0 -6760
  43. package/runtime/knowledge/hfs/slots.yaml +0 -2783
  44. package/runtime/knowledge/patterns/fe/folder.yaml +0 -425
  45. package/runtime/knowledge/sonar-gate.yaml +0 -151
  46. package/runtime/modules/kernel/removed-vocabulary.yaml +0 -458
  47. package/runtime/modules/models/registry.yaml +0 -221
  48. package/runtime/modules/models/runtimes.yaml +0 -556
  49. package/runtime/modules/models/tiers.yaml +0 -66
  50. package/runtime/scripts/api/git/cat-file.mjs +0 -4
  51. package/runtime/scripts/api/git/config-get.mjs +0 -9
  52. package/runtime/scripts/api/git/diff.mjs +0 -4
  53. package/runtime/scripts/api/git/lib.mjs +0 -80
  54. package/runtime/scripts/api/git/ls-files.mjs +0 -5
  55. package/runtime/scripts/api/git/ls-tree.mjs +0 -4
  56. package/runtime/scripts/api/git/merge-base.mjs +0 -8
  57. package/runtime/scripts/api/git/remote.mjs +0 -4
  58. package/runtime/scripts/api/git/rev-parse-query.mjs +0 -4
  59. package/runtime/scripts/api/git/show.mjs +0 -5
  60. package/runtime/scripts/api/git/tag.mjs +0 -4
  61. package/runtime/scripts/hfs/allows.mjs +0 -77
  62. package/runtime/scripts/hfs/architecture/ast-walks.mjs +0 -250
  63. package/runtime/scripts/hfs/architecture/automatic-gates.mjs +0 -103
  64. package/runtime/scripts/hfs/architecture/backend-app-files.mjs +0 -114
  65. package/runtime/scripts/hfs/architecture/backend.mjs +0 -462
  66. package/runtime/scripts/hfs/architecture/background-unowned.mjs +0 -254
  67. package/runtime/scripts/hfs/architecture/canon-clones.mjs +0 -291
  68. package/runtime/scripts/hfs/architecture/canon-jsx-clones.mjs +0 -224
  69. package/runtime/scripts/hfs/architecture/client-reaches-server.mjs +0 -102
  70. package/runtime/scripts/hfs/architecture/clones.mjs +0 -287
  71. package/runtime/scripts/hfs/architecture/component-tiers.mjs +0 -161
  72. package/runtime/scripts/hfs/architecture/config-unread.mjs +0 -16
  73. package/runtime/scripts/hfs/architecture/config.mjs +0 -407
  74. package/runtime/scripts/hfs/architecture/connection-map.mjs +0 -350
  75. package/runtime/scripts/hfs/architecture/constructor-deps.mjs +0 -115
  76. package/runtime/scripts/hfs/architecture/context-coupling.mjs +0 -117
  77. package/runtime/scripts/hfs/architecture/context-map.mjs +0 -355
  78. package/runtime/scripts/hfs/architecture/context-owner.mjs +0 -102
  79. package/runtime/scripts/hfs/architecture/context-platform-tables.mjs +0 -65
  80. package/runtime/scripts/hfs/architecture/context-transaction.mjs +0 -75
  81. package/runtime/scripts/hfs/architecture/contract-bounds.mjs +0 -72
  82. package/runtime/scripts/hfs/architecture/contract-fixture-guard.mjs +0 -177
  83. package/runtime/scripts/hfs/architecture/contracts-readonly.mjs +0 -360
  84. package/runtime/scripts/hfs/architecture/contracts.mjs +0 -489
  85. package/runtime/scripts/hfs/architecture/cross-app-duplicate.mjs +0 -81
  86. package/runtime/scripts/hfs/architecture/dead-exports-bindings.mjs +0 -173
  87. package/runtime/scripts/hfs/architecture/dead-exports.mjs +0 -420
  88. package/runtime/scripts/hfs/architecture/default-deny.mjs +0 -175
  89. package/runtime/scripts/hfs/architecture/doc-language.mjs +0 -45
  90. package/runtime/scripts/hfs/architecture/entity-registry.mjs +0 -51
  91. package/runtime/scripts/hfs/architecture/entrypoint.mjs +0 -75
  92. package/runtime/scripts/hfs/architecture/error-codes.mjs +0 -54
  93. package/runtime/scripts/hfs/architecture/error-masked.mjs +0 -78
  94. package/runtime/scripts/hfs/architecture/fe-slot-allows.mjs +0 -44
  95. package/runtime/scripts/hfs/architecture/feature-shape.mjs +0 -60
  96. package/runtime/scripts/hfs/architecture/framework-pinned.mjs +0 -41
  97. package/runtime/scripts/hfs/architecture/frontend-block-render.mjs +0 -112
  98. package/runtime/scripts/hfs/architecture/frontend-grammar.mjs +0 -193
  99. package/runtime/scripts/hfs/architecture/frontend-routing.mjs +0 -198
  100. package/runtime/scripts/hfs/architecture/frontend-world-render.mjs +0 -368
  101. package/runtime/scripts/hfs/architecture/frontend-world.mjs +0 -374
  102. package/runtime/scripts/hfs/architecture/frontend.mjs +0 -248
  103. package/runtime/scripts/hfs/architecture/function-spec-providers.mjs +0 -185
  104. package/runtime/scripts/hfs/architecture/hfs-graph.mjs +0 -77
  105. package/runtime/scripts/hfs/architecture/hfs.mjs +0 -394
  106. package/runtime/scripts/hfs/architecture/hooks-are-hooks.mjs +0 -118
  107. package/runtime/scripts/hfs/architecture/i18n-keys.mjs +0 -213
  108. package/runtime/scripts/hfs/architecture/identity.mjs +0 -121
  109. package/runtime/scripts/hfs/architecture/index.mjs +0 -402
  110. package/runtime/scripts/hfs/architecture/injection-token-exported.mjs +0 -69
  111. package/runtime/scripts/hfs/architecture/jwt-ast.mjs +0 -231
  112. package/runtime/scripts/hfs/architecture/machine-ast.mjs +0 -232
  113. package/runtime/scripts/hfs/architecture/managed-scripts.mjs +0 -32
  114. package/runtime/scripts/hfs/architecture/module-per-transport.mjs +0 -237
  115. package/runtime/scripts/hfs/architecture/next-data-contract.mjs +0 -126
  116. package/runtime/scripts/hfs/architecture/next-data-inference.mjs +0 -192
  117. package/runtime/scripts/hfs/architecture/next-data-key.mjs +0 -374
  118. package/runtime/scripts/hfs/architecture/next-data-symbols.mjs +0 -26
  119. package/runtime/scripts/hfs/architecture/next-data.mjs +0 -425
  120. package/runtime/scripts/hfs/architecture/operation-contract-roots.mjs +0 -55
  121. package/runtime/scripts/hfs/architecture/owners.mjs +0 -142
  122. package/runtime/scripts/hfs/architecture/package-shape.mjs +0 -92
  123. package/runtime/scripts/hfs/architecture/presentation.mjs +0 -173
  124. package/runtime/scripts/hfs/architecture/reachability.mjs +0 -330
  125. package/runtime/scripts/hfs/architecture/register-once.mjs +0 -212
  126. package/runtime/scripts/hfs/architecture/registration.mjs +0 -372
  127. package/runtime/scripts/hfs/architecture/render-graph.mjs +0 -449
  128. package/runtime/scripts/hfs/architecture/render-prop-across-server.mjs +0 -58
  129. package/runtime/scripts/hfs/architecture/required-files.mjs +0 -237
  130. package/runtime/scripts/hfs/architecture/root-packages.mjs +0 -78
  131. package/runtime/scripts/hfs/architecture/route-files-thin.mjs +0 -133
  132. package/runtime/scripts/hfs/architecture/schema-owner.mjs +0 -288
  133. package/runtime/scripts/hfs/architecture/server-action.mjs +0 -78
  134. package/runtime/scripts/hfs/architecture/side-boundary.mjs +0 -13
  135. package/runtime/scripts/hfs/architecture/source-names-shape.mjs +0 -320
  136. package/runtime/scripts/hfs/architecture/source-names.mjs +0 -393
  137. package/runtime/scripts/hfs/architecture/sql-keys.mjs +0 -344
  138. package/runtime/scripts/hfs/architecture/sql-owner.mjs +0 -291
  139. package/runtime/scripts/hfs/architecture/sql-returning.mjs +0 -76
  140. package/runtime/scripts/hfs/architecture/sql-token-forms.mjs +0 -117
  141. package/runtime/scripts/hfs/architecture/sql-tokens.mjs +0 -587
  142. package/runtime/scripts/hfs/architecture/staged-consumers.mjs +0 -42
  143. package/runtime/scripts/hfs/architecture/surface-nesting.mjs +0 -127
  144. package/runtime/scripts/hfs/architecture/surface.mjs +0 -88
  145. package/runtime/scripts/hfs/architecture/symbols.mjs +0 -273
  146. package/runtime/scripts/hfs/architecture/test-world-files.mjs +0 -263
  147. package/runtime/scripts/hfs/architecture/tiers.mjs +0 -256
  148. package/runtime/scripts/hfs/architecture/transport-owner.mjs +0 -248
  149. package/runtime/scripts/hfs/architecture/type-context.mjs +0 -335
  150. package/runtime/scripts/hfs/architecture/typescript.mjs +0 -477
  151. package/runtime/scripts/hfs/architecture/unit-spec-providers.mjs +0 -165
  152. package/runtime/scripts/hfs/declaration-shape.mjs +0 -196
  153. package/runtime/scripts/hfs/declaration-slots.mjs +0 -89
  154. package/runtime/scripts/hfs/edition-slots.mjs +0 -80
  155. package/runtime/scripts/hfs/explicit-surface-rule.mjs +0 -59
  156. package/runtime/scripts/hfs/linear-text.mjs +0 -30
  157. package/runtime/scripts/hfs/manifest-shape.mjs +0 -474
  158. package/runtime/scripts/hfs/param-names.mjs +0 -13
  159. package/runtime/scripts/hfs/path-findings.mjs +0 -167
  160. package/runtime/scripts/hfs/repo-identity.mjs +0 -89
  161. package/runtime/scripts/hfs/rule-catalog.mjs +0 -458
  162. package/runtime/scripts/hfs/rule-params-shape.mjs +0 -103
  163. package/runtime/scripts/hfs/rules/database-constants.mjs +0 -25
  164. package/runtime/scripts/hfs/rules/database-migrations.mjs +0 -684
  165. package/runtime/scripts/hfs/rules/fe-no-tests.mjs +0 -68
  166. package/runtime/scripts/hfs/rules/read.mjs +0 -45
  167. package/runtime/scripts/hfs/rules/secrets.mjs +0 -79
  168. package/runtime/scripts/hfs/rules/spec-placement.mjs +0 -28
  169. package/runtime/scripts/hfs/slot-app-view.mjs +0 -97
  170. package/runtime/scripts/hfs/slot-classify.mjs +0 -69
  171. package/runtime/scripts/hfs/slot-errors.mjs +0 -12
  172. package/runtime/scripts/hfs/slot-imports.mjs +0 -98
  173. package/runtime/scripts/hfs/slot-manifest-shape.mjs +0 -111
  174. package/runtime/scripts/hfs/slot-match.mjs +0 -164
  175. package/runtime/scripts/hfs/slot-path.mjs +0 -6
  176. package/runtime/scripts/hfs/slot-required.mjs +0 -95
  177. package/runtime/scripts/hfs/slot-semantic-problems.mjs +0 -175
  178. package/runtime/scripts/hfs/slot-side-problems.mjs +0 -32
  179. package/runtime/scripts/hfs/slots.mjs +0 -306
  180. package/runtime/scripts/hfs/test-world-slot.mjs +0 -5
  181. package/runtime/scripts/hfs/trailing-slashes.mjs +0 -8
  182. package/runtime/scripts/hfs/typescript-programs.mjs +0 -95
  183. package/runtime/scripts/hfs/view.mjs +0 -180
  184. package/runtime/scripts/lib/declaration-surface.mjs +0 -166
  185. package/runtime/scripts/lib/dockerfile.mjs +0 -164
  186. package/runtime/scripts/lib/env.mjs +0 -18
  187. package/runtime/scripts/lib/event-contract.mjs +0 -102
  188. package/runtime/scripts/lib/git-hooks-dir.mjs +0 -30
  189. package/runtime/scripts/lib/git.mjs +0 -35
  190. package/runtime/scripts/lib/glob.mjs +0 -32
  191. package/runtime/scripts/lib/grammar-lint.mjs +0 -57
  192. package/runtime/scripts/lib/i18n.mjs +0 -82
  193. package/runtime/scripts/lib/in-order.mjs +0 -90
  194. package/runtime/scripts/lib/json-clone.mjs +0 -70
  195. package/runtime/scripts/lib/json.mjs +0 -44
  196. package/runtime/scripts/lib/language.mjs +0 -233
  197. package/runtime/scripts/lib/list.mjs +0 -26
  198. package/runtime/scripts/lib/mutation-fence.mjs +0 -20
  199. package/runtime/scripts/lib/package-at.mjs +0 -62
  200. package/runtime/scripts/lib/path-key.mjs +0 -124
  201. package/runtime/scripts/lib/read-text.mjs +0 -47
  202. package/runtime/scripts/lib/regex.mjs +0 -3
  203. package/runtime/scripts/lib/rule-packs.mjs +0 -243
  204. package/runtime/scripts/lib/same-text.mjs +0 -4
  205. package/runtime/scripts/lib/secret-patterns.mjs +0 -230
  206. package/runtime/scripts/lib/sops-envelope.mjs +0 -212
  207. package/runtime/scripts/lib/stack-services.mjs +0 -191
  208. package/runtime/scripts/lib/ts-analysis.mjs +0 -39
  209. package/runtime/scripts/lib/ts-ast.mjs +0 -63
  210. package/runtime/scripts/lib/walk.mjs +0 -45
  211. package/runtime/scripts/lib/yaml-cached.mjs +0 -14
@@ -1,477 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { contextFromProjects } from './type-context.mjs';
4
- import { createRequire } from 'node:module';
5
- import { canonical, isInside, slash } from './config.mjs';
6
- import { crossesSide } from './side-boundary.mjs';
7
- import { sameOrUnder } from '../../lib/path-key.mjs';
8
- import { createTypeScriptProgram, readTypeScriptProject, resolveTypeScriptModule, sharedInProgramRun, typeScriptProjectReferencePath } from '../typescript-programs.mjs';
9
- import { readJsonFile } from '../../lib/json.mjs';
10
- import { sourceLocation } from '../../lib/ts-ast.mjs';
11
- import { locateDeclaration } from '../slots.mjs';
12
- export { unwrapExpression } from '../../lib/ts-analysis.mjs';
13
- const CODE_EXTENSIONS = /\.(?:[cm]?[jt]sx?)$/i;
14
- const SCRIPT_TAIL = '[cm]?[jt]sx?';
15
- const TEST_FILE = new RegExp(String.raw `(?:^|[.-])(?:spec|test)\.${SCRIPT_TAIL}$`, 'i');
16
- const ASSET_EXTENSION_NAMES = 'css|scss|sass|less|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|eot|ya?ml|json';
17
- const ASSET_EXTENSION = new RegExp(String.raw `\.(?:${ASSET_EXTENSION_NAMES})$`, 'i');
18
- // Framework build output a tsconfig may include (Next writes `.next/types/**/*.ts` back into tsconfig.json on
19
- // every build) is compiled for type resolution but is never source: it is gitignored, regenerated, and no
20
- // canon or architecture rule applies to it (inc-ffe60c49f502).
21
- const GENERATED_SEGMENTS = new Set(['.next', '.turbo', '.vercel', '.output', '.nuxt', '.svelte-kit', '.expo', '.docusaurus', '.swc', '.cache']);
22
- function isGeneratedPath(root, fileName) {
23
- return slash(path.relative(root, fileName)).split('/').slice(0, -1).some((segment) => GENERATED_SEGMENTS.has(segment));
24
- }
25
- function diagnosticMessage(ts, diagnostic) {
26
- return ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
27
- }
28
- function compilerError(ts, root, diagnostic, project, ruleId = 'ARCH_TSCONFIG_INVALID') {
29
- const fileName = diagnostic.file?.fileName;
30
- let line;
31
- let column;
32
- if (diagnostic.file && diagnostic.start !== undefined && Number.isInteger(diagnostic.start)) {
33
- const point = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
34
- line = point.line + 1;
35
- column = point.character + 1;
36
- }
37
- return {
38
- ruleId,
39
- project,
40
- ...(fileName && isInside(root, fileName) ? { path: slash(path.relative(root, fileName)) } : {}),
41
- ...(line ? { line, column } : {}),
42
- message: diagnosticMessage(ts, diagnostic),
43
- };
44
- }
45
- /**
46
- * Load TypeScript through the target package boundary, never through StarCi's own dependency graph. A side folder of an app has no
47
- * package.json of its own: the app root's one manifest is the boundary its TypeScript is installed under.
48
- */
49
- function loadTargetTypeScript(repositoryRoot) {
50
- const packageFile = path.join(locateDeclaration(repositoryRoot).appRoot, 'package.json');
51
- if (!fs.existsSync(packageFile))
52
- throw new Error('ARCH_TYPESCRIPT_MISSING: target package.json is required to resolve target-installed TypeScript.');
53
- const targetRequire = createRequire(packageFile);
54
- let resolved;
55
- let ts;
56
- try {
57
- resolved = targetRequire.resolve('typescript');
58
- ts = targetRequire('typescript');
59
- }
60
- catch {
61
- throw new Error('ARCH_TYPESCRIPT_MISSING: install TypeScript in the checked repository; StarCi does not substitute its own parser.');
62
- }
63
- if (!ts?.createProgram || !ts?.resolveModuleName || !ts?.readConfigFile) {
64
- throw new Error('ARCH_TYPESCRIPT_INVALID: the target TypeScript package does not expose the compiler API.');
65
- }
66
- return { ts, resolved, version: String(ts.version ?? 'unknown') };
67
- }
68
- const readJson = (file) => readJsonFile(file, {});
69
- function pathAliasMatches(specifier, paths = {}) {
70
- return Object.keys(paths).some(pattern => {
71
- if (!pattern.includes('*'))
72
- return pattern === specifier;
73
- const [before = '', after] = pattern.split('*');
74
- return specifier.startsWith(before) && specifier.endsWith(after ?? '');
75
- });
76
- }
77
- function importDeclarationRuntime(ts, node) {
78
- const clause = node.importClause;
79
- if (!clause)
80
- return true;
81
- if (clause.isTypeOnly)
82
- return false;
83
- if (clause.name)
84
- return true;
85
- const named = clause.namedBindings;
86
- if (named && ts.isNamedImports(named))
87
- return named.elements.some(element => !element.isTypeOnly);
88
- return Boolean(named);
89
- }
90
- function exportDeclarationRuntime(ts, node) {
91
- if (node.isTypeOnly)
92
- return false;
93
- if (node.exportClause && ts.isNamedExports(node.exportClause))
94
- return node.exportClause.elements.some(element => !element.isTypeOnly);
95
- return true;
96
- }
97
- function runtimeImport(ts, node) {
98
- if (ts.isImportDeclaration(node))
99
- return importDeclarationRuntime(ts, node);
100
- if (ts.isExportDeclaration(node))
101
- return exportDeclarationRuntime(ts, node);
102
- return true;
103
- }
104
- export function isUnshadowedCommonJsRequire(ts, checker, expression) {
105
- if (!ts.isIdentifier(expression) || expression.text !== 'require')
106
- return false;
107
- const symbol = checker?.getSymbolAtLocation(expression);
108
- if (!symbol)
109
- return true;
110
- const declarations = symbol.getDeclarations?.() ?? [];
111
- return declarations.length > 0 && declarations.every(declaration => declaration.getSourceFile().isDeclarationFile);
112
- }
113
- /**
114
- * The files a template-literal import of data can load. import(`../messages/${locale}.json`) - the
115
- * next-intl request config - is bundled as a context of every file under ../messages whose name ends in
116
- * .json, so that set is the dependency, exactly and statically. Only a relative static head naming an
117
- * existing directory and a data-asset extension tail qualify; code never does, since a context of code would
118
- * be an import graph nobody wrote down. Returns the specifiers, or null when the import stays unproven.
119
- */
120
- /** The data-asset extension tail and relative head of an import template, or null when the template cannot name a data context. */
121
- function assetContextParts(ts, argument) {
122
- if (!argument || !ts.isTemplateExpression(argument))
123
- return null;
124
- const head = argument.head.text;
125
- const spans = argument.templateSpans;
126
- const tail = spans[spans.length - 1]?.literal.text ?? '';
127
- if (!/^\.\.?\//.test(head) || !head.endsWith('/') || !/^\.[a-z0-9]+$/i.test(tail) || !ASSET_EXTENSION.test(tail))
128
- return null;
129
- if (spans.slice(0, -1).some(span => span.literal.text.split('/').includes('..')))
130
- return null;
131
- return { head, tail };
132
- }
133
- /** The specifiers of every file below `directory` (node_modules skipped) whose name ends in `tail`, sorted by name at each level. */
134
- function assetFileSpecifiers(directory, head, tail) {
135
- const specifiers = [];
136
- const visit = (dir) => {
137
- for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
138
- if (entry.name === 'node_modules')
139
- continue;
140
- const absolute = path.join(dir, entry.name);
141
- if (entry.isDirectory())
142
- visit(absolute);
143
- else if (entry.isFile() && entry.name.toLowerCase().endsWith(tail.toLowerCase()))
144
- specifiers.push(`${head}${slash(path.relative(directory, absolute))}`);
145
- }
146
- };
147
- visit(directory);
148
- return specifiers;
149
- }
150
- function assetContextSpecifiers(ts, sourceFile, argument) {
151
- const parts = assetContextParts(ts, argument);
152
- if (!parts)
153
- return null;
154
- const directory = path.resolve(path.dirname(sourceFile.fileName), parts.head);
155
- let stat;
156
- try {
157
- stat = fs.statSync(directory);
158
- }
159
- catch {
160
- return null;
161
- }
162
- if (!stat.isDirectory())
163
- return null;
164
- const specifiers = assetFileSpecifiers(directory, parts.head, parts.tail);
165
- return specifiers.length ? specifiers : null;
166
- }
167
- function staticModuleReference(ts, node, found, unproven) {
168
- if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) {
169
- found.push({ node: node.moduleSpecifier, specifier: node.moduleSpecifier.text, runtime: runtimeImport(ts, node), declaration: node });
170
- return true;
171
- }
172
- else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)
173
- && node.moduleReference.expression && ts.isStringLiteralLike(node.moduleReference.expression)) {
174
- found.push({ node: node.moduleReference.expression, specifier: node.moduleReference.expression.text, runtime: !node.isTypeOnly, declaration: node });
175
- return true;
176
- }
177
- else if (ts.isImportTypeNode(node)) {
178
- const literal = ts.isLiteralTypeNode(node.argument) && ts.isStringLiteralLike(node.argument.literal) ? node.argument.literal : null;
179
- if (literal)
180
- found.push({ node: literal, specifier: literal.text, runtime: false, declaration: node });
181
- else
182
- unproven.push({ node, kind: 'TypeScript import type' });
183
- return true;
184
- }
185
- return false;
186
- }
187
- function dynamicImportReference(ts, sourceFile, node, found, unproven) {
188
- const first = node.arguments[0];
189
- const context = [1, 2].includes(node.arguments.length) ? assetContextSpecifiers(ts, sourceFile, first) : null;
190
- if ([1, 2].includes(node.arguments.length) && first && ts.isStringLiteralLike(first)) {
191
- found.push({ node: first, specifier: first.text, runtime: true, declaration: node });
192
- }
193
- else if (context && first) {
194
- for (const specifier of context)
195
- found.push({ node: first, specifier, runtime: true, declaration: node });
196
- }
197
- else
198
- unproven.push({ node, kind: 'dynamic import()' });
199
- }
200
- function requireReference(ts, _checker, node, found, unproven) {
201
- const first = node.arguments[0];
202
- if (node.arguments.length === 1 && first && ts.isStringLiteralLike(first)) {
203
- found.push({ node: first, specifier: first.text, runtime: true, declaration: node });
204
- }
205
- else
206
- unproven.push({ node, kind: 'dynamic require()' });
207
- }
208
- function callModuleReference(ts, sourceFile, checker, node, found, unproven) {
209
- if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword)
210
- dynamicImportReference(ts, sourceFile, node, found, unproven);
211
- else if (ts.isCallExpression(node) && isUnshadowedCommonJsRequire(ts, checker, node.expression))
212
- requireReference(ts, checker, node, found, unproven);
213
- }
214
- function moduleReferences(ts, sourceFile, checker) {
215
- const found = [];
216
- const unproven = [];
217
- const visit = (node) => {
218
- if (!staticModuleReference(ts, node, found, unproven))
219
- callModuleReference(ts, sourceFile, checker, node, found, unproven);
220
- ts.forEachChild(node, visit);
221
- };
222
- visit(sourceFile);
223
- return { found, unproven };
224
- }
225
- function isProductionSource(root, sourceFile) {
226
- return isInside(root, sourceFile.fileName)
227
- && CODE_EXTENSIONS.test(sourceFile.fileName)
228
- && !sourceFile.isDeclarationFile
229
- && !TEST_FILE.test(sourceFile.fileName)
230
- && !slash(sourceFile.fileName).includes('/node_modules/')
231
- && !isGeneratedPath(root, sourceFile.fileName);
232
- }
233
- function workspaceMetadata(config) {
234
- const backendAppRoots = config.backend.apps.map(item => path.join(config.root, ...item.split('/')));
235
- const create = (relative) => {
236
- const root = path.join(config.root, ...relative.split('/'));
237
- const pkg = readJson(path.join(root, 'package.json'));
238
- const routeRoots = config.frontend.routes.map(item => path.join(config.root, ...item.split('/')));
239
- return { root: canonical(root), relative, name: typeof pkg.name === 'string' ? pkg.name : null, exports: pkg.exports, manifest: pkg, workspace: true,
240
- app: routeRoots.some(route => isInside(root, route))
241
- || backendAppRoots.some(appRoot => isInside(appRoot, root) || isInside(root, appRoot)) };
242
- };
243
- const roots = config.workspaces.map(create);
244
- // A side of an app has no package.json: the app root's one manifest names the package the side's root files belong to.
245
- const rootPackage = readJson(path.join(config.packageRoot ?? config.root, 'package.json')) ?? {};
246
- roots.push({ root: canonical(config.root), relative: '.', name: typeof rootPackage.name === 'string' ? rootPackage.name : null, exports: rootPackage.exports,
247
- app: config.frontend.routes.some(item => isInside(config.root, path.join(config.root, ...item.split('/')))) || config.kinds.includes('backend') });
248
- return roots.sort((a, b) => b.root.length - a.root.length);
249
- }
250
- function workspaceOf(workspaces, file) {
251
- return workspaces.find(workspace => isInside(workspace.root, file)) ?? null;
252
- }
253
- function exportPatternCapture(pattern, request) {
254
- if (!pattern.includes('*'))
255
- return pattern === request ? '' : null;
256
- const [before = '', after = ''] = pattern.split('*');
257
- return request.startsWith(before) && request.endsWith(after) ? request.slice(before.length, request.length - after.length) : null;
258
- }
259
- export function exportTargetStrings(value) {
260
- if (typeof value === 'string')
261
- return [value];
262
- if (Array.isArray(value))
263
- return value.flatMap(exportTargetStrings);
264
- if (value && typeof value === 'object' && !Object.keys(value).some(key => key.startsWith('.')))
265
- return Object.values(value).flatMap(exportTargetStrings);
266
- return [];
267
- }
268
- /** The package-relative export targets a request (`.` or `./sub`) of a workspace package declares, from exports, else types/main. */
269
- function rootExportCandidates(declaration, request) {
270
- if (request !== '.')
271
- return [];
272
- return exportTargetStrings(declaration);
273
- }
274
- function exportMapCandidates(declaration, request) {
275
- const keys = Object.keys(declaration);
276
- if (!keys.some(key => key.startsWith('.')))
277
- return rootExportCandidates(declaration, request);
278
- const candidates = [];
279
- for (const key of keys) {
280
- const capture = exportPatternCapture(key, request);
281
- if (capture !== null)
282
- candidates.push(...exportTargetStrings(declaration[key]).map(target => target.replaceAll('*', capture)));
283
- }
284
- return candidates;
285
- }
286
- function exportCandidates(workspace, specifier) {
287
- if (!workspace.name || !sameOrUnder(specifier, workspace.name))
288
- return [];
289
- const request = specifier === workspace.name ? '.' : `.${specifier.slice(workspace.name.length)}`;
290
- const declaration = workspace.exports;
291
- if (typeof declaration === 'string' || Array.isArray(declaration))
292
- return rootExportCandidates(declaration, request);
293
- if (declaration && typeof declaration === 'object')
294
- return exportMapCandidates(declaration, request);
295
- return [];
296
- }
297
- const SOURCE_EXTENSIONS = { '.d.ts': ['.ts', '.tsx'], '.d.mts': ['.mts'], '.d.cts': ['.cts'], '.js': ['.ts', '.tsx'], '.jsx': ['.tsx'], '.mjs': ['.mts'], '.cjs': ['.cts'] };
298
- /** rootDir and outDir of a workspace package's build tsconfig (tsconfig.build.json, else tsconfig.json), extends followed; null when it declares none. */
299
- function workspaceBuildLayout(ts, workspace) {
300
- if (workspace.layout !== undefined)
301
- return workspace.layout;
302
- workspace.layout = null;
303
- for (const name of ['tsconfig.build.json', 'tsconfig.json']) {
304
- const file = path.join(workspace.root, name);
305
- if (!fs.existsSync(file))
306
- continue;
307
- const read = ts.readConfigFile(file, ts.sys.readFile);
308
- if (read.error)
309
- continue;
310
- const { options } = ts.parseJsonConfigFileContent(read.config, ts.sys, workspace.root, undefined, file);
311
- if (options.outDir) {
312
- workspace.layout = { rootDir: options.rootDir ? path.resolve(options.rootDir) : path.join(workspace.root, 'src'), outDir: path.resolve(options.outDir) };
313
- break;
314
- }
315
- }
316
- return workspace.layout ?? null;
317
- }
318
- /** The source file a built export target (`./dist/sub/index.js`, `.d.ts`) stands for: outDir back to rootDir, else the dist-to-src layout; null when none exists. */
319
- function sourceOfTarget(ts, workspace, target) {
320
- const absolute = path.resolve(workspace.root, target);
321
- const layout = workspaceBuildLayout(ts, workspace);
322
- const extension = Object.keys(SOURCE_EXTENSIONS).filter(item => absolute.endsWith(item)).sort((a, b) => b.length - a.length)[0];
323
- const sourceRoots = [];
324
- if (layout && isInside(layout.outDir, absolute))
325
- sourceRoots.push([layout.outDir, layout.rootDir]);
326
- const first = slash(path.relative(workspace.root, absolute)).split('/')[0];
327
- if (first)
328
- sourceRoots.push([path.join(workspace.root, first), path.join(workspace.root, 'src')]);
329
- if (!extension)
330
- return null;
331
- for (const [from, to] of sourceRoots) {
332
- const stem = path.join(to, path.relative(from, absolute)).slice(0, -extension.length);
333
- for (const candidate of SOURCE_EXTENSIONS[extension] ?? [])
334
- if (fs.existsSync(stem + candidate))
335
- return canonical(stem + candidate);
336
- }
337
- return null;
338
- }
339
- const manifestEntryTargets = (manifest) => [manifest?.types, manifest?.typings, manifest?.module, manifest?.main].filter((item) => typeof item === 'string');
340
- const packageIndexSource = (workspace) => {
341
- for (const name of ['index.ts', 'index.tsx'])
342
- if (fs.existsSync(path.join(workspace.root, 'src', name)))
343
- return canonical(path.join(workspace.root, 'src', name));
344
- return null;
345
- };
346
- /** The source entry a workspace import resolves to without a build: its export targets mapped back to source, `src/index.ts` for the package root. */
347
- export function workspaceSourceEntry(ts, workspace, specifier) {
348
- if (!workspace.workspace || !workspace.name || !sameOrUnder(specifier, workspace.name))
349
- return null;
350
- const isRoot = specifier === workspace.name;
351
- const candidates = isRoot && !workspace.exports ? manifestEntryTargets(workspace.manifest) : exportCandidates(workspace, specifier);
352
- for (const target of candidates) {
353
- if (!target.startsWith('./') || target.includes('..'))
354
- continue;
355
- const source = sourceOfTarget(ts, workspace, target);
356
- if (source)
357
- return source;
358
- }
359
- return isRoot ? packageIndexSource(workspace) : null;
360
- }
361
- /** Every source file the package.json `exports` of a workspace package maps (each non-wildcard subpath, dist back to source): its public entries. */
362
- export function workspaceExportSources(ts, workspace) {
363
- const declaration = workspace.exports;
364
- if (!declaration || typeof declaration !== 'object' || Array.isArray(declaration))
365
- return [];
366
- const sources = new Set();
367
- for (const [key, value] of Object.entries(declaration)) {
368
- if (!key.startsWith('.') || key.includes('*'))
369
- continue;
370
- for (const target of exportTargetStrings(value)) {
371
- if (!target.startsWith('./') || target.includes('..'))
372
- continue;
373
- const source = sourceOfTarget(ts, workspace, target);
374
- if (source)
375
- sources.add(source);
376
- }
377
- }
378
- return [...sources];
379
- }
380
- function packageExported(ts, workspace, specifier, actualTarget) {
381
- return exportCandidates(workspace, specifier).some(target => {
382
- if (!target.startsWith('./') || target.includes('..'))
383
- return false;
384
- const expected = canonical(path.resolve(workspace.root, target));
385
- return expected === canonical(actualTarget) || sourceOfTarget(ts, workspace, target) === canonical(actualTarget);
386
- });
387
- }
388
- /** The root workspace package of the app (`packages/agent-sdk`) a specifier names, its name or a subpath of it; the longest name when several match. */
389
- export function rootPackageOf(config, specifier) {
390
- let found = null;
391
- for (const item of config.rootPackages ?? [])
392
- if (sameOrUnder(specifier, item.name) && (found === null || item.name.length > found.name.length))
393
- found = item;
394
- return found;
395
- }
396
- /** Whether a specifier into a root package names one of its entry points: a subpath its `exports` declare, or its root through `exports`, `main`/`types` or `src/index`. A path into its source is not an entry point. */
397
- export function rootPackageEntryDeclared(item, specifier) {
398
- if (exportCandidates(item, specifier).length > 0)
399
- return true;
400
- return specifier === item.name && !item.exports && (manifestEntryTargets(item.manifest).length > 0 || packageIndexSource(item) !== null);
401
- }
402
- /** The subpaths a root package declares for import (`.` first), for the message of a refused deep import. */
403
- export function rootPackageEntries(item) {
404
- const declaration = item.exports;
405
- const keys = declaration && typeof declaration === 'object' && !Array.isArray(declaration) ? Object.keys(declaration).filter(key => key.startsWith('.')) : ['.'];
406
- return (keys.length ? keys : ['.']).map(key => (key === '.' ? item.name : `${item.name}${key.slice(1)}`));
407
- }
408
- function boundaryViolation(root, edge, fromWorkspace, toWorkspace, ruleId, message) {
409
- return {
410
- ruleId,
411
- path: relativePath(root, edge.from),
412
- line: edge.line,
413
- column: edge.column,
414
- specifier: edge.specifier,
415
- resolvedPath: relativePath(root, edge.to),
416
- message,
417
- fromPackage: fromWorkspace?.name ?? fromWorkspace?.relative,
418
- toPackage: toWorkspace?.name ?? toWorkspace?.relative,
419
- };
420
- }
421
- /** Parse configured tsconfigs, then build only selected programs and their project-reference closure. */
422
- export function buildTypeScriptContext(config, injectedTypeScript, paths = []) {
423
- const loaded = injectedTypeScript ? { ts: injectedTypeScript, resolved: '(injected test compiler)', version: String(injectedTypeScript.version) }
424
- : loadTargetTypeScript(config.root);
425
- // config.hfs is the opened slot resolver (functions), so it never keys a shared value: the repository declaration it was opened
426
- // from (plain data) identifies it, the manifest being the runtime's one.
427
- const context = sharedInProgramRun('architecture-context', loaded.ts, { config: { ...config, hfs: config.hfs?.repo ?? null }, paths }, () => typeScriptContext(config, loaded, paths));
428
- // Callers add to and sort the errors: each gets its own list.
429
- return { ...context, errors: [...context.errors] };
430
- }
431
- function typeScriptContext(config, loaded, paths) {
432
- return contextFromProjects(config, loaded, paths, {
433
- canonical, compilerError, isInside, slash, readTypeScriptProject, typeScriptProjectReferencePath,
434
- sameOrUnder, createTypeScriptProgram, isProductionSource, sourceLocation, workspaceMetadata, workspaceOf,
435
- pathAliasMatches, moduleReferences, workspaceSourceEntry, resolveTypeScriptModule, crossesSide, assetExtension: ASSET_EXTENSION,
436
- relativePath, packageExported, boundaryViolation, rootPackageOf, rootPackageEntryDeclared, rootPackageEntries,
437
- });
438
- }
439
- export function relativePath(root, fileName) {
440
- return slash(path.relative(root, fileName));
441
- }
442
- export function reachableViolation(edges, firstEdge, forbidden, { follow = () => true } = {}) {
443
- const queue = [{ file: firstEdge.to, chain: [firstEdge.from, firstEdge.to] }];
444
- const visited = new Set();
445
- while (queue.length) {
446
- const current = queue.shift();
447
- if (!current)
448
- break;
449
- if (visited.has(current.file))
450
- continue;
451
- visited.add(current.file);
452
- if (forbidden(current.file))
453
- return current.chain;
454
- for (const edge of edges.get(current.file) ?? [])
455
- if (follow(edge))
456
- queue.push({ file: edge.to, chain: [...current.chain, edge.to] });
457
- }
458
- return null;
459
- }
460
- /** A framework identity the checkers cannot prove statically. */
461
- export const UNPROVEN_FRAMEWORK = '(unproven framework identity)';
462
- /* ---- the AST walks every architecture checker shares ---- */
463
- /** The names of `expected` an import or re-export statement binds (all of them for a namespace or star form). */
464
- export function referencedExports(ts, statement, expected) {
465
- if (ts.isImportDeclaration(statement)) {
466
- const bindings = statement.importClause?.namedBindings;
467
- if (!bindings || ts.isNamespaceImport(bindings))
468
- return bindings ? [...expected] : [];
469
- return bindings.elements.map(element => element.propertyName?.text ?? element.name.text).filter(name => expected.has(name));
470
- }
471
- if (ts.isExportDeclaration(statement)) {
472
- if (!statement.exportClause || ts.isNamespaceExport(statement.exportClause))
473
- return [...expected];
474
- return statement.exportClause.elements.map(element => element.propertyName?.text ?? element.name.text).filter(name => expected.has(name));
475
- }
476
- return [...expected];
477
- }
@@ -1,165 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { machineKit } from './machine-ast.mjs';
4
- import { constructorDependencies } from './constructor-deps.mjs';
5
- import { treeOf } from './required-files.mjs';
6
- import { byCodeUnit } from '../../lib/list.mjs';
7
- import { importsOf } from '../../lib/ts-analysis.mjs';
8
- import { checkFunctionSubject, functionSubjectExports, keyOf as literalKey, valueObjectSubjects } from './function-spec-providers.mjs';
9
- /**
10
- * R48 `unit-spec-providers` (BE_SPEC_QUALITY), the unit test standard's rule 3: the unit spec of a service builds its
11
- * subject with `Test.createTestingModule({ providers: [...] })`, and that providers array EQUALS the constructor
12
- * dependencies of the service under test: the service class first, then one provider for each required constructor parameter.
13
- * A parameter decorated by `Optional()` imported from `@nestjs/common` may be omitted to exercise its absent-provider branch.
14
- *
15
- * The service under test is the sibling `<name>.service.ts` of every `<name>.service.spec.ts` under src/ or apps/ (a spec is
16
- * outside the production program, so it is read from disk). A parameter decorated with a custom `Inject<Thing>()` provides
17
- * the token that decorator's `injector<T>(TOKEN)` names; an undecorated parameter of a class type provides that class (see
18
- * constructor-deps.mjs). Providers are matched by the exported name of the imported binding (`import { CACHE as C }` is
19
- * CACHE), never by text. A provider is a class, or `{ provide: TOKEN, useValue: double }` and nothing else. A sibling
20
- * containing only exported functions instead provides its complete real function object and exercises it through module.get;
21
- * callable named re-exports count, while constants, enums, type-only exports and overload signatures do not. A value-object subject (an
22
- * undecorated class whose constructor parameters carry no injection token) is built with `new`, Nest never constructs it.
23
- *
24
- * Findings: an extra provider, a missing provider, a service that is not the first provider, a dependency whose token cannot
25
- * be resolved, a spec with no createTestingModule providers array, and a provider that is neither a class nor
26
- * `{ provide, useValue }`. Which double a `useValue` is, and whether other specs exist at all, are other rules' business.
27
- */
28
- export const UNIT_SPEC_PROVIDERS_RULE_IDS = ['BE_SPEC_QUALITY'];
29
- const RULE = 'BE_SPEC_QUALITY';
30
- const SPEC_ROOT = /^(?:src|apps)\//u;
31
- /** The `Test.createTestingModule(...)` calls of a spec. */
32
- function testingModules(ts, sourceFile) {
33
- const calls = [];
34
- const visit = (node) => {
35
- if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'createTestingModule')
36
- calls.push(node);
37
- ts.forEachChild(node, visit);
38
- };
39
- visit(sourceFile);
40
- return calls;
41
- }
42
- function providerList(ts, call, rel, report) {
43
- const options = call.arguments[0];
44
- const property = options && ts.isObjectLiteralExpression(options) ? options.properties.find(item => literalKey(ts, item) === 'providers') : null;
45
- const list = property && ts.isPropertyAssignment(property) && ts.isArrayLiteralExpression(property.initializer) ? property.initializer : null;
46
- if (!list)
47
- report(call, `${rel}: Test.createTestingModule has no literal \`providers\` array; list the service and each constructor dependency there.`);
48
- return list;
49
- }
50
- function readProviders(ts, list, rel, nameOf, report) {
51
- const provided = [];
52
- let readable = true;
53
- for (const element of list.elements) {
54
- if (ts.isIdentifier(element)) {
55
- provided.push({ name: nameOf(element), node: element, isClass: true });
56
- continue;
57
- }
58
- if (ts.isObjectLiteralExpression(element)) {
59
- const keys = element.properties.map(item => literalKey(ts, item));
60
- const provide = element.properties.find(item => literalKey(ts, item) === 'provide');
61
- const value = provide && ts.isPropertyAssignment(provide) ? provide.initializer : null;
62
- if (keys.length === 2 && keys.includes('useValue') && value && ts.isIdentifier(value)) {
63
- provided.push({ name: nameOf(value), node: element, isClass: false });
64
- continue;
65
- }
66
- }
67
- readable = false;
68
- report(element, `${rel}: a provider is a class or \`{ provide: TOKEN, useValue: double }\` and nothing else (no useClass, useFactory, useExisting, spread or computed token).`);
69
- }
70
- return { provided, readable };
71
- }
72
- function serviceClassFor(ts, rel, serviceRel, serviceFile, imports, list, report) {
73
- const first = list.elements[0];
74
- const serviceName = first && ts.isIdentifier(first) ? imports.get(first.text) : null;
75
- const target = serviceName ? path.posix.normalize(path.posix.join(path.posix.dirname(rel), serviceName.module)).replace(/\.[cm]?[jt]s$/u, '') : null;
76
- const serviceClass = serviceName && target === serviceRel.replace(/\.ts$/u, '')
77
- ? serviceFile.sourceFile.statements.find((statement) => ts.isClassDeclaration(statement) && statement.name?.text === serviceName.name) : null;
78
- if (!serviceClass)
79
- report(first ?? list, `${rel}: the first provider is the service under test, imported from ./${path.posix.basename(serviceRel, '.ts')}.`);
80
- return serviceClass ? { serviceClass, serviceName: serviceName } : null; // a class is found only when the service name resolved
81
- }
82
- function checkDependencies(kit, rel, service, serviceFile, list, provided, report) {
83
- const { serviceName, serviceClass } = service;
84
- const checker = kit.checkerOf(serviceFile.sourceFile);
85
- const dependencies = constructorDependencies(kit, serviceFile, serviceClass);
86
- const expected = [];
87
- for (const dependency of dependencies) {
88
- if (dependency.kind === 'unresolved') {
89
- report(list, `${rel}: a constructor dependency of ${serviceName.name} cannot be resolved to a token (${dependency.reason}), so its provider cannot be checked; inject it through an exported Inject<Thing>() decorator or a class type.`);
90
- continue;
91
- }
92
- const optional = kit.decorators(dependency.parameter).some(decorator => {
93
- const expression = decorator.expression;
94
- return kit.ts.isCallExpression(expression) && expression.arguments.length === 0
95
- && kit.isImportOf(checker, expression.expression, 'Optional', '@nestjs/common');
96
- });
97
- expected.push({ name: dependency.name, optional });
98
- }
99
- const remaining = [...expected];
100
- for (const item of provided.slice(1)) {
101
- const index = remaining.findIndex(dependency => dependency.name === item.name);
102
- if (index === -1)
103
- report(item.node, `${rel}: ${item.name} is provided but is not a constructor dependency of ${serviceName.name}; a unit spec provides exactly what the constructor needs.`);
104
- else
105
- remaining.splice(index, 1);
106
- }
107
- for (const dependency of remaining.filter(item => !item.optional))
108
- report(list, `${rel}: ${dependency.name} is a constructor dependency of ${serviceName.name} but is not provided; add \`{ provide: ${dependency.name}, useValue: double }\` (or the class itself) to the providers.`);
109
- }
110
- function checkTestingModule({ ts, kit, rel, serviceRel, serviceFile, imports, call, report }) {
111
- const list = providerList(ts, call, rel, report);
112
- if (!list)
113
- return;
114
- const names = functionSubjectExports(ts, serviceFile.sourceFile, kit.checkerOf(serviceFile.sourceFile));
115
- if (names) {
116
- checkFunctionSubject({ ts, rel, serviceRel, imports, call, list, names, report });
117
- return;
118
- }
119
- const nameOf = (identifier) => imports.get(identifier.text)?.name ?? identifier.text;
120
- const { provided, readable } = readProviders(ts, list, rel, nameOf, report);
121
- if (!readable)
122
- return;
123
- const service = serviceClassFor(ts, rel, serviceRel, serviceFile, imports, list, report);
124
- if (!service)
125
- return;
126
- checkDependencies(kit, rel, service, serviceFile, list, provided, report);
127
- }
128
- function checkServiceSpec({ config, graph, kit, ts, rel, violations }) {
129
- const abs = path.join(config.root, ...rel.split('/'));
130
- if (!fs.existsSync(abs))
131
- return false;
132
- const sourceFile = ts.createSourceFile(abs, fs.readFileSync(abs, 'utf8'), ts.ScriptTarget.Latest, true);
133
- const report = (node, message) => { violations.push({ ruleId: RULE, path: rel, ...kit.at(rel, sourceFile, node), message }); };
134
- // importsOf stores every binding's specifier under moduleKey, which defaults to 'module'
135
- const imports = new Map(Array.from(importsOf(ts, sourceFile), ([local, record]) => [local, { name: record.name, module: record.module }]));
136
- const serviceRel = rel.replace(/\.spec\.ts$/u, '.ts');
137
- const serviceFile = graph.files.get(serviceRel);
138
- if (!serviceFile) {
139
- report(sourceFile, `${rel} has no ${path.posix.basename(serviceRel)} beside it; a service spec sits next to the service it tests.`);
140
- return true;
141
- }
142
- const modules = testingModules(ts, sourceFile);
143
- if (!modules.length && valueObjectSubjects(ts, serviceFile.sourceFile))
144
- return true;
145
- if (!modules.length) {
146
- report(sourceFile, `${rel} never calls Test.createTestingModule({ providers: [...] }); build the service from a testing module holding exactly its constructor dependencies.`);
147
- return true;
148
- }
149
- for (const call of modules)
150
- checkTestingModule({ ts, kit, rel, serviceRel, serviceFile, imports, call, report });
151
- return true;
152
- }
153
- export function checkUnitSpecProviders(input) {
154
- const { config, graph } = input;
155
- const kit = machineKit(input);
156
- const { ts } = kit;
157
- const violations = [];
158
- let specs = 0;
159
- const tree = treeOf(config.root);
160
- for (const rel of [...tree.files].filter(file => SPEC_ROOT.test(file) && file.endsWith('.service.spec.ts')).sort(byCodeUnit)) {
161
- if (checkServiceSpec({ config, graph, kit, ts, rel, violations }))
162
- specs += 1;
163
- }
164
- return { violations, coverage: { status: 'checked', specs, files: graph.files.size } };
165
- }