@yearofthedan/warp 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +9 -8
  2. package/dist/analysis/imports.d.ts +3 -1
  3. package/dist/analysis/imports.js +5 -1
  4. package/dist/analysis/typescript.js +2 -1
  5. package/dist/app/check.js +2 -1
  6. package/dist/app/checkModel.js +1 -1
  7. package/dist/app/load.js +12 -12
  8. package/dist/builtins/advice.d.ts +8 -0
  9. package/dist/builtins/advice.js +42 -0
  10. package/dist/builtins/dependency-direction/dependencyDirection.js +32 -15
  11. package/dist/builtins/index.js +2 -0
  12. package/dist/builtins/module-externals/moduleExternals.js +10 -9
  13. package/dist/builtins/no-cross-module-reexport/noCrossModuleReexport.js +16 -5
  14. package/dist/builtins/place.js +5 -3
  15. package/dist/builtins/unresolved-import/unresolvedImport.d.ts +2 -0
  16. package/dist/builtins/unresolved-import/unresolvedImport.js +15 -0
  17. package/dist/builtins/unused-declaration/declarations.js +1 -1
  18. package/dist/builtins/unused-declaration/empty.js +16 -9
  19. package/dist/builtins/unused-declaration/grants.js +8 -11
  20. package/dist/builtins/unused-declaration/surfaces.js +11 -19
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/model/archetype/builder.d.ts +11 -11
  24. package/dist/model/archetype/builder.js +14 -21
  25. package/dist/model/archetype/data.d.ts +19 -13
  26. package/dist/model/archetype/draft.d.ts +2 -9
  27. package/dist/model/archetype/draft.js +48 -59
  28. package/dist/model/archetype/fixes.d.ts +37 -0
  29. package/dist/model/archetype/fixes.js +234 -0
  30. package/dist/model/archetype/reach.js +34 -80
  31. package/dist/model/archetype/references.d.ts +1 -1
  32. package/dist/model/archetype/references.js +13 -28
  33. package/dist/model/archetype/requirements.js +3 -6
  34. package/dist/model/archetype/resolve.d.ts +2 -3
  35. package/dist/model/archetype/resolve.js +85 -67
  36. package/dist/model/archetype/rulesets.js +0 -7
  37. package/dist/model/archetype/settings.js +4 -19
  38. package/dist/model/facts.d.ts +6 -0
  39. package/dist/reporters/model.js +8 -9
  40. package/package.json +1 -1
package/README.md CHANGED
@@ -9,8 +9,8 @@ what each may use, and warp reports the code that steps outside it:
9
9
  - files and functions that are too large or too tangled to follow.
10
10
  - parts of the config that the code no longer uses.
11
11
 
12
- `warp diff` reports only what a change made new or worse, so it can run on a pull request or after every edit of a
13
- coding agent.
12
+ `warp check` judges the whole codebase, for CI. `warp diff` reports only what a change made new or worse, so it can
13
+ run after every edit of a coding agent.
14
14
 
15
15
  ## Quick start
16
16
 
@@ -32,25 +32,26 @@ const app = archetype('app')
32
32
  c
33
33
  .module('utils', dir('src/utils'), exposes(all()))
34
34
  .module('db', dir('src/db'), exposes(all()))
35
- .module('api', dir('src/api'), exposes(all()).using((m) => [m.db, m.utils, pkg('*')])),
35
+ .module('api', dir('src/api'), exposes(all()).using((m) => [m.db, m.utils, pkg('*')]))
36
+ .testModule('tests', files('src/**/*.test.ts')),
36
37
  )
37
38
  .entry(files('src/index.ts'))
38
- .tests(using([pkg('vitest')]));
39
+ .testUsing([pkg('vitest')]);
39
40
 
40
41
  const base = ruleset().on(app.modules.tests, { 'function-cohesion': false });
41
42
 
42
- export default defineConfig({ root: app, tests: files('src/**/*.test.ts'), rulesets: { default: base } });
43
+ export default defineConfig({ root: app, rulesets: { default: base } });
43
44
  ```
44
45
 
45
46
  Then check it, and after an edit, see what the edit broke:
46
47
 
47
48
  ```sh
48
- pnpm exec warp check # every finding in the working tree
49
- pnpm exec warp diff HEAD # what changed since the last commit made new or worse
49
+ pnpm exec warp check # every finding in the working tree, for CI
50
+ pnpm exec warp diff HEAD # what changed since the last commit made new or worse, for an edit hook
50
51
  ```
51
52
 
52
53
  ```text
