@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
+ * The recipe registry: one Markdown file per recipe in `projects/sdk-tools/recipes/`, with a front
3
+ * matter block (format in recipes/README.md). The MCP serves them through get_recipe and as
4
+ * resources; `sdk-tools add` writes the files of their template parts (`recipes/parts/<part>/`).
5
+ */
6
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
7
+ import { join, sep } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { NotFoundError } from './catalog.mjs';
10
+
11
+ /** @typedef {import('../types.js').Recipe} Recipe */
12
+ /** @typedef {import('../types.js').RecipeFile} RecipeFile */
13
+ /** @typedef {{ [key: string]: string | I18nTree }} I18nTree */
14
+ /** @typedef {{ part: string, template: string, target: string, shared: boolean }} PartFile */
15
+
16
+ const RECIPES_DIR = fileURLToPath(new URL('../../recipes/', import.meta.url));
17
+ const REQUIRED = ['id', 'title', 'summary'];
18
+
19
+ /**
20
+ * Parses one recipe file. Front matter values are strings, `true`/`false`, or `[a, b]` lists.
21
+ * @param {string} text
22
+ * @param {string} file for error messages
23
+ * @returns {Recipe}
24
+ */
25
+ export function parseRecipe(text, file) {
26
+ const match = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(text.replace(/\r\n/g, '\n'));
27
+ if (!match) throw new Error(`${file}: a recipe starts with a --- front matter block`);
28
+ /** @type {Record<string, string | boolean | string[]>} */
29
+ const meta = {};
30
+ for (const line of match[1].split('\n')) {
31
+ if (!line.trim()) continue;
32
+ const field = /^([A-Za-z][\w]*):\s*(.*)$/.exec(line);
33
+ if (!field) throw new Error(`${file}: bad front matter line "${line}"`);
34
+ const raw = field[2].trim();
35
+ meta[field[1]] =
36
+ raw === 'true' || raw === 'false'
37
+ ? raw === 'true'
38
+ : /^\[.*\]$/.test(raw)
39
+ ? raw
40
+ .slice(1, -1)
41
+ .split(',')
42
+ .map((s) => s.trim())
43
+ .filter(Boolean)
44
+ : raw;
45
+ }
46
+ for (const key of REQUIRED) if (typeof meta[key] !== 'string' || !meta[key]) throw new Error(`${file}: front matter needs "${key}"`);
47
+ const { id, title, summary, kitCandidate = false, tags = [], parts = [] } = meta;
48
+ /** @param {string | boolean | string[]} value */
49
+ const list = (value) => (Array.isArray(value) ? value : [String(value)]);
50
+ return {
51
+ id: String(id),
52
+ title: String(title),
53
+ summary: String(summary),
54
+ kitCandidate: kitCandidate === true,
55
+ tags: list(tags),
56
+ body: match[2].trim(),
57
+ parts: list(parts),
58
+ files: [],
59
+ i18nKeys: [],
60
+ };
61
+ }
62
+
63
+ /** Template files end in `.tpl`, so the repo's linters and compilers skip them. */
64
+ const TEMPLATE_SUFFIX = '.tpl';
65
+ /** Each part may hold `i18n.json`: `{ en, es, pt }` trees of keys under `<app>.<name>`. */
66
+ const PART_I18N = 'i18n.json';
67
+
68
+ /**
69
+ * @param {string} dir
70
+ * @returns {string[]} files under dir, relative with `/`, sorted
71
+ */
72
+ function walk(dir) {
73
+ return readdirSync(dir, { recursive: true, encoding: 'utf8' })
74
+ .filter((name) => statSync(join(dir, name)).isFile())
75
+ .map((name) => name.split(sep).join('/'))
76
+ .sort();
77
+ }
78
+
79
+ /**
80
+ * The files a recipe writes, in part order. Files of a part that is not the recipe's own (its id)
81
+ * are shared with other recipes: `add` keeps an existing copy instead of refusing it.
82
+ * @param {Pick<Recipe, 'id' | 'parts'>} recipe
83
+ * @param {string} [dir] the recipes folder
84
+ * @returns {PartFile[]}
85
+ */
86
+ export function recipePartFiles(recipe, dir = RECIPES_DIR) {
87
+ return recipe.parts.flatMap((part) => {
88
+ const root = join(dir, 'parts', part);
89
+ let files;
90
+ try {
91
+ files = walk(root);
92
+ } catch {
93
+ throw new Error(`${recipe.id}.md: no template part "${part}" (recipes/parts/${part}/)`);
94
+ }
95
+ return files
96
+ .filter((file) => file.endsWith(TEMPLATE_SUFFIX))
97
+ .map((file) => ({ part, template: join(root, file), target: file.slice(0, -TEMPLATE_SUFFIX.length), shared: part !== recipe.id }));
98
+ });
99
+ }
100
+
101
+ /**
102
+ * The i18n trees of a recipe's parts, merged per language. Two parts that give one key different
103
+ * values are a broken recipe.
104
+ * @param {Pick<Recipe, 'id' | 'parts'>} recipe
105
+ * @param {string} [dir]
106
+ * @returns {Record<string, I18nTree>}
107
+ */
108
+ export function recipeI18n(recipe, dir = RECIPES_DIR) {
109
+ const merged = /** @type {Record<string, I18nTree>} */ (Object.create(null));
110
+ /**
111
+ * @param {I18nTree} into
112
+ * @param {I18nTree} from
113
+ * @param {string} at
114
+ */
115
+ const merge = (into, from, at) => {
116
+ for (const [key, value] of Object.entries(from)) {
117
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype')
118
+ throw new Error(`${recipe.id}.md: i18n key ${at}${key} is not allowed`);
119
+ const existing = Object.hasOwn(into, key) ? into[key] : undefined;
120
+ if (typeof value === 'string') {
121
+ if (existing !== undefined && existing !== value) throw new Error(`${recipe.id}.md: parts disagree on i18n key ${at}${key}`);
122
+ into[key] = value;
123
+ } else {
124
+ if (typeof existing === 'string') throw new Error(`${recipe.id}.md: parts disagree on i18n key ${at}${key}`);
125
+ merge((into[key] = existing ?? {}), value, `${at}${key}.`);
126
+ }
127
+ }
128
+ };
129
+ for (const part of recipe.parts) {
130
+ let text;
131
+ try {
132
+ text = readFileSync(join(dir, 'parts', part, PART_I18N), 'utf8');
133
+ } catch {
134
+ continue;
135
+ }
136
+ /** @type {Record<string, I18nTree>} */
137
+ const bundle = JSON.parse(text);
138
+ for (const [language, tree] of Object.entries(bundle)) {
139
+ if (!/^[a-z]{2}(-[A-Z]{2})?$/.test(language)) throw new Error(`${recipe.id}.md: ${language} is not a language code`);
140
+ merge((merged[language] ??= {}), tree, `${language}:`);
141
+ }
142
+ }
143
+ return merged;
144
+ }
145
+
146
+ /**
147
+ * @param {I18nTree} tree
148
+ * @param {string} [prefix]
149
+ * @returns {string[]}
150
+ */
151
+ export function flattenKeys(tree, prefix = '') {
152
+ return Object.entries(tree).flatMap(([key, value]) => (typeof value === 'string' ? [`${prefix}${key}`] : flattenKeys(value, `${prefix}${key}.`)));
153
+ }
154
+
155
+ /**
156
+ * Fills in what a recipe writes, so get_recipe and `add` describe the same files.
157
+ * @param {Recipe} recipe
158
+ * @param {string} dir
159
+ * @returns {Recipe}
160
+ */
161
+ function withFiles(recipe, dir) {
162
+ const files = recipePartFiles(recipe, dir).map(({ part, target, shared }) => ({ path: target.replaceAll('__name__', '<name>'), shared, part }));
163
+ const i18n = recipeI18n(recipe, dir);
164
+ const languages = Object.keys(i18n).sort();
165
+ const keys = languages.length ? flattenKeys(i18n[languages[0]]).sort() : [];
166
+ for (const language of languages) {
167
+ if (flattenKeys(i18n[language]).sort().join() !== keys.join())
168
+ throw new Error(`${recipe.id}.md: i18n keys differ between ${languages[0]} and ${language}`);
169
+ }
170
+ return { ...recipe, files, i18nKeys: keys };
171
+ }
172
+
173
+ /**
174
+ * Every recipe in `dir`, sorted by id. README.md documents the format and is not a recipe.
175
+ * @param {string} [dir]
176
+ * @returns {Recipe[]}
177
+ */
178
+ export function loadRecipes(dir = RECIPES_DIR) {
179
+ return readdirSync(dir)
180
+ .filter((name) => name.endsWith('.md') && name !== 'README.md')
181
+ .map((name) => {
182
+ const recipe = parseRecipe(readFileSync(join(dir, name), 'utf8'), name);
183
+ if (`${recipe.id}.md` !== name) throw new Error(`${name}: the file name must be <id>.md (id is "${recipe.id}")`);
184
+ return withFiles(recipe, dir);
185
+ })
186
+ .sort((a, b) => a.id.localeCompare(b.id));
187
+ }
188
+
189
+ /**
190
+ * @param {Recipe[]} recipes
191
+ * @param {string} id
192
+ * @returns {Recipe}
193
+ */
194
+ export function findRecipe(recipes, id) {
195
+ const found = recipes.find((r) => r.id === id.trim().toLowerCase());
196
+ if (!found) throw new NotFoundError(`no recipe "${id}". Recipes: ${recipes.map((r) => r.id).join(', ')}.`);
197
+ return found;
198
+ }
@@ -0,0 +1,249 @@
1
+ /**
2
+ * `sdk-tools mcp`: an MCP server over stdio for agents building apps with @sixbell-telco/sdk.
3
+ * Every answer comes from the SDK installed in the app (its manifest) and the same check engine as
4
+ * `sdk-tools check`, so it matches the kit version the app really uses.
5
+ */
6
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
7
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
8
+ import { existsSync, readFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import { z } from 'zod';
11
+ import { getComponent, getTokens, listComponents, NotFoundError, searchComponents } from './catalog.mjs';
12
+ import { findTerm, GlossaryError, loadGlossary } from './glossary.mjs';
13
+ import { loadManifest, ManifestError } from './manifest.mjs';
14
+ import { findRecipe, loadRecipes } from './recipes.mjs';
15
+ import { upgradeGuide } from './upgrade-guide.mjs';
16
+ import { checkUsage } from './usage.mjs';
17
+
18
+ /**
19
+ * @typedef {import('@modelcontextprotocol/sdk/types.js').CallToolResult} CallToolResult
20
+ * @typedef {{ cwd: string, manifestPath?: string }} ServerOptions
21
+ */
22
+
23
+ /** The server name agents see: its tools show up as `SixbellSdk:<tool>`. */
24
+ const SERVER_NAME = 'SixbellSdk';
25
+
26
+ /** @returns {string} */
27
+ function version() {
28
+ return JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
29
+ }
30
+
31
+ /**
32
+ * Runs a tool body and turns its value into JSON text, and a known failure into a tool error with
33
+ * the message only (never a stack trace), so the agent can act on it.
34
+ * @param {() => unknown | Promise<unknown>} body
35
+ * @returns {Promise<CallToolResult>}
36
+ */
37
+ async function answer(body) {
38
+ try {
39
+ const value = await body();
40
+ return { content: [{ type: 'text', text: JSON.stringify(value, null, 1) }] };
41
+ } catch (thrown) {
42
+ const known = thrown instanceof ManifestError || thrown instanceof NotFoundError || thrown instanceof GlossaryError;
43
+ const message = thrown instanceof Error ? thrown.message : String(thrown);
44
+ return { isError: true, content: [{ type: 'text', text: known ? message : `sdk-tools failed: ${message}` }] };
45
+ }
46
+ }
47
+
48
+ /**
49
+ * The configured server (not yet connected), for `serve`.
50
+ * @param {ServerOptions} options
51
+ * @returns {McpServer}
52
+ */
53
+ function createServer({ cwd, manifestPath }) {
54
+ const server = new McpServer(
55
+ { name: SERVER_NAME, version: version() },
56
+ {
57
+ instructions:
58
+ 'Facts about the Enghouse Networks UI Kit (@sixbell-telco/sdk) installed in this app. Use these tools instead of guessing: search_components or list_components to find a kit component, get_component for its exact inputs and allowed values, get_tokens for theme colors and roles, get_recipe for how to build a screen or a local component, check_usage to verify your template before you finish, get_upgrade_guide for what an SDK upgrade involves, and get_glossary for what a kit term means. Use the glossary terms when you write about the kit.',
59
+ },
60
+ );
61
+ const manifest = () => loadManifest({ cwd, manifestPath }).manifest;
62
+ const recipes = loadRecipes();
63
+ const readOnly = { readOnlyHint: true, openWorldHint: false };
64
+
65
+ server.registerTool(
66
+ 'list_components',
67
+ {
68
+ title: 'List kit components',
69
+ description:
70
+ "List every component, directive and pipe of the installed @sixbell-telco/sdk: selector (st-*), class name, kind, entry point and a one-line description. Use it to see what the kit has. For one component's inputs, call get_component.",
71
+ inputSchema: { kind: z.enum(['component', 'directive', 'pipe']).optional().describe('Only this kind. Leave empty for all.') },
72
+ annotations: readOnly,
73
+ },
74
+ ({ kind }) => answer(() => listComponents(manifest(), { kind })),
75
+ );
76
+
77
+ server.registerTool(
78
+ 'search_components',
79
+ {
80
+ title: 'Search kit components',
81
+ description:
82
+ 'Find kit components for a need, by words such as "dialog", "table", "date picker" or "status badge". Returns the best matches with selector, entry point and description. Then call get_component with the selector you pick.',
83
+ inputSchema: { query: z.string().min(1).describe('What you need, in a few words. Example: "confirm dialog".') },
84
+ annotations: readOnly,
85
+ },
86
+ ({ query }) => answer(() => searchComponents(manifest(), query)),
87
+ );
88
+
89
+ server.registerTool(
90
+ 'get_component',
91
+ {
92
+ title: 'Get a kit component',
93
+ description:
94
+ "Get the exact API of one kit component from the installed SDK: inputs with their allowed values and defaults, outputs, content slots, the import line, a starting template, related components, Storybook examples, and do and don't rules. Use only the inputs and values it lists.",
95
+ inputSchema: {
96
+ selector: z.string().min(1).describe('The selector or class name. Examples: "st-dialog", "dialog", "DialogComponent", "stTextColor".'),
97
+ },
98
+ annotations: readOnly,
99
+ },
100
+ ({ selector }) => answer(() => getComponent(manifest(), selector)),
101
+ );
102
+
103
+ server.registerTool(
104
+ 'get_tokens',
105
+ {
106
+ title: 'Get theme tokens',
107
+ description:
108
+ 'Get the theme tokens of the installed SDK: semantic colors (use as bg-<token>, text-<token>, border-<token>), radius, shadow, easing, animation, font and text roles, plus deprecated tokens and their replacements. Use these instead of palette colors (bg-red-500), hex values or arbitrary values.',
109
+ inputSchema: {
110
+ group: z.string().optional().describe('Only one group: color, radius, shadow, ease, animate, font or text. Leave empty for all.'),
111
+ },
112
+ annotations: readOnly,
113
+ },
114
+ ({ group }) => answer(() => getTokens(manifest(), { group })),
115
+ );
116
+
117
+ server.registerTool(
118
+ 'check_usage',
119
+ {
120
+ title: 'Check kit usage',
121
+ description:
122
+ 'Check a template or component against the kit, with the same rules as `sdk-tools check` (kit API, allowed input values, imports, design rules: no raw colors, arbitrary values, inline styles or restyled kit components). Pass a file path inside the app, or a snippet (HTML template or a whole .component.ts). Returns findings with rule, line and message; fix every error and check again. It does not type-check; run `sdk-tools check` for that.',
123
+ inputSchema: {
124
+ file: z.string().optional().describe('A file path relative to the app folder. Example: "src/app/orders/orders.component.html".'),
125
+ snippet: z.string().optional().describe('Template or component source to check without saving it.'),
126
+ language: z.enum(['html', 'ts']).optional().describe('What the snippet is. Default: ts when it has @Component( or imports, else html.'),
127
+ },
128
+ annotations: { readOnlyHint: true, openWorldHint: false },
129
+ },
130
+ ({ file, snippet, language }) =>
131
+ answer(async () => {
132
+ if ((file === undefined) === (snippet === undefined)) throw new NotFoundError('pass either file or snippet (one of them, not both)');
133
+ const { path } = loadManifest({ cwd, manifestPath });
134
+ const result = await checkUsage({ cwd, manifestPath: path, file, snippet, language });
135
+ return { ...result, ok: result.counts.errors === 0 };
136
+ }),
137
+ );
138
+
139
+ server.registerTool(
140
+ 'get_recipe',
141
+ {
142
+ title: 'Get a recipe',
143
+ description: `Get a step-by-step recipe for building something with the kit. Recipes: ${recipes.map((r) => `${r.id} (${r.summary})`).join('; ')}. Call it with no id to list them.`,
144
+ inputSchema: {
145
+ id: z
146
+ .string()
147
+ .optional()
148
+ .describe(`The recipe id: ${recipes.map((r) => r.id).join(', ')}.`),
149
+ },
150
+ annotations: readOnly,
151
+ },
152
+ ({ id }) =>
153
+ answer(() =>
154
+ id
155
+ ? findRecipe(recipes, id)
156
+ : { recipes: recipes.map(({ id: recipeId, title, summary, kitCandidate }) => ({ id: recipeId, title, summary, kitCandidate })) },
157
+ ),
158
+ );
159
+
160
+ server.registerTool(
161
+ 'get_upgrade_guide',
162
+ {
163
+ title: 'Get the upgrade guide',
164
+ description:
165
+ 'Get what moving the app between two @sixbell-telco/sdk versions involves, from the installed SDK: the ng update migrations that would run (sdk-tools upgrade applies them), the steps no migration applies, and the changelog consumer-upgrade steps of every version in between. Use it before or after an upgrade; versions above the installed one are an error (upgrade first).',
166
+ inputSchema: {
167
+ from: z.string().min(1).describe('The version the app is on. Examples: "4.5.0", "3.x".'),
168
+ to: z.string().min(1).describe('The version to move to, at most the installed one. Example: "4.6.0".'),
169
+ },
170
+ annotations: readOnly,
171
+ },
172
+ ({ from, to }) => answer(() => upgradeGuide({ cwd, manifestPath, from, to })),
173
+ );
174
+
175
+ server.registerTool(
176
+ 'get_glossary',
177
+ {
178
+ title: 'Get the kit glossary',
179
+ description:
180
+ 'Get the kit glossary from the installed SDK: each term (surface, role, variant, slot, host, child, finding ...) with its definition, an example and the words not to use for it. Pass a term for one entry, or nothing for all of them. A rejected word (for example `modal`) returns the term to use instead.',
181
+ inputSchema: { term: z.string().optional().describe('One term. Examples: "surface", "menu param". Leave empty for all terms.') },
182
+ annotations: readOnly,
183
+ },
184
+ ({ term }) =>
185
+ answer(() => {
186
+ const { version, entries } = loadGlossary({ cwd, manifestPath });
187
+ return term ? findTerm(entries, term) : { sdkVersion: version, terms: entries };
188
+ }),
189
+ );
190
+
191
+ server.registerResource(
192
+ 'glossary',
193
+ 'sixbell-sdk://glossary',
194
+ {
195
+ title: 'GLOSSARY.md',
196
+ description: 'The kit glossary of the installed SDK: one line per term, with an example and the words not to use.',
197
+ mimeType: 'text/markdown',
198
+ },
199
+ (uri) => {
200
+ let text;
201
+ try {
202
+ text = loadGlossary({ cwd, manifestPath }).text;
203
+ } catch (thrown) {
204
+ text = thrown instanceof Error ? thrown.message : String(thrown);
205
+ }
206
+ return { contents: [{ uri: uri.href, mimeType: 'text/markdown', text }] };
207
+ },
208
+ );
209
+
210
+ server.registerResource(
211
+ 'design',
212
+ 'sixbell-sdk://design',
213
+ { title: 'DESIGN.md', description: "The app's DESIGN.md: the kit's styling, composition and accessibility rules.", mimeType: 'text/markdown' },
214
+ (uri) => {
215
+ const path = join(cwd, 'DESIGN.md');
216
+ const text = existsSync(path)
217
+ ? readFileSync(path, 'utf8')
218
+ : `No DESIGN.md in ${cwd}. Apps built from the MFE templates carry one at the root; copy it from the template the app was created from.`;
219
+ return { contents: [{ uri: uri.href, mimeType: 'text/markdown', text }] };
220
+ },
221
+ );
222
+ for (const recipe of recipes) {
223
+ server.registerResource(
224
+ `recipe-${recipe.id}`,
225
+ `sixbell-sdk://recipes/${recipe.id}`,
226
+ { title: recipe.title, description: recipe.summary, mimeType: 'text/markdown' },
227
+ (uri) => ({ contents: [{ uri: uri.href, mimeType: 'text/markdown', text: `# ${recipe.title}\n\n${recipe.body}\n` }] }),
228
+ );
229
+ }
230
+ return server;
231
+ }
232
+
233
+ /**
234
+ * Serves over stdio until the client disconnects. Library code that logs with console.log would
235
+ * corrupt the protocol on stdout, so console output goes to stderr while the server runs.
236
+ * @param {ServerOptions} options
237
+ * @returns {Promise<void>}
238
+ */
239
+ export async function serve(options) {
240
+ console.log = console.info = console.debug = console.error;
241
+ const server = createServer(options);
242
+ const transport = new StdioServerTransport();
243
+ const closed = new Promise((done) => {
244
+ transport.onclose = () => done(undefined);
245
+ process.stdin.once('end', () => done(undefined));
246
+ });
247
+ await server.connect(transport);
248
+ await closed;
249
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * `get_upgrade_guide`: what moving between two @sixbell-telco/sdk versions involves, read from the
3
+ * SDK installed in the app: the `ng update` migrations that would run (schematics/migration.json),
4
+ * the steps no migration applies (schematics/manual-steps.json) and the changelog's "Consumer
5
+ * upgrade" sections, for every version in (from, to].
6
+ */
7
+ import { existsSync, readFileSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+ import { compareVersions, selectMigrations } from '../upgrade/upgrade.mjs';
10
+ import { NotFoundError } from './catalog.mjs';
11
+ import { loadManifest } from './manifest.mjs';
12
+
13
+ /** @typedef {import('../types.js').UpgradeGuide} UpgradeGuide */
14
+
15
+ /**
16
+ * `4.6.0` as is; a partial version means the newest of its line (`3.x` and `3` are 3.999999.999999).
17
+ * @param {string} value
18
+ * @returns {string | null}
19
+ */
20
+ export function normalizeVersion(value) {
21
+ const match = /^v?(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?$/i.exec(String(value ?? '').trim());
22
+ if (!match) return null;
23
+ const [, major, minor, patch] = match;
24
+ const open = (/** @type {string | undefined} */ part) => part === undefined || /^[x*]$/i.test(part);
25
+ if (open(minor)) return `${major}.999999.999999`;
26
+ return `${major}.${minor}.${open(patch) ? '999999' : patch}`;
27
+ }
28
+
29
+ /**
30
+ * The `### Consumer upgrade` section of each released version in the changelog, as top-level list
31
+ * items with their nested lines. `[Unreleased]` counts as `unreleasedAs` when that version has no
32
+ * heading of its own (a development build of the package).
33
+ * @param {string} changelog
34
+ * @param {string} unreleasedAs
35
+ * @returns {{ versions: string[], sections: Map<string, string[]> }}
36
+ */
37
+ export function consumerUpgradeSections(changelog, unreleasedAs) {
38
+ /** @type {Map<string, string[]>} */
39
+ const sections = new Map();
40
+ const versions = [];
41
+ /** @type {string | null} */
42
+ let version = null;
43
+ let inSection = false;
44
+ /** @type {string[]} */
45
+ let items = [];
46
+ const flush = () => {
47
+ if (version && items.length)
48
+ sections.set(
49
+ version,
50
+ items.map((item) => item.trimEnd()),
51
+ );
52
+ items = [];
53
+ };
54
+ const headings = new Set([...changelog.matchAll(/^## \[(\d+\.\d+\.\d+)\]/gm)].map((m) => m[1]));
55
+ for (const line of changelog.split('\n')) {
56
+ const release = /^## \[([^\]]+)\]/.exec(line);
57
+ if (release) {
58
+ flush();
59
+ inSection = false;
60
+ version = release[1] === 'Unreleased' ? (headings.has(unreleasedAs) ? null : unreleasedAs) : release[1];
61
+ if (version) versions.push(version);
62
+ continue;
63
+ }
64
+ if (/^### /.test(line)) {
65
+ flush();
66
+ inSection = /^### Consumer upgrade\s*$/.test(line);
67
+ continue;
68
+ }
69
+ if (!inSection || !version) continue;
70
+ if (/^(?:- |\d+\. )/.test(line)) items.push(line.replace(/^(?:- |\d+\. )/, ''));
71
+ else if (/^\s+\S/.test(line) && items.length) items[items.length - 1] += `\n${line}`;
72
+ }
73
+ flush();
74
+ return { versions, sections };
75
+ }
76
+
77
+ /**
78
+ * @param {{ cwd: string, manifestPath?: string, from: string, to: string }} options
79
+ * @returns {UpgradeGuide}
80
+ */
81
+ export function upgradeGuide({ cwd, manifestPath, from, to }) {
82
+ const sdkDir = dirname(loadManifest({ cwd, manifestPath }).path);
83
+ const pkg = JSON.parse(readFileSync(join(sdkDir, 'package.json'), 'utf8'));
84
+ const installed = String(pkg.version);
85
+ const low = normalizeVersion(from);
86
+ const high = normalizeVersion(to);
87
+ if (!low || !high) throw new NotFoundError(`"${!low ? from : to}" is not a version. Pass versions like "4.5.0" or "3.x".`);
88
+ if (compareVersions(low, high) >= 0) throw new NotFoundError(`from (${from}) must be older than to (${to}).`);
89
+ if (compareVersions(high, installed) > 0)
90
+ throw new NotFoundError(
91
+ `The installed @sixbell-telco/sdk is ${installed}; its guide covers versions up to ${installed}, not ${to}. Ask for a range up to ${installed}, or upgrade first (npx @sixbell-telco/sdk-tools upgrade --to ${to}) and ask again.`,
92
+ );
93
+ const changelogPath = join(sdkDir, 'CHANGELOG.md');
94
+ const { versions, sections } = consumerUpgradeSections(existsSync(changelogPath) ? readFileSync(changelogPath, 'utf8') : '', installed);
95
+ const known = new Set([...versions, installed]);
96
+ if (!/[x*]|^\d+$/i.test(to.trim()) && !known.has(high))
97
+ throw new NotFoundError(
98
+ `${to} is not a release of @sixbell-telco/sdk known to the installed ${installed} (its changelog lists ${[...known].join(', ')}).`,
99
+ );
100
+ const inRange = (/** @type {string} */ v) => compareVersions(v, low) > 0 && compareVersions(v, high) <= 0;
101
+ const stepsPath = join(sdkDir, 'schematics', 'manual-steps.json');
102
+ /** @type {{ id: string, version: string, step: string }[]} */
103
+ const steps = existsSync(stepsPath) ? JSON.parse(readFileSync(stepsPath, 'utf8')).steps : [];
104
+ return {
105
+ installed,
106
+ from,
107
+ to,
108
+ migrations: selectMigrations(sdkDir, low, high).migrations,
109
+ manualSteps: steps.filter((s) => inRange(s.version)).map(({ id, version, step }) => ({ id, version, step })),
110
+ consumerUpgrade: [...sections]
111
+ .filter(([version]) => inRange(version))
112
+ .sort(([a], [b]) => compareVersions(a, b))
113
+ .map(([version, items]) => ({ version, steps: items })),
114
+ command: `npx @sixbell-telco/sdk-tools upgrade --to ${compareVersions(high, installed) === 0 ? installed : to} --dry-run`,
115
+ };
116
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * check_usage: the lint of `sdk-tools check` (kit API and design rules) on one file of the app or on
3
+ * a snippet. A snippet is written to a temporary folder inside the app, linted there with the same
4
+ * engine (ESLint only lints files under the app's folder, and the design rules need the app's
5
+ * Tailwind entry), and removed, so its findings equal `sdk-tools check <file> --no-typecheck`.
6
+ */
7
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { isAbsolute, join, relative, resolve } from 'node:path';
9
+ import { check } from '../check.mjs';
10
+
11
+ /** @typedef {import('../types.js').CheckResult} CheckResult */
12
+
13
+ /**
14
+ * `ts` for a component file (a `@Component(` decorator or an import), `html` otherwise.
15
+ * @param {string} snippet
16
+ * @returns {'html' | 'ts'}
17
+ */
18
+ export function snippetLanguage(snippet) {
19
+ return /@Component\s*\(|^\s*import\s/m.test(snippet) ? 'ts' : 'html';
20
+ }
21
+
22
+ /**
23
+ * @param {{ cwd: string, manifestPath: string, file?: string, snippet?: string, language?: 'html' | 'ts' }} options
24
+ * @returns {Promise<CheckResult & { checked: string }>}
25
+ */
26
+ export async function checkUsage({ cwd, manifestPath, file, snippet, language }) {
27
+ if ((file === undefined) === (snippet === undefined)) throw new Error('pass either file or snippet, not both');
28
+ if (file !== undefined) {
29
+ const path = resolve(cwd, file);
30
+ const rel = relative(cwd, path);
31
+ if (rel.startsWith('..') || isAbsolute(rel)) throw new Error(`${file} is outside the app folder ${cwd}; pass a path inside it`);
32
+ const result = await check({ cwd, paths: [rel], typecheck: false, manifestPath });
33
+ return { checked: rel, ...result };
34
+ }
35
+ const name = `snippet.component.${language ?? snippetLanguage(snippet ?? '')}`;
36
+ const dir = mkdtempSync(join(cwd, '.sdk-tools-snippet-'));
37
+ try {
38
+ writeFileSync(join(dir, name), snippet ?? '');
39
+ const result = await check({ cwd, paths: [relative(cwd, dir)], typecheck: false, manifestPath });
40
+ return {
41
+ checked: name,
42
+ findings: result.findings.map((f) => ({ ...f, file: f.file ? name : f.file })),
43
+ counts: result.counts,
44
+ };
45
+ } finally {
46
+ rmSync(dir, { recursive: true, force: true });
47
+ }
48
+ }