@yearofthedan/warp 0.3.0 → 0.4.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 (41) 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 +31 -43
  8. package/dist/builtins/advice.js +9 -9
  9. package/dist/builtins/dependency-direction/dependencyDirection.js +1 -1
  10. package/dist/builtins/module-externals/moduleExternals.js +3 -2
  11. package/dist/builtins/unused-declaration/empty.js +11 -10
  12. package/dist/builtins/unused-declaration/grants.js +17 -7
  13. package/dist/builtins/unused-declaration/surfaces.js +16 -6
  14. package/dist/cli.js +14 -11
  15. package/dist/config/loadConfig.d.ts +7 -1
  16. package/dist/config/loadConfig.js +83 -12
  17. package/dist/index.d.ts +0 -1
  18. package/dist/index.js +0 -1
  19. package/dist/model/archetype/data.d.ts +13 -23
  20. package/dist/model/archetype/data.js +1 -1
  21. package/dist/model/archetype/fixes.d.ts +5 -7
  22. package/dist/model/archetype/fixes.js +121 -90
  23. package/dist/model/archetype/language.d.ts +16 -0
  24. package/dist/model/archetype/language.js +419 -0
  25. package/dist/model/archetype/reach.d.ts +8 -3
  26. package/dist/model/archetype/reach.js +122 -56
  27. package/dist/model/archetype/references.d.ts +11 -5
  28. package/dist/model/archetype/references.js +59 -118
  29. package/dist/model/archetype/requirements.d.ts +3 -3
  30. package/dist/model/archetype/requirements.js +65 -58
  31. package/dist/model/archetype/resolve.d.ts +1 -0
  32. package/dist/model/archetype/resolve.js +23 -54
  33. package/dist/model/archetype/rulesets.d.ts +2 -1
  34. package/dist/model/archetype/rulesets.js +72 -42
  35. package/dist/reporters/model.js +4 -3
  36. package/dist/rules/registry.js +1 -1
  37. package/package.json +3 -2
  38. package/dist/model/archetype/builder.d.ts +0 -183
  39. package/dist/model/archetype/builder.js +0 -78
  40. package/dist/model/archetype/draft.d.ts +0 -30
  41. package/dist/model/archetype/draft.js +0 -264
