@yearofthedan/warp 0.3.0 → 0.4.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 (45) hide show
  1. package/README.md +20 -22
  2. package/dist/app/check.d.ts +3 -1
  3. package/dist/app/check.js +3 -2
  4. package/dist/app/configLines.d.ts +5 -0
  5. package/dist/app/configLines.js +24 -0
  6. package/dist/app/load.d.ts +2 -2
  7. package/dist/app/load.js +32 -44
  8. package/dist/app/unclassified.js +1 -1
  9. package/dist/builtins/advice.js +9 -9
  10. package/dist/builtins/dependency-direction/dependencyDirection.js +7 -2
  11. package/dist/builtins/module-externals/moduleExternals.js +3 -2
  12. package/dist/builtins/unused-declaration/empty.js +11 -10
  13. package/dist/builtins/unused-declaration/grants.js +39 -11
  14. package/dist/builtins/unused-declaration/surfaces.js +16 -6
  15. package/dist/cli.js +37 -17
  16. package/dist/config/loadConfig.d.ts +8 -2
  17. package/dist/config/loadConfig.js +107 -14
  18. package/dist/git/cache.js +5 -1
  19. package/dist/index.d.ts +0 -1
  20. package/dist/index.js +0 -1
  21. package/dist/model/archetype/data.d.ts +14 -23
  22. package/dist/model/archetype/data.js +1 -1
  23. package/dist/model/archetype/fixes.d.ts +5 -7
  24. package/dist/model/archetype/fixes.js +132 -90
  25. package/dist/model/archetype/language.d.ts +16 -0
  26. package/dist/model/archetype/language.js +432 -0
  27. package/dist/model/archetype/reach.d.ts +8 -3
  28. package/dist/model/archetype/reach.js +122 -56
  29. package/dist/model/archetype/references.d.ts +11 -5
  30. package/dist/model/archetype/references.js +59 -118
  31. package/dist/model/archetype/requirements.d.ts +3 -3
  32. package/dist/model/archetype/requirements.js +75 -58
  33. package/dist/model/archetype/resolve.d.ts +1 -0
  34. package/dist/model/archetype/resolve.js +26 -56
  35. package/dist/model/archetype/rulesets.d.ts +2 -1
  36. package/dist/model/archetype/rulesets.js +74 -43
  37. package/dist/model/archetype/settings.d.ts +1 -0
  38. package/dist/model/archetype/settings.js +5 -0
  39. package/dist/reporters/model.js +4 -3
  40. package/dist/rules/registry.js +2 -2
  41. package/package.json +4 -2
  42. package/dist/model/archetype/builder.d.ts +0 -183
  43. package/dist/model/archetype/builder.js +0 -78
  44. package/dist/model/archetype/draft.d.ts +0 -30
  45. package/dist/model/archetype/draft.js +0 -264
