@yearofthedan/warp 0.2.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 (54) hide show
  1. package/README.md +24 -25
  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.d.ts +3 -1
  6. package/dist/app/check.js +5 -3
  7. package/dist/app/checkModel.js +1 -1
  8. package/dist/app/configLines.d.ts +5 -0
  9. package/dist/app/configLines.js +24 -0
  10. package/dist/app/load.d.ts +2 -2
  11. package/dist/app/load.js +31 -43
  12. package/dist/builtins/advice.d.ts +8 -0
  13. package/dist/builtins/advice.js +42 -0
  14. package/dist/builtins/dependency-direction/dependencyDirection.js +33 -16
  15. package/dist/builtins/index.js +2 -0
  16. package/dist/builtins/module-externals/moduleExternals.js +11 -9
  17. package/dist/builtins/no-cross-module-reexport/noCrossModuleReexport.js +16 -5
  18. package/dist/builtins/place.js +5 -3
  19. package/dist/builtins/unresolved-import/unresolvedImport.d.ts +2 -0
  20. package/dist/builtins/unresolved-import/unresolvedImport.js +15 -0
  21. package/dist/builtins/unused-declaration/declarations.js +1 -1
  22. package/dist/builtins/unused-declaration/empty.js +19 -11
  23. package/dist/builtins/unused-declaration/grants.js +22 -15
  24. package/dist/builtins/unused-declaration/surfaces.js +24 -22
  25. package/dist/cli.js +14 -11
  26. package/dist/config/loadConfig.d.ts +7 -1
  27. package/dist/config/loadConfig.js +83 -12
  28. package/dist/index.d.ts +0 -1
  29. package/dist/index.js +0 -1
  30. package/dist/model/archetype/data.d.ts +25 -29
  31. package/dist/model/archetype/data.js +1 -1
  32. package/dist/model/archetype/fixes.d.ts +35 -0
  33. package/dist/model/archetype/fixes.js +265 -0
  34. package/dist/model/archetype/language.d.ts +16 -0
  35. package/dist/model/archetype/language.js +419 -0
  36. package/dist/model/archetype/reach.d.ts +8 -3
  37. package/dist/model/archetype/reach.js +142 -122
  38. package/dist/model/archetype/references.d.ts +11 -5
  39. package/dist/model/archetype/references.js +58 -132
  40. package/dist/model/archetype/requirements.d.ts +3 -3
  41. package/dist/model/archetype/requirements.js +65 -61
  42. package/dist/model/archetype/resolve.d.ts +3 -3
  43. package/dist/model/archetype/resolve.js +64 -77
  44. package/dist/model/archetype/rulesets.d.ts +2 -1
  45. package/dist/model/archetype/rulesets.js +72 -49
  46. package/dist/model/archetype/settings.js +4 -19
  47. package/dist/model/facts.d.ts +6 -0
  48. package/dist/reporters/model.js +9 -9
  49. package/dist/rules/registry.js +1 -1
  50. package/package.json +3 -2
  51. package/dist/model/archetype/builder.d.ts +0 -183
  52. package/dist/model/archetype/builder.js +0 -85
  53. package/dist/model/archetype/draft.d.ts +0 -37
  54. package/dist/model/archetype/draft.js +0 -275
@@ -6,6 +6,7 @@ export interface FileFacts {
6
6
  lines: number;
7
7
  imports: ImportEdge[];
8
8
  externals: ExternalImport[];
9
+ unresolved: UnresolvedImport[];
9
10
  members: MemberGraph;
10
11
  functions: FunctionFacts[];
11
12
  }
@@ -28,6 +29,11 @@ export interface ExternalImport {
28
29
  reExport?: true;
29
30
  line: number;
30
31
  }
32
+ export interface UnresolvedImport {
33
+ from: string;
34
+ specifier: string;
35
+ line: number;
36
+ }
31
37
  export type MemberKind = 'function' | 'class' | 'state' | 'type' | 'code';
