@starci/eslint-grammar-core 0.22.0 → 0.23.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 (69) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/lib/app-shell-create.js +2 -2
  3. package/package.json +4 -2
  4. package/runtime/bundle.json +2 -68
  5. package/runtime/engine/by-code-unit.mjs +0 -12
  6. package/runtime/engine/config.mjs +0 -461
  7. package/runtime/engine/invalid-config.mjs +0 -15
  8. package/runtime/engine/model-config.mjs +0 -112
  9. package/runtime/engine/orca-config.mjs +0 -34
  10. package/runtime/engine/plain-object.mjs +0 -5
  11. package/runtime/engine/release-config.mjs +0 -32
  12. package/runtime/engine/removed-vocabulary.mjs +0 -27
  13. package/runtime/engine/resources-config.mjs +0 -59
  14. package/runtime/engine/runtime-root.mjs +0 -138
  15. package/runtime/engine/secrets.mjs +0 -202
  16. package/runtime/engine/sonar-config.mjs +0 -24
  17. package/runtime/engine/yaml.mjs +0 -161
  18. package/runtime/knowledge/grammars/core/playbook.yaml +0 -1198
  19. package/runtime/knowledge/grammars/index.yaml +0 -114
  20. package/runtime/knowledge/hfs/canon-pins.yaml +0 -720
  21. package/runtime/knowledge/hfs/rules.yaml +0 -6760
  22. package/runtime/knowledge/hfs/slots.yaml +0 -2783
  23. package/runtime/knowledge/ui/presentation/font.yaml +0 -101
  24. package/runtime/knowledge/ui/presentation/padding.yaml +0 -217
  25. package/runtime/modules/kernel/removed-vocabulary.yaml +0 -458
  26. package/runtime/modules/models/registry.yaml +0 -221
  27. package/runtime/modules/models/runtimes.yaml +0 -556
  28. package/runtime/modules/models/tiers.yaml +0 -66
  29. package/runtime/scripts/hfs/allows.mjs +0 -77
  30. package/runtime/scripts/hfs/architecture/component-tiers.mjs +0 -161
  31. package/runtime/scripts/hfs/architecture/config.mjs +0 -407
  32. package/runtime/scripts/hfs/architecture/root-packages.mjs +0 -78
  33. package/runtime/scripts/hfs/architecture/side-boundary.mjs +0 -13
  34. package/runtime/scripts/hfs/architecture/type-context.mjs +0 -335
  35. package/runtime/scripts/hfs/architecture/typescript.mjs +0 -477
  36. package/runtime/scripts/hfs/declaration-shape.mjs +0 -196
  37. package/runtime/scripts/hfs/declaration-slots.mjs +0 -89
  38. package/runtime/scripts/hfs/edition-slots.mjs +0 -80
  39. package/runtime/scripts/hfs/manifest-shape.mjs +0 -474
  40. package/runtime/scripts/hfs/param-names.mjs +0 -13
  41. package/runtime/scripts/hfs/rule-catalog.mjs +0 -458
  42. package/runtime/scripts/hfs/rule-params-shape.mjs +0 -103
  43. package/runtime/scripts/hfs/slot-app-view.mjs +0 -97
  44. package/runtime/scripts/hfs/slot-classify.mjs +0 -69
  45. package/runtime/scripts/hfs/slot-errors.mjs +0 -12
  46. package/runtime/scripts/hfs/slot-imports.mjs +0 -98
  47. package/runtime/scripts/hfs/slot-manifest-shape.mjs +0 -111
  48. package/runtime/scripts/hfs/slot-match.mjs +0 -164
  49. package/runtime/scripts/hfs/slot-path.mjs +0 -6
  50. package/runtime/scripts/hfs/slot-required.mjs +0 -95
  51. package/runtime/scripts/hfs/slot-semantic-problems.mjs +0 -175
  52. package/runtime/scripts/hfs/slot-side-problems.mjs +0 -32
  53. package/runtime/scripts/hfs/slots.mjs +0 -306
  54. package/runtime/scripts/hfs/typescript-programs.mjs +0 -95
  55. package/runtime/scripts/hfs/view.mjs +0 -180
  56. package/runtime/scripts/lib/glob.mjs +0 -32
  57. package/runtime/scripts/lib/grammar-lint.mjs +0 -57
  58. package/runtime/scripts/lib/i18n.mjs +0 -82
  59. package/runtime/scripts/lib/json-clone.mjs +0 -70
  60. package/runtime/scripts/lib/json.mjs +0 -44
  61. package/runtime/scripts/lib/list.mjs +0 -26
  62. package/runtime/scripts/lib/path-key.mjs +0 -124
  63. package/runtime/scripts/lib/read-text.mjs +0 -47
  64. package/runtime/scripts/lib/regex.mjs +0 -3
  65. package/runtime/scripts/lib/source-phrases.mjs +0 -34
  66. package/runtime/scripts/lib/ts-analysis.mjs +0 -39
  67. package/runtime/scripts/lib/ts-ast.mjs +0 -63
  68. package/runtime/scripts/lib/walk.mjs +0 -45
  69. package/runtime/scripts/lib/yaml-cached.mjs +0 -14
