@sixbell-telco/sdk-tools 0.0.0-stage → 0.1.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 (58) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +277 -2
  3. package/data/security-floors.json +47 -0
  4. package/package.json +43 -4
  5. package/recipes/README.md +53 -0
  6. package/recipes/crud-list.md +21 -0
  7. package/recipes/custom-component.md +35 -0
  8. package/recipes/detail-page.md +19 -0
  9. package/recipes/form-dialog.md +17 -0
  10. package/recipes/parts/crud-list/i18n.json +83 -0
  11. package/recipes/parts/crud-list/src/app/features/__name__/__name__.routes.ts.tpl +30 -0
  12. package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.html.tpl +102 -0
  13. package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.spec.ts.tpl +101 -0
  14. package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.ts.tpl +143 -0
  15. package/recipes/parts/detail-page/i18n.json +32 -0
  16. package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.html.tpl +35 -0
  17. package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.spec.ts.tpl +58 -0
  18. package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.ts.tpl +68 -0
  19. package/recipes/parts/entity/i18n.json +5 -0
  20. package/recipes/parts/entity/src/app/features/__name__/__name__.model.ts.tpl +9 -0
  21. package/recipes/parts/entity/src/app/features/__name__/__name__.service.spec.ts.tpl +29 -0
  22. package/recipes/parts/entity/src/app/features/__name__/__name__.service.ts.tpl +33 -0
  23. package/recipes/parts/form-dialog/i18n.json +35 -0
  24. package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.html.tpl +33 -0
  25. package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.spec.ts.tpl +69 -0
  26. package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.ts.tpl +73 -0
  27. package/src/add/add.mjs +251 -0
  28. package/src/check/config.mjs +112 -0
  29. package/src/check/exceptions.mjs +103 -0
  30. package/src/check/federation.mjs +224 -0
  31. package/src/check/finding.mjs +23 -0
  32. package/src/check/harness.mjs +146 -0
  33. package/src/check/i18n.mjs +218 -0
  34. package/src/check/integration.mjs +566 -0
  35. package/src/check/security.mjs +165 -0
  36. package/src/check/steps.mjs +37 -0
  37. package/src/check/styles.mjs +347 -0
  38. package/src/check/wiring.mjs +198 -0
  39. package/src/check.mjs +333 -0
  40. package/src/cli.mjs +551 -0
  41. package/src/docs/docs.mjs +154 -0
  42. package/src/doctor/doctor.mjs +492 -0
  43. package/src/format.mjs +102 -0
  44. package/src/info/info.mjs +149 -0
  45. package/src/init/init.mjs +490 -0
  46. package/src/init/merge.mjs +191 -0
  47. package/src/init/template.mjs +292 -0
  48. package/src/mcp/catalog.mjs +248 -0
  49. package/src/mcp/glossary.mjs +75 -0
  50. package/src/mcp/manifest.mjs +53 -0
  51. package/src/mcp/recipes.mjs +198 -0
  52. package/src/mcp/server.mjs +249 -0
  53. package/src/mcp/upgrade-guide.mjs +116 -0
  54. package/src/mcp/usage.mjs +48 -0
  55. package/src/project/project.mjs +220 -0
  56. package/src/types.d.ts +448 -0
  57. package/src/upgrade/lockstep.mjs +153 -0
  58. package/src/upgrade/upgrade.mjs +623 -0
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Project wiring step: pubsub, host-owned code in a child, the static dev menu and starter leftovers.
3
+ * Ids: MFE_CHILD_PUBSUB_001, MFE_HOST_PUBSUB_001, MFE_CHILD_CONFIG_001, MFE_MENU_001/002,
4
+ * MFE_GUAS_MENU_003/004, MFE_FEATURE_MENU_001, MFE_IDENTITY_001.
5
+ */
6
+ import { readText, walk } from '../project/project.mjs';
7
+ import { finding } from './finding.mjs';
8
+
9
+ /**
10
+ * @typedef {import('../types.js').Finding} Finding
11
+ * @typedef {import('../types.js').ProjectInfo} ProjectInfo
12
+ */
13
+
14
+ const PUBSUB = 'src/app/core/services/pubsub/pubsub.service.ts';
15
+ const MENU = 'src/app/core/models/Menu.ts';
16
+
17
+ /**
18
+ * The body of `name(...) { ... }` in a class, or null.
19
+ * @param {string} source
20
+ * @param {string} name
21
+ */
22
+ function methodBody(source, name) {
23
+ const match = new RegExp(`\\b${name}\\s*\\([^)]*\\)\\s*(?::\\s*[\\w<>]+\\s*)?\\{`).exec(source);
24
+ if (!match) return null;
25
+ let depth = 0;
26
+ for (let index = match.index + match[0].length - 1; index < source.length; index += 1) {
27
+ if (source[index] === '{') depth += 1;
28
+ else if (source[index] === '}' && --depth === 0) return source.slice(match.index + match[0].length, index);
29
+ }
30
+ return null;
31
+ }
32
+
33
+ /**
34
+ * @param {ProjectInfo} project
35
+ * @returns {Finding[]}
36
+ */
37
+ function pubsub(project) {
38
+ const source = readText(project.root, PUBSUB);
39
+ if (project.role === 'host') {
40
+ if (source === null) return [finding('MFE_HOST_PUBSUB_001', PUBSUB, 'A host needs PubsubService to answer the children PERMISSIONS requests.')];
41
+ if (!source.includes('subscribeToPermissionsEvents') || !/PERMISSIONS[._]RESPONSE/.test(source))
42
+ return [
43
+ finding('MFE_HOST_PUBSUB_001', PUBSUB, 'The host PubsubService must wire subscribeToPermissionsEvents and publish PERMISSIONS.RESPONSE.'),
44
+ ];
45
+ return [];
46
+ }
47
+ if (source === null) return [finding('MFE_CHILD_PUBSUB_001', PUBSUB, 'A child needs PubsubService for the host AUTH events.')];
48
+ const method = ['subscribeToChildAuthEvents', 'subscribeToAuthEvents'].find((name) => source.includes(name));
49
+ if (!method)
50
+ return [finding('MFE_CHILD_PUBSUB_001', PUBSUB, 'The child PubsubService must subscribe to the host AUTH events (subscribeToAuthEvents).')];
51
+ if (/router\.navigate/.test(methodBody(source, method) ?? ''))
52
+ return [
53
+ finding(
54
+ 'MFE_CHILD_PUBSUB_001',
55
+ PUBSUB,
56
+ `The child AUTH handler (${method}) must not call router.navigate: it only sets the user and session; the host navigates.`,
57
+ ),
58
+ ];
59
+ return [];
60
+ }
61
+
62
+ /**
63
+ * MFE_CHILD_CONFIG_001: request bypass by context, not by URL, and no host manifest loading in a child.
64
+ * @param {ProjectInfo} project
65
+ * @returns {Finding[]}
66
+ */
67
+ function childConfig(project) {
68
+ const { root } = project;
69
+ /** @type {Finding[]} */
70
+ const findings = [];
71
+ const interceptor = 'src/app/core/interceptors/token/token.interceptor.ts';
72
+ const interceptorSource = readText(root, interceptor);
73
+ if (interceptorSource !== null) {
74
+ if (/\.includes\(\s*['"`]/.test(interceptorSource) && /mfe_config|configuration|assets\//.test(interceptorSource))
75
+ findings.push(
76
+ finding(
77
+ 'MFE_CHILD_CONFIG_001',
78
+ interceptor,
79
+ 'The token interceptor must not skip requests by URL substring: mark them with the BYPASS_INTERCEPTOR context.',
80
+ ),
81
+ );
82
+ else if (!interceptorSource.includes('context.get(BYPASS_INTERCEPTOR)'))
83
+ findings.push(finding('MFE_CHILD_CONFIG_001', interceptor, 'The token interceptor must honor the BYPASS_INTERCEPTOR request context.'));
84
+ }
85
+ const loader = 'src/app/core/services/mfe-configuration/configuration-loader.service.ts';
86
+ const loaderSource = readText(root, loader);
87
+ if (loaderSource !== null) {
88
+ if (!loaderSource.includes('BYPASS_INTERCEPTOR'))
89
+ findings.push(
90
+ finding('MFE_CHILD_CONFIG_001', loader, 'The configuration loader must mark its asset requests with the BYPASS_INTERCEPTOR context.'),
91
+ );
92
+ if (/loadManifest|federation\.manifest/.test(loaderSource) && /manifest\.json/.test(loaderSource))
93
+ findings.push(finding('MFE_CHILD_CONFIG_001', loader, 'A child configuration loader must not load the host federation manifest.'));
94
+ }
95
+ return findings;
96
+ }
97
+
98
+ /**
99
+ * Keys of `const NAME ... = { ... }`.
100
+ * @param {string} source
101
+ * @param {string} name
102
+ */
103
+ function objectKeys(source, name) {
104
+ const body = new RegExp(`\\b${name}\\b[^=]*=\\s*\\{([^}]*)\\}`).exec(source)?.[1] ?? '';
105
+ return [...body.matchAll(/['"]?([\w-]+)['"]?\s*:/g)].map((match) => match[1]);
106
+ }
107
+
108
+ /**
109
+ * The bracket-matched array literal that `opener` (ending at its `[`) starts, or ''.
110
+ * @param {string} source
111
+ * @param {RegExp} opener
112
+ */
113
+ function arrayAfter(source, opener) {
114
+ const match = opener.exec(source);
115
+ if (!match) return '';
116
+ let depth = 0;
117
+ for (let index = match.index + match[0].length - 1; index < source.length; index += 1) {
118
+ if (source[index] === '[') depth += 1;
119
+ else if (source[index] === ']' && --depth === 0) return source.slice(match.index + match[0].length, index);
120
+ }
121
+ return '';
122
+ }
123
+
124
+ /**
125
+ * The static dev menu (src/app/core/models/Menu.ts), in hosts and child harnesses.
126
+ * @param {ProjectInfo} project
127
+ * @returns {Finding[]}
128
+ */
129
+ function staticMenu(project) {
130
+ const source = readText(project.root, MENU);
131
+ if (source === null)
132
+ return [finding('MFE_MENU_001', MENU, 'The static menu file for local and showcase navigation is missing (src/app/core/models/Menu.ts).')];
133
+ /** @type {Finding[]} */
134
+ const findings = [];
135
+ if (!source.includes('staticMenus') || !source.includes('MENU_ICONS'))
136
+ findings.push(finding('MFE_MENU_002', MENU, 'Menu.ts must define staticMenus and MENU_ICONS for local and showcase navigation.'));
137
+ if (!/\bmenuSidebarIcon\b/.test(source))
138
+ findings.push(finding('MFE_GUAS_MENU_004', MENU, 'Menu.ts must export menuSidebarIcon, which resolves the sidebar icons.'));
139
+ const iconKeys = new Set(objectKeys(source, 'MENU_ICONS'));
140
+ const submenus = [...source.matchAll(/submenu\s*:\s*\[([\s\S]*?)\]/g)].flatMap((match) =>
141
+ [...match[1].matchAll(/\btag\s*:\s*['"]([^'"]+)['"]/g)].map((tag) => tag[1]),
142
+ );
143
+ for (const tag of new Set(submenus)) {
144
+ if (iconKeys.has(tag))
145
+ findings.push(finding('MFE_GUAS_MENU_003', MENU, `MENU_ICONS maps top-level section tags only: remove the submenu tag "${tag}".`));
146
+ }
147
+ const topLevel = arrayAfter(source, /\bstaticMenus\b[^=]*=\s*\[/);
148
+ for (const block of topLevel.matchAll(/\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}/g)) {
149
+ const page = /page\s*:\s*['"]([^'"]+)['"]/.exec(block[0])?.[1];
150
+ if (page && /\/(detail|visor|traces|edit|view)(\/|$)|:id|:uuid/i.test(page) && !/\bsub[mM]enus?\b/.test(block[0]))
151
+ findings.push(finding('MFE_FEATURE_MENU_001', MENU, `The top-level menu entry "${page}" is a detail page: nest it under its section instead.`));
152
+ }
153
+ return findings;
154
+ }
155
+
156
+ const STARTER_TOKENS = [
157
+ 'microfrontend-starter',
158
+ 'microfrontend_starter',
159
+ 'microfrontendStarter',
160
+ 'MFE Starter',
161
+ 'Microfrontend Starter',
162
+ 'starter_session',
163
+ 'YOUR_DOMAIN',
164
+ 'YOUR_APP',
165
+ 'TODO_PROJECT',
166
+ ];
167
+
168
+ /**
169
+ * MFE_IDENTITY_001: starter identity tokens left in package, angular, proxy or runtime files.
170
+ * @param {ProjectInfo} project
171
+ * @returns {Finding[]}
172
+ */
173
+ function identity(project) {
174
+ const { root } = project;
175
+ const files = [
176
+ ...['package.json', 'angular.json', 'proxy-config.json', 'sonar-project.properties'].filter((file) => readText(root, file) !== null),
177
+ ...walk(root, 'src', (file) => /\.(ts|html|json|js|css)$/.test(file) && !file.endsWith('.spec.ts')),
178
+ ];
179
+ /** @type {Finding[]} */
180
+ const findings = [];
181
+ for (const file of files) {
182
+ // The pre-boot <title> of index.html: sdk-tools init does not rename it, and the title strategy replaces it.
183
+ let text = readText(root, file) ?? '';
184
+ if (file === 'src/index.html') text = text.replace(/<title>[^<]*<\/title>/, '');
185
+ const token = STARTER_TOKENS.find((candidate) => text.includes(candidate));
186
+ if (token) findings.push(finding('MFE_IDENTITY_001', file, `Starter identity "${token}" is still here: replace it with the project identity.`));
187
+ }
188
+ return findings;
189
+ }
190
+
191
+ /**
192
+ * @param {ProjectInfo} project
193
+ * @returns {Finding[]}
194
+ */
195
+ export function wiringStep(project) {
196
+ if (!project.role) return [];
197
+ return [...pubsub(project), ...(project.role === 'child' ? childConfig(project) : []), ...staticMenu(project), ...identity(project)];
198
+ }
package/src/check.mjs ADDED
@@ -0,0 +1,333 @@
1
+ /**
2
+ * `sdk-tools check`: one findings list for an app built with @sixbell-telco/sdk.
3
+ *
4
+ * - lint: the @sixbell-telco/eslint-plugin-sdk rules (kit API, DaisyUI component classes, banned
5
+ * utilities), shadcn-lint-angular's design rules against the app's own theme (raw colors,
6
+ * arbitrary values, inline styles, restyling kit components, unknown classes) and Angular
7
+ * control flow, over `.html` templates, inline templates and `.ts` files, with this tool's own
8
+ * config (the project's ESLint config is not used).
9
+ * - typecheck: TypeScript and Angular strict template diagnostics through the compiler API
10
+ * (TypeScript errors never hide template errors).
11
+ * - project steps (src/check/): federation, harness, wiring, config, i18n, styles and security,
12
+ * with the mfe-tools ids as rules. Findings `sdk-tools.exceptions.json` covers are excepted.
13
+ */
14
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
15
+ import { createRequire } from 'node:module';
16
+ import { join, relative, resolve } from 'node:path';
17
+ import { pathToFileURL } from 'node:url';
18
+
19
+ import { applyExceptions } from './check/exceptions.mjs';
20
+ import { projectFindings } from './check/steps.mjs';
21
+
22
+ /**
23
+ * @typedef {import('./types.js').Finding} Finding
24
+ * @typedef {import('./types.js').CheckOptions} CheckOptions
25
+ * @typedef {import('./types.js').CheckResult} CheckResult
26
+ * @typedef {typeof import('../../eslint-plugin-sdk/src/index.mjs').default} SdkPlugin
27
+ * @typedef {import('../../eslint-plugin-sdk/src/types.js').Manifest} Manifest
28
+ * @typedef {import('eslint').Linter.Config} LintConfig
29
+ */
30
+
31
+ /** @returns {Promise<SdkPlugin>} */
32
+ async function loadPlugin() {
33
+ const installed = '@sixbell-telco/eslint-plugin-sdk';
34
+ try {
35
+ return (await import(installed)).default;
36
+ } catch {
37
+ // In the ui-kit monorepo the plugin is a sibling project, not an installed package.
38
+ return (await import(new URL('../../eslint-plugin-sdk/src/index.mjs', import.meta.url).href)).default;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Attribute names, inputs and outputs of the project's own directives (`@Directive` classes under
44
+ * the linted paths), and the `ng-content select` attributes of its own components. A camelCase
45
+ * attribute on a kit element that one of them owns is not a kit mistake. Component inputs are left
46
+ * out: they never sit on a kit element.
47
+ * @param {string} cwd
48
+ * @param {string[]} paths
49
+ * @returns {string[]}
50
+ */
51
+ export function projectDirectiveNames(cwd, paths) {
52
+ /** @type {Set<string>} */
53
+ const names = new Set();
54
+ /** @param {string} path */
55
+ const walk = (path) => {
56
+ if (!existsSync(path)) return;
57
+ if (statSync(path).isDirectory()) {
58
+ for (const name of readdirSync(path)) if (name !== 'node_modules' && !name.startsWith('.')) walk(join(path, name));
59
+ return;
60
+ }
61
+ if (!/\.(ts|html)$/.test(path) || path.endsWith('.spec.ts')) return;
62
+ const text = readFileSync(path, 'utf8');
63
+ // Content projection markers of the app's own components: <ng-content select="[iconPickerTrigger]">.
64
+ for (const [, select] of text.matchAll(/<ng-content[^>]*\bselect=["']([^"']+)["']/g)) {
65
+ for (const [, attribute] of select.matchAll(/\[([\w-]+)/g)) names.add(attribute);
66
+ }
67
+ if (!path.endsWith('.ts') || !text.includes('@Directive(')) return;
68
+ for (const [, selector] of text.matchAll(/selector:\s*['"`]([^'"`]+)['"`]/g)) {
69
+ for (const [, attribute] of selector.matchAll(/\[([\w-]+)/g)) names.add(attribute);
70
+ }
71
+ for (const [, name] of text.matchAll(/(\w+)\s*=\s*(?:input|model|output)(?:\.required)?\s*[<(]/g)) names.add(name);
72
+ for (const [, alias] of text.matchAll(/alias:\s*['"](\w+)['"]/g)) names.add(alias);
73
+ for (const [, alias, name] of text.matchAll(/@(?:Input|Output)\(\s*(?:['"](\w+)['"])?[^)]*\)\s*(?:set\s+)?(\w+)/g)) names.add(alias ?? name);
74
+ };
75
+ for (const path of paths) walk(resolve(cwd, path));
76
+ return [...names].sort();
77
+ }
78
+
79
+ /**
80
+ * The app's Tailwind entry: the first CSS file in angular.json build styles, else src/styles.css.
81
+ * @param {string} cwd
82
+ * @returns {string | null}
83
+ */
84
+ export function tailwindEntry(cwd) {
85
+ try {
86
+ /** @type {{ projects?: Record<string, { architect?: { build?: { options?: { styles?: (string | { input: string })[] } } } }> }} */
87
+ const angular = JSON.parse(readFileSync(join(cwd, 'angular.json'), 'utf8'));
88
+ for (const project of Object.values(angular.projects ?? {})) {
89
+ const styles = project.architect?.build?.options?.styles ?? [];
90
+ const css = styles.map((style) => (typeof style === 'string' ? style : style.input)).find((file) => file?.endsWith('.css'));
91
+ if (css && existsSync(join(cwd, css))) return css;
92
+ }
93
+ } catch {
94
+ // no angular.json: fall back below
95
+ }
96
+ return existsSync(join(cwd, 'src/styles.css')) ? 'src/styles.css' : null;
97
+ }
98
+
99
+ /**
100
+ * Design rules from shadcn-lint-angular (an Angular port of @shadcn/lint), with the app's Tailwind
101
+ * entry, so only the kit theme's tokens are valid. Kit components (`st-*`) own their color,
102
+ * typography and surface: around them only layout and spacing utilities are allowed.
103
+ * @type {Record<string, import('eslint').Linter.RuleEntry>}
104
+ */
105
+ const DESIGN_RULES = {
106
+ 'shadcn/no-raw-colors': 'error',
107
+ 'shadcn/no-arbitrary-values': 'error',
108
+ 'shadcn/no-inline-styles': 'error',
109
+ 'shadcn/no-unknown-classes': 'warn',
110
+ 'shadcn/no-restyle': ['error', { allow: ['layout', 'spacing'], contracts: [{ pattern: '/^st-/' }] }],
111
+ };
112
+
113
+ /**
114
+ * The flat config `check` lints with (the project's own ESLint config is not used).
115
+ * @param {{ manifest?: Manifest, knownAttributes?: string[], entry?: string | null }} [options]
116
+ * @returns {Promise<LintConfig[]>}
117
+ */
118
+ export async function lintConfig({ manifest, knownAttributes = [], entry = null } = {}) {
119
+ const plugin = await loadPlugin();
120
+ const { default: angular } = await import('angular-eslint');
121
+ const { default: tseslint } = await import('typescript-eslint');
122
+ // shadcn-lint-angular's plugin type does not match ESLint's Plugin type exactly.
123
+ const shadcn = /** @type {import('eslint').ESLint.Plugin} */ (/** @type {unknown} */ ((await import('shadcn-lint-angular')).plugin));
124
+ const settings = {
125
+ sixbellSdk: { ...(manifest ? { manifest } : {}), knownAttributes },
126
+ shadcn: { ...(entry ? { entryPoint: entry } : {}), themeImports: ['^@sixbell-telco/sdk'] },
127
+ };
128
+ const [templates, imports] = plugin.configs.recommended;
129
+ const angularTemplate = {
130
+ '@angular-eslint/template': /** @type {import('eslint').ESLint.Plugin} */ (/** @type {unknown} */ (angular.templatePlugin)),
131
+ };
132
+ return [
133
+ // Test files hold fixture templates, not app UI.
134
+ { ignores: ['**/node_modules/**', '**/dist/**', '**/.angular/**', '**/coverage/**', '**/*.spec.ts', '**/*.stories.ts'] },
135
+ // eslint-disable comments are ignored: they name the project's own rules (unknown here), and a
136
+ // kit finding must not be silenced from the code.
137
+ { linterOptions: { noInlineConfig: true, reportUnusedDisableDirectives: 'off' } },
138
+ {
139
+ ...imports,
140
+ languageOptions: { parser: tseslint.parser },
141
+ processor: angular.processInlineTemplates,
142
+ plugins: { ...imports.plugins, shadcn },
143
+ rules: { ...imports.rules, ...DESIGN_RULES },
144
+ settings,
145
+ },
146
+ {
147
+ ...templates,
148
+ plugins: { ...templates.plugins, ...angularTemplate, shadcn },
149
+ rules: { ...templates.rules, ...DESIGN_RULES, '@angular-eslint/template/prefer-control-flow': 'error' },
150
+ settings,
151
+ },
152
+ ];
153
+ }
154
+
155
+ /** @type {Record<number, Finding['severity']>} */
156
+ const SEVERITY = { 1: 'warn', 2: 'error' };
157
+
158
+ /**
159
+ * @param {{ cwd: string, paths: string[], fix?: boolean, manifest?: Manifest, onProgress?: (message: string) => void }} options
160
+ * @returns {Promise<Finding[]>}
161
+ */
162
+ export async function lint({ cwd, paths, fix = false, manifest, onProgress = () => {} }) {
163
+ const { ESLint } = await import('eslint');
164
+ const knownAttributes = projectDirectiveNames(cwd, paths);
165
+ const entry = tailwindEntry(cwd);
166
+ const eslint = new ESLint({
167
+ cwd,
168
+ overrideConfigFile: true,
169
+ overrideConfig: await lintConfig({ manifest, knownAttributes, entry }),
170
+ fix,
171
+ errorOnUnmatchedPattern: false,
172
+ });
173
+ onProgress(`Linting ${paths.join(', ')} (kit API, design rules against ${entry ?? 'the theme'})…`);
174
+ const results = await eslint.lintFiles(paths);
175
+ if (fix) await ESLint.outputFixes(results);
176
+ /** @param {import('eslint').Linter.LintMessage} m */
177
+ const ignoredDirective = (m) => !m.ruleId && /has no effect because you have 'noInlineConfig'/.test(m.message);
178
+ return results.flatMap((result) =>
179
+ result.messages
180
+ .filter((m) => !ignoredDirective(m))
181
+ .map((m) => ({
182
+ rule: m.ruleId ?? 'lint/parse',
183
+ // eslint-plugin-sdk rules carry the mfe-tools id as their messageId.
184
+ ...(m.messageId && /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(m.messageId) ? { id: m.messageId } : {}),
185
+ severity: m.fatal ? 'error' : SEVERITY[m.severity],
186
+ file: relative(cwd, result.filePath),
187
+ line: m.line ?? 0,
188
+ column: m.column ?? 0,
189
+ message: m.message,
190
+ ...(m.fix ? { fixable: true } : {}),
191
+ })),
192
+ );
193
+ }
194
+
195
+ /** @param {string} cwd */
196
+ function defaultProject(cwd) {
197
+ return ['tsconfig.app.json', 'tsconfig.json'].map((name) => join(cwd, name)).find(existsSync);
198
+ }
199
+
200
+ /**
201
+ * TypeScript and Angular template diagnostics of the project, through the Angular compiler API
202
+ * loaded from the project's own node_modules (so its Angular version is the one that checks).
203
+ * @param {{ cwd: string, project?: string }} options
204
+ * @returns {Promise<Finding[]>}
205
+ */
206
+ export async function typecheck({ cwd, project = defaultProject(cwd) }) {
207
+ if (!project)
208
+ return [
209
+ {
210
+ rule: 'typecheck/no-tsconfig',
211
+ severity: 'error',
212
+ file: '',
213
+ line: 0,
214
+ column: 0,
215
+ message: 'no tsconfig.app.json or tsconfig.json; pass --project',
216
+ },
217
+ ];
218
+ const require = createRequire(join(cwd, 'noop.js'));
219
+ const ngc = await import(pathToFileURL(require.resolve('@angular/compiler-cli')).href);
220
+ const { default: ts } = await import(pathToFileURL(require.resolve('typescript')).href);
221
+ const config = ngc.readConfiguration(resolve(cwd, project));
222
+ if (config.errors?.length) {
223
+ return config.errors.map((/** @type {import('typescript').Diagnostic} */ d) => ({
224
+ rule: `typecheck/TS${d.code}`,
225
+ severity: 'error',
226
+ file: '',
227
+ line: 0,
228
+ column: 0,
229
+ message: ts.flattenDiagnosticMessageText(d.messageText, ' '),
230
+ }));
231
+ }
232
+ const options = { ...config.options, noEmit: true };
233
+ const program = new ngc.NgtscProgram(config.rootNames, options, ngc.createCompilerHost({ options }));
234
+ await program.compiler.analyzeAsync();
235
+ const diagnostics = [
236
+ ...program.getTsSyntacticDiagnostics(),
237
+ ...program.getTsSemanticDiagnostics(),
238
+ ...program.getNgStructuralDiagnostics(),
239
+ ...program.getNgSemanticDiagnostics(),
240
+ ];
241
+ return diagnostics
242
+ .filter((d) => d.category === ts.DiagnosticCategory.Error)
243
+ .map((d) => {
244
+ const position = d.file && d.start !== undefined ? d.file.getLineAndCharacterOfPosition(d.start) : null;
245
+ return {
246
+ rule: `typecheck/${d.code < 0 ? `NG${String(-d.code).slice(2)}` : `TS${d.code}`}`,
247
+ severity: 'error',
248
+ file: d.file ? relative(cwd, d.file.fileName) : '',
249
+ line: position ? position.line + 1 : 0,
250
+ column: position ? position.character + 1 : 0,
251
+ message: ts.flattenDiagnosticMessageText(d.messageText, ' ').split(' 1. ')[0].trim(),
252
+ };
253
+ });
254
+ }
255
+
256
+ /** @param {string} cwd */
257
+ function installedManifest(cwd) {
258
+ try {
259
+ return createRequire(join(cwd, 'noop.js')).resolve('@sixbell-telco/sdk/manifest.json');
260
+ } catch {
261
+ return null;
262
+ }
263
+ }
264
+
265
+ /** The test setup files at the app root that `check` lints with src by default. */
266
+ const TEST_SETUP_FILES = ['setup-jest.ts', 'test-setup.ts'];
267
+
268
+ /**
269
+ * The default paths: src, plus the app-root test setup file (global SDK mocks live there).
270
+ * @param {string} cwd
271
+ */
272
+ export function defaultPaths(cwd) {
273
+ return ['src', ...TEST_SETUP_FILES.filter((file) => existsSync(join(cwd, file)))];
274
+ }
275
+
276
+ /**
277
+ * True when `paths` cover the whole app: one of them is the app root or its src folder, however it
278
+ * is spelled (`src`, `./src`, `src/app/..`, an absolute path).
279
+ * @param {string} cwd
280
+ * @param {string[]} paths
281
+ */
282
+ export function coversApp(cwd, paths) {
283
+ const root = resolve(cwd);
284
+ return paths.some((path) => [root, join(root, 'src')].includes(resolve(root, path)));
285
+ }
286
+
287
+ /**
288
+ * Runs the checks and returns `{ findings, counts }`.
289
+ * @param {CheckOptions} [options]
290
+ * @returns {Promise<CheckResult>}
291
+ */
292
+ export async function check({
293
+ cwd = process.cwd(),
294
+ paths = defaultPaths(cwd),
295
+ fix = false,
296
+ typecheck: withTypecheck = true,
297
+ project,
298
+ manifestPath,
299
+ projectSteps = coversApp(cwd, paths),
300
+ today,
301
+ onProgress = () => {},
302
+ } = {}) {
303
+ const manifest = manifestPath ? JSON.parse(readFileSync(resolve(cwd, manifestPath), 'utf8')) : undefined;
304
+ /** @type {Finding[]} */
305
+ const findings = [];
306
+ if (!manifest && !installedManifest(cwd)) {
307
+ findings.push({
308
+ rule: 'manifest/not-found',
309
+ severity: 'warn',
310
+ file: '',
311
+ line: 0,
312
+ column: 0,
313
+ message:
314
+ '@sixbell-telco/sdk/manifest.json not found (SDK 4.6.0 or later ships it): the kit rules cannot check templates. Upgrade the SDK or pass --manifest',
315
+ });
316
+ }
317
+ findings.push(...(await lint({ cwd, paths, fix, manifest, onProgress })));
318
+ if (withTypecheck) {
319
+ onProgress('Type-checking templates with the Angular compiler…');
320
+ findings.push(...(await typecheck({ cwd, project })));
321
+ }
322
+ if (projectSteps) {
323
+ onProgress('Checking federation, shell, i18n, styles and security floors…');
324
+ findings.push(...projectFindings(resolve(cwd)));
325
+ }
326
+ const applied = applyExceptions(resolve(cwd), findings, today);
327
+ // One field for consumers: the mfe-tools id, or null for a lint, typecheck or tool finding without one.
328
+ const kept = applied.findings
329
+ .map((item) => ({ ...item, id: item.id ?? null }))
330
+ .sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
331
+ const counts = { errors: kept.filter((f) => f.severity === 'error').length, warnings: kept.filter((f) => f.severity === 'warn').length };
332
+ return { findings: kept, counts, excepted: applied.excepted };
333
+ }