53
- new: src/utils/slug.ts:1 [dependency-direction] src/utils/slug.ts (app.utils src/utils) imports src/db/client.ts (app.db src/db), which is outside utils's reach: utils may use nothing. Add what holds src/db/client.ts to a using if the dependency is intended, or move the code.
54
+ new: src/utils/slug.ts:1 [dependency-direction] src/utils/slug.ts (app.utils src/utils) imports src/db/client.ts (app.db src/db), which is outside utils's reach. Declare db above utils in app and add m.db to the using of app.utils, or move the code.
54
55
  ```
55
56
 
56
57
  ## Read next
@@ -1,13 +1,15 @@
1
1
  import { type Checker, type Program } from 'typescript/sync';
2
- import type { ExternalImport, ImportEdge } from '../model/facts.ts';
2
+ import type { ExternalImport, ImportEdge, UnresolvedImport } from '../model/facts.ts';
3
3
  import type { Source } from './source.ts';
4
4
  export interface Resolver {
5
5
  checker: Checker;
6
6
  program: Program;
7
7
  relative: (pathOrFileName: string) => string | undefined;
8
+ exists: (fileName: string) => boolean;
8
9
  }
9
10
  export interface FileEdges {
10
11
  imports: ImportEdge[];
11
12
  externals: ExternalImport[];
13
+ unresolved: UnresolvedImport[];
12
14
  }
13
15
  export declare const fileEdges: (source: Source, resolver: Resolver) => FileEdges;
@@ -2,9 +2,10 @@ import { SyntaxKind } from 'typescript/ast';
2
2
  import { isExportAssignment, isExportDeclaration, isIdentifier, isImportDeclaration, isNamedExports, isNamedImports, isNamespaceImport, isStringLiteralLikeNode, } from 'typescript/ast/is';
3
3
  import { SymbolFlags } from 'typescript/sync';
4
4
  import { isBuiltin } from 'node:module';
5
+ import { dirname, resolve } from 'node:path';
5
6
  export const fileEdges = (source, resolver) => {
6
7
  const exported = locallyExportedNames(source.sourceFile);
7
- const edges = { imports: [], externals: [] };
8
+ const edges = { imports: [], externals: [], unresolved: [] };
8
9
  for (const statement of source.sourceFile.statements) {
9
10
  const declaration = moduleDeclaration(statement, exported);
10
11
  if (!declaration)
@@ -15,9 +16,12 @@ export const fileEdges = (source, resolver) => {
15
16
  edges.imports.push(...statementEdges(statement, declaration, via, source, resolver));
16
17
  else if (isBare(declaration.specifier.text))
17
18
  edges.externals.push(externalImport(statement, declaration, source));
19
+ else if (!resolved?.resolvedFileName && !namesFileOnDisk(declaration.specifier.text, source, resolver))
20
+ edges.unresolved.push({ from: source.file, specifier: declaration.specifier.text, line: source.line(statement) });
18
21
  }
19
22
  return edges;
20
23
  };
24
+ const namesFileOnDisk = (specifier, source, resolver) => resolver.exists(resolve(dirname(source.sourceFile.fileName), specifier));
21
25
  const isBare = (specifier) => !specifier.startsWith('.') && !specifier.startsWith('/');
22
26
  const packageOf = (specifier) => {
23
27
  const segments = specifier.split('/');
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { readFileSync, statSync } from 'node:fs';
2
+ import { existsSync, readFileSync, statSync } from 'node:fs';
3
3
  import { join, relative, sep } from 'node:path';
4
4
  import { API } from 'typescript/sync';
5
5
  import { freshFacts } from '../app/facts.js';
@@ -74,6 +74,7 @@ const analyzeProgram = ({ program, checker }, files, fresh, done) => {
74
74
  program,
75
75
  checker,
76
76
  relative: (path) => byPath.get(path) ?? byPath.get(path.toLowerCase()),
77
+ exists: existsSync,
77
78
  };
78
79
  const analyzed = new Map();
79
80
  for (const [fileName, file] of files) {
package/dist/app/check.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { checkModel } from './checkModel.js';
2
2
  import { resolveModel } from '../model/archetype/resolve.js';
3
3
  export const modelProject = ({ analyzer, foldersAt, facts }, root, config) => {
4
- const project = analyzer.analyze(root, config.tsconfig, facts);
4
+ const analyzed = analyzer.analyze(root, config.tsconfig, facts);
5
+ const project = { files: analyzed.files.filter((file) => file.path !== config.file) };
5
6
  const files = project.files.map((file) => file.path);
6
7
  return { model: resolveModel(config, foldersAt(root), files), project };
7
8
  };
@@ -14,7 +14,7 @@ const placed = (model, finding) => {
14
14
  const module = model.moduleOf(finding.file);
15
15
  if (!module)
16
16
  return finding;
17
- return { ...finding, module: model.isTest(finding.file) ? `${module.id}:tests` : module.id };
17
+ return { ...finding, module: module.id };
18
18
  };
19
19
  const run = (rule, shared, settled) => {
20
20
  if (rule.scope === 'project')
package/dist/app/load.js CHANGED
@@ -20,7 +20,7 @@ export const loadConfigData = (raw, { builtins, ruleset, file = 'warp.config.ts'
20
20
  };
21
21
  if (!isRecord(raw))
22
22
  throw new ConfigError('config: expected an object, defineConfig({ root })');
23
- const unknownKeys = Object.keys(raw).filter((key) => !['root', 'tsconfig', 'tests', 'plugins', 'rulesets'].includes(key));
23
+ const unknownKeys = Object.keys(raw).filter((key) => !['root', 'tsconfig', 'plugins', 'rulesets'].includes(key));
24
24
  if (unknownKeys.length > 0)
25
25
  fail(`config: unknown key ${unknownKeys.join(', ')}`);
26
26
  const root = recordedAs(raw.root, 'archetype');
@@ -41,7 +41,6 @@ export const loadConfigData = (raw, { builtins, ruleset, file = 'warp.config.ts'
41
41
  root: root.definition.name,
42
42
  archetypes: Object.fromEntries(drafts.map(({ data }) => [data.name, archetypeData(data)])),
43
43
  tsconfig: tsconfigs(raw.tsconfig, fail),
44
- ...testPatterns(raw.tests, fail),
45
44
  };
46
45
  const config = withRuleset(structure, raw.rulesets, ruleset, (value, at) => toRules(check, value, at), fail);
47
46
  checkUnused(drafts, fail);
@@ -50,7 +49,17 @@ export const loadConfigData = (raw, { builtins, ruleset, file = 'warp.config.ts'
50
49
  failed();
51
50
  return { config, rules, warnings };
52
51
  };
53
- const archetypeData = ({ name, inline, description, identify, requires, modules, exposes, provides, tests, }) => defined({ name, inline, description, identify, requires, modules: modules.map(defined), exposes, provides, tests });
52
+ const archetypeData = ({ name, inline, description, identify, requires, modules, exposes, provides, testUsing, }) => defined({
53
+ name,
54
+ inline,
55
+ description,
56
+ identify,
57
+ requires,
58
+ modules: modules.map(defined),
59
+ exposes,
60
+ provides,
61
+ testUsing,
62
+ });
54
63
  const plugins = (value, fail) => {
55
64
  if (value === undefined)
56
65
  return {};
@@ -59,15 +68,6 @@ const plugins = (value, fail) => {
59
68
  fail('config.plugins: expected plugins by namespace');
60
69
  return {};
61
70
  };
62
- const testPatterns = (value, fail) => {
63
- if (value === undefined)
64
- return {};
65
- const selector = recordedAs(value, 'selector');
66
- if (selector?.kind === 'files' && selector.patterns.every(isName))
67
- return { tests: [...selector.patterns] };
68
- fail("config.tests: expected the test entry files, files('**/*.test.ts', ...)");
69
- return {};
70
- };
71
71
  const tsconfigs = (value, fail) => {
72
72
  const paths = [value ?? 'tsconfig.json'].flat();
73
73
  if (paths.length === 0 || !paths.every(isName))
@@ -0,0 +1,8 @@
1
+ import type { RefData } from '../model/archetype/data.ts';
2
+ import type { Fix } from '../model/archetype/fixes.ts';
3
+ import type { Verdicts } from '../model/archetype/reach.ts';
4
+ import type { Model } from '../model/archetype/resolve.ts';
5
+ export declare const refText: (ref: RefData) => string;
6
+ export declare const sentence: (parts: readonly string[]) => string;
7
+ export declare const reachSize: (verdicts: Verdicts, file: string) => number;
8
+ export declare const fixSteps: (model: Model, fixes: readonly Fix[]) => string[];
@@ -0,0 +1,42 @@
1
+ import { show } from '../model/archetype/references.js';
2
+ export const refText = (ref) => (ref.kind === 'module' ? `m.${show(ref)}` : show(ref));
3
+ export const sentence = (parts) => parts.length < 2 ? (parts[0] ?? '') : `${parts.slice(0, -1).join(', ')} and ${parts.at(-1)}`;
4
+ export const reachSize = (verdicts, file) => new Set((verdicts.reach(file) ?? []).flatMap((grant) => (grant.ref === undefined ? [] : [grant.ref]))).size;
5
+ const instances = (model, archetype) => {
6
+ const count = model.modules.filter((module) => module.archetype === archetype).length;
7
+ return count > 1 ? ` (all ${count} ${archetype} modules)` : '';
8
+ };
9
+ const step = (model, fix, refs) => {
10
+ switch (fix.kind) {
11
+ case 'using':
12
+ return `add ${refText(fix.ref)} to ${fix.site}`;
13
+ case 'declare':
14
+ return `declare ${fix.module} above ${fix.above} in ${fix.archetype}`;
15
+ case 'require':
16
+ return `require ${fix.name} in ${fix.archetype}, have ${fix.provider} provide m.${fix.module} as ${fix.name}`;
17
+ case 'expose':
18
+ return `expose ${sentence(refs.map(refText))} from ${fix.archetype}${instances(model, fix.archetype)}`;
19
+ case 'expose-file':
20
+ return `add '${fix.pattern}' to what ${fix.archetype} exposes`;
21
+ }
22
+ };
23
+ export const fixSteps = (model, fixes) => {
24
+ const steps = [];
25
+ for (const [at, fix] of fixes.entries()) {
26
+ if (fix.kind !== 'expose') {
27
+ steps.push(step(model, fix, []));
28
+ continue;
29
+ }
30
+ const previous = fixes[at - 1];
31
+ if (previous?.kind === 'expose' && previous.archetype === fix.archetype)
32
+ continue;
33
+ const refs = [];
34
+ for (const next of fixes.slice(at)) {
35
+ if (next.kind !== 'expose' || next.archetype !== fix.archetype)
36
+ break;
37
+ refs.push(next.ref);
38
+ }
39
+ steps.push(step(model, fix, refs));
40
+ }
41
+ return steps;
42
+ };
@@ -1,5 +1,8 @@
1
1
  import { exposesText } from '../../model/archetype/references.js';
2
+ import { fixSteps, reachSize, sentence } from '../advice.js';
2
3
  import { place } from '../place.js';
4
+ import { title } from '../shared.js';
5
+ import { fixesFor } from '../../model/archetype/fixes.js';
3
6
  import { noOptions } from '../../rules/rule.js';
4
7
  const id = 'dependency-direction';
5
8
  export const dependencyDirection = {
@@ -41,28 +44,42 @@ const refused = (context, from, to, refusal, edges) => {
41
44
  };
42
45
  };
43
46
  const explain = ({ config, model, verdicts }, from, to, refusal) => {
44
- const source = model.moduleOf(from);
45
47
  if (isLoose(model, to))
46
48
  return `which is in no module yet. Add a module that holds ${to}, then add it to a using if the dependency is intended.`;
47
49
  if (refusal.reason === 'test')
48
50
  return 'a test file. Production code never imports tests: move what both need out of the test file into the module it tests.';
51
+ const instead = refusal.reason === 'private' ? throughSurface({ config, model, verdicts }, from, to, refusal.hiddenBy) : '';
52
+ return `${why(config, model, verdicts, from, to, refusal)}. ${instead || advise(config, model, verdicts, from, to)}`;
53
+ };
54
+ const why = (config, model, verdicts, from, to, refusal) => {
55
+ const source = model.moduleOf(from);
49
56
  if (refusal.reason === 'private') {
50
57
  const { hiddenBy } = refusal;
51
- return (`which ${hiddenBy.id} keeps private (it exposes ${exposesText(verdicts.exposes(hiddenBy))}). ` +
52
- `Import what ${hiddenBy.id} exposes, or expose ${to} from ${hiddenBy.archetype ?? hiddenBy.name} if other modules should reach it.`);
58
+ return `which ${hiddenBy.id} keeps private (it exposes ${exposesText(verdicts.exposes(hiddenBy))})`;
53
59
  }
54
- if (refusal.reason === 'above') {
55
- const folder = source.kind === 'files' ? source.parent : source;
56
- return (`which is above ${folder.id}. A module reaches up only through what it requires: ` +
57
- `require it in ${namedArchetype(config, folder.archetype)} and have an ancestor provide it, or move it below.`);
60
+ if (refusal.reason === 'above')
61
+ return `which is above ${(source.kind === 'dir' ? source : source.parent).id}`;
62
+ return `which is outside ${source.name ?? source.id}'s reach`;
63
+ };
64
+ const throughSurface = ({ config, model, verdicts }, from, to, hiddenBy) => {
65
+ if (model.isTest(to))
66
+ return '';
67
+ for (const file of verdicts.surface(hiddenBy)) {
68
+ const fixes = fixesFor(config, model, from, file);
69
+ if (!fixes)
70
+ continue;
71
+ const once = fixes.length > 0 ? `, once you ${sentence(fixSteps(model, fixes))}` : '';
72
+ return `Import what ${hiddenBy.id} exposes instead${once}.`;
58
73
  }
59
- const owner = source.name ?? source.id;
60
- const uses = Map.groupBy(verdicts.reach(from).filter((grant) => grant.ref !== undefined), (grant) => grant.owner);
61
- const reaches = uses.size > 0
62
- ? `: ${[...uses].map(([by, grants]) => `${by} uses ${grants.map((grant) => grant.ref).join(', ')}`).join('; ')}`
63
- : `: ${owner} may use nothing`;
64
- return (`which is outside ${owner}'s reach${reaches}. ` +
65
- `Add what holds ${to} to a using if the dependency is intended, or move the code.`);
74
+ return '';
75
+ };
76
+ const advise = (config, model, verdicts, from, to) => {
77
+ const fixes = fixesFor(config, model, from, to);
78
+ if (!fixes)
79
+ return 'No declared path allows this: either the import or the structure is wrong.';
80
+ const steps = fixSteps(model, fixes);
81
+ const size = reachSize(verdicts, from);
82
+ const more = size > 0 && fixes.some((fix) => fix.kind === 'using') ? ` (+${size} more in reach)` : '';
83
+ return `${title(sentence(steps))}, or move the code.${more}`;
66
84
  };