@@ -1,77 +0,0 @@
1
- import path from 'node:path';
2
- import { braceVariants, globExpression } from '../lib/glob.mjs';
3
- import { declaredLogicOf } from './manifest-shape.mjs';
4
- /**
5
- * What a slot's `requires`, `allows` and `forbids` entries (knowledge/hfs/slots.yaml) say about a file, read through the
6
- * resolver of scripts/hfs/slots.mjs. The machine checks that judge "this folder holds only what its slot allows"
7
- * (feature-shape, fe-slot-allows) and the front-end lint rules (through `hfs.allows(file)` of scripts/hfs/view.mjs) read it here so no check keeps a path list.
8
- *
9
- * An entry is a name relative to the slot instance root: `<var>` is the instance's bound variable when the slot binds it
10
- * (`<feature>`, `<capability>`) and one path segment of any text otherwise (`<action>`), `*` and `?` stay inside a segment,
11
- * `{a,b}` alternates, a trailing `/` names a directory and everything below it. A slot also admits, unlisted, the unit spec beside each
12
- * measured file it names (isMeasuredSpec): a file it declares in `logic`, or a named file of a logic role.
13
- */
14
- const VAR = /<([A-Za-z][A-Za-z0-9-]*)>/g;
15
- const SPEC = /\.spec\.ts$/;
16
- /**
17
- * Whether `relative` is the unit spec `<stem>.spec.ts` of a measured file beside it that the slot names: a file the slot declares in
18
- * `logic`, or a `requires`/`allows` file of a logic role (ruleParams.be.logicRoles), in a slot whose coverage is required and whose tests
19
- * are unit-beside. The slot admits that spec without listing it, as unit-test-colocated (R47) accepts it.
20
- */
21
- function isMeasuredSpec(resolver, classified, slot, relative, named) {
22
- if (!SPEC.test(relative) || slot.coverage !== 'required' || slot.tests !== 'unit-beside')
23
- return false;
24
- const subject = relative.replace(SPEC, '.ts');
25
- if (declaredLogicOf(slot).includes(subject))
26
- return true;
27
- const role = /\.([a-z0-9-]+)\.ts$/.exec(subject)?.[1];
28
- // An app resolver keeps no rule parameters of its own: a path on a side reads that side's.
29
- const params = classified.side ? resolver.sides?.[classified.side]?.ruleParams() : resolver.ruleParams?.();
30
- return (params?.logicRoles ?? []).includes(role) && named.some((matcher) => matcher.expression.test(subject));
31
- }
32
- function matchersOf(entries, bindings) {
33
- return (entries ?? []).flatMap((entry) => {
34
- const directory = entry.endsWith('/');
35
- const body = directory ? entry.slice(0, -1) : entry;
36
- const filled = body.replace(VAR, (_whole, name) => bindings[name] ?? '*');
37
- return braceVariants(filled).map((variant) => ({ entry, directory, expression: globExpression(directory ? `${variant}/**` : variant) }));
38
- });
39
- }
40
- /** The path of `file` below the instance root of the slot that owns it. */
41
- export function relativeToRoot(file, root) {
42
- return root && file.startsWith(`${root}/`) ? file.slice(root.length + 1) : path.posix.basename(file);
43
- }
44
- /**
45
- * Whether the slot that owns `file` names it in `requires` or `allows` (and does not forbid it); null when no enabled slot
46
- * owns it. Unlike allowsFile it judges a slot that lists only `requires` too, so a folder closed by its slot (an app's
47
- * src/) is read from the slot and never from a check's own list.
48
- */
49
- export function slotAdmitsFile(resolver, file) {
50
- const classified = resolver.classifyPath(file);
51
- if (classified.status === 'no-slot' || classified.status === 'ambiguous' || !classified.slot)
52
- return null;
53
- const slot = resolver.slot(classified.slot);
54
- const relative = relativeToRoot(classified.path, classified.root);
55
- const named = matchersOf([...(slot.requires ?? []), ...(slot.allows ?? [])], classified.bindings);
56
- const hit = named.some(matcher => matcher.expression.test(relative)) || isMeasuredSpec(resolver, classified, slot, relative, named);
57
- const forbidden = matchersOf(slot.forbids, classified.bindings).some(matcher => matcher.expression.test(relative) || matcher.expression.test(`${relative}/`));
58
- return hit && !forbidden;
59
- }
60
- /**
61
- * {slot, root, relative, allowed, entry?, forbiddenBy?} for a repository-relative file, or null when no enabled slot owns
62
- * it or the slot names no `allows`. `allowed` is true when the relative path matches a `requires` or `allows` entry.
63
- */
64
- export function allowsFile(resolver, file) {
65
- const classified = resolver.classifyPath(file);
66
- if (classified.status === 'no-slot' || classified.status === 'ambiguous' || !classified.slot)
67
- return null;
68
- const slot = resolver.slot(classified.slot);
69
- if (!slot?.allows?.length)
70
- return null;
71
- const relative = relativeToRoot(classified.path, classified.root);
72
- const named = matchersOf([...(slot.requires ?? []), ...slot.allows], classified.bindings);
73
- const hit = named.find(matcher => matcher.expression.test(relative));
74
- const spec = !hit && isMeasuredSpec(resolver, classified, slot, relative, named);
75
- const forbidden = matchersOf(slot.forbids, classified.bindings).find(matcher => matcher.expression.test(relative) || matcher.expression.test(`${relative}/`));
76
- return { slot: slot.id, root: classified.root, relative, allowed: (Boolean(hit) || spec) && !forbidden, entry: hit?.entry, forbiddenBy: forbidden?.entry, allows: slot.allows };
77
- }
@@ -1,161 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { byCodeUnit } from '../../lib/list.mjs';
4
- /**
5
- * The component tier ladder, checked on the source of a component library and of a component tree.
6
- *
7
- * FE_GRAMMAR_TIER_DIRECTION a grammar component imports a tier above it (the ladder leaf, branch, composite, frame: a tier imports
8
- * nothing above itself), type-only imports included, through a shared untiered module as well;
9
- * `tiers.grammar` of knowledge/hfs/slots.yaml is the matrix
10
- * FE_GRAMMAR_TIER_STAMP a `data-tier` stamp names a tier other than the folder the file sits in (`atom`, `primitive` and
11
- * `composition` are not tiers)
12
- * FE_TIER_DIRECTION (layers) a component imports a layer at or above its own: blocks, frames, composites, branches, leaves
13
- *
14
- * A library is a folder holding `src/core/<tier>/<Name>/`; a tree is a folder holding `components/<layer>/<Unit>/` that no hfs
15
- * front-end slot already judges (an app without hfs.json, such as the harness desktop app).
16
- */
17
- export const COMPONENT_TIER_RULE_IDS = ['FE_GRAMMAR_TIER_DIRECTION', 'FE_GRAMMAR_TIER_STAMP'];
18
- const SKIPPED = new Set(['node_modules', '.git', 'dist', '.next', 'storybook-static', 'proof']);
19
- const SOURCE = /\.(?:ts|tsx)$/u;
20
- const TEST_OR_STORY = /\.(?:stories|spec|test)\.[jt]sx?$/u;
21
- const IMPORT = /(?:\bimport|\bexport)\b[^'"`;]*?\bfrom\s*['"]([^'"]+)['"]|\bimport\s*['"]([^'"]+)['"]|\bimport\(\s*['"]([^'"]+)['"]\s*\)/gu;
22
- const STAMP = /["']?data-tier["']?\s*[=:]\s*\{?\s*["']([a-z-]+)["']/gu;
23
- const LIBRARY_FILE = /^(.*?)src\/core\/(leaf|branch|composite|frame)\/([^/]+)\//u;
24
- function walk(root, dir = '') {
25
- const out = [];
26
- for (const entry of fs.readdirSync(path.join(root, dir), { withFileTypes: true })) {
27
- if (SKIPPED.has(entry.name))
28
- continue;
29
- const rel = dir === '' ? entry.name : `${dir}/${entry.name}`;
30
- if (entry.isDirectory())
31
- out.push(...walk(root, rel));
32
- else if (SOURCE.test(entry.name) && !entry.name.endsWith('.d.ts') && !TEST_OR_STORY.test(entry.name))
33
- out.push(rel);
34
- }
35
- return out;
36
- }
37
- const lineOf = (text, index) => text.slice(0, index).split('\n').length;
38
- /** The file an import specifier names, as a repo-relative path in `files`, or null (a package, or a file outside the walk). */
39
- function resolveImport(files, from, specifier) {
40
- if (!specifier.startsWith('.'))
41
- return null;
42
- const base = path.posix.normalize(path.posix.join(path.posix.dirname(from), specifier)).replace(/\.(?:js|mjs|cjs)$/u, '');
43
- for (const candidate of [`${base}.ts`, `${base}.tsx`, `${base}/index.ts`, `${base}/index.tsx`, base])
44
- if (files.has(candidate))
45
- return candidate;
46
- return null;
47
- }
48
- function edgesOf(root, files, cache, file) {
49
- const cached = cache.get(file);
50
- if (cached)
51
- return cached;
52
- const text = fs.readFileSync(path.join(root, ...file.split('/')), 'utf8');
53
- const edges = [];
54
- for (const match of text.matchAll(IMPORT)) {
55
- const specifier = match[1] ?? match[2] ?? match[3] ?? '';
56
- const to = resolveImport(files, file, specifier);
57
- if (to !== null)
58
- edges.push({ to, line: lineOf(text, match.index ?? 0), specifier });
59
- }
60
- const entry = { text, edges };
61
- cache.set(file, entry);
62
- return entry;
63
- }
64
- /** The tier (the folder under `src/core`) and the component of a grammar source file, or null for a file outside the ladder. */
65
- const gradeOf = (file) => {
66
- const match = LIBRARY_FILE.exec(file);
67
- return match === null ? null : { tier: match[2], unit: `${match[1]}${match[2]}/${match[3]}` };
68
- };
69
- /**
70
- * Check the component libraries under `root` against `matrix` (`tiers.grammar`). Not applicable when no folder holds
71
- * `src/core/<tier>/<Name>/`. A file outside the tier folders (a shared helper under `src/core`) is not a tier, but an import that
72
- * reaches a higher tier through it is the importing tier's edge.
73
- */
74
- export function checkGrammarLibraries({ root, matrix }) {
75
- const all = walk(root).filter(file => /(?:^|\/)src\//u.test(file));
76
- const library = all.filter(file => gradeOf(file) !== null);
77
- if (!library.length)
78
- return { violations: [], coverage: { status: 'not-applicable' } };
79
- const files = new Set(all);
80
- const cache = new Map();
81
- const violations = [];
82
- const tiers = new Set(Object.keys(matrix));
83
- let edgesChecked = 0;
84
- let stamps = 0;
85
- for (const file of library.sort(byCodeUnit)) {
86
- const from = gradeOf(file);
87
- const { text, edges } = edgesOf(root, files, cache, file);
88
- for (const stamp of text.matchAll(STAMP)) {
89
- stamps += 1;
90
- if (stamp[1] !== from.tier) {
91
- violations.push({ ruleId: 'FE_GRAMMAR_TIER_STAMP', path: file, line: lineOf(text, stamp.index ?? 0), column: 1,
92
- message: `${file} stamps data-tier="${stamp[1]}" and sits in the ${from.tier} folder: the stamp is the folder (${[...tiers].join(', ')}).` });
93
- }
94
- }
95
- // Follow shared untiered modules, so a leaf cannot reach a frame by one hop of indirection.
96
- const queue = edges.map(edge => ({ edge, via: [] }));
97
- const seen = new Set();
98
- for (let next = queue.shift(); next !== undefined; next = queue.shift()) {
99
- const { edge, via } = next;
100
- const target = gradeOf(edge.to);
101
- if (target === null) {
102
- if (seen.has(edge.to) || !edge.to.includes('/src/') && !edge.to.startsWith('src/'))
103
- continue;
104
- seen.add(edge.to);
105
- for (const onward of edgesOf(root, files, cache, edge.to).edges)
106
- queue.push({ edge: { ...onward, line: edge.line }, via: [...via, edge.to] });
107
- continue;
108
- }
109
- if (target.unit === from.unit)
110
- continue;
111
- edgesChecked += 1;
112
- if ((matrix[from.tier]?.mayImport ?? []).includes(target.tier))
113
- continue;
114
- violations.push({ ruleId: 'FE_GRAMMAR_TIER_DIRECTION', path: file, line: edge.line, column: 1, specifier: edge.specifier, resolvedPath: edge.to,
115
- message: `${file} (${from.tier}) imports ${edge.to} (${target.tier})${via.length ? ` through ${via.join(' -> ')}` : ''}: a ${from.tier} may import only ${(matrix[from.tier]?.mayImport ?? []).join(', ') || 'nothing'}. Type-only imports count.` });
116
- }
117
- }
118
- const unique = new Map(violations.map(violation => [`${violation.ruleId}|${violation.path}|${violation.line}|${violation.resolvedPath ?? ''}`, violation]));
119
- return { violations: [...unique.values()], coverage: { status: 'checked', files: library.length, edgesChecked, stamps } };
120
- }
121
- const LAYER_FILE = /^(.*?)components\/([^/]+)\/([^/]+)\//u;
122
- /**
123
- * Check a component tree under `root` that no hfs slot judges: a component imports only the layers after its own (`layers` in order,
124
- * the first layer imports all below it). The layers are the folder names of slot fe.components.
125
- */
126
- export function checkComponentLayers({ root, layers }) {
127
- const all = walk(root).filter(file => /(?:^|\/)src\//u.test(file));
128
- const placed = (file) => {
129
- const match = LAYER_FILE.exec(file);
130
- const layer = match === null ? -1 : layers.indexOf(match[2]);
131
- return match === null || layer < 0 ? null : { layer, unit: `${match[1]}components/${match[2]}/${match[3]}` };
132
- };
133
- const tree = all.filter(file => placed(file) !== null);
134
- if (!tree.length)
135
- return { violations: [], coverage: { status: 'not-applicable' } };
136
- const files = new Set(all);
137
- const cache = new Map();
138
- const violations = [];
139
- let edgesChecked = 0;
140
- for (const file of tree.sort(byCodeUnit)) {
141
- const from = placed(file);
142
- for (const edge of edgesOf(root, files, cache, file).edges) {
143
- const target = placed(edge.to);
144
- if (target === null || target.unit === from.unit)
145
- continue;
146
- edgesChecked += 1;
147
- if (target.layer > from.layer)
148
- continue;
149
- violations.push({ ruleId: 'FE_TIER_DIRECTION', path: file, line: edge.line, column: 1, specifier: edge.specifier, resolvedPath: edge.to,
150
- message: `${file}: a ${layers[from.layer]} component may import only the layers after it (${layers.slice(from.layer + 1).join(', ') || 'none'}); it imports a ${layers[target.layer]}. Type-only imports count.` });
151
- }
152
- }
153
- return { violations, coverage: { status: 'checked', files: tree.length, edgesChecked } };
154
- }
155
- /** The machine check: the grammar libraries of the repository, judged by `tiers.grammar` of the slot manifest. */
156
- export function checkGrammarTiers({ config }) {
157
- const matrix = config.hfs.manifest.tiers.grammar;
158
- if (matrix === undefined)
159
- return { violations: [], coverage: { status: 'not-applicable' } };
160
- return checkGrammarLibraries({ root: config.root, matrix });
161
- }
@@ -1,407 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { slash } from '../../lib/path-key.mjs';
4
- import { readJsonFile as readJson } from '../../lib/json.mjs';
5
- import { isInside } from '../../lib/walk.mjs';
6
- import { createSlotResolver, openHfs, readRepoDeclaration } from '../slots.mjs';
7
- import { ROOT_PACKAGE_SLOTS, rootPackageRecord, rootWorkspaceDirectories } from './root-packages.mjs';
8
- import { byCodeUnit } from '../../lib/list.mjs';
9
- import { grammarContractFor } from '../../lib/grammar-lint.mjs';
10
- /** A file's identity: its resolved real path, or the resolved path when it does not exist. */
11
- function canonical(file) {
12
- const absolute = path.resolve(file);
13
- try {
14
- return path.resolve(fs.realpathSync(absolute));
15
- }
16
- catch {
17
- return absolute;
18
- }
19
- }
20
- function exactKeys(value, allowed, label) {
21
- if (!value || typeof value !== 'object' || Array.isArray(value))
22
- throw new Error(`${label} must be an object.`);
23
- const unknown = Object.keys(value).filter(key => !allowed.has(key));
24
- if (unknown.length) {
25
- unknown.sort(byCodeUnit);
26
- throw new Error(`${label} has unsupported fields: ${unknown.join(', ')}.`);
27
- }
28
- }
29
- /**
30
- * The git repository `root` sits in, found by walking up for a `.git` entry (a directory in a clone, a
31
- * file in a worktree), or null when there is none. It is the outer boundary a `file:` dependency may
32
- * resolve into: a checked project is routinely one package of a repository that also ships the packages
33
- * it consumes, and `--root` is the project, not the repository.
34
- */
35
- function enclosingRepository(root) {
36
- let cursor = path.resolve(root);
37
- for (;;) {
38
- if (fs.existsSync(path.join(cursor, '.git')))
39
- return cursor;
40
- const parent = path.dirname(cursor);
41
- if (parent === cursor)
42
- return null;
43
- cursor = parent;
44
- }
45
- }
46
- function existingPackageDirectory(absolute) {
47
- try {
48
- if (!fs.lstatSync(absolute).isDirectory())
49
- return false;
50
- const manifest = fs.lstatSync(path.join(absolute, 'package.json'));
51
- return manifest.isFile() && !manifest.isSymbolicLink();
52
- }
53
- catch {
54
- return false;
55
- }
56
- }
57
- function existingDirectory(root, relative) {
58
- try {
59
- return fs.lstatSync(path.join(root, relative)).isDirectory();
60
- }
61
- catch {
62
- return false;
63
- }
64
- }
65
- function existingRegularFile(root, relative) {
66
- try {
67
- const stat = fs.lstatSync(path.join(root, ...relative.split('/')));
68
- return stat.isFile() && !stat.isSymbolicLink();
69
- }
70
- catch {
71
- return false;
72
- }
73
- }
74
- function admitWorkspace(root, directories, queue, candidate, label = 'local package', strict = false) {
75
- const absolute = path.resolve(candidate);
76
- if (!isInside(root, absolute) || absolute === root || !existingDirectory(root, slash(path.relative(root, absolute)))) {
77
- if (strict)
78
- throw new Error(`${label} must resolve to a package directory inside the repository.`);
79
- return;
80
- }
81
- const manifest = path.join(absolute, 'package.json');
82
- try {
83
- if (!fs.lstatSync(manifest).isFile() || fs.lstatSync(manifest).isSymbolicLink()) {
84
- if (strict)
85
- throw new Error(`${label} must resolve to a regular package.json inside the repository.`);
86
- return;
87
- }
88
- }
89
- catch (error) {
90
- const message = error instanceof Error ? error.message : '';
91
- if (strict)
92
- throw new Error(message.startsWith(label) ? message : `${label} must resolve to a regular package.json inside the repository.`);
93
- return;
94
- }
95
- const relative = slash(path.relative(root, absolute));
96
- if (!directories.has(relative)) {
97
- directories.add(relative);
98
- queue.push(absolute);
99
- }
100
- }
101
- function expandSegment(base, segment) {
102
- if (segment !== '*')
103
- return [path.join(base, segment)];
104
- if (!fs.existsSync(base) || !fs.lstatSync(base).isDirectory())
105
- return [];
106
- return fs.readdirSync(base, { withFileTypes: true })
107
- .filter(item => item.isDirectory())
108
- .sort((a, b) => byCodeUnit(a.name, b.name))
109
- .map(item => path.join(base, item.name));
110
- }
111
- function workspaceCandidates(packageRoot, normalized) {
112
- const segments = normalized.split('/');
113
- if (path.isAbsolute(normalized) || segments.some(segment => segment === '..' || (segment.includes('*') && segment !== '*'))) {
114
- throw new Error(`Unsupported local workspace pattern: ${normalized}.`);
115
- }
116
- let candidates = [packageRoot];
117
- for (const segment of segments)
118
- candidates = candidates.flatMap(base => expandSegment(base, segment));
119
- return { candidates, wildcard: segments.includes('*') };
120
- }
121
- const admitFileDependency = (walk, section, name, value) => {
122
- const { root, appPackageRoot, packageRoot, sideRoot, repository, state } = walk;
123
- if (typeof value !== 'string' || !value.startsWith('file:'))
124
- return;
125
- const absolute = path.resolve(sideRoot ? appPackageRoot : packageRoot, value.slice('file:'.length));
126
- if (sideRoot && !isInside(root, absolute) && isInside(appPackageRoot, absolute))
127
- return;
128
- const label = `${section}.${name} file dependency`;
129
- if (isInside(root, absolute)) {
130
- admitWorkspace(root, state.directories, state.queue, absolute, label, true);
131
- return;
132
- }
133
- if (!repository || !isInside(repository, absolute) || !existingPackageDirectory(absolute)) {
134
- throw new Error(`${label} must resolve to a package directory inside the repository.`);
135
- }
136
- };
137
- function admitFileDependencies(walk, pkg) {
138
- for (const section of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {
139
- for (const [name, value] of Object.entries(pkg?.[section] ?? {}))
140
- admitFileDependency(walk, section, name, value);
141
- }
142
- }
143
- const admitPackageWorkspaces = (walk, pkg) => {
144
- const { root, packageRoot, sideRoot, side, state } = walk;
145
- const declared = pkg?.workspaces;
146
- const patterns = Array.isArray(declared) ? declared : declared?.packages;
147
- for (const pattern of Array.isArray(patterns) ? patterns : []) {
148
- if (typeof pattern !== 'string' || !pattern.trim())
149
- throw new Error('package.json workspace entries must be non-empty paths.');
150
- const written = slash(pattern.trim()).replace(/^\.\//, '');
151
- if (sideRoot && !written.startsWith(`${side}/`))
152
- continue;
153
- const normalized = sideRoot ? written.slice((side ?? '').length + 1) : written;
154
- const { candidates, wildcard } = workspaceCandidates(packageRoot, normalized);
155
- // npm expands a `*` segment to the directories that hold a package.json and skips the rest (an empty or untracked folder is
156
- // HFS_EMPTY_DIR / HFS_SLOT_UNDECLARED, never a reason to analyse nothing); a literal workspace path must resolve. A `*`
157
- // pattern may match nothing: every app declares the same workspaces (fe/apps/*, fe/packages/*, HFS_MONO_WORKSPACES) whether
158
- // or not it has a package yet, and the root patterns are held to that fixed list by the rule, not here.
159
- for (const candidate of candidates)
160
- admitWorkspace(root, state.directories, state.queue, candidate, `workspace ${normalized}`, !wildcard);
161
- }
162
- };
163
- /**
164
- * The npm workspaces below `root`. The one package.json of an app is at `packageRoot` (the app root; `root` is its side folder):
165
- * its workspace patterns under `<side>/` are this side's, read relative to the side folder, and every other pattern is the other
166
- * side's.
167
- */
168
- function workspaceDirectories(root, { packageRoot: appPackageRoot = root, side = null } = {}) {
169
- const directories = new Set();
170
- const queue = [root];
171
- const visited = new Set();
172
- const repository = enclosingRepository(root);
173
- while (queue.length) {
174
- const packageRoot = queue.shift(); // length checked by the loop condition
175
- if (visited.has(packageRoot))
176
- continue;
177
- visited.add(packageRoot);
178
- const sideRoot = side !== null && packageRoot === root;
179
- const pkg = readJson(path.join(sideRoot ? appPackageRoot : packageRoot, 'package.json'));
180
- const walk = { root, appPackageRoot, packageRoot, sideRoot, side, repository, state: { directories, queue } };
181
- admitPackageWorkspaces(walk, pkg);
182
- admitFileDependencies(walk, pkg);
183
- }
184
- return [...directories].sort(byCodeUnit);
185
- }
186
- /**
187
- * The workspace packages of the app root that no side owns: the `workspaces` patterns of the app's one package.json that do not start
188
- * with a side folder (`packages/*`), and the directories the slots `app.packages` and `app.module-registry` place under `packages/`
189
- * even when the manifest forgot to list them. A side imports them as first-party packages (through their entry points), never as
190
- * "outside the side". A side of the app is judged here; the app root itself already counts them among its workspaces.
191
- */
192
- function rootPackageRecords(root, packageRoot, side, opened) {
193
- if (side === null)
194
- return [];
195
- const candidates = new Set(rootWorkspaceDirectories(packageRoot));
196
- if (opened.manifest && existingDirectory(packageRoot, 'packages')) {
197
- const resolver = createSlotResolver(opened.manifest, readRepoDeclaration(opened.manifest, packageRoot));
198
- const container = path.join(packageRoot, 'packages');
199
- for (const entry of fs.readdirSync(container, { withFileTypes: true }).filter(item => item.isDirectory())) {
200
- const slot = resolver.classifyPath(`packages/${entry.name}`).slot;
201
- if (slot !== undefined && ROOT_PACKAGE_SLOTS.has(slot))
202
- candidates.add(path.join(container, entry.name));
203
- }
204
- }
205
- return [...candidates].sort(byCodeUnit).filter(candidate => !isInside(root, candidate))
206
- .flatMap(candidate => rootPackageRecord(packageRoot, candidate, canonical) ?? []);
207
- }
208
- function discoveredProjects(root, workspaces) {
209
- const projects = [];
210
- if (fs.existsSync(path.join(root, 'tsconfig.json')))
211
- projects.push('tsconfig.json');
212
- for (const workspace of workspaces) {
213
- for (const name of ['tsconfig.json', 'tsconfig.app.json', 'tsconfig.build.json']) {
214
- const candidate = `${workspace}/${name}`;
215
- if (fs.existsSync(path.join(root, ...candidate.split('/')))) {
216
- projects.push(candidate);
217
- break;
218
- }
219
- }
220
- }
221
- return [...new Set(projects)];
222
- }
223
- function inferredLayout(root, workspaces) {
224
- // HFS: frontend source roots live only under workspace packages (apps/<app>/, packages/<pkg>/);
225
- // the repository root itself is never a frontend source root.
226
- // The route, feature, component, hook and module roles are app slots (fe.route, fe.feature, fe.components, fe.hooks, fe.modules:
227
- // apps/<app>/src/...); a workspace package is tier `package` and holds none of them - its own src/hooks is package source, and a
228
- // grammar package's tier folders make it a component root below.
229
- const appWorkspaces = workspaces.filter(prefix => prefix.startsWith('apps/'));
230
- const collect = (suffix) => appWorkspaces.map(prefix => `${prefix}/${suffix}`).filter(relative => existingDirectory(root, relative));
231
- // A design-system workspace whose src carries tier dirs (leaves/branches/…) IS a component root;
232
- // collecting its src/components too would nest two roots in one role and fail the disjoint check.
233
- const tierSources = new Set(workspaces.map(prefix => `${prefix}/src`)
234
- .filter(source => ['leaves', 'branches', 'blocks', 'frames', 'overlays', 'composites', 'layouts', 'product-shells', 'pages']
235
- .some(tier => existingDirectory(root, `${source}/${tier}`))));
236
- const components = collect('src/components')
237
- .filter(relative => !tierSources.has(path.posix.dirname(relative)));
238
- components.push(...tierSources);
239
- return {
240
- routes: collect('src/app'),
241
- features: collect('src/features'),
242
- components: [...new Set(components)],
243
- hooks: collect('src/hooks'),
244
- // src/redux/ (fe.redux) is a modules-tier owner beside src/modules/ (owner ruling 2026-10-13, fe-stack state-global).
245
- modules: [...collect('src/modules'), ...collect('src/redux')],
246
- transport: collect('src/modules/api'),
247
- };
248
- }
249
- function assertFrontendRolesDisjoint(root, frontend) {
250
- const roles = ['routes', 'features', 'components', 'hooks', 'modules'];
251
- const entries = roles.flatMap(role => frontend[role].map(relative => ({
252
- role,
253
- relative,
254
- absolute: path.join(root, ...relative.split('/')),
255
- })));
256
- for (let index = 0; index < entries.length; index += 1)
257
- for (let other = index + 1; other < entries.length; other += 1) {
258
- const left = entries[index];
259
- const right = entries[other];
260
- if (!left || !right)
261
- continue;
262
- if (isInside(left.absolute, right.absolute) || isInside(right.absolute, left.absolute)) {
263
- throw new Error(`Architecture frontend role roots must be disjoint; ${left.role} ${left.relative} overlaps ${right.role} ${right.relative}.`);
264
- }
265
- }
266
- }
267
- const SKIPPED_DIRECTORIES = new Set(['node_modules', '.git', 'dist', '.next', '.turbo', 'coverage', 'test-results', '.starciwork', '.starcistacks']);
268
- function directoriesUnder(root, relative, depth) {
269
- const out = [];
270
- const visit = (dir, left) => {
271
- let entries;
272
- try {
273
- entries = fs.readdirSync(path.join(root, ...dir.split('/').filter(Boolean)), { withFileTypes: true });
274
- }
275
- catch {
276
- return;
277
- }
278
- for (const entry of entries) {
279
- if (!entry.isDirectory() || SKIPPED_DIRECTORIES.has(entry.name))
280
- continue;
281
- const child = dir ? `${dir}/${entry.name}` : entry.name;
282
- out.push(child);
283
- if (left > 1)
284
- visit(child, left - 1);
285
- }
286
- };
287
- visit(relative, depth);
288
- return out;
289
- }
290
- /** The owner entry a slot instance exposes: index.ts/index.tsx, a package's src/index.ts, an app's app.module.ts. */
291
- function ownerEntry(root, ownerRoot, tier) {
292
- let candidates;
293
- if (tier === 'package')
294
- candidates = ['src/index.ts', 'src/index.tsx', 'index.ts', 'index.tsx'];
295
- else if (tier === 'app')
296
- candidates = ['app.module.ts'];
297
- else
298
- candidates = ['index.ts', 'index.tsx'];
299
- for (const candidate of candidates) {
300
- const relative = `${ownerRoot}/${candidate}`;
301
- if (existingRegularFile(root, relative))
302
- return relative;
303
- }
304
- return null;
305
- }
306
- /**
307
- * Owners are derived from the slot manifest: every directory that an `owner: true` slot matches, with its entry file.
308
- * An instance with no entry file is not listed: the required-files check reports the missing entry.
309
- */
310
- function derivedOwners(root, resolver) {
311
- const seen = new Map();
312
- for (const directory of directoriesUnder(root, '', 6)) {
313
- const owner = resolver.ownerOf(directory);
314
- if (!owner || owner.root !== directory || seen.has(owner.root))
315
- continue;
316
- const slot = resolver.slot(owner.slot);
317
- if (!slot)
318
- continue;
319
- const entry = ownerEntry(root, owner.root, slot.tier);
320
- if (entry)
321
- seen.set(owner.root, { id: `${owner.slot}:${owner.root}`, root: owner.root, entry, slot: owner.slot, tier: slot.tier });
322
- }
323
- return [...seen.values()].sort((a, b) => a.root.localeCompare(b.root));
324
- }
325
- const DECLARED_HANDLER_DECORATORS = ['CommandHandler', 'QueryHandler'];
326
- /**
327
- * The selected family's component contract with derived consumers: every app's globals.css is a style
328
- * source, every app and every workspace package that depends on its package is a consumer. null when no app has
329
- * a globals.css to judge (the contract is then reported unavailable, never passed).
330
- */
331
- function derivedGrammar(root, packageRoot, workspaces, apps, family) {
332
- const styleSources = apps.map(app => `apps/${app.name}/src/app/globals.css`).filter(relative => existingRegularFile(root, relative));
333
- if (!styleSources.length)
334
- return null;
335
- const contract = grammarContractFor(family);
336
- // Every fe app and package is an npm workspace that declares what it imports (HFS_MONO_WORKSPACE_DEP): each workspace that
337
- // declares the Grammar package is a consumer, and so is the app root's manifest when it does.
338
- const declaresGrammar = (pkg) => Boolean(pkg && [pkg.dependencies, pkg.peerDependencies, pkg.devDependencies].some(section => section && Object.hasOwn(section, contract.package)));
339
- const appManifest = slash(path.relative(root, path.join(packageRoot, 'package.json')));
340
- const consumerManifests = declaresGrammar(readJson(path.join(packageRoot, 'package.json'))) ? [appManifest] : [];
341
- for (const workspace of workspaces) {
342
- if (!workspace.startsWith('packages/') && !workspace.startsWith('apps/'))
343
- continue;
344
- const manifest = `${workspace}/package.json`;
345
- const pkg = readJson(path.join(root, ...manifest.split('/')));
346
- if (declaresGrammar(pkg))
347
- consumerManifests.push(manifest);
348
- }
349
- if (!consumerManifests.length)
350
- return null;
351
- return { ...contract, styleSources, consumerManifests };
352
- }
353
- /**
354
- * Resolve the layout contract from hfs.json and the slot manifest (knowledge/hfs/slots.yaml). A repository carries only hfs.json. Owners, roots and the tier of every path come from slots; the contract
355
- * has no ignore, waiver or baseline field.
356
- */
357
- export function loadArchitectureConfig(repositoryRoot, { hfs } = {}) {
358
- const root = fs.realpathSync(path.resolve(repositoryRoot));
359
- if (!fs.lstatSync(root).isDirectory())
360
- throw new Error('Repository root must be a directory.');
361
- const opened = hfs ?? openHfs({ repoRoot: root });
362
- const { profile, apps } = opened.repo;
363
- // A side of an app (the side folder is the root the machine judges) keeps its dependencies in the app root's one package.json.
364
- const side = opened.repo.side ?? null;
365
- const packageRoot = side === null ? root : path.dirname(root);
366
- const workspaces = workspaceDirectories(root, { packageRoot, side });
367
- const appDirs = apps.map(app => `apps/${app.name}`);
368
- const inferred = inferredLayout(root, [...new Set([...workspaces, ...appDirs])].sort(byCodeUnit));
369
- const kinds = [profile === 'be' ? 'backend' : 'frontend'];
370
- const projects = discoveredProjects(root, [...new Set([...workspaces, ...appDirs])].sort(byCodeUnit));
371
- if (!projects.length)
372
- throw new Error('The repository has no tsconfig.json to derive a TypeScript project from.');
373
- const backend = {
374
- modules: ['src/modules'],
375
- // The layered feature root is the api kind (src/features/api/<feature>/: application/ and transport/<protocol>/); the cli
376
- // feature root (src/features/cli/) has its own shape, held by its slot and the cli rules.
377
- features: ['src/features/api'],
378
- apps: ['apps'],
379
- moduleRegistration: { providerIdentity: 'exported-class-token', handlerDecorators: [...DECLARED_HANDLER_DECORATORS] },
380
- };
381
- const frontend = {
382
- routes: inferred.routes,
383
- features: inferred.features,
384
- components: inferred.components,
385
- hooks: inferred.hooks,
386
- modules: inferred.modules,
387
- transport: inferred.transport,
388
- grammar: profile === 'fe' ? derivedGrammar(root, packageRoot, workspaces, apps, opened.repo.grammar) : null,
389
- };
390
- if (profile === 'fe')
391
- assertFrontendRolesDisjoint(root, frontend);
392
- return {
393
- root,
394
- packageRoot,
395
- repository: enclosingRepository(root),
396
- kinds,
397
- projects,
398
- workspaces,
399
- rootPackages: rootPackageRecords(root, packageRoot, side, opened),
400
- apps: apps.map(app => ({ name: app.name, kind: app.kind })),
401
- hfs: opened,
402
- owners: derivedOwners(root, opened),
403
- backend,
404
- frontend,
405
- };
406
- }
407
- export { canonical, exactKeys, isInside, slash };