@@ -1,66 +1,83 @@
1
- import { recordedAs } from './builder.js';
2
- const usedRequirements = (drafts) => new Set(drafts
3
- .flatMap((draft) => [...draft.modules.flatMap((module) => module.using), ...draft.testUsing])
4
- .map((value) => recordedAs(value, 'ref'))
5
- .map((ref) => ref?.kind === 'required' && ref.name));
6
- export const checkUnused = (drafts, fail) => {
7
- for (const draft of drafts.filter((candidate) => !candidate.data.inline)) {
8
- const inline = drafts.filter((candidate) => candidate.data.name.startsWith(`${draft.data.name}.`));
9
- const used = usedRequirements([draft, ...inline]);
10
- for (const name of Object.keys(draft.data.requires)) {
11
- if (!used.has(name))
12
- fail(`${draft.data.name} requires ${name}, which no module lists in using`);
13
- }
1
+ import { exposedProblem, show } from './references.js';
2
+ const namedOf = (archetype) => archetype.split('.')[0];
3
+ const sitesOf = (archetypes) => Object.values(archetypes).flatMap((holder) => holder.modules
4
+ .filter((module) => module.kind === 'dir' && !archetypes[module.archetype]?.inline)
5
+ .map((module) => ({ holder, module })));
6
+ export const markTests = (archetypes, fail) => {
7
+ const sites = sitesOf(archetypes);
8
+ for (const archetype of Object.values(archetypes).filter((candidate) => !candidate.inline)) {
9
+ const using = sites.filter((site) => site.module.archetype === archetype.name);
10
+ const tests = using.filter((site) => site.module.test).length;
11
+ if (tests === 0)
12
+ continue;
13
+ if (tests < using.length)
14
+ fail(`${archetype.name} is used by production and test modules; an archetype holds one or the other`);
15
+ else
16
+ archetype.test = true;
14
17
  }
18
+ for (const archetype of Object.values(archetypes))
19
+ if (archetype.inline && archetypes[namedOf(archetype.name)]?.test)
20
+ archetype.test = true;
15
21
  };
16
- export const checkRequirements = (archetypes, root, fail) => {
17
- const provisions = Object.values(archetypes).flatMap((archetype) => Object.entries(archetype.provides).map(([name, ref]) => ({
18
- archetype: archetype.name,
19
- name,
20
- module: archetype.modules.find((module) => module.name === ref.module),
21
- used: false,
22
- })));
23
- walk({ archetypes, provisions, fail, missing: new Set(), visited: new Set() }, archetypes[root], '', new Map());
24
- return provisions
25
- .filter((p) => !p.used)
26
- .map((p) => `${p.archetype} provides ${p.name}, which nothing below requires`);
27
- };
28
- const walk = (state, archetype, path, above) => {
29
- const at = path === '' ? archetype.name : `${path} (${archetype.name})`;
30
- if (!archetype.inline) {
31
- for (const [name, requirement] of Object.entries(archetype.requires)) {
32
- answer(state, at, archetype.name, name, requirement, above.get(name));
33
- }
22
+ export const checkInputs = (archetypes, pending, fail) => {
23
+ const uses = pending.filter((entry) => entry.ref.kind === 'required');
24
+ const usesOf = (archetype) => uses.filter((entry) => namedOf(entry.archetype) === archetype);
25
+ for (const archetype of Object.values(archetypes).filter((candidate) => !candidate.inline)) {
26
+ const inputs = [...archetype.requires, ...(archetype.testRequires ?? [])];
27
+ const shadowed = shadowsOf(archetypes, archetype.name, inputs);
28
+ for (const [module, name] of shadowed)
29
+ fail(`${module} shadows the input ${name}; rename one`);
30
+ const used = new Set(usesOf(archetype.name).map((entry) => entry.ref.name));
31
+ const names = new Set(shadowed.map(([, name]) => name));
32
+ for (const name of inputs.filter((input) => !used.has(input) && !names.has(input)))
33
+ fail(`${archetype.name} requires ${name}, which none of its modules names in dependencies`);
34
34
  }
35
- const below = new Map(above);
36
- for (const provision of state.provisions.filter((p) => p.archetype === archetype.name))
37
- below.set(provision.name, provision);
38
- const signature = JSON.stringify([...below].map(([name, provision]) => [name, provision.archetype]));
39
- for (const module of archetype.modules) {
40
- if (module.kind !== 'dir' || state.visited.has(`${module.archetype}|${signature}`))
41
- continue;
42
- state.visited.add(`${module.archetype}|${signature}`);
43
- walk(state, state.archetypes[module.archetype], path === '' ? module.name : `${path}.${module.name}`, below);
35
+ for (const site of sitesOf(archetypes)) {
36
+ const archetype = archetypes[site.module.archetype];
37
+ if (archetype)
38
+ checkSite(archetypes, site, archetype, usesOf(archetype.name), fail);
44
39
  }
45
40
  };
46
- const answer = (state, at, archetype, name, requirement, provider) => {
47
- if (!provider) {
48
- if (!state.missing.has(`${archetype}.${name}`))
49
- state.fail(`${at} requires ${name}, which nothing above it provides`);
50
- state.missing.add(`${archetype}.${name}`);
51
- return;
52
- }
53
- provider.used = true;
54
- if (!fits(requirement, provider.module)) {
55
- state.fail(`${at} requires ${name} as ${requirementText(requirement)}; ${provider.archetype} provides ${name} from ${provider.module.name}, ${moduleText(state, provider.module)}`);
41
+ const shadowsOf = (archetypes, named, inputs) => Object.values(archetypes)
42
+ .filter((archetype) => namedOf(archetype.name) === named)
43
+ .flatMap((archetype) => archetype.modules
44
+ .filter((module) => inputs.includes(module.name))
45
+ .map((module) => [`${archetype.name}.${module.name}`, module.name]));
46
+ const checkSite = (archetypes, { holder, module }, archetype, uses, fail) => {
47
+ const where = `${holder.name}.${module.name}`;
48
+ for (const name of archetype.requires.filter((input) => !module.inputs?.[input]))
49
+ fail(`${where} uses ${archetype.name}, which requires ${name}; ${binding(module.inputs, name, where)}`);
50
+ for (const name of (archetype.testRequires ?? []).filter((input) => !module.testInputs?.[input]))
51
+ fail(`${where} uses ${archetype.name}, whose tests require ${name}; name it in ${where}.test.dependencies`);
52
+ const bound = { ...module.inputs, ...module.testInputs };
53
+ for (const entry of uses) {
54
+ const ref = entry.ref;
55
+ const given = bound[ref.name];
56
+ if (!given || ref.surface === undefined)
57
+ continue;
58
+ const problem = surfaceProblem(archetypes, holder, given, ref.surface, entry.tests);
59
+ if (problem)
60
+ fail(`${entry.where}: '${ref.name}.${ref.surface}': ${where} binds ${ref.name} to ${show(given)}; ${problem}`);
56
61
  }
57
62
  };
58
- const moduleText = (state, module) => {
59
- if (module.kind !== 'dir')
60
- return `a ${module.kind} module`;
61
- return state.archetypes[module.archetype].inline ? 'a dir module' : `modules of ${module.archetype}`;
63
+ const binding = (inputs, name, where) => inputs?.[`npm:${name}`]
64
+ ? `bind the package by name in ${where}.dependencies, { ${name}: npm:${name} }`
65
+ : `name it in ${where}.dependencies`;
66
+ const archetypeAt = (archetypes, holder, up) => archetypes[holder.name
67
+ .split('.')
68
+ .slice(0, Math.max(holder.name.split('.').length - up, 1))
69
+ .join('.')];
70
+ const surfaceProblem = (archetypes, holder, binding, surface, tests) => {
71
+ if (binding.kind === 'package')
72
+ return `a package has no surfaces`;
73
+ if (binding.surface !== undefined)
74
+ return `${show(binding)} is a surface already`;
75
+ if (binding.kind === 'required')
76
+ return undefined;
77
+ const at = archetypeAt(archetypes, holder, binding.up ?? 0);
78
+ const module = at.modules.find((candidate) => candidate.name === binding.module);
79
+ if (module?.kind !== 'dir')
80
+ return `${binding.module} has no named surfaces`;
81
+ const inside = archetypes[module.archetype];
82
+ return exposedProblem(binding.module, { exposes: inside.exposes, testExposes: Object.keys(inside.testExposes ?? {}) }, surface, tests);
62
83
  };
63
- const requirementText = (requirement) => requirement.kind === 'archetype' ? `modules of ${requirement.archetype}` : `${requirement.kind}()`;
64
- const fits = (requirement, module) => requirement.kind === 'archetype'
65
- ? module.kind === 'dir' && module.archetype === requirement.archetype
66
- : module.kind === requirement.kind;
@@ -7,6 +7,7 @@ export interface ModuleView {
7
7
  id: string;
8
8
  name?: string;
9
9
  kind: 'dir' | 'files' | 'test';
10
+ test?: true;
10
11
  dir: string;
11
12
  archetype?: string;
12
13
  captures: Record<string, string>;
@@ -2,6 +2,7 @@ import { ConfigError } from '../configError.js';
2
2
  export const declarationOf = (config, module) => module.parent && config.archetypes[module.parent.archetype].modules.find((data) => data.name === module.name);
3
3
  export const rootId = '(root)';
4
4
  const placeholders = /\{(\w+)\}/g;
5
+ const asWritten = (path) => path.replaceAll('{name}', '*');
5
6
  const join = (dir, name) => (dir === '' ? name : `${dir}/${name}`);
6
7
  const parentDir = (path) => path.slice(0, Math.max(path.lastIndexOf('/'), 0));
7
8
  const fill = (pattern, captures) => {
@@ -15,10 +16,8 @@ export const fillPattern = (pattern, captures) => {
15
16
  return 'filled' in filled ? filled.filled : undefined;
16
17
  };
17
18
  export const resolveModel = (config, folders, files) => {
18
- const resolution = { config, folders, byDir: new Map(), mirrors: new Map(), errors: new Set() };
19
+ const resolution = { config, folders, byDir: new Map(), errors: new Set() };
19
20
  const root = build(resolution, { dir: '', archetype: config.archetypes[config.root], captures: {} });
20
- for (const module of walk(root))
21
- mirrorsOf(resolution, module);
22
21
  const moduleOf = new Map();
23
22
  for (const file of [...files].sort())
24
23
  moduleOf.set(file, assign(resolution, file));
@@ -29,43 +28,15 @@ export const resolveModel = (config, folders, files) => {
29
28
  root,
30
29
  modules: [...walk(root)],
31
30
  moduleOf: (file) => moduleOf.get(file),
32
- isTest: (file) => moduleOf.get(file)?.kind === 'test',
31
+ isTest: (file) => moduleOf.get(file)?.test === true,
33
32
  };
34
33
  };
35
34
  const assign = (resolution, file) => {
36
35
  const folder = deepest(resolution.byDir, file);
37
- const module = mirrorClaim(resolution, file) ?? claimOf(resolution, folder, file) ?? place(resolution, folder, file);
36
+ const module = claimOf(resolution, folder, file) ?? place(resolution, folder, file);
38
37
  module.files.push(file);
39
38
  return module;
40
39
  };
41
- const mirrorsOf = (resolution, holder) => {
42
- if (holder.kind !== 'dir')
43
- return;
44
- for (const declared of resolution.config.archetypes[holder.archetype].modules) {
45
- if (declared.kind !== 'test' || declared.locator.kind !== 'mirror')
46
- continue;
47
- const { from, to } = declared.locator;
48
- const where = `${holder.id}: ${holder.archetype}.${declared.name} mirror('${from}', '${to}')`;
49
- if (holder.dir !== from && !holder.dir.startsWith(`${from}/`)) {
50
- resolution.errors.add(`${where} needs a folder under ${from}; this module is not in it`);
51
- continue;
52
- }
53
- const target = `${to}${holder.dir.slice(from.length)}`;
54
- const taken = resolution.mirrors.get(target);
55
- if (taken)
56
- resolution.errors.add(`${target}: mirrored by ${taken.holder.id} and ${holder.id}; one folder mirrors one module`);
57
- else
58
- resolution.mirrors.set(target, { holder, name: declared.name });
59
- }
60
- };
61
- const mirrorClaim = (resolution, file) => {
62
- for (let dir = parentDir(file); dir !== ''; dir = parentDir(dir)) {
63
- const mirror = resolution.mirrors.get(dir);
64
- if (mirror)
65
- return childModule(mirror.holder, mirror.name, 'test');
66
- }
67
- return undefined;
68
- };
69
40
  const walk = function* (module) {
70
41
  yield module;
71
42
  for (const child of module.children)
@@ -110,6 +81,7 @@ const childModule = (folder, name, kind) => {
110
81
  id,
111
82
  name,
112
83
  kind,
84
+ ...(kind === 'test' ? { test: true } : {}),
113
85
  dir: folder.dir,
114
86
  captures: folder.captures,
115
87
  parent: folder,
@@ -128,38 +100,39 @@ const claimOf = (resolution, folder, file) => {
128
100
  const claims = archetype.modules
129
101
  .filter((declared) => declared.kind === 'test')
130
102
  .flatMap((declared) => {
131
- const score = locates(level, declared.locator, file);
103
+ const score = locates(level, declared.patterns, file);
132
104
  return score === undefined ? [] : [{ name: declared.name, score }];
133
105
  });
134
- if (claims.length === 0)
106
+ if (claims.length === 0) {
107
+ if (at.test)
108
+ return at;
135
109
  continue;
110
+ }
136
111
  const best = claims.reduce((top, claim) => (claim.score > top.score ? claim : top));
137
112
  const tied = claims.filter((claim) => claim !== best && claim.score === best.score);
138
113
  if (tied.length > 0)
139
- resolution.errors.add(`${file}: claimed by ${archetype.name}'s test modules ${[best, ...tied].map((claim) => claim.name).join(' and ')}, which are equally specific; narrow one of their selectors`);
114
+ resolution.errors.add(`${file}: claimed by ${archetype.name}'s test modules ${[best, ...tied].map((claim) => claim.name).join(' and ')}, which are equally specific; narrow one of their patterns`);
140
115
  return childModule(level, best.name, 'test');
141
116
  }
142
117
  return undefined;
143
118
  };
144
- const locates = (module, locator, file) => {
145
- if (locator.kind === 'mirror')
146
- return undefined;
119
+ const locates = (module, patterns, file) => {
147
120
  const path = module.dir === '' ? file : file.slice(module.dir.length + 1);
148
- const scores = locator.patterns.flatMap((pattern) => {
121
+ const scores = patterns.flatMap((pattern) => {
149
122
  const filled = fillPattern(pattern, module.captures);
150
123
  if (filled === undefined)
151
124
  return [];
152
- const glob = locator.kind === 'dir' ? `${filled}/**` : filled;
153
- return globRegex(glob).test(path) ? [specificity(glob)] : [];
125
+ return globRegex(filled).test(path) ? [specificity(filled)] : [];
154
126
  });
155
127
  return scores.length === 0 ? undefined : Math.max(...scores);
156
128
  };
157
129
  const pathOf = (module) => module.parent?.name === undefined ? module.name : `${pathOf(module.parent)}.${module.name}`;
158
- const build = (resolution, { dir, archetype, captures, parent, name }) => {
130
+ const build = (resolution, { dir, archetype, captures, parent, name, test }) => {
159
131
  const module = {
160
132
  id: dir === '' ? rootId : dir,
161
133
  ...(name === undefined ? {} : { name }),
162
134
  kind: 'dir',
135
+ ...(test ? { test: true } : {}),
163
136
  dir,
164
137
  archetype: archetype.name,
165
138
  captures,
@@ -183,6 +156,7 @@ const build = (resolution, { dir, archetype, captures, parent, name }) => {
183
156
  captures: winner.captures,
184
157
  parent: module,
185
158
  name: winner.module.name,
159
+ test: winner.module.test === true,
186
160
  }));
187
161
  }
188
162
  return module;
@@ -200,7 +174,8 @@ const claimsIn = (resolution, module, archetype) => {
200
174
  const claimsOf = (resolution, module, declared) => {
201
175
  const child = resolution.config.archetypes[declared.archetype];
202
176
  return declared.paths.flatMap((path) => matchFolders(resolution.folders, module.dir, path).flatMap((match) => {
203
- const captures = identify(resolution, child, match.dir, match.captures, module, { declared, path });
177
+ const inherited = child.inline ? { ...module.captures, ...match.captures } : match.captures;
178
+ const captures = identify(resolution, child, match.dir, inherited, module, { declared, path });
204
179
  return captures ? [{ module: declared, path, archetype: child, ...match, captures }] : [];
205
180
  }));
206
181
  };
@@ -223,10 +198,6 @@ const identify = (resolution, archetype, dir, captures, parent, claim) => {
223
198
  const how = archetype.identify;
224
199
  if (how === undefined)
225
200
  return captures;
226
- if ('match' in how) {
227
- const matched = how.match(dir, chain(parent));
228
- return matched === false ? undefined : { ...captures, ...matched };
229
- }
230
201
  const marker = fill(how.marker, captures);
231
202
  if ('missing' in marker) {
232
203
  resolution.errors.add(`${dir}: ${archetype.name}'s marker '${how.marker}' names {${marker.missing}}, which its dir path doesn't capture` +
@@ -245,12 +216,11 @@ const sharedHint = (resolution, parent, { declared, path }, missing) => {
245
216
  if (!sibling)
246
217
  return '';
247
218
  const folder = path.slice(path.lastIndexOf('/') + 1);
248
- const shown = sibling.paths.map((candidate) => `'${candidate}'`).join(', ');
249
- return (`. A literal dir() binds no placeholders. If ${sibling.name} use ${declared.name}, it is shared: move ${folder} ` +
250
- `out of the folders dir(${shown}) matches, for example into shared/${folder}, and declare it as its own module ` +
251
- `with dir('shared/{${missing}}')`);
219
+ const shown = sibling.paths.map((candidate) => `'${asWritten(candidate)}'`).join(', ');
220
+ return (`. A literal dir binds no placeholders. If ${sibling.name} use ${declared.name}, it is shared: move ${folder} ` +
221
+ `out of the folders dir: ${shown} matches, for example into shared/${folder}, and declare it as its own module ` +
222
+ `with dir: 'shared/*'`);
252
223
  };
253
- const chain = (module) => (module.parent ? [...chain(module.parent), module] : [module]);
254
224
  const compareRanks = (a, b) => {
255
225
  const index = a.findIndex((value, at) => value !== b[at]);
256
226
  return index < 0 ? 0 : a[index] - b[index];
@@ -259,7 +229,7 @@ const mostSpecific = (resolution, archetype, dir, claims) => {
259
229
  const best = claims.reduce((top, claim) => (compareRanks(claim.rank, top.rank) > 0 ? claim : top));
260
230
  const tied = claims.filter((claim) => claim.module !== best.module && compareRanks(claim.rank, best.rank) === 0);
261
231
  if (tied.length > 0) {
262
- const names = [best, ...tied].map((claim) => `${claim.module.name} ('${claim.path}')`).join(' and ');
232
+ const names = [best, ...tied].map((claim) => `${claim.module.name} ('${asWritten(claim.path)}')`).join(' and ');
263
233
  resolution.errors.add(`${dir}: ${archetype.name}'s dir modules ${names} are equally specific; narrow one of the paths`);
264
234
  }
265
235
  return best;
@@ -280,7 +250,7 @@ const filesModule = (resolution, module, archetype, candidates, file) => {
280
250
  for (const pattern of declared.patterns) {
281
251
  const filled = fill(pattern, module.captures);
282
252
  if ('missing' in filled) {
283
- resolution.errors.add(`${module.id}: ${archetype.name}.${declared.name} '${pattern}' names {${filled.missing}}, which ${module.id} doesn't capture`);
253
+ resolution.errors.add(`${archetype.name}.${declared.name}.files: '${pattern}' names {${filled.missing}}, which ${module.id} doesn't capture`);
284
254
  }
285
255
  else if (globRegex(filled.filled).test(path))
286
256
  matches.push({ module: declared.name, pattern, score: specificity(filled.filled) });
@@ -297,7 +267,7 @@ const filesModule = (resolution, module, archetype, candidates, file) => {
297
267
  const tie = (clash) => {
298
268
  const names = clash.map((match) => `${match.module} ('${match.pattern}')`).join(' and ');
299
269
  const folders = clash.every((match) => match.pattern.endsWith('/**'));
300
- const fix = folders ? 'declare the folders with dir(), where the deeper folder wins' : 'narrow one of the patterns';
270
+ const fix = folders ? 'declare the folders with dir, where the deeper folder wins' : 'narrow one of the patterns';
301
271
  return `files modules ${names} are equally specific; ${fix}`;
302
272
  };
303
273
  export const specificity = (pattern) => {
@@ -1,4 +1,5 @@
1
- import type { ConfigData, RuleSettingsData } from './data.ts';
1
+ import { type ConfigData, type RuleSettingsData } from './data.ts';
2
2
  import { type Fail } from './shared.ts';
3
3
  export type ParseRules = (value: unknown, at: string) => RuleSettingsData | undefined;
4
4
  export declare const withRuleset: (config: ConfigData, rulesets: unknown, name: string | undefined, parse: ParseRules, fail: Fail) => ConfigData;
5
+ export declare const recommended = "warp:recommended";
@@ -1,67 +1,98 @@
1
1
  import { ConfigError } from '../configError.js';
2
- import { recordedAs } from './builder.js';
3
- import { isName, isRecord, list } from './shared.js';
2
+ import { isTestData } from './data.js';
3
+ import { isRecord, list } from './shared.js';
4
4
  export const withRuleset = (config, rulesets, name, parse, fail) => {
5
5
  const named = rulesetsOf(rulesets, fail);
6
6
  if (name !== undefined && !named.has(name)) {
7
7
  const names = [...named.keys()];
8
- throw new ConfigError(`no ruleset called ${name}. ${names.length > 0 ? `Rulesets: ${names.join(', ')}` : 'The config declares none'}`);
8
+ throw new ConfigError(`rulesets: no ruleset called ${name}. ${names.length > 0 ? `Rulesets: ${names.join(', ')}` : 'The config declares none'}`);
9
9
  }
10
- const chosen = named.get(name ?? 'default');
11
- return chosen ? applied(config, layersOf(chosen, named, fail), parse, fail) : config;
10
+ const chosen = name ?? 'default';
11
+ if (!named.has(chosen))
12
+ return applied(config, [{ settings: 'off', at: 'rulesets' }], parse, fail);
13
+ const { layers, recommends } = layersOf(config, chosen, named, fail);
14
+ const base = recommends ? [] : [{ settings: 'off', at: `rulesets.${chosen}` }];
15
+ return applied(config, [...base, ...layers], parse, fail);
12
16
  };
17
+ export const recommended = 'warp:recommended';
18
+ const rulesetKeys = ['extends', 'rules', 'test', 'on'];
13
19
  const rulesetsOf = (value, fail) => {
14
20
  const named = new Map();
15
21
  if (value === undefined)
16
22
  return named;
17
23
  if (!isRecord(value)) {
18
- fail('config.rulesets: expected rulesets by name, { default: base, edit }');
24
+ fail('rulesets: expected rulesets by name, { default: { extends: [warp:recommended] } }');
19
25
  return named;
20
26
  }
21
27
  for (const [name, ruleset] of Object.entries(value)) {
22
- const recorded = recordedAs(ruleset, 'ruleset');
23
- if (recorded)
24
- named.set(name, recorded);
25
- else
26
- fail(`config.rulesets.${name}: expected a ruleset, ruleset().rules(...)`);
28
+ if (!isRecord(ruleset)) {
29
+ fail(`rulesets.${name}: expected a ruleset, { extends: [warp:recommended], rules: {...} }`);
30
+ continue;
31
+ }
32
+ for (const key of Object.keys(ruleset).filter((key) => !rulesetKeys.includes(key)))
33
+ fail(`rulesets.${name}: unknown key ${key}; a ruleset takes ${rulesetKeys.join(', ')}`);
34
+ named.set(name, ruleset);
27
35
  }
28
36
  return named;
29
37
  };
30
- const layersOf = (ruleset, named, fail) => {
31
- const label = (of) => [...named].find(([, candidate]) => candidate === of)?.[0] ?? 'extends';
32
- const chain = [];
33
- for (let current = ruleset; current;) {
34
- chain.unshift(current);
35
- if (current.base === undefined)
36
- break;
37
- const base = recordedAs(current.base, 'ruleset');
38
- if (!base)
39
- fail(`rulesets.${label(current)}.extends: expected a ruleset`);
40
- current = base;
38
+ const layersOf = (config, name, named, fail, seen = []) => {
39
+ const ruleset = named.get(name);
40
+ const at = `rulesets.${name}`;
41
+ const inherited = basesOf(config, name, named, fail, seen);
42
+ const layers = [...inherited.layers];
43
+ if (ruleset.rules !== undefined)
44
+ layers.push({ settings: ruleset.rules, at: `${at}.rules` });
45
+ if (ruleset.test !== undefined)
46
+ for (const target of testTargets(config))
47
+ layers.push({ target, settings: ruleset.test, at: `${at}.test` });
48
+ if (ruleset.on !== undefined)
49
+ layers.push(...onLayers(config, at, ruleset.on, fail));
50
+ return { layers, recommends: inherited.recommends };
51
+ };
52
+ const basesOf = (config, name, named, fail, seen) => {
53
+ const at = `rulesets.${name}`;
54
+ const declared = named.get(name).extends;
55
+ const bases = declared === undefined ? [] : [declared].flat();
56
+ const found = { layers: [], recommends: false };
57
+ for (const base of bases) {
58
+ if (base === recommended)
59
+ found.recommends = true;
60
+ else if (typeof base !== 'string' || !named.has(base))
61
+ fail(`${at}.extends: '${String(base)}' is no ruleset; extend ${list([recommended, ...named.keys()], 'nothing')}`);
62
+ else if (seen.includes(base))
63
+ fail(`${at}.extends: ${[...seen, name, base].join(' extends ')}, a loop`);
64
+ else {
65
+ const extended = layersOf(config, base, named, fail, [...seen, name]);
66
+ found.layers.push(...extended.layers);
67
+ found.recommends ||= extended.recommends;
68
+ }
41
69
  }
42
- return chain.flatMap((of) => {
43
- const at = `rulesets.${label(of)}`;
44
- return of.entries.map(({ target, settings }) => {
45
- if (target === undefined)
46
- return { settings, at: `${at}.rules` };
47
- const resolved = targetOf(target);
48
- if (!resolved) {
49
- fail(`${at}.on: expected an archetype or one of its modules, such as component or component.modules.logic`);
50
- return { settings: undefined, at };
51
- }
52
- const shown = resolved.module === undefined
53
- ? resolved.archetype
54
- : `${resolved.archetype.replaceAll('.', '.modules.')}.modules.${resolved.module}`;
55
- return { target: resolved, settings, at: `${at}.on(${shown})` };
56
- });
70
+ return found;
71
+ };
72
+ const onLayers = (config, at, on, fail) => {
73
+ if (!isRecord(on)) {
74
+ fail(`${at}.on: expected settings by archetype or module, { app.adapters: {...} }`);
75
+ return [];
76
+ }
77
+ return Object.entries(on).flatMap(([path, settings]) => {
78
+ const target = targetOf(config, path);
79
+ if (target)
80
+ return [{ target, settings, at: `${at}.on.${path}` }];
81
+ fail(`${at}.on.${path}: no archetype or module called ${path}; name an archetype, or archetype.module`);
82
+ return [];
57
83
  });
58
84
  };
59
- const targetOf = (value) => {
60
- const archetype = recordedAs(value, 'archetype');
61
- if (archetype)
62
- return isName(archetype.definition.name) ? { archetype: archetype.definition.name } : undefined;
63
- const handle = recordedAs(value, 'handle');
64
- return handle && { archetype: handle.archetype, module: handle.module };
85
+ const testTargets = (config) => Object.values(config.archetypes).flatMap((archetype) => archetype.modules.filter(isTestData).map((module) => ({ archetype: archetype.name, module: module.name })));
86
+ const targetOf = (config, path) => {
87
+ if (config.archetypes[path])
88
+ return { archetype: path };
89
+ for (let at = path.lastIndexOf('.'); at > 0; at = path.lastIndexOf('.', at - 1)) {
90
+ const archetype = config.archetypes[path.slice(0, at)];
91
+ const module = path.slice(at + 1);
92
+ if (archetype?.modules.some((declared) => declared.name === module))
93
+ return { archetype: archetype.name, module };
94
+ }
95
+ return undefined;
65
96
  };
66
97
  const applied = (config, layers, parse, fail) => {
67
98
  let rules = config.rules;
@@ -19,3 +19,4 @@ export declare const rulesOf: (config: ConfigData, model: Model, rules: readonly
19
19
  id: string;
20
20
  defaults?: object;
21
21
  }[]) => RulesOf;
22
+ export declare const anyRuleOn: (config: ConfigData) => boolean;
@@ -47,3 +47,8 @@ export const rulesOf = (config, model, rules) => {
47
47
  })),
48
48
  };
49
49
  };
50
+ const turnsOn = (rules) => rules !== undefined && rules !== 'off' && Object.values(rules).some((setting) => setting !== false);
51
+ export const anyRuleOn = (config) => config.rules === undefined ||
52
+ (config.rules !== 'off' && config.rules['*'] !== false) ||
53
+ turnsOn(config.rules) ||
54
+ Object.values(config.archetypes).some((archetype) => turnsOn(archetype.rules) || archetype.modules.some((module) => turnsOn(module.rules)));
@@ -15,8 +15,8 @@ export const modelText = (model, rules) => {
15
15
  };
16
16
  visit(model.root, 0);
17
17
  const total = (modules) => modules.reduce((sum, module) => sum + module.files.length, 0);
18
- const files = total(model.modules.filter((module) => module.kind !== 'test'));
19
- const tests = total(model.modules.filter((module) => module.kind === 'test'));
18
+ const files = total(model.modules.filter((module) => !module.test));
19
+ const tests = total(model.modules.filter((module) => module.test));
20
20
  const loose = model.modules.reduce((sum, module) => sum + module.looseFiles.length, 0);
21
21
  const tested = tests > 0 ? `, ${count(tests, 'test file')}` : '';
22
22
  lines.push('', `${model.modules.length} modules, ${files} files${tested}, ${loose} loose.`);
@@ -40,7 +40,7 @@ const heading = (module) => {
40
40
  const captures = Object.entries(module.captures)
41
41
  .map(([key, value]) => ` {${key}=${value}}`)
42
42
  .join('');
43
- const contents = owned > 0 ? `, ${count(owned)}` : '';
43
+ const contents = owned > 0 ? `, ${count(owned, module.test ? 'test file' : 'file')}` : '';
44
44
  return `${module.name ?? 'root'}: ${module.archetype}${captures}${contents}`;
45
45
  };
46
46
  export const modelJson = (model, rules) => JSON.stringify({
@@ -48,6 +48,7 @@ export const modelJson = (model, rules) => JSON.stringify({
48
48
  id: module.id,
49
49
  name: module.name,
50
50
  kind: module.kind,
51
+ ...(module.test ? { test: true } : {}),
51
52
  archetype: module.archetype,
52
53
  captures: module.captures,
53
54
  parent: module.parent?.id,
@@ -9,13 +9,13 @@ export const registry = (rules) => {
9
9
  return byId;
10
10
  };
11
11
  const name = /^[a-z][a-z0-9-]*$/;
12
- export const pluginRules = (plugins) => Object.entries(plugins).flatMap(([namespace, plugin]) => namespaced(namespace, plugin, `config.plugins.${namespace}`));
12
+ export const pluginRules = (plugins) => Object.entries(plugins).flatMap(([namespace, plugin]) => namespaced(namespace, plugin, `plugins.${namespace}`));
13
13
  const namespaced = (namespace, plugin, at) => {
14
14
  if (!name.test(namespace))
15
15
  throw new ConfigError(`${at}: a namespace is lowercase letters, digits and dashes`);
16
16
  const rules = typeof plugin === 'object' && plugin !== null ? plugin.rules : undefined;
17
17
  if (!Array.isArray(rules))
18
- throw new ConfigError(`${at}: expected a plugin, { rules: Rule[] }, imported in a warp.config.ts`);
18
+ throw new ConfigError(`${at}: expected a plugin, { rules: Rule[] }, as the default export of its file`);
19
19
  return rules.map((rule, index) => {
20
20
  const where = `${at}.rules[${index}]`;
21
21
  if (typeof rule?.id !== 'string' || !name.test(rule.id))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yearofthedan/warp",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Architectural fitness checks for TypeScript codebases",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -29,12 +29,14 @@
29
29
  "build": "tsc -p tsconfig.build.json"
30
30
  },
31
31
  "dependencies": {
32
- "typescript": "7.1.0-beta"
32
+ "typescript": "7.1.0-beta",
33
+ "yaml": "2.9.1"
33
34
  },
34
35
  "devDependencies": {
35
36
  "@stryker-mutator/core": "10.1.1",
36
37
  "@stryker-mutator/vitest-runner": "10.1.1",
37
38
  "@types/node": "26.6.6",
39
+ "c8": "10.1.3",
38
40
  "secretlint": "14.0.1",
39
41
  "vite-plus": "catalog:"
40
42
  },