32
38
  export interface Member {
33
39
  name: string;
@@ -14,10 +14,11 @@ export const modelText = (model, rules) => {
14
14
  visit(child, depth + 1);
15
15
  };
16
16
  visit(model.root, 0);
17
- const files = model.modules.reduce((sum, module) => sum + module.files.length, 0);
17
+ const total = (modules) => modules.reduce((sum, module) => sum + module.files.length, 0);
18
+ const files = total(model.modules.filter((module) => !module.test));
19
+ const tests = total(model.modules.filter((module) => module.test));
18
20
  const loose = model.modules.reduce((sum, module) => sum + module.looseFiles.length, 0);
19
- const tests = model.modules.reduce((sum, module) => sum + module.tests.length, 0);
20
- const tested = tests > 0 ? `, ${count(tests, 'test')}` : '';
21
+ const tested = tests > 0 ? `, ${count(tests, 'test file')}` : '';
21
22
  lines.push('', `${model.modules.length} modules, ${files} files${tested}, ${loose} loose.`);
22
23
  return lines.join('\n');
23
24
  };
@@ -34,27 +35,26 @@ const heading = (module) => {
34
35
  const owned = module.files.length - module.looseFiles.length;
35
36
  if (module.kind === 'files')
36
37
  return count(owned);
38
+ if (module.kind === 'test')
39
+ return count(owned, 'test file');
37
40
  const captures = Object.entries(module.captures)
38
41
  .map(([key, value]) => ` {${key}=${value}}`)
39
42
  .join('');
40
- const contents = [
41
- ...(owned > 0 ? [count(owned)] : []),
42
- ...(module.tests.length > 0 ? [count(module.tests.length, 'test')] : []),
43
- ];
44
- return `${module.name ?? 'root'}: ${module.archetype}${captures}${contents.map((part) => `, ${part}`).join('')}`;
43
+ const contents = owned > 0 ? `, ${count(owned, module.test ? 'test file' : 'file')}` : '';
44
+ return `${module.name ?? 'root'}: ${module.archetype}${captures}${contents}`;
45
45
  };
46
46
  export const modelJson = (model, rules) => JSON.stringify({
47
47
  modules: model.modules.map((module) => ({
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,
54
55
  children: module.children.map((child) => child.id),
55
56
  files: module.files,
56
57
  looseFiles: module.looseFiles,
57
- tests: module.tests,
58
58
  ...(rules ? { rules: rules.module(module) } : {}),
59
59
  })),
60
60
  }, null, 2);
