@sixbell-telco/sdk-tools 0.1.2 → 0.1.4
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.
- package/CHANGELOG.md +20 -0
- package/README.md +10 -2
- package/package.json +2 -4
- package/src/cli.mjs +19 -3
- package/src/mcp/manifest.mjs +51 -2
- package/src/mcp/protocol.mjs +240 -0
- package/src/mcp/recipes.mjs +5 -2
- package/src/mcp/server.mjs +57 -56
- package/src/mcp/usage.mjs +37 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.1.4] - 2026-11-19
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **mcp**: a server stopped while `check_usage` lints a snippet no longer leaves a `.sdk-tools-snippet-*` folder in the app, and a later snippet check removes folders a killed server left more than 10 minutes ago
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- **mcp**: the README and `mcp --help` start a component root's server with `node` and the app's installed sdk-tools (about 35 ms) instead of `npx --prefix`
|
|
19
|
+
|
|
20
|
+
## [0.1.3] - 2026-11-19
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- **mcp**: answers an agent host about 3x faster (about 40 ms to `initialize`, was about 130 ms) through its own stdio layer instead of `@modelcontextprotocol/sdk`, which with `zod` is no longer a dependency; what the host receives is byte for byte the same
|
|
25
|
+
|
|
26
|
+
### Added
|
|
27
|
+
|
|
28
|
+
- **mcp**: `--cwd <dir>` names the app folder; started at a component root, the server finds the one app folder below it (`mfe/`), and the not-installed error names `--cwd` (NSU-142)
|
|
29
|
+
|
|
10
30
|
## [0.1.2] - 2026-11-18
|
|
11
31
|
|
|
12
32
|
### Added
|
package/README.md
CHANGED
|
@@ -110,7 +110,9 @@ Findings have the same shape as `check`'s, plus `repo` (the repo's folder relati
|
|
|
110
110
|
|
|
111
111
|
## mcp
|
|
112
112
|
|
|
113
|
-
`sdk-tools mcp` starts an MCP server over stdio, named `SixbellSdk`. Its tools answer from the `@sixbell-telco/sdk` installed in the folder
|
|
113
|
+
`sdk-tools mcp` starts an MCP server over stdio, named `SixbellSdk`. Its tools answer from the `@sixbell-telco/sdk` installed in the app folder (the SDK's `manifest.json`), so an agent gets the facts of the version the app really uses. `check_usage` runs the same lint as `check`.
|
|
114
|
+
|
|
115
|
+
The app folder is `--cwd <dir>`, else the folder the server starts in when the SDK is installed there, else the one folder directly under it whose `package.json` lists `@sixbell-telco/sdk`. With more than one such folder the tools return an error naming them; pass `--cwd`.
|
|
114
116
|
|
|
115
117
|
Add it to the app's `.mcp.json`:
|
|
116
118
|
|
|
@@ -118,6 +120,12 @@ Add it to the app's `.mcp.json`:
|
|
|
118
120
|
{ "mcpServers": { "SixbellSdk": { "command": "npx", "args": ["@sixbell-telco/sdk-tools", "mcp"] } } }
|
|
119
121
|
```
|
|
120
122
|
|
|
123
|
+
A component repo set (the `.mcp.json` at the component root, the app in `mfe/`) runs the `sdk-tools` the app already has as a devDependency with `node`. It answers in about 35 ms and never downloads the package; on a cold npx cache, `npx -y` can pass an agent host's start limit (Claude Code gives up after 30 seconds). The path is relative to the folder the session opens in:
|
|
124
|
+
|
|
125
|
+
```json
|
|
126
|
+
{ "mcpServers": { "SixbellSdk": { "command": "node", "args": ["mfe/node_modules/@sixbell-telco/sdk-tools/src/cli.mjs", "mcp", "--cwd", "mfe"] } } }
|
|
127
|
+
```
|
|
128
|
+
|
|
121
129
|
| Tool | Returns |
|
|
122
130
|
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
123
131
|
| `list_components` | Every component, directive and pipe: selector, class, kind, entry point, one-line description (`kind` filters) |
|
|
@@ -131,7 +139,7 @@ Add it to the app's `.mcp.json`:
|
|
|
131
139
|
|
|
132
140
|
Resources: `sixbell-sdk://design` (the app's `DESIGN.md`), `sixbell-sdk://glossary` (the installed SDK's `GLOSSARY.md`; an SDK before 4.6.0 gets a one-line message) and `sixbell-sdk://recipes/<id>`. Recipes live in [`recipes/`](recipes), whose README documents the format.
|
|
133
141
|
|
|
134
|
-
A tool that needs the manifest returns an error naming the fix when the SDK is not installed or ships no manifest (SDK 4.6.0 or later). `--manifest <file>` answers from another manifest.
|
|
142
|
+
A tool that needs the manifest returns an error naming the folder and the fix when the SDK is not installed or ships no manifest (SDK 4.6.0 or later). `--manifest <file>` answers from another manifest.
|
|
135
143
|
|
|
136
144
|
## init
|
|
137
145
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sixbell-telco/sdk-tools",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"description": "CLI and MCP server for apps built with @sixbell-telco/sdk: check templates, imports and types against the installed SDK, and create or upgrade MFEs from their template repos",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -27,13 +27,11 @@
|
|
|
27
27
|
"node": "^22.12.0 || ^24.0.0"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
31
30
|
"@sixbell-telco/eslint-plugin-sdk": "0.1.1",
|
|
32
31
|
"angular-eslint": "^19.0.0",
|
|
33
32
|
"eslint": "^9.0.0",
|
|
34
33
|
"shadcn-lint-angular": "0.1.2",
|
|
35
|
-
"typescript-eslint": "^8.0.0"
|
|
36
|
-
"zod": "^4.4.3"
|
|
34
|
+
"typescript-eslint": "^8.0.0"
|
|
37
35
|
},
|
|
38
36
|
"peerDependencies": {
|
|
39
37
|
"@angular-devkit/core": "^19.0.0",
|
package/src/cli.mjs
CHANGED
|
@@ -118,23 +118,39 @@ const VERBS = {
|
|
|
118
118
|
usage: 'sdk-tools mcp [options]',
|
|
119
119
|
help: [
|
|
120
120
|
'Starts an MCP server on stdin/stdout (server name SixbellSdk). Its tools answer from the',
|
|
121
|
-
'@sixbell-telco/sdk installed in the
|
|
121
|
+
'@sixbell-telco/sdk installed in the app folder and run the same checks as sdk-tools check:',
|
|
122
122
|
'list_components, search_components, get_component, get_tokens, check_usage, get_recipe.',
|
|
123
|
-
"Resources: the app's DESIGN.md and the recipes.
|
|
123
|
+
"Resources: the app's DESIGN.md and the recipes.",
|
|
124
|
+
'',
|
|
125
|
+
'The app folder is --cwd, else the current folder when the SDK is installed there, else the',
|
|
126
|
+
'one folder directly under it whose package.json lists @sixbell-telco/sdk (a component root',
|
|
127
|
+
'such as componentes/timezone/ with the app in mfe/). With several such folders, pass --cwd.',
|
|
124
128
|
'',
|
|
125
129
|
'Options:',
|
|
130
|
+
' --cwd <dir> the app folder (relative to the current folder)',
|
|
126
131
|
' --manifest <file> answer from this manifest instead of the installed SDK',
|
|
127
132
|
'',
|
|
128
133
|
'Example (.mcp.json of an app):',
|
|
129
134
|
' { "mcpServers": { "SixbellSdk": { "command": "npx", "args": ["@sixbell-telco/sdk-tools", "mcp"] } } }',
|
|
135
|
+
"Example (.mcp.json of a component root, app in mfe/; runs the app's installed sdk-tools):",
|
|
136
|
+
' { "mcpServers": { "SixbellSdk": { "command": "node",',
|
|
137
|
+
' "args": ["mfe/node_modules/@sixbell-telco/sdk-tools/src/cli.mjs", "mcp", "--cwd", "mfe"] } } }',
|
|
130
138
|
].join('\n'),
|
|
131
139
|
options: {
|
|
140
|
+
cwd: { type: 'string' },
|
|
132
141
|
manifest: { type: 'string' },
|
|
133
142
|
help: { type: 'boolean', short: 'h', default: false },
|
|
134
143
|
},
|
|
135
144
|
async run(values) {
|
|
145
|
+
const { statSync } = await import('node:fs');
|
|
146
|
+
const { resolve } = await import('node:path');
|
|
147
|
+
const explicit = typeof values.cwd === 'string';
|
|
148
|
+
const cwd = resolve(explicit ? /** @type {string} */ (values.cwd) : '.');
|
|
149
|
+
if (explicit && !statSync(cwd, { throwIfNoEntry: false })?.isDirectory()) throw new UsageError(`--cwd ${cwd} is not a folder`);
|
|
136
150
|
const { serve } = await import('./mcp/server.mjs');
|
|
137
|
-
|
|
151
|
+
// --manifest stays relative to where the server starts, not to the app folder.
|
|
152
|
+
const manifestPath = typeof values.manifest === 'string' ? resolve(values.manifest) : undefined;
|
|
153
|
+
await serve({ cwd, explicit, manifestPath });
|
|
138
154
|
// The client is gone: exit without writing to stdout, which carried the protocol.
|
|
139
155
|
process.exit(0);
|
|
140
156
|
},
|
package/src/mcp/manifest.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* The manifest the MCP tools answer from: `@sixbell-telco/sdk/manifest.json` of the SDK installed
|
|
3
3
|
* in the app (resolved from the app's folder), so every answer matches the version the app uses.
|
|
4
4
|
*/
|
|
5
|
-
import { readFileSync } from 'node:fs';
|
|
5
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
6
6
|
import { createRequire } from 'node:module';
|
|
7
7
|
import { join, resolve } from 'node:path';
|
|
8
8
|
|
|
@@ -17,6 +17,55 @@ const SDK = '@sixbell-telco/sdk';
|
|
|
17
17
|
/** A problem the user fixes in the app (install or upgrade the SDK), reported without a stack. */
|
|
18
18
|
export class ManifestError extends Error {}
|
|
19
19
|
|
|
20
|
+
/** @param {string} dir @returns {boolean} the SDK resolves from `dir` (its node_modules or above). */
|
|
21
|
+
function hasSdk(dir) {
|
|
22
|
+
try {
|
|
23
|
+
createRequire(join(dir, 'noop.js')).resolve(`${SDK}/package.json`);
|
|
24
|
+
return true;
|
|
25
|
+
} catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** @param {string} dir @returns {boolean} `dir`/package.json lists the SDK as a dependency. */
|
|
31
|
+
function declaresSdk(dir) {
|
|
32
|
+
try {
|
|
33
|
+
const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
|
|
34
|
+
return [pkg.dependencies, pkg.devDependencies, pkg.peerDependencies].some((deps) => deps && Object.hasOwn(deps, SDK));
|
|
35
|
+
} catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The app folder the server answers for. `cwd` itself when the SDK resolves from it. Otherwise,
|
|
42
|
+
* for a session opened at a component root (`componentes/timezone/` with the app in `mfe/`), the
|
|
43
|
+
* one folder directly under `cwd` whose package.json lists the SDK. Several such folders, or none,
|
|
44
|
+
* is a ManifestError naming them and `--cwd`. `explicit` (from --cwd) skips the search.
|
|
45
|
+
* @param {string} cwd
|
|
46
|
+
* @param {{ explicit?: boolean }} [options]
|
|
47
|
+
* @returns {string}
|
|
48
|
+
*/
|
|
49
|
+
export function findApp(cwd, { explicit = false } = {}) {
|
|
50
|
+
if (explicit || hasSdk(cwd)) return cwd;
|
|
51
|
+
/** @type {string[]} */
|
|
52
|
+
let names = [];
|
|
53
|
+
try {
|
|
54
|
+
names = readdirSync(cwd, { withFileTypes: true })
|
|
55
|
+
.filter((e) => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules' && declaresSdk(join(cwd, e.name)))
|
|
56
|
+
.map((e) => e.name)
|
|
57
|
+
.sort();
|
|
58
|
+
} catch {
|
|
59
|
+
// unreadable: no candidates
|
|
60
|
+
}
|
|
61
|
+
if (names.length === 1) return join(cwd, names[0]);
|
|
62
|
+
if (names.length > 1)
|
|
63
|
+
throw new ManifestError(
|
|
64
|
+
`@sixbell-telco/sdk is not installed in ${cwd}, and more than one folder under it is an app: ${names.join(', ')}. Fix: start the MCP server with --cwd <app folder> (for example sdk-tools mcp --cwd ${names[0]}), then restart the server.`,
|
|
65
|
+
);
|
|
66
|
+
return cwd;
|
|
67
|
+
}
|
|
68
|
+
|
|
20
69
|
/**
|
|
21
70
|
* The installed manifest, or the one at `manifestPath`. Throws ManifestError naming the fix when
|
|
22
71
|
* the SDK is missing or too old to ship a manifest.
|
|
@@ -46,7 +95,7 @@ export function loadManifest({ cwd, manifestPath }) {
|
|
|
46
95
|
throw new ManifestError(
|
|
47
96
|
version
|
|
48
97
|
? `@sixbell-telco/sdk ${version} is installed in ${cwd} but ships no manifest.json (SDK 4.6.0 or later ships it). Fix: npm install @sixbell-telco/sdk@latest, then restart the MCP server.`
|
|
49
|
-
: `@sixbell-telco/sdk is not installed in ${cwd}. Fix: start the MCP server
|
|
98
|
+
: `@sixbell-telco/sdk is not installed in ${cwd}${existsSync(join(cwd, 'package.json')) ? '' : ' or a folder directly under it'}. Fix: start the MCP server with --cwd <app folder> (the one with package.json and node_modules), or run npm install @sixbell-telco/sdk there, then restart the server.`,
|
|
50
99
|
);
|
|
51
100
|
}
|
|
52
101
|
return { path, manifest: JSON.parse(readFileSync(path, 'utf8')) };
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The part of MCP this server uses, over stdio: initialize, ping, tools and resources.
|
|
3
|
+
*
|
|
4
|
+
* Hand-written so `sdk-tools mcp` answers an agent host in tens of milliseconds: the
|
|
5
|
+
* @modelcontextprotocol/sdk McpServer took about 65 ms to load (zod, ajv and the schemas of the
|
|
6
|
+
* whole protocol). What a host receives is held to the bytes the SDK server sent by
|
|
7
|
+
* test/fixtures/mcp-surface.json (tool and resource lists, validation and not-found errors,
|
|
8
|
+
* protocol version negotiation), and the tests drive it with the SDK's own client.
|
|
9
|
+
*/
|
|
10
|
+
import { createInterface } from 'node:readline';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @typedef {{ type: 'text', text: string }} TextContent
|
|
14
|
+
* @typedef {{ content: TextContent[], isError?: boolean }} ToolResult
|
|
15
|
+
* @typedef {{ description?: string, type: 'string', minLength?: number, enum?: string[] }} StringSchema
|
|
16
|
+
* @typedef {{ $schema: string, type: 'object', properties: Record<string, StringSchema>, required?: string[] }} InputSchema
|
|
17
|
+
* @typedef {{ readOnlyHint?: boolean, openWorldHint?: boolean }} ToolAnnotations
|
|
18
|
+
* @typedef {{ title: string, description: string, inputSchema: InputSchema, annotations: ToolAnnotations }} ToolConfig
|
|
19
|
+
* @typedef {{ title: string, description: string, mimeType: string }} ResourceConfig
|
|
20
|
+
* @typedef {{ uri: string, mimeType: string, text: string }} ResourceContent
|
|
21
|
+
* @typedef {{ jsonrpc?: string, id?: string | number, method?: string, params?: any }} Message
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** The protocol versions the SDK server accepted, newest first; any other gets the newest. */
|
|
25
|
+
const SUPPORTED_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];
|
|
26
|
+
|
|
27
|
+
/** A string the tool may go without. */
|
|
28
|
+
export function optionalString(/** @type {string} */ description, /** @type {string[]} */ values = []) {
|
|
29
|
+
/** @type {StringSchema} */
|
|
30
|
+
const schema = { description, type: 'string' };
|
|
31
|
+
if (values.length) schema.enum = values;
|
|
32
|
+
return schema;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A string the tool needs, not empty. */
|
|
36
|
+
export function requiredString(/** @type {string} */ description) {
|
|
37
|
+
return /** @type {StringSchema} */ ({ type: 'string', minLength: 1, description });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* A tool's input: an object of string properties; the required ones are those with minLength.
|
|
42
|
+
* @param {Record<string, StringSchema>} properties
|
|
43
|
+
* @returns {InputSchema}
|
|
44
|
+
*/
|
|
45
|
+
export function inputSchema(properties) {
|
|
46
|
+
const required = Object.keys(properties).filter((key) => properties[key].minLength !== undefined);
|
|
47
|
+
return {
|
|
48
|
+
$schema: 'http://json-schema.org/draft-07/schema#',
|
|
49
|
+
type: 'object',
|
|
50
|
+
properties,
|
|
51
|
+
...(required.length ? { required } : {}),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** @param {unknown} value */
|
|
56
|
+
function typeName(value) {
|
|
57
|
+
if (value === null) return 'null';
|
|
58
|
+
if (Array.isArray(value)) return 'array';
|
|
59
|
+
if (typeof value === 'number' && Number.isNaN(value)) return 'nan';
|
|
60
|
+
return typeof value;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The problems of `args` against `schema`, one line each, in property order (the wording the SDK
|
|
65
|
+
* server's validation gave, so an agent that retries sees the same text).
|
|
66
|
+
* @param {InputSchema} schema
|
|
67
|
+
* @param {Record<string, unknown>} args
|
|
68
|
+
* @returns {string[]}
|
|
69
|
+
*/
|
|
70
|
+
function validate(schema, args) {
|
|
71
|
+
const required = new Set(schema.required ?? []);
|
|
72
|
+
/** @type {string[]} */
|
|
73
|
+
const problems = [];
|
|
74
|
+
for (const [key, property] of Object.entries(schema.properties)) {
|
|
75
|
+
const value = args[key];
|
|
76
|
+
if (value === undefined && !required.has(key)) continue;
|
|
77
|
+
if (property.enum) {
|
|
78
|
+
if (!property.enum.includes(/** @type {string} */ (value)))
|
|
79
|
+
problems.push(`Invalid option: expected one of ${property.enum.map((v) => JSON.stringify(v)).join('|')} at ${key}`);
|
|
80
|
+
} else if (typeof value !== 'string') {
|
|
81
|
+
problems.push(`Invalid input: expected string, received ${typeName(value)} at ${key}`);
|
|
82
|
+
// zod still ran the length check on an array, so a short one got a second line.
|
|
83
|
+
if (Array.isArray(value) && property.minLength !== undefined && value.length < property.minLength)
|
|
84
|
+
problems.push(`Too small: expected array to have >=${property.minLength} items at ${key}`);
|
|
85
|
+
} else if (property.minLength !== undefined && value.length < property.minLength)
|
|
86
|
+
problems.push(`Too small: expected string to have >=${property.minLength} characters at ${key}`);
|
|
87
|
+
}
|
|
88
|
+
return problems;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A JSON-RPC error answered to a request. */
|
|
92
|
+
class RpcError extends Error {
|
|
93
|
+
/** @param {number} code @param {string} message */
|
|
94
|
+
constructor(code, message) {
|
|
95
|
+
super(message);
|
|
96
|
+
this.code = code;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** An MCP server with tools and fixed-URI resources, answering one JSON-RPC message at a time. */
|
|
101
|
+
export class Server {
|
|
102
|
+
/** @type {Map<string, { config: ToolConfig, run: (args: any) => Promise<ToolResult> }>} */
|
|
103
|
+
#tools = new Map();
|
|
104
|
+
/** @type {Map<string, { name: string, config: ResourceConfig, read: (uri: URL) => { contents: ResourceContent[] } }>} */
|
|
105
|
+
#resources = new Map();
|
|
106
|
+
|
|
107
|
+
/** @param {{ name: string, version: string, instructions: string }} info */
|
|
108
|
+
constructor(info) {
|
|
109
|
+
this.info = info;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @param {string} name
|
|
114
|
+
* @param {ToolConfig} config
|
|
115
|
+
* @param {(args: any) => Promise<ToolResult>} run
|
|
116
|
+
*/
|
|
117
|
+
registerTool(name, config, run) {
|
|
118
|
+
this.#tools.set(name, { config, run });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* @param {string} name
|
|
123
|
+
* @param {string} uri
|
|
124
|
+
* @param {ResourceConfig} config
|
|
125
|
+
* @param {(uri: URL) => { contents: ResourceContent[] }} read
|
|
126
|
+
*/
|
|
127
|
+
registerResource(name, uri, config, read) {
|
|
128
|
+
this.#resources.set(uri, { name, config, read });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The response line for one incoming message, or null for a notification or a response.
|
|
133
|
+
* @param {Message} message
|
|
134
|
+
* @returns {Promise<string | null>}
|
|
135
|
+
*/
|
|
136
|
+
async handle(message) {
|
|
137
|
+
if (message === null || typeof message !== 'object' || message.id === undefined || typeof message.method !== 'string') return null;
|
|
138
|
+
const { id } = message;
|
|
139
|
+
try {
|
|
140
|
+
const result = await this.#answer(message.method, message.params ?? {});
|
|
141
|
+
return JSON.stringify({ result, jsonrpc: '2.0', id });
|
|
142
|
+
} catch (thrown) {
|
|
143
|
+
if (!(thrown instanceof RpcError)) throw thrown;
|
|
144
|
+
return JSON.stringify({ jsonrpc: '2.0', id, error: { code: thrown.code, message: thrown.message } });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** @param {string} method @param {any} params */
|
|
149
|
+
async #answer(method, params) {
|
|
150
|
+
switch (method) {
|
|
151
|
+
case 'initialize':
|
|
152
|
+
return {
|
|
153
|
+
protocolVersion: SUPPORTED_VERSIONS.includes(params.protocolVersion) ? params.protocolVersion : SUPPORTED_VERSIONS[0],
|
|
154
|
+
capabilities: { tools: { listChanged: true }, resources: { listChanged: true } },
|
|
155
|
+
serverInfo: { name: this.info.name, version: this.info.version },
|
|
156
|
+
instructions: this.info.instructions,
|
|
157
|
+
};
|
|
158
|
+
case 'ping':
|
|
159
|
+
return {};
|
|
160
|
+
case 'tools/list':
|
|
161
|
+
return {
|
|
162
|
+
tools: [...this.#tools].map(([name, { config }]) => ({
|
|
163
|
+
name,
|
|
164
|
+
title: config.title,
|
|
165
|
+
description: config.description,
|
|
166
|
+
inputSchema: config.inputSchema,
|
|
167
|
+
annotations: config.annotations,
|
|
168
|
+
execution: { taskSupport: 'forbidden' },
|
|
169
|
+
})),
|
|
170
|
+
};
|
|
171
|
+
case 'tools/call':
|
|
172
|
+
return this.#call(params.name, params.arguments ?? {});
|
|
173
|
+
case 'resources/list':
|
|
174
|
+
return {
|
|
175
|
+
resources: [...this.#resources].map(([uri, { name, config }]) => ({
|
|
176
|
+
uri,
|
|
177
|
+
name,
|
|
178
|
+
title: config.title,
|
|
179
|
+
description: config.description,
|
|
180
|
+
mimeType: config.mimeType,
|
|
181
|
+
})),
|
|
182
|
+
};
|
|
183
|
+
case 'resources/templates/list':
|
|
184
|
+
return { resourceTemplates: [] };
|
|
185
|
+
case 'resources/read': {
|
|
186
|
+
const resource = this.#resources.get(params.uri);
|
|
187
|
+
if (!resource) throw new RpcError(-32602, `MCP error -32602: Resource ${params.uri} not found`);
|
|
188
|
+
return resource.read(new URL(params.uri));
|
|
189
|
+
}
|
|
190
|
+
default:
|
|
191
|
+
throw new RpcError(-32601, 'Method not found');
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* @param {string} name
|
|
197
|
+
* @param {Record<string, unknown>} args
|
|
198
|
+
* @returns {Promise<ToolResult>}
|
|
199
|
+
*/
|
|
200
|
+
async #call(name, args) {
|
|
201
|
+
const tool = this.#tools.get(name);
|
|
202
|
+
/** @param {string} text */
|
|
203
|
+
const failed = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text: `MCP error -32602: ${text}` }], isError: true });
|
|
204
|
+
if (!tool) return failed(`Tool ${name} not found`);
|
|
205
|
+
const problems = validate(tool.config.inputSchema, args);
|
|
206
|
+
if (problems.length) return failed(`Input validation error: Invalid arguments for tool ${name}: ${problems.join('\n')}`);
|
|
207
|
+
// Like the SDK, the tool gets only the properties it declares.
|
|
208
|
+
const known = Object.fromEntries(
|
|
209
|
+
Object.keys(tool.config.inputSchema.properties)
|
|
210
|
+
.filter((k) => args[k] !== undefined)
|
|
211
|
+
.map((k) => [k, args[k]]),
|
|
212
|
+
);
|
|
213
|
+
return tool.run(known);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Reads newline-delimited JSON-RPC from `input` and writes each answer to `output` as soon as
|
|
218
|
+
* it is ready, until `input` ends. A line that is not JSON gets no answer, as with the SDK.
|
|
219
|
+
* @param {NodeJS.ReadableStream} input
|
|
220
|
+
* @param {NodeJS.WritableStream} output
|
|
221
|
+
* @returns {Promise<void>}
|
|
222
|
+
*/
|
|
223
|
+
serve(input, output) {
|
|
224
|
+
const lines = createInterface({ input, crlfDelay: Infinity });
|
|
225
|
+
lines.on('line', (line) => {
|
|
226
|
+
if (!line.trim()) return;
|
|
227
|
+
let message;
|
|
228
|
+
try {
|
|
229
|
+
message = JSON.parse(line);
|
|
230
|
+
} catch {
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
this.handle(message).then(
|
|
234
|
+
(answer) => answer && output.write(`${answer}\n`),
|
|
235
|
+
(thrown) => console.error(`sdk-tools mcp: ${thrown instanceof Error ? thrown.stack : thrown}`),
|
|
236
|
+
);
|
|
237
|
+
});
|
|
238
|
+
return new Promise((done) => lines.once('close', () => done()));
|
|
239
|
+
}
|
|
240
|
+
}
|
package/src/mcp/recipes.mjs
CHANGED
|
@@ -172,16 +172,19 @@ function withFiles(recipe, dir) {
|
|
|
172
172
|
|
|
173
173
|
/**
|
|
174
174
|
* Every recipe in `dir`, sorted by id. README.md documents the format and is not a recipe.
|
|
175
|
+
* `files: false` skips reading the template parts (`files` and `i18nKeys` stay empty): the MCP
|
|
176
|
+
* server lists recipes at startup and reads the parts on the first get_recipe call.
|
|
175
177
|
* @param {string} [dir]
|
|
178
|
+
* @param {{ files?: boolean }} [options]
|
|
176
179
|
* @returns {Recipe[]}
|
|
177
180
|
*/
|
|
178
|
-
export function loadRecipes(dir = RECIPES_DIR) {
|
|
181
|
+
export function loadRecipes(dir = RECIPES_DIR, { files = true } = {}) {
|
|
179
182
|
return readdirSync(dir)
|
|
180
183
|
.filter((name) => name.endsWith('.md') && name !== 'README.md')
|
|
181
184
|
.map((name) => {
|
|
182
185
|
const recipe = parseRecipe(readFileSync(join(dir, name), 'utf8'), name);
|
|
183
186
|
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);
|
|
187
|
+
return files ? withFiles(recipe, dir) : recipe;
|
|
185
188
|
})
|
|
186
189
|
.sort((a, b) => a.id.localeCompare(b.id));
|
|
187
190
|
}
|
package/src/mcp/server.mjs
CHANGED
|
@@ -3,21 +3,17 @@
|
|
|
3
3
|
* Every answer comes from the SDK installed in the app (its manifest) and the same check engine as
|
|
4
4
|
* `sdk-tools check`, so it matches the kit version the app really uses.
|
|
5
5
|
*/
|
|
6
|
-
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
7
|
-
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
8
6
|
import { existsSync, readFileSync } from 'node:fs';
|
|
9
7
|
import { join } from 'node:path';
|
|
10
|
-
import { z } from 'zod';
|
|
11
8
|
import { getComponent, getTokens, listComponents, NotFoundError, searchComponents } from './catalog.mjs';
|
|
12
9
|
import { findTerm, GlossaryError, loadGlossary } from './glossary.mjs';
|
|
13
|
-
import { loadManifest, ManifestError } from './manifest.mjs';
|
|
10
|
+
import { findApp, loadManifest, ManifestError } from './manifest.mjs';
|
|
11
|
+
import { inputSchema, optionalString, requiredString, Server } from './protocol.mjs';
|
|
14
12
|
import { findRecipe, loadRecipes } from './recipes.mjs';
|
|
15
|
-
import { upgradeGuide } from './upgrade-guide.mjs';
|
|
16
|
-
import { checkUsage } from './usage.mjs';
|
|
17
13
|
|
|
18
14
|
/**
|
|
19
|
-
* @typedef {import('
|
|
20
|
-
* @typedef {{ cwd: string, manifestPath?: string }} ServerOptions
|
|
15
|
+
* @typedef {import('./protocol.mjs').ToolResult} CallToolResult
|
|
16
|
+
* @typedef {{ cwd: string, explicit?: boolean, manifestPath?: string }} ServerOptions
|
|
21
17
|
*/
|
|
22
18
|
|
|
23
19
|
/** The server name agents see: its tools show up as `SixbellSdk:<tool>`. */
|
|
@@ -41,25 +37,31 @@ async function answer(body) {
|
|
|
41
37
|
} catch (thrown) {
|
|
42
38
|
const known = thrown instanceof ManifestError || thrown instanceof NotFoundError || thrown instanceof GlossaryError;
|
|
43
39
|
const message = thrown instanceof Error ? thrown.message : String(thrown);
|
|
44
|
-
return {
|
|
40
|
+
return { content: [{ type: 'text', text: known ? message : `sdk-tools failed: ${message}` }], isError: true };
|
|
45
41
|
}
|
|
46
42
|
}
|
|
47
43
|
|
|
48
44
|
/**
|
|
49
45
|
* The configured server (not yet connected), for `serve`.
|
|
50
46
|
* @param {ServerOptions} options
|
|
51
|
-
* @returns {
|
|
47
|
+
* @returns {Server}
|
|
52
48
|
*/
|
|
53
|
-
function createServer({ cwd, manifestPath }) {
|
|
54
|
-
const server = new
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
)
|
|
61
|
-
|
|
62
|
-
const
|
|
49
|
+
function createServer({ cwd: start, explicit = false, manifestPath }) {
|
|
50
|
+
const server = new Server({
|
|
51
|
+
name: SERVER_NAME,
|
|
52
|
+
version: version(),
|
|
53
|
+
instructions:
|
|
54
|
+
'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.',
|
|
55
|
+
});
|
|
56
|
+
// The app folder: the start folder, or the one app directly under it (a component root).
|
|
57
|
+
// Found on each call, so installing the SDK or adding the app needs no restart.
|
|
58
|
+
const app = () => findApp(start, { explicit });
|
|
59
|
+
const manifest = () => loadManifest({ cwd: app(), manifestPath }).manifest;
|
|
60
|
+
// Ids, titles and bodies now; the files and i18n keys get_recipe returns on its first call.
|
|
61
|
+
const recipes = loadRecipes(undefined, { files: false });
|
|
62
|
+
/** @type {ReturnType<typeof loadRecipes> | undefined} */
|
|
63
|
+
let withFiles;
|
|
64
|
+
const fullRecipes = () => (withFiles ??= loadRecipes());
|
|
63
65
|
const readOnly = { readOnlyHint: true, openWorldHint: false };
|
|
64
66
|
|
|
65
67
|
server.registerTool(
|
|
@@ -68,7 +70,7 @@ function createServer({ cwd, manifestPath }) {
|
|
|
68
70
|
title: 'List kit components',
|
|
69
71
|
description:
|
|
70
72
|
"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:
|
|
73
|
+
inputSchema: inputSchema({ kind: optionalString('Only this kind. Leave empty for all.', ['component', 'directive', 'pipe']) }),
|
|
72
74
|
annotations: readOnly,
|
|
73
75
|
},
|
|
74
76
|
({ kind }) => answer(() => listComponents(manifest(), { kind })),
|
|
@@ -80,7 +82,7 @@ function createServer({ cwd, manifestPath }) {
|
|
|
80
82
|
title: 'Search kit components',
|
|
81
83
|
description:
|
|
82
84
|
'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:
|
|
85
|
+
inputSchema: inputSchema({ query: requiredString('What you need, in a few words. Example: "confirm dialog".') }),
|
|
84
86
|
annotations: readOnly,
|
|
85
87
|
},
|
|
86
88
|
({ query }) => answer(() => searchComponents(manifest(), query)),
|
|
@@ -92,9 +94,9 @@ function createServer({ cwd, manifestPath }) {
|
|
|
92
94
|
title: 'Get a kit component',
|
|
93
95
|
description:
|
|
94
96
|
"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:
|
|
97
|
-
},
|
|
97
|
+
inputSchema: inputSchema({
|
|
98
|
+
selector: requiredString('The selector or class name. Examples: "st-dialog", "dialog", "DialogComponent", "stTextColor".'),
|
|
99
|
+
}),
|
|
98
100
|
annotations: readOnly,
|
|
99
101
|
},
|
|
100
102
|
({ selector }) => answer(() => getComponent(manifest(), selector)),
|
|
@@ -106,9 +108,9 @@ function createServer({ cwd, manifestPath }) {
|
|
|
106
108
|
title: 'Get theme tokens',
|
|
107
109
|
description:
|
|
108
110
|
'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:
|
|
111
|
-
},
|
|
111
|
+
inputSchema: inputSchema({
|
|
112
|
+
group: optionalString('Only one group: color, radius, shadow, ease, animate, font or text. Leave empty for all.'),
|
|
113
|
+
}),
|
|
112
114
|
annotations: readOnly,
|
|
113
115
|
},
|
|
114
116
|
({ group }) => answer(() => getTokens(manifest(), { group })),
|
|
@@ -120,17 +122,19 @@ function createServer({ cwd, manifestPath }) {
|
|
|
120
122
|
title: 'Check kit usage',
|
|
121
123
|
description:
|
|
122
124
|
'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:
|
|
125
|
-
snippet:
|
|
126
|
-
language:
|
|
127
|
-
},
|
|
125
|
+
inputSchema: inputSchema({
|
|
126
|
+
file: optionalString('A file path relative to the app folder. Example: "src/app/orders/orders.component.html".'),
|
|
127
|
+
snippet: optionalString('Template or component source to check without saving it.'),
|
|
128
|
+
language: optionalString('What the snippet is. Default: ts when it has @Component( or imports, else html.', ['html', 'ts']),
|
|
129
|
+
}),
|
|
128
130
|
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
129
131
|
},
|
|
130
132
|
({ file, snippet, language }) =>
|
|
131
133
|
answer(async () => {
|
|
132
134
|
if ((file === undefined) === (snippet === undefined)) throw new NotFoundError('pass either file or snippet (one of them, not both)');
|
|
135
|
+
const cwd = app();
|
|
133
136
|
const { path } = loadManifest({ cwd, manifestPath });
|
|
137
|
+
const { checkUsage } = await import('./usage.mjs');
|
|
134
138
|
const result = await checkUsage({ cwd, manifestPath: path, file, snippet, language });
|
|
135
139
|
return { ...result, ok: result.counts.errors === 0 };
|
|
136
140
|
}),
|
|
@@ -141,18 +145,13 @@ function createServer({ cwd, manifestPath }) {
|
|
|
141
145
|
{
|
|
142
146
|
title: 'Get a recipe',
|
|
143
147
|
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
|
-
},
|
|
148
|
+
inputSchema: inputSchema({ id: optionalString(`The recipe id: ${recipes.map((r) => r.id).join(', ')}.`) }),
|
|
150
149
|
annotations: readOnly,
|
|
151
150
|
},
|
|
152
151
|
({ id }) =>
|
|
153
152
|
answer(() =>
|
|
154
153
|
id
|
|
155
|
-
? findRecipe(
|
|
154
|
+
? findRecipe(fullRecipes(), id)
|
|
156
155
|
: { recipes: recipes.map(({ id: recipeId, title, summary, kitCandidate }) => ({ id: recipeId, title, summary, kitCandidate })) },
|
|
157
156
|
),
|
|
158
157
|
);
|
|
@@ -163,13 +162,13 @@ function createServer({ cwd, manifestPath }) {
|
|
|
163
162
|
title: 'Get the upgrade guide',
|
|
164
163
|
description:
|
|
165
164
|
'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:
|
|
168
|
-
to:
|
|
169
|
-
},
|
|
165
|
+
inputSchema: inputSchema({
|
|
166
|
+
from: requiredString('The version the app is on. Examples: "4.5.0", "3.x".'),
|
|
167
|
+
to: requiredString('The version to move to, at most the installed one. Example: "4.6.0".'),
|
|
168
|
+
}),
|
|
170
169
|
annotations: readOnly,
|
|
171
170
|
},
|
|
172
|
-
({ from, to }) => answer(() => upgradeGuide({ cwd, manifestPath, from, to })),
|
|
171
|
+
({ from, to }) => answer(async () => (await import('./upgrade-guide.mjs')).upgradeGuide({ cwd: app(), manifestPath, from, to })),
|
|
173
172
|
);
|
|
174
173
|
|
|
175
174
|
server.registerTool(
|
|
@@ -178,12 +177,12 @@ function createServer({ cwd, manifestPath }) {
|
|
|
178
177
|
title: 'Get the kit glossary',
|
|
179
178
|
description:
|
|
180
179
|
'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:
|
|
180
|
+
inputSchema: inputSchema({ term: optionalString('One term. Examples: "surface", "menu param". Leave empty for all terms.') }),
|
|
182
181
|
annotations: readOnly,
|
|
183
182
|
},
|
|
184
183
|
({ term }) =>
|
|
185
184
|
answer(() => {
|
|
186
|
-
const { version, entries } = loadGlossary({ cwd, manifestPath });
|
|
185
|
+
const { version, entries } = loadGlossary({ cwd: app(), manifestPath });
|
|
187
186
|
return term ? findTerm(entries, term) : { sdkVersion: version, terms: entries };
|
|
188
187
|
}),
|
|
189
188
|
);
|
|
@@ -199,7 +198,7 @@ function createServer({ cwd, manifestPath }) {
|
|
|
199
198
|
(uri) => {
|
|
200
199
|
let text;
|
|
201
200
|
try {
|
|
202
|
-
text = loadGlossary({ cwd, manifestPath }).text;
|
|
201
|
+
text = loadGlossary({ cwd: app(), manifestPath }).text;
|
|
203
202
|
} catch (thrown) {
|
|
204
203
|
text = thrown instanceof Error ? thrown.message : String(thrown);
|
|
205
204
|
}
|
|
@@ -212,6 +211,12 @@ function createServer({ cwd, manifestPath }) {
|
|
|
212
211
|
'sixbell-sdk://design',
|
|
213
212
|
{ title: 'DESIGN.md', description: "The app's DESIGN.md: the kit's styling, composition and accessibility rules.", mimeType: 'text/markdown' },
|
|
214
213
|
(uri) => {
|
|
214
|
+
let cwd;
|
|
215
|
+
try {
|
|
216
|
+
cwd = app();
|
|
217
|
+
} catch (thrown) {
|
|
218
|
+
return { contents: [{ uri: uri.href, mimeType: 'text/markdown', text: thrown instanceof Error ? thrown.message : String(thrown) }] };
|
|
219
|
+
}
|
|
215
220
|
const path = join(cwd, 'DESIGN.md');
|
|
216
221
|
const text = existsSync(path)
|
|
217
222
|
? readFileSync(path, 'utf8')
|
|
@@ -238,12 +243,8 @@ function createServer({ cwd, manifestPath }) {
|
|
|
238
243
|
*/
|
|
239
244
|
export async function serve(options) {
|
|
240
245
|
console.log = console.info = console.debug = console.error;
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
const
|
|
244
|
-
|
|
245
|
-
process.stdin.once('end', () => done(undefined));
|
|
246
|
-
});
|
|
247
|
-
await server.connect(transport);
|
|
248
|
-
await closed;
|
|
246
|
+
// A host stops the server with a signal; exiting normally runs the exit handlers, which remove a
|
|
247
|
+
// snippet folder check_usage is still linting.
|
|
248
|
+
for (const signal of /** @type {const} */ (['SIGTERM', 'SIGINT', 'SIGHUP'])) process.once(signal, () => process.exit(0));
|
|
249
|
+
await createServer(options).serve(process.stdin, process.stdout);
|
|
249
250
|
}
|
package/src/mcp/usage.mjs
CHANGED
|
@@ -4,12 +4,44 @@
|
|
|
4
4
|
* engine (ESLint only lints files under the app's folder, and the design rules need the app's
|
|
5
5
|
* Tailwind entry), and removed, so its findings equal `sdk-tools check <file> --no-typecheck`.
|
|
6
6
|
*/
|
|
7
|
-
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
8
8
|
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
9
9
|
import { check } from '../check.mjs';
|
|
10
10
|
|
|
11
11
|
/** @typedef {import('../types.js').CheckResult} CheckResult */
|
|
12
12
|
|
|
13
|
+
const SNIPPET_PREFIX = '.sdk-tools-snippet-';
|
|
14
|
+
/** A snippet folder older than this was left by a server that was killed mid-check. */
|
|
15
|
+
const STALE_MS = 10 * 60 * 1000;
|
|
16
|
+
|
|
17
|
+
/** Snippet folders being linted now; removed on exit if the check never got to its finally. */
|
|
18
|
+
const live = new Set();
|
|
19
|
+
process.once('exit', () => {
|
|
20
|
+
for (const dir of live) rmSync(dir, { recursive: true, force: true });
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Removes snippet folders in `cwd` that a killed server left behind (SIGKILL, a crash). Only old
|
|
25
|
+
* ones: a newer folder may belong to another server checking right now.
|
|
26
|
+
* @param {string} cwd
|
|
27
|
+
*/
|
|
28
|
+
function sweepStale(cwd) {
|
|
29
|
+
let names;
|
|
30
|
+
try {
|
|
31
|
+
names = readdirSync(cwd).filter((name) => name.startsWith(SNIPPET_PREFIX));
|
|
32
|
+
} catch {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
for (const name of names) {
|
|
36
|
+
const dir = join(cwd, name);
|
|
37
|
+
try {
|
|
38
|
+
if (Date.now() - statSync(dir).mtimeMs > STALE_MS) rmSync(dir, { recursive: true, force: true });
|
|
39
|
+
} catch {
|
|
40
|
+
// gone already
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
13
45
|
/**
|
|
14
46
|
* `ts` for a component file (a `@Component(` decorator or an import), `html` otherwise.
|
|
15
47
|
* @param {string} snippet
|
|
@@ -33,7 +65,9 @@ export async function checkUsage({ cwd, manifestPath, file, snippet, language })
|
|
|
33
65
|
return { checked: rel, ...result };
|
|
34
66
|
}
|
|
35
67
|
const name = `snippet.component.${language ?? snippetLanguage(snippet ?? '')}`;
|
|
36
|
-
|
|
68
|
+
sweepStale(cwd);
|
|
69
|
+
const dir = mkdtempSync(join(cwd, SNIPPET_PREFIX));
|
|
70
|
+
live.add(dir);
|
|
37
71
|
try {
|
|
38
72
|
writeFileSync(join(dir, name), snippet ?? '');
|
|
39
73
|
const result = await check({ cwd, paths: [relative(cwd, dir)], typecheck: false, manifestPath });
|
|
@@ -44,5 +78,6 @@ export async function checkUsage({ cwd, manifestPath, file, snippet, language })
|
|
|
44
78
|
};
|
|
45
79
|
} finally {
|
|
46
80
|
rmSync(dir, { recursive: true, force: true });
|
|
81
|
+
live.delete(dir);
|
|
47
82
|
}
|
|
48
83
|
}
|