67
85
  const isLoose = (model, file) => model.moduleOf(file).looseFiles.includes(file);
68
- const namedArchetype = (config, name) => config.archetypes[name].inline ? namedArchetype(config, name.slice(0, name.lastIndexOf('.'))) : name;
@@ -8,8 +8,10 @@ import { moduleExternals } from './module-externals/moduleExternals.js';
8
8
  import { noCrossModuleReexport } from './no-cross-module-reexport/noCrossModuleReexport.js';
9
9
  import { noCycle } from './no-cycle/noCycle.js';
10
10
  import { noDoubleExport } from './no-double-export/noDoubleExport.js';
11
+ import { unresolvedImport } from './unresolved-import/unresolvedImport.js';
11
12
  import { unusedDeclaration } from './unused-declaration/unusedDeclaration.js';
12
13
  export const builtinRules = [
14
+ unresolvedImport,
13
15
  dependencyDirection,
14
16
  moduleExternals,
15
17
  noDoubleExport,
@@ -1,12 +1,13 @@
1
1
  import { listsPackage } from '../packages.js';
2
2
  import { place } from '../place.js';
3
+ import { sitesOf } from '../../model/archetype/fixes.js';
3
4
  import { noOptions } from '../../rules/rule.js';
4
5
  const id = 'module-externals';
5
6
  export const moduleExternals = {
6
7
  id,
7
8
  scope: 'project',
8
9
  parseOptions: noOptions,
9
- check: ({ model, verdicts, project, atFile }) => project.files.flatMap((file) => {
10
+ check: ({ config, model, verdicts, project, atFile }) => project.files.flatMap((file) => {
10
11
  const reach = verdicts.reach(file.path);
11
12
  if (!reach || !atFile(file.path).on)
12
13
  return [];
@@ -14,28 +15,28 @@ export const moduleExternals = {
14
15
  const byPackage = Map.groupBy(file.externals, (external) => external.package);
15
16
  return [...byPackage].flatMap(([name, edges]) => {
16
17
  const outside = edges.filter((edge) => !packages.some((grant) => listsPackage(grant.package, edge)));
17
- return outside.length === 0 ? [] : [refused(model, file.path, name, outside, packages)];
18
+ return outside.length === 0 ? [] : [refused(config, model, file.path, name, outside, packages)];
18
19
  });
19
20
  }),
20
21
  };
21
- const refused = (model, from, name, edges, packages) => {
22
+ const refused = (config, model, from, name, edges, packages) => {
22
23
  const module = model.moduleOf(from);
23
24
  const owner = module.name ?? module.id;
24
25
  const names = [...new Set(edges.flatMap((edge) => edge.names))];
25
26
  const specifiers = [...new Set(edges.map((edge) => edge.specifier))];
26
27
  const imports = edges.every((edge) => edge.typeOnly) ? 'imports types from' : 'imports';
27
- const uses = Map.groupBy(packages, (grant) => grant.owner);
28
- const lists = uses.size > 0
29
- ? `: ${[...uses].map(([by, grants]) => `${by} uses ${grants.map((grant) => grant.ref).join(', ')}`).join('; ')}`
30
- : ': no using in its reach lists a package';
28
+ const site = sitesOf(config, model, from)[0];
29
+ const where = site?.label ?? 'a using';
30
+ const listed = new Set(packages.map((grant) => grant.ref)).size;
31
+ const more = listed > 0 ? ` (+${listed} more in reach)` : '';
31
32
  return {
32
33
  rule: id,
33
34
  key: `${id}:${from}->${name}`,
34
35
  file: from,
35
36
  line: edges[0].line,
36
37
  value: Math.max(1, names.length),
37
- message: `${from} (${place(model, from, module)}) ${imports} ${specifiers.join(', ')}, a package outside ${owner}'s reach${lists}. ` +
38
- `Add pkg('${name}') to a using if the dependency is intended, or move the code.`,
38
+ message: `${from} (${place(model, from, module)}) ${imports} ${specifiers.join(', ')}, a package outside ${owner}'s reach. ` +
39
+ `Add pkg('${name}') to ${where}, or move the code.${more}`,
39
40
  details: { from: module.id, package: name, edges },
40
41
  };
41
42
  };
@@ -5,7 +5,7 @@ export const noCrossModuleReexport = {
5
5
  id,
6
6
  scope: 'project',
7
7
  parseOptions: noOptions,
8
- check: ({ model, project, atFile }) => project.files.flatMap((file) => {
8
+ check: ({ model, verdicts, project, atFile }) => project.files.flatMap((file) => {
9
9
  const module = model.moduleOf(file.path);
10
10
  if (!module || !atFile(file.path).on)
11
11
  return [];
@@ -14,7 +14,8 @@ export const noCrossModuleReexport = {
14
14
  const target = model.moduleOf(to);
15
15
  if (!target || owns(module, target))
16
16
  return [];
17
- return [passedThrough(model, module, target, to, edges)];
17
+ const blocked = importersOf(project, file.path, to).filter((importer) => !owns(target, model.moduleOf(importer)) && !verdicts.verdict(importer, to)?.allowed);
18
+ return [passedThrough(model, module, target, to, edges, blocked)];
18
19
  });
19
20
  }),
20
21
  };
@@ -24,7 +25,10 @@ const owns = (module, target) => {
24
25
  return true;
25
26
  return false;
26
27
  };
27
- const passedThrough = (model, module, target, to, edges) => {
28
+ const importersOf = (project, file, to) => project.files
29
+ .filter((other) => other.imports.some((edge) => edge.via === file && edge.to === to && !edge.reExport))
30
+ .map((other) => other.path);
31
+ const passedThrough = (model, module, target, to, edges, blocked) => {
28
32
  const from = edges[0].from;
29
33
  const names = [...new Set(edges.flatMap((edge) => edge.names))];
30
34
  const what = names.length > 0 ? names.join(', ') : 'everything';
@@ -35,8 +39,8 @@ const passedThrough = (model, module, target, to, edges) => {
35
39
  line: edges[0].line,
36
40
  value: Math.max(1, names.length),
37
41
  message: `${from} (${place(model, from, module)}) re-exports ${what} from ${to} (${place(model, to, target)}), so its ` +
38
- `importers reach ${target.id} through ${module.id}. Have importers that need it use ${target.id} directly, give ` +
39
- `${module.id} its own type that hides it, or move it into ${module.id} if ${module.id} owns it.`,
42
+ `importers reach ${target.id} through ${module.id}. ${direct(target, blocked)}give ${module.id} its own type that ` +
43
+ `hides it, or move it into ${module.id} if ${module.id} owns it.`,
40
44
  details: {
41
45
  from: module.id,
42
46
  to: target.id,
@@ -45,3 +49,10 @@ const passedThrough = (model, module, target, to, edges) => {
45
49
  },
46
50
  };
47
51
  };
52
+ const direct = (target, blocked) => {
53
+ if (blocked.length === 0)
54
+ return `Have importers that need it use ${target.id} directly, `;
55
+ const count = blocked.length - 1;
56
+ const others = count > 0 ? ` and ${count} other importer${count > 1 ? 's' : ''}` : '';
57
+ return `${blocked[0]}${others} may not use ${target.id} directly, so `;
58
+ };
@@ -1,6 +1,8 @@
1
1
  export const place = (model, file, module = model.moduleOf(file)) => {
2
- if (module.kind === 'files')
3
- return `${module.name} of ${module.parent.archetype} ${module.parent.id}`;
4
- const role = module.looseFiles.includes(file) ? 'loose in ' : model.isTest(file) ? 'a test of ' : '';
2
+ if (module.kind !== 'dir') {
3
+ const role = module.kind === 'test' ? 'test module ' : '';
4
+ return `${role}${module.name} of ${module.parent.archetype} ${module.parent.id}`;
5
+ }
6
+ const role = module.looseFiles.includes(file) ? 'loose in ' : '';
5
7
  return `${role}${module.archetype} ${module.id}`;
6
8
  };
@@ -0,0 +1,2 @@
1
+ import { type FileRule } from '../../rules/rule.ts';
2
+ export declare const unresolvedImport: FileRule;
@@ -0,0 +1,15 @@
1
+ import { noOptions } from '../../rules/rule.js';
2
+ const id = 'unresolved-import';
3
+ export const unresolvedImport = {
4
+ id,
5
+ parseOptions: noOptions,
6
+ check: ({ file }) => file.unresolved.map(({ from, specifier, line }) => ({
7
+ rule: id,
8
+ key: `${id}:${from}->${specifier}`,
9
+ file: from,
10
+ line,
11
+ value: 1,
12
+ message: `${specifier} from ${from} resolves to no file. Fix the path, or add the file it names.`,
13
+ details: { from, specifier },
14
+ })),
15
+ };
@@ -8,7 +8,7 @@ export const holding = ({ model, project }) => {
8
8
  };
9
9
  export const instancesOf = ({ model, held }, archetype) => model.modules.filter((module) => module.archetype === archetype && held.has(module));
10
10
  export const childrenNamed = ({ held }, instances, name) => instances.flatMap((instance) => instance.children.filter((child) => child.name === name && held.has(child)));
11
- export const named = (module) => (module.id === '.' ? 'the root' : module.id);
11
+ export const named = (module) => (module.parent === undefined ? 'the root' : module.id);
12
12
  export const within = (module, holder) => {
13
13
  for (let at = module; at; at = at.parent)
14
14
  if (at === holder)
@@ -2,21 +2,28 @@ import { childrenNamed, instancesOf, named, unused } from './declarations.js';
2
2
  export const emptyModules = (context) => Object.values(context.config.archetypes).flatMap((archetype) => {
3
3
  const instances = instancesOf(context, archetype.name);
4
4
  const on = instances.some((instance) => context.atModule(instance).on);
5
- const declared = [
6
- ...archetype.modules.map((module) => ({ module, name: module.name, layer: 'production' })),
7
- ...(archetype.tests?.modules ?? []).map((module) => ({
8
- module,
9
- name: `tests.${module.name}`,
10
- layer: 'test',
11
- })),
12
- ];
5
+ const declared = archetype.modules.map((module) => ({
6
+ module,
7
+ name: module.name,
8
+ layer: module.kind === 'test' ? 'test' : 'production',
9
+ }));
13
10
  return declared
14
11
  .filter(({ name }) => on && childrenNamed(context, instances, name).length === 0)
15
12
  .map(({ module, name, layer }) => empty(context, `${archetype.name}.${name}`, module, layer, instances));
16
13
  });
17
14
  const empty = (context, declaredIn, module, layer, instances) => {
18
- const selector = module.kind === 'dir' ? `dir(${quoted(module.paths)})` : `files(${quoted(module.patterns)})`;
15
+ const selector = selectorText(module);
19
16
  const where = instances.map(named).join(', ');
20
17
  return unused(context.config, declaredIn, `${declaredIn} matches no files: ${selector} finds nothing in ${where}. Fix the selector, or remove the module.`, { kind: 'empty', declaredIn, layer, selector });
21
18
  };
22
19
  const quoted = (patterns) => patterns.map((pattern) => `'${pattern}'`).join(', ');
20
+ const selectorText = (module) => {
21
+ if (module.kind === 'dir')
22
+ return `dir(${quoted(module.paths)})`;
23
+ if (module.kind === 'files')
24
+ return `files(${quoted(module.patterns)})`;
25
+ const { locator } = module;
26
+ if (locator.kind === 'mirror')
27
+ return `mirror('${locator.from}', '${locator.to}')`;
28
+ return `${locator.kind}(${quoted(locator.patterns)})`;
29
+ };
@@ -5,11 +5,11 @@ export const unusedGrants = (context) => {
5
5
  const used = usedRefs(context);
6
6
  return declared(context)
7
7
  .filter(({ ref, holders }) => !used.has(ref) && holders.some((holder) => context.atModule(holder).on))
8
- .map(({ ref, declaredIn, layer, holders }) => {
8
+ .map(({ ref, declaredIn, layer, holders, kit }) => {
9
9
  const using = show(ref);
10
10
  const modules = holders.map((holder) => holder.id);
11
11
  const names = holders.map(named).join(', ');
12
- const files = layer === 'test' ? `tests of ${names}` : names;
12
+ const files = kit ? `the tests of ${names}` : names;
13
13
  return unused(context.config, `${declaredIn}->${using}`, `${declaredIn} uses ${using}, but nothing in ${files} imports through it. Remove it from the using.`, { kind: 'grant', declaredIn, layer, using, modules });
14
14
  });
15
15
  };
@@ -17,20 +17,17 @@ const declared = (context) => Object.values(context.config.archetypes).flatMap((
17
17
  const instances = instancesOf(context, archetype.name);
18
18
  const modules = archetype.modules.flatMap((module) => {
19
19
  const holders = childrenNamed(context, instances, module.name);
20
- const declaredIn = `${archetype.name}.${module.name}`;
21
- const tests = module.kind === 'files' ? (module.tests?.using ?? []) : [];
22
- return [
23
- ...module.using.map((ref) => ({ ref, declaredIn, layer: 'production', holders })),
24
- ...tests.map((ref) => ({ ref, declaredIn: `${declaredIn}.tests`, layer: 'test', holders })),
25
- ];
20
+ const layer = module.kind === 'test' ? 'test' : 'production';
21
+ return module.using.map((ref) => ({ ref, declaredIn: `${archetype.name}.${module.name}`, layer, holders }));
26
22
  });
27
- const layer = (archetype.tests?.using ?? []).map((ref) => ({
23
+ const kit = (archetype.testUsing ?? []).map((ref) => ({
28
24
  ref,
29
- declaredIn: `${archetype.name}.tests`,
25
+ declaredIn: `${archetype.name}.testUsing`,
30
26
  layer: 'test',
31
27
  holders: instances,
28
+ kit: true,
32
29
  }));
33
- return [...modules, ...layer];
30
+ return [...modules, ...kit];
34
31
  });
35
32
  const usedRefs = ({ project, verdicts }) => {
36
33
  const used = new Set();
@@ -13,18 +13,22 @@ export const unusedSurfaces = (context) => {
13
13
  const reached = (context, edges, holder, files) => edges.some(({ from, to }) => files.has(to) && !within(context.model.moduleOf(from), holder));
14
14
  const declared = (context) => Object.values(context.config.archetypes).flatMap((archetype) => {
15
15
  const instances = instancesOf(context, archetype.name).filter((instance) => instance !== context.model.root);
16
- const own = archetype.exposes ? production(context, archetype.name, archetype.exposes, instances) : [];
16
+ const judged = isEntry(archetype.exposes)
17
+ ? instances.filter((instance) => !isTopLevel(context, instance))
18
+ : instances;
19
+ const own = archetype.exposes ? surfaces(context, archetype.name, archetype.exposes, judged, 'production') : [];
17
20
  const modules = archetype.modules.flatMap((module) => {
18
21
  const holders = childrenNamed(context, instances, module.name);
19
- return module.kind === 'files' && module.exposes
20
- ? production(context, `${archetype.name}.${module.name}`, module.exposes, holders)
22
+ const layer = module.kind === 'test' ? 'test' : 'production';
23
+ return module.kind !== 'dir' && module.exposes
24
+ ? surfaces(context, `${archetype.name}.${module.name}`, module.exposes, holders, layer)
21
25
  : [];
22
26
  });
23
- const tests = archetype.tests?.exposes ? test(`${archetype.name}.tests`, archetype.tests.exposes, instances) : [];
24
- return [...own, ...modules, ...tests];
27
+ return [...own, ...modules];
25
28
  });
26
- const production = (context, declaredIn, exposes, holders) => {
27
- const layer = 'production';
29
+ const isEntry = (exposes) => exposes?.kind === 'files' && exposes.entry === true;
30
+ const isTopLevel = (context, module) => module.parent === context.model.root;
31
+ const surfaces = (context, declaredIn, exposes, holders, layer) => {
28
32
  if (exposes.kind !== 'surfaces')
29
33
  return [
30
34
  { declaredIn, layer, exposes: whole(exposes), holders, files: (holder) => context.verdicts.surface(holder) },
@@ -37,18 +41,6 @@ const production = (context, declaredIn, exposes, holders) => {
37
41
  files: (holder) => context.verdicts.surface(holder, name),
38
42
  }));
39
43
  };
40
- const test = (declaredIn, exposes, holders) => {
41
- const layer = 'test';
42
- const filesOf = (holder, names) => new Set(holder.children
43
- .filter((child) => child.test && (names === undefined || names.has(child.name)))
44
- .flatMap((child) => child.files));
45
- if (exposes.kind !== 'surfaces')
46
- return [{ declaredIn, layer, exposes: whole(exposes), holders, files: (holder) => filesOf(holder) }];
47
- return Object.entries(exposes.surfaces).map(([name, refs]) => {
48
- const names = new Set(refs.flatMap((ref) => (ref.kind === 'module' ? [`tests.${ref.module}`] : [])));
49
- return { declaredIn, layer, exposes: `exposes ${name}`, holders, files: (holder) => filesOf(holder, names) };
50
- });
51
- };
52
44
  const whole = (exposes) => {
53
45
  if (exposes.kind === 'all')
54
46
  return 'exposes(all())';
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { all, archetype, contains, defineConfig, dir, exposes, files, pkg, ruleset, using, type ModuleHandle, type Selector, type Ruleset, type RuleSettings, type WarpConfig, type All, type Archetype, type Exposed, type Using, type UsingContext, type Package, type Reference, type Shape, } from './model/archetype/builder.ts';
1
+ export { all, archetype, contains, defineConfig, dir, exposes, files, mirror, pkg, ruleset, using, type ModuleHandle, type Selector, type Ruleset, type RuleSettings, type WarpConfig, type All, type Archetype, type Exposed, type Using, type TestUsing, type UsingContext, type Package, type Reference, type Shape, } from './model/archetype/builder.ts';
2
2
  export { loadConfigData, type LoadedConfigData } from './app/load.ts';
3
3
  export type * from './model/archetype/data.ts';
4
4
  export type { Complexity, FunctionFacts, ImportEdge, FileFacts, Member, MemberGraph, MemberKind, } from './model/facts.ts';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { all, archetype, contains, defineConfig, dir, exposes, files, pkg, ruleset, using, } from './model/archetype/builder.js';
1
+ export { all, archetype, contains, defineConfig, dir, exposes, files, mirror, pkg, ruleset, using, } from './model/archetype/builder.js';
2
2
  export { loadConfigData } from './app/load.js';
3
3
  export { ConfigError } from './model/configError.js';
4
4
  export { wholeNumberOptions, } from './rules/rule.js';