@@ -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.2.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' = '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 'tests' ? 'tests names the test layer' : 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
- }
67
- export interface ContainsContext<R> {
68
- required: R;
69
- self: Self;
70
- }
71
- export type Identify = IdentifyData;
72
- export type ArchetypeBuilder<N extends string | undefined, C, H, R, E, P = unknown> = ArchetypeMethods<N, C, H, R, E, P> & {
73
- readonly modules: H;
74
- };
75
- export interface ArchetypeMethods<N extends string | undefined, C, H, R, E, P> extends Archetype<N, E, P, H> {
76
- identify(identify: Identify): ArchetypeBuilder<N, C, H, R, E, P>;
77
- requires<const R2 extends Record<string, AnyArchetype | Shape>>(requires: R2): ArchetypeBuilder<N, C, H, {
78
- readonly [K in keyof R2]: RequiredRef<R2[K]>;
79
- }, E, P>;
80
- contains<C2, H2>(modules: (m: Modules<{}, {}>, context: ContainsContext<R>) => Modules<C2, H2>): ArchetypeBuilder<N, C2, H2, R, E, P>;
81
- exposes<const E2 extends Surfaces>(exposes: (s: C) => E2): ArchetypeBuilder<N, C, H, R, E2, P>;
82
- exposes(exposes: Exposed): ArchetypeBuilder<N, C, H, R, {}, P>;
83
- entry(entry: Selector<'files'>): ArchetypeBuilder<N, C, H, R, {}, P>;
84
- provides(provides: (s: C) => Record<string, Reference>): ArchetypeBuilder<N, C, H, R, E, P>;
85
- description(description: string): ArchetypeBuilder<N, C, H, R, E, P>;
86
- tests(layer: Archetype<undefined, any, C, any>): ArchetypeBuilder<N, C, With<H, 'tests', ModuleHandle>, R, E, P>;
87
- tests(locator: Selector, layer?: Archetype<undefined, any, C, any>): ArchetypeBuilder<N, C, With<H, 'tests', ModuleHandle>, R, E, P>;
88
- using<P2 = any>(using: Using<P2>): ArchetypeBuilder<N, C, H, R, E, P2>;
89
- }
90
- export interface Ruleset {
91
- readonly [rulesetBrand]: true;
92
- rules(settings: RuleSettings): Ruleset;
93
- on(target: Archetype<string, any, any, any> | ModuleHandle, settings: RuleSettings): Ruleset;
94
- extends(base: Ruleset): Ruleset;
95
- }
96
- export interface WarpConfig {
97
- root: Archetype<string, any, any, any>;
98
- tsconfig?: string | readonly string[];
99
- tests?: Selector<'files'>;
100
- plugins?: Record<string, unknown>;
101
- rulesets?: Record<string, Ruleset>;
102
- }
103
- export type RecordedRef = {
104
- kind: 'module';
105
- module: string;
106
- surface?: string;
107
- } | {
108
- kind: 'required';
109
- name: string;
110
- surface?: string;
111
- } | {
112
- kind: 'package';
113
- pattern: string;
114
- };
115
- export interface RecordedSelector {
116
- kind: 'dir' | 'files';
117
- patterns: readonly unknown[];
118
- }
119
- export interface RecordedModule {
120
- name: unknown;
121
- selector: unknown;
122
- archetype?: unknown;
123
- extra: readonly unknown[];
124
- }
125
- export interface RecordedDefinition {
126
- name: unknown;
127
- identify?: unknown;
128
- requires: unknown;
129
- modules: unknown;
130
- exposes?: unknown;
131
- entry?: unknown;
132
- provides?: unknown;
133
- description?: unknown;
134
- tests?: {
135
- locator?: unknown;
136
- layer?: unknown;
137
- extra: readonly unknown[];
138
- };
139
- }
140
- export interface RecordedArchetype {
141
- definition: RecordedDefinition;
142
- using?: unknown;
143
- }
144
- export interface RecordedRuleset {
145
- base?: unknown;
146
- entries: readonly {
147
- target?: unknown;
148
- settings: unknown;
149
- }[];
150
- }
151
- interface Recorded {
152
- ref: RecordedRef;
153
- self: true;
154
- all: true;
155
- shape: 'dir' | 'files';
156
- selector: RecordedSelector;
157
- modules: readonly RecordedModule[];
158
- archetype: RecordedArchetype;
159
- handle: {
160
- archetype: unknown;
161
- module: unknown;
162
- };
163
- ruleset: RecordedRuleset;
164
- }
165
- export declare const recordedAs: <T extends keyof Recorded>(value: unknown, type: T) => Recorded[T] | undefined;
166
- export declare const moduleRefs: () => unknown;
167
- export declare const requiredRefs: () => unknown;
168
- export declare const self: Self;
169
- export declare const inlineName: (holder: string, module: string) => string;
170
- export declare function archetype(): ArchetypeBuilder<undefined, {}, {}, {}, {}>;
171
- export declare function archetype<const N extends string>(name: N): ArchetypeBuilder<N, {}, {}, {}, {}>;
172
- export declare const using: <P = any>(using: Using<P>) => ArchetypeBuilder<undefined, {}, {}, {}, {}, P>;
173
- export declare const exposes: (exposes: Exposed) => ArchetypeBuilder<undefined, {}, {}, {}, {}>;
174
- export declare const contains: <C2, H2>(modules: (m: Modules<{}, {}>, context: ContainsContext<{}>) => Modules<C2, H2>) => ArchetypeBuilder<undefined, C2, H2, {}, {}>;
175
- export declare const all: () => All;
176
- export declare function dir(): Shape;
177
- export declare function dir(...paths: [string, ...string[]]): Selector<'dir'>;
178
- export declare function files(): Shape;
179
- export declare function files(...patterns: [string, ...string[]]): Selector<'files'>;
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,85 +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
- });
20
- export const inlineName = (holder, module) => `${holder}.${module}`;
21
- const handles = (holder, entries, tests) => ({
22
- ...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
28
- ? {
29
- modules: handles(inlineName(String(holder), entry.name), anonymous.modules, anonymous.tests),
30
- }
31
- : {};
32
- return [entry.name, Object.freeze({ ...handle, ...nested })];
33
- })),
34
- ...(tests === undefined ? {} : { tests: Object.freeze(record('handle', { archetype: holder, module: 'tests' })) }),
35
- });
36
- const builder = (state) => {
37
- const { definition } = state;
38
- const define = (field) => (value) => builder({ ...state, definition: { ...definition, [field]: value } });
39
- return {
40
- modules: handles(definition.name, definition.modules, definition.tests),
41
- name: definition.name,
42
- ...record('archetype', state),
43
- identify: define('identify'),
44
- requires: define('requires'),
45
- contains: (contains) => define('modules')(recordedAs(contains(modules([]), { required: requiredRefs(), self }), 'modules')),
46
- exposes: define('exposes'),
47
- entry: define('entry'),
48
- provides: define('provides'),
49
- description: define('description'),
50
- tests: (first, ...rest) => {
51
- const located = recordedAs(first, 'selector') !== undefined;
52
- const [layer, ...extra] = located ? rest : [first, ...rest];
53
- return define('tests')({ ...(located ? { locator: first } : {}), layer, extra });
54
- },
55
- using: (using) => builder({ ...state, using }),
56
- };
57
- };
58
- const start = (name) => builder({ definition: { name, requires: {}, modules: [] } });
59
- export function archetype(name) {
60
- return start(name);
61
- }
62
- export const using = (using) => start(undefined).using(using);
63
- export const exposes = (exposes) => start(undefined).exposes(exposes);
64
- export const contains = (modules) => start(undefined).contains(modules);
65
- export const all = () => Object.freeze(record('all', true));
66
- const selector = (kind, patterns) => Object.freeze(patterns.length === 0 ? record('shape', kind) : record('selector', { kind, patterns }));
67
- export function dir(...paths) {
68
- return selector('dir', paths);
69
- }
70
- export function files(...patterns) {
71
- return selector('files', patterns);
72
- }
73
- export const pkg = (pattern) => ref({ kind: 'package', pattern });
74
- export const defineConfig = (config) => config;
75
- const rulesetOf = (state) => ({
76
- ...record('ruleset', state),
77
- rules: (settings) => rulesetOf({ ...state, entries: [...state.entries, { settings }] }),
78
- on: (target, settings) => rulesetOf({ ...state, entries: [...state.entries, { target, settings }] }),
79
- extends: (base) => {
80
- if (state.base !== undefined)
81
- throw new ConfigError('ruleset().extends: a ruleset extends one base');
82
- return rulesetOf({ ...state, base });
83
- },
84
- });
85
- export const ruleset = () => rulesetOf({ entries: [] });
@@ -1,37 +0,0 @@
1
- import { type RecordedDefinition } from './builder.ts';
2
- import type { ArchetypeData, LocatorData, ModuleData } from './data.ts';
3
- import { type Fail } from './shared.ts';
4
- export interface DraftTests {
5
- locator?: LocatorData;
6
- modules: DraftModule[];
7
- using: unknown[];
8
- exposes?: DraftExposes;
9
- }
10
- export interface DraftModule {
11
- data: ModuleData;
12
- using: unknown[];
13
- tests?: DraftTests;
14
- }
15
- export type DraftExposes = {
16
- kind: 'all';
17
- } | {
18
- kind: 'files';
19
- patterns: string[];
20
- entry?: true;
21
- } | {
22
- kind: 'surfaces';
23
- surfaces: Record<string, unknown[]>;
24
- };
25
- export interface Draft {
26
- data: ArchetypeData;
27
- modules: DraftModule[];
28
- exposes?: DraftExposes;
29
- provides: Record<string, unknown>;
30
- tests?: DraftTests;
31
- }
32
- export interface Collected extends RecordedDefinition {
33
- inline?: true;
34
- using?: unknown;
35
- }
36
- export declare const collect: (root: RecordedDefinition, fail: Fail) => Map<string, Collected>;
37
- export declare const draft: (name: string, state: Collected, fail: Fail) => Draft;
@@ -1,275 +0,0 @@
1
- import { inlineName, moduleRefs, requiredRefs, recordedAs, self, } from './builder.js';
2
- import { isName, isRecord } from './shared.js';
3
- export const collect = (root, fail) => {
4
- const byName = new Map();
5
- const pending = [root];
6
- for (let definition = pending.shift(); definition; definition = pending.shift()) {
7
- const known = byName.get(definition.name);
8
- if (!isName(definition.name))
9
- fail(`archetype(${JSON.stringify(definition.name)}): a name is a non-empty string`);
10
- else if (known && known !== definition)
11
- fail(`two archetypes are named ${definition.name}: give each its own name`);
12
- else if (!known) {
13
- byName.set(definition.name, definition);
14
- pending.push(...reached(definition));
15
- }
16
- }
17
- return byName;
18
- };
19
- const named = (value) => {
20
- const definition = recordedAs(value, 'archetype')?.definition;
21
- return definition && definition.name !== undefined ? [definition] : [];
22
- };
23
- const reached = (definition) => [
24
- ...entriesOf(definition.modules).flatMap((entry) => named(entry.archetype)),
25
- ...Object.values(isRecord(definition.requires) ? definition.requires : {}).flatMap(named),
26
- ...inlineArchetypes(definition),
27
- ];
28
- const anonymousOf = (entry) => {
29
- const definition = recordedAs(entry.archetype, 'archetype')?.definition;
30
- return definition?.name === undefined ? definition : undefined;
31
- };
32
- const inlineArchetypes = (holder) => isName(holder.name)
33
- ? entriesOf(holder.modules).flatMap((entry) => isInline(entry) && isName(entry.name)
34
- ? [
35
- {
36
- ...anonymousOf(entry),
37
- name: inlineName(holder.name, entry.name),
38
- inline: true,
39
- requires: holder.requires,
40
- modules: anonymousOf(entry)?.modules ?? [],
41
- description: undefined,
42
- },
43
- ]
44
- : [])
45
- : [];
46
- const isInline = (entry) => (entry.archetype === undefined || anonymousOf(entry) !== undefined) &&
47
- recordedAs(entry.selector, 'selector')?.kind === 'dir';
48
- const entriesOf = (modules) => (Array.isArray(modules) ? modules : []);
49
- const callback = (value) => (typeof value === 'function' ? value(moduleRefs()) : undefined);
50
- export const draft = (name, state, fail) => {
51
- checkFields(name, state, fail);
52
- const identify = identifyData(name, state.identify, fail);
53
- const requires = requirements(name, state.requires, fail);
54
- const modules = draftModules(name, state.modules, fail);
55
- const exposes = surfaceOf(name, state, fail);
56
- const provides = state.provides === undefined ? {} : callback(state.provides);
57
- if (!isRecord(provides))
58
- fail(`${name}.provides: expected a callback returning modules by name, (m) => ({ strings: m.strings })`);
59
- const tests = testsOf(name, state.tests, 'dir', fail);
60
- return {
61
- data: {
62
- name,
63
- ...(state.inline ? { inline: true } : {}),
64
- description: state.description,
65
- identify,
66
- requires,
67
- modules: modules.map((module) => module.data),
68
- provides: {},
69
- },
70
- modules,
71
- ...(exposes ? { exposes } : {}),
72
- provides: isRecord(provides) ? provides : {},
73
- ...(tests ? { tests } : {}),
74
- };
75
- };
76
- const testsOf = (where, value, kind, fail) => {
77
- if (value === undefined)
78
- return undefined;
79
- if (value.extra.length > 0)
80
- fail(`${where}.tests: takes a locator and an archetype, .tests(dir('e2e'), using([...]))`);
81
- const locator = value.locator === undefined ? undefined : selectorOf(`${where}.tests`, value.locator, fail);
82
- const recorded = value.layer === undefined ? undefined : recordedAs(value.layer, 'archetype');
83
- if (value.layer !== undefined && recorded?.definition.name !== undefined)
84
- fail(`${where}.tests: a test layer is an archetype of its own: contains(...), using(...) or exposes(...)`);
85
- const layer = recorded?.definition.name === undefined ? recorded?.definition : undefined;
86
- if (layer)
87
- checkLayer(`${where}.tests`, layer, fail);
88
- const modules = layer
89
- ? draftModules(`${where}.tests`, layer.modules, fail).map((module) => testModule(where, module, fail))
90
- : [];
91
- if (kind === 'files' && modules.length > 0)
92
- fail(`${where}.tests: a files module's tests hold no modules; give them to its folder's archetype`);
93
- if (kind === 'files' && !locator)
94
- fail(`${where}.tests: a files module names where its tests are, .tests(files('*.logic.test.ts'))`);
95
- const exposes = exposesOf(`${where}.tests.exposes`, layer?.exposes, true, fail);
96
- return {
97
- ...(locator ? { locator } : {}),
98
- modules,
99
- using: usingOf(`${where}.tests`, recorded?.using, fail),
100
- ...(exposes ? { exposes } : {}),
101
- };
102
- };
103
- const checkLayer = (where, layer, fail) => {
104
- for (const field of ['identify', 'provides', 'tests', 'entry'])
105
- if (layer[field] !== undefined)
106
- fail(`${where}.${field}: a test layer holds test modules, its using and what it exposes`);
107
- if (isRecord(layer.requires) && Object.keys(layer.requires).length > 0)
108
- fail(`${where}.requires: a test layer sees what its holder requires`);
109
- };
110
- const testModule = (where, module, fail) => {
111
- const at = `${where}.tests.${module.data.name}`;
112
- if (module.data.kind !== 'files')
113
- fail(`${at}: a test module is a files module, files('*.dsl.ts')`);
114
- if (module.using.length > 0)
115
- fail(`${at}: a test module sees what its layer sees; give the layer .using()`);
116
- const data = module.data;
117
- return { ...module, data: { ...data, exposes: data.exposes ?? { kind: 'all' } } };
118
- };
119
- const surfaceOf = (name, state, fail) => {
120
- if (state.entry === undefined)
121
- return exposesOf(`${name}.exposes`, state.exposes, true, fail);
122
- if (state.exposes !== undefined)
123
- fail(`${name}: an entry is the module's whole surface; give it .entry(...) or .exposes(...)`);
124
- const selector = recordedAs(state.entry, 'selector');
125
- if (selector?.kind === 'files' && selector.patterns.every(isName))
126
- return { kind: 'files', patterns: selector.patterns, entry: true };
127
- fail(`${name}.entry: expected the module's entry files, files('index.ts')`);
128
- return undefined;
129
- };
130
- const exposesOf = (where, value, surfaces, fail) => {
131
- if (value === undefined)
132
- return undefined;
133
- if (recordedAs(value, 'all'))
134
- return { kind: 'all' };
135
- const selector = recordedAs(value, 'selector');
136
- if (selector?.kind === 'files' && selector.patterns.every(isName))
137
- return { kind: 'files', patterns: selector.patterns };
138
- const returned = surfaces ? callback(value) : undefined;
139
- if (isRecord(returned))
140
- return {
141
- kind: 'surfaces',
142
- surfaces: Object.fromEntries(Object.entries(returned).map(([surface, refs]) => [surface, [refs].flat()])),
143
- };
144
- const shapes = surfaces ? `all(), files('a.ts', ...) or (m) => ({ render: m.dom })` : `all() or files('a.ts', ...)`;
145
- fail(`${where}: expected ${shapes}`);
146
- return undefined;
147
- };
148
- const checkFields = (name, state, fail) => {
149
- if (state.description !== undefined && typeof state.description !== 'string')
150
- fail(`${name}.description: expected a string`);
151
- if (!Array.isArray(state.modules))
152
- fail(`${name}.contains: expected the modules chain, (m) => m.module(...)`);
153
- };
154
- const draftModules = (archetype, recorded, fail) => {
155
- const modules = [];
156
- for (const entry of entriesOf(recorded)) {
157
- const module = draftModule(archetype, entry, fail);
158
- if (modules.some((other) => other.data.name === module.data.name))
159
- fail(`${archetype}: module '${module.data.name}' is already declared`);
160
- else
161
- modules.push(module);
162
- }
163
- return modules;
164
- };
165
- const draftModule = (archetype, entry, fail) => {
166
- const { name } = entry;
167
- if (!isName(name) || name.includes('.'))
168
- fail(`${archetype}: a module's name is a non-empty string without dots, not ${JSON.stringify(name)}`);
169
- const where = `${archetype}.${String(name)}`;
170
- if (name === 'tests')
171
- fail(`${where}: tests names a module's test layer; give the module another name`);
172
- const { kind, patterns } = selectorOf(where, entry.selector, fail);
173
- if (entry.extra.length > 0)
174
- fail(`${where}: .module() takes a name, a selector and an archetype`);
175
- const { named, anonymous, using } = archetypeOf(where, archetype, entry.archetype, fail);
176
- const description = anonymous?.description;
177
- const common = { name: name, using: [], ...(description === undefined ? {} : { description }) };
178
- if (anonymous)
179
- checkAnonymous(where, kind, anonymous, fail);
180
- if (kind === 'dir')
181
- return {
182
- data: { kind, ...common, paths: patterns, archetype: named ?? inlineName(archetype, name) },
183
- using,
184
- };
185
- if (named !== undefined)
186
- fail(`${where}: an archetype makes a folder module; use dir(...), not files(...)`);
187
- const exposes = exposesOf(`${where}.exposes`, anonymous?.exposes, false, fail);
188
- const tests = testsOf(where, anonymous?.tests, 'files', fail);
189
- return {
190
- data: { kind, ...common, patterns, ...(exposes ? { exposes } : {}) },
191
- using,
192
- ...(tests ? { tests } : {}),
193
- };
194
- };
195
- const archetypeOf = (where, holder, value, fail) => {
196
- if (value === undefined)
197
- return { using: [] };
198
- if (value === self)
199
- return { named: holder, using: [] };
200
- const recorded = recordedAs(value, 'archetype');
201
- if (!recorded) {
202
- fail(`${where}: expected an archetype, such as component, using(...) or exposes(all())`);
203
- return { using: [] };
204
- }
205
- const using = usingOf(where, recorded.using, fail);
206
- const { definition } = recorded;
207
- return definition.name === undefined ? { anonymous: definition, using } : { named: definition.name, using };
208
- };
209
- const checkAnonymous = (where, kind, definition, fail) => {
210
- if (definition.description !== undefined && typeof definition.description !== 'string')
211
- fail(`${where}.description: expected a string`);
212
- if (isRecord(definition.requires) && Object.keys(definition.requires).length > 0)
213
- fail(`${where}.requires: a module's own archetype sees what its holder requires; name the archetype to require more`);
214
- if (kind === 'dir')
215
- return;
216
- const hasModules = Array.isArray(definition.modules) && definition.modules.length > 0;
217
- const folderOnly = [
218
- ...(hasModules ? ['contains'] : []),
219
- ...['identify', 'provides', 'entry'].filter((field) => definition[field] !== undefined),
220
- ];
221
- for (const field of folderOnly)
222
- fail(`${where}.${field}: a files module has no modules; use dir(...) for ${field}`);
223
- };
224
- const selectorOf = (where, value, fail) => {
225
- const selector = recordedAs(value, 'selector');
226
- if (!selector) {
227
- fail(`${where}: expected a selector, files('*.ts') or dir('src/ui')`);
228
- return { kind: 'files', patterns: [] };
229
- }
230
- const patterns = selector.patterns;
231
- if (!patterns.every(isName))
232
- fail(`${where}: ${selector.kind}() takes non-empty strings`);
233
- if (selector.kind === 'dir')
234
- checkDirPaths(where, patterns, fail);
235
- return { kind: selector.kind, patterns };
236
- };
237
- const usingOf = (where, value, fail) => {
238
- const using = typeof value === 'function' ? value(moduleRefs(), { required: requiredRefs() }) : (value ?? []);
239
- if (Array.isArray(using))
240
- return using;
241
- fail(`${where}.using: expected a list of references, or a callback returning one`);
242
- return [];
243
- };
244
- const checkDirPaths = (where, paths, fail) => {
245
- for (const path of paths.filter((path) => isName(path) && !isDirPath(path)))
246
- fail(`${where}: a dir path is folder names and {placeholders}, a whole segment each, not '${String(path)}'`);
247
- };
248
- const isDirPath = (path) => path.split('/').every((segment) => segment !== '.' && segment !== '..' && /^(\{\w+\}|[^{}*]+)$/.test(segment));
249
- const requirements = (archetype, value, fail) => {
250
- if (!isRecord(value)) {
251
- fail(`${archetype}.requires: expected requirements by name, { testRunner, strings: dir() }`);
252
- return {};
253
- }
254
- const result = {};
255
- for (const [name, requirement] of Object.entries(value)) {
256
- const shape = recordedAs(requirement, 'shape');
257
- const required = recordedAs(requirement, 'archetype')?.definition.name;
258
- if (shape)
259
- result[name] = { kind: shape };
260
- else if (isName(required))
261
- result[name] = { kind: 'archetype', archetype: required };
262
- else
263
- fail(`${archetype}.requires.${name}: expected an archetype, dir() or files()`);
264
- }
265
- return result;
266
- };
267
- const identifyData = (archetype, value, fail) => {
268
- const keys = isRecord(value) ? Object.keys(value) : [];
269
- if (value === undefined || (keys.length === 1 && isName(value.marker)))
270
- return value;
271
- if (keys.length === 1 && typeof value.match === 'function')
272
- return value;
273
- fail(`${archetype}.identify: expected { marker: '{name}.dom.ts' } or { match: (dir, chain) => ... }`);
274
- return undefined;
275
- };