@@ -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;
@@ -223,10 +197,6 @@ const identify = (resolution, archetype, dir, captures, parent, claim) => {
223
197
  const how = archetype.identify;
224
198
  if (how === undefined)
225
199
  return captures;
226
- if ('match' in how) {
227
- const matched = how.match(dir, chain(parent));
228
- return matched === false ? undefined : { ...captures, ...matched };
229
- }
230
200
  const marker = fill(how.marker, captures);
231
201
  if ('missing' in marker) {
232
202
  resolution.errors.add(`${dir}: ${archetype.name}'s marker '${how.marker}' names {${marker.missing}}, which its dir path doesn't capture` +
@@ -245,12 +215,11 @@ const sharedHint = (resolution, parent, { declared, path }, missing) => {
245
215
  if (!sibling)
246
216
  return '';
247
217
  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}}')`);
218
+ const shown = sibling.paths.map((candidate) => `'${asWritten(candidate)}'`).join(', ');
219
+ return (`. A literal dir binds no placeholders. If ${sibling.name} use ${declared.name}, it is shared: move ${folder} ` +
220
+ `out of the folders dir: ${shown} matches, for example into shared/${folder}, and declare it as its own module ` +
221
+ `with dir: 'shared/*'`);
252
222
  };
253
- const chain = (module) => (module.parent ? [...chain(module.parent), module] : [module]);
254
223
  const compareRanks = (a, b) => {
255
224
  const index = a.findIndex((value, at) => value !== b[at]);
256
225
  return index < 0 ? 0 : a[index] - b[index];
@@ -259,7 +228,7 @@ const mostSpecific = (resolution, archetype, dir, claims) => {
259
228
  const best = claims.reduce((top, claim) => (compareRanks(claim.rank, top.rank) > 0 ? claim : top));
260
229
  const tied = claims.filter((claim) => claim.module !== best.module && compareRanks(claim.rank, best.rank) === 0);
261
230
  if (tied.length > 0) {
262
- const names = [best, ...tied].map((claim) => `${claim.module.name} ('${claim.path}')`).join(' and ');
231
+ const names = [best, ...tied].map((claim) => `${claim.module.name} ('${asWritten(claim.path)}')`).join(' and ');
263
232
  resolution.errors.add(`${dir}: ${archetype.name}'s dir modules ${names} are equally specific; narrow one of the paths`);
264
233
  }
265
234
  return best;
@@ -297,7 +266,7 @@ const filesModule = (resolution, module, archetype, candidates, file) => {
297
266
  const tie = (clash) => {
298
267
  const names = clash.map((match) => `${match.module} ('${match.pattern}')`).join(' and ');
299
268
  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';
269
+ const fix = folders ? 'declare the folders with dir, where the deeper folder wins' : 'narrow one of the patterns';
301
270
  return `files modules ${names} are equally specific; ${fix}`;
302
271
  };
303
272
  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,97 @@
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
8
  throw new ConfigError(`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
+ }
69
+ }
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 [];
41
76
  }
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
- });
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
+ const at = path.lastIndexOf('.');
90
+ const archetype = config.archetypes[path.slice(0, at)];
91
+ const module = path.slice(at + 1);
92
+ return at > 0 && archetype?.modules.some((declared) => declared.name === module)
93
+ ? { archetype: archetype.name, module }
94
+ : undefined;
65
95
  };
66
96
  const applied = (config, layers, parse, fail) => {
67
97
  let rules = config.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,
@@ -15,7 +15,7 @@ const namespaced = (namespace, plugin, at) => {
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.0",
4
4
  "description": "Architectural fitness checks for TypeScript codebases",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -29,7 +29,8 @@
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",
@@ -1,183 +0,0 @@
1
- import type { IdentifyData } from './data.ts';
2
- declare const referenceBrand: unique symbol;
3
- declare const packageBrand: unique symbol;
4
- declare const shapeBrand: unique symbol;
5
- declare const selectorBrand: unique symbol;
6
- declare const selfBrand: unique symbol;
7
- declare const exposesType: unique symbol;
8
- declare const usingType: unique symbol;
9
- declare const modulesType: unique symbol;
10
- declare const allBrand: unique symbol;
11
- declare const handleBrand: unique symbol;
12
- declare const rulesetBrand: unique symbol;
13
- export interface Reference {
14
- readonly [referenceBrand]: true;
15
- }
16
- export interface Package {
17
- readonly [packageBrand]: true;
18
- }
19
- export interface Shape {
20
- readonly [shapeBrand]: 'dir' | 'files';
21
- }
22
- export interface Selector<K extends 'dir' | 'files' | 'mirror' = 'dir' | 'files'> {
23
- readonly [selectorBrand]: K;
24
- }
25
- export interface Self {
26
- readonly [selfBrand]: true;
27
- }
28
- export interface ModuleHandle {
29
- readonly [handleBrand]: true;
30
- }
31
- export type RuleSettings = 'off' | Record<string, boolean | object>;
32
- export interface All {
33
- readonly [allBrand]: true;
34
- }
35
- export interface Archetype<N extends string | undefined = string, E = unknown, P = unknown, H = unknown> {
36
- readonly name: N;
37
- readonly [exposesType]?: E;
38
- readonly [usingType]?: (s: P) => void;
39
- readonly [modulesType]?: H;
40
- }
41
- export type AnyArchetype = Archetype<any, any, any, any>;
42
- export type SurfaceRefs<E> = Reference & {
43
- readonly [K in keyof E]: Reference;
44
- };
45
- type AnySurface = Reference & {
46
- readonly [surface: string]: Reference;
47
- };
48
- type RequiredRef<A> = A extends Archetype<string, infer E> ? SurfaceRefs<E> : Reference;
49
- export interface UsingContext {
50
- readonly required: Readonly<Record<string, AnySurface>>;
51
- }
52
- export type Using<P> = readonly (Reference | Package)[] | ((m: P, context: UsingContext) => readonly (Reference | Package)[]);
53
- type Surfaces = Record<string, Reference | readonly Reference[]>;
54
- export type Exposed = All | Selector<'files'>;
55
- type NewName<K extends string, C> = K extends keyof C ? `module '${K}' is already declared` : K;
56
- type With<C, K extends string, T> = C & {
57
- readonly [k in K]: T;
58
- };
59
- type HandleOf<N, H> = N extends string ? ModuleHandle : {} extends H ? ModuleHandle : ModuleHandle & {
60
- readonly modules: H;
61
- };
62
- export interface Modules<C, H> {
63
- module<const K extends string>(name: NewName<K, C>, selector: Selector<'files'>, archetype?: Archetype<undefined, {}, C, {}>): Modules<With<C, K, Reference>, With<H, K, ModuleHandle>>;
64
- module<const K extends string>(name: NewName<K, C>, selector: Selector<'dir'>, archetype: Self): Modules<With<C, K, AnySurface>, With<H, K, ModuleHandle>>;
65
- module<const K extends string, N extends string | undefined = undefined, E = {}, H2 = {}>(name: NewName<K, C>, selector: Selector<'dir'>, archetype?: Archetype<N, E, C, H2>): Modules<With<C, K, SurfaceRefs<E>>, With<H, K, HandleOf<N, H2>>>;
66
- testModule<const K extends string>(name: NewName<K, C>, selector: Selector<'files' | 'dir' | 'mirror'>, archetype?: Archetype<undefined, {}, C, {}>): Modules<With<C, K, Reference>, With<H, K, ModuleHandle>>;
67
- }
68
- export type TestUsing<C, R> = readonly (Reference | Package)[] | ((m: C, context: {
69
- readonly required: R;
70
- }) => readonly (Reference | Package)[]);
71
- export interface ContainsContext<R> {
72
- required: R;
73
- self: Self;
74
- }
75
- export type Identify = IdentifyData;
76
- export type ArchetypeBuilder<N extends string | undefined, C, H, R, E, P = unknown> = ArchetypeMethods<N, C, H, R, E, P> & {
77
- readonly modules: H;
78
- };
79
- export interface ArchetypeMethods<N extends string | undefined, C, H, R, E, P> extends Archetype<N, E, P, H> {
80
- identify(identify: Identify): ArchetypeBuilder<N, C, H, R, E, P>;
81
- requires<const R2 extends Record<string, AnyArchetype | Shape>>(requires: R2): ArchetypeBuilder<N, C, H, {
82
- readonly [K in keyof R2]: RequiredRef<R2[K]>;
83
- }, E, P>;
84
- contains<C2, H2>(modules: (m: Modules<{}, {}>, context: ContainsContext<R>) => Modules<C2, H2>): ArchetypeBuilder<N, C2, H2, R, E, P>;
85
- exposes<const E2 extends Surfaces>(exposes: (s: C) => E2): ArchetypeBuilder<N, C, H, R, E2, P>;
86
- exposes(exposes: Exposed): ArchetypeBuilder<N, C, H, R, {}, P>;
87
- entry(entry: Selector<'files'>): ArchetypeBuilder<N, C, H, R, {}, P>;
88
- provides(provides: (s: C) => Record<string, Reference>): ArchetypeBuilder<N, C, H, R, E, P>;
89
- description(description: string): ArchetypeBuilder<N, C, H, R, E, P>;
90
- testUsing(using: TestUsing<C, R>): ArchetypeBuilder<N, C, H, R, E, P>;
91
- using<P2 = any>(using: Using<P2>): ArchetypeBuilder<N, C, H, R, E, P2>;
92
- }
93
- export interface Ruleset {
94
- readonly [rulesetBrand]: true;
95
- rules(settings: RuleSettings): Ruleset;
96
- on(target: Archetype<string, any, any, any> | ModuleHandle, settings: RuleSettings): Ruleset;
97
- extends(base: Ruleset): Ruleset;
98
- }
99
- export interface WarpConfig {
100
- root: Archetype<string, any, any, any>;
101
- tsconfig?: string | readonly string[];
102
- plugins?: Record<string, unknown>;
103
- rulesets?: Record<string, Ruleset>;
104
- }
105
- export type RecordedRef = {
106
- kind: 'module';
107
- module: string;
108
- surface?: string;
109
- } | {
110
- kind: 'required';
111
- name: string;
112
- surface?: string;
113
- } | {
114
- kind: 'package';
115
- pattern: string;
116
- };
117
- export interface RecordedSelector {
118
- kind: 'dir' | 'files' | 'mirror';
119
- patterns: readonly unknown[];
120
- }
121
- export interface RecordedModule {
122
- name: unknown;
123
- selector: unknown;
124
- archetype?: unknown;
125
- extra: readonly unknown[];
126
- test?: true;
127
- }
128
- export interface RecordedDefinition {
129
- name: unknown;
130
- identify?: unknown;
131
- requires: unknown;
132
- modules: unknown;
133
- exposes?: unknown;
134
- entry?: unknown;
135
- provides?: unknown;
136
- description?: unknown;
137
- testUsing?: unknown;
138
- }
139
- export interface RecordedArchetype {
140
- definition: RecordedDefinition;
141
- using?: unknown;
142
- }
143
- export interface RecordedRuleset {
144
- base?: unknown;
145
- entries: readonly {
146
- target?: unknown;
147
- settings: unknown;
148
- }[];
149
- }
150
- interface Recorded {
151
- ref: RecordedRef;
152
- self: true;
153
- all: true;
154
- shape: 'dir' | 'files';
155
- selector: RecordedSelector;
156
- modules: readonly RecordedModule[];
157
- archetype: RecordedArchetype;
158
- handle: {
159
- archetype: unknown;
160
- module: unknown;
161
- };
162
- ruleset: RecordedRuleset;
163
- }
164
- export declare const recordedAs: <T extends keyof Recorded>(value: unknown, type: T) => Recorded[T] | undefined;
165
- export declare const moduleRefs: () => unknown;
166
- export declare const requiredRefs: () => unknown;
167
- export declare const self: Self;
168
- export declare const inlineName: (holder: string, module: string) => string;
169
- export declare function archetype(): ArchetypeBuilder<undefined, {}, {}, {}, {}>;
170
- export declare function archetype<const N extends string>(name: N): ArchetypeBuilder<N, {}, {}, {}, {}>;
171
- export declare const using: <P = any>(using: Using<P>) => ArchetypeBuilder<undefined, {}, {}, {}, {}, P>;
172
- export declare const exposes: (exposes: Exposed) => ArchetypeBuilder<undefined, {}, {}, {}, {}>;
173
- export declare const contains: <C2, H2>(modules: (m: Modules<{}, {}>, context: ContainsContext<{}>) => Modules<C2, H2>) => ArchetypeBuilder<undefined, C2, H2, {}, {}>;
174
- export declare const all: () => All;
175
- export declare function dir(): Shape;
176
- export declare function dir(...paths: [string, ...string[]]): Selector<'dir'>;
177
- export declare function files(): Shape;
178
- export declare function files(...patterns: [string, ...string[]]): Selector<'files'>;
179
- export declare const mirror: (from: string, to: string) => Selector<'mirror'>;
180
- export declare const pkg: (pattern: string) => Package;
181
- export declare const defineConfig: <const C extends WarpConfig>(config: C) => C;
182
- export declare const ruleset: () => Ruleset;
183
- export {};
@@ -1,78 +0,0 @@
1
- import { ConfigError } from '../configError.js';
2
- const recorded = Symbol('warp.recorded');
3
- const record = (type, data) => ({ [recorded]: { type, data } });
4
- export const recordedAs = (value, type) => {
5
- const entry = value?.[recorded];
6
- return entry?.type === type ? entry.data : undefined;
7
- };
8
- const ref = (data) => Object.freeze(record('ref', data));
9
- const surfaces = (base) => new Proxy(ref(base), {
10
- get: (target, key) => (typeof key === 'string' ? ref({ ...base, surface: key }) : Reflect.get(target, key)),
11
- });
12
- const names = (make) => new Proxy({}, { get: (_, key) => surfaces(make(String(key))) });
13
- export const moduleRefs = () => names((module) => ({ kind: 'module', module }));
14
- export const requiredRefs = () => names((name) => ({ kind: 'required', name }));
15
- export const self = Object.freeze(record('self', true));
16
- const modules = (entries) => ({
17
- ...record('modules', entries),
18
- module: (name, selector, archetype, ...extra) => modules([...entries, { name, selector, archetype, extra }]),
19
- testModule: (name, selector, archetype, ...extra) => modules([...entries, { name, selector, archetype, extra, test: true }]),
20
- });
21
- export const inlineName = (holder, module) => `${holder}.${module}`;
22
- const handles = (holder, entries) => Object.fromEntries((Array.isArray(entries) ? entries : [])
23
- .filter((entry) => typeof entry.name === 'string')
24
- .map((entry) => {
25
- const handle = record('handle', { archetype: holder, module: entry.name });
26
- const anonymous = recordedAs(entry.archetype, 'archetype')?.definition;
27
- const nested = anonymous && anonymous.name === undefined && !entry.test
28
- ? { modules: handles(inlineName(String(holder), entry.name), anonymous.modules) }
29
- : {};
30
- return [entry.name, Object.freeze({ ...handle, ...nested })];
31
- }));
32
- const builder = (state) => {
33
- const { definition } = state;
34
- const define = (field) => (value) => builder({ ...state, definition: { ...definition, [field]: value } });
35
- return {
36
- modules: handles(definition.name, definition.modules),
37
- name: definition.name,
38
- ...record('archetype', state),
39
- identify: define('identify'),
40
- requires: define('requires'),
41
- contains: (contains) => define('modules')(recordedAs(contains(modules([]), { required: requiredRefs(), self }), 'modules')),
42
- exposes: define('exposes'),
43
- entry: define('entry'),
44
- provides: define('provides'),
45
- description: define('description'),
46
- testUsing: define('testUsing'),
47
- using: (using) => builder({ ...state, using }),
48
- };
49
- };
50
- const start = (name) => builder({ definition: { name, requires: {}, modules: [] } });
51
- export function archetype(name) {
52
- return start(name);
53
- }
54
- export const using = (using) => start(undefined).using(using);
55
- export const exposes = (exposes) => start(undefined).exposes(exposes);
56
- export const contains = (modules) => start(undefined).contains(modules);
57
- export const all = () => Object.freeze(record('all', true));
58
- const selector = (kind, patterns) => Object.freeze(patterns.length === 0 ? record('shape', kind) : record('selector', { kind, patterns }));
59
- export function dir(...paths) {
60
- return selector('dir', paths);
61
- }
62
- export function files(...patterns) {
63
- return selector('files', patterns);
64
- }
65
- export const mirror = (from, to) => Object.freeze(record('selector', { kind: 'mirror', patterns: [from, to] }));
66
- export const pkg = (pattern) => ref({ kind: 'package', pattern });
67
- export const defineConfig = (config) => config;
68
- const rulesetOf = (state) => ({
69
- ...record('ruleset', state),
70
- rules: (settings) => rulesetOf({ ...state, entries: [...state.entries, { settings }] }),
71
- on: (target, settings) => rulesetOf({ ...state, entries: [...state.entries, { target, settings }] }),
72
- extends: (base) => {
73
- if (state.base !== undefined)
74
- throw new ConfigError('ruleset().extends: a ruleset extends one base');
75
- return rulesetOf({ ...state, base });
76
- },
77
- });
78
- export const ruleset = () => rulesetOf({ entries: [] });