@punica/form-mcp 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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +49 -2
  3. package/bundled/form/controller/index.d.ts +73 -0
  4. package/bundled/form/decorator/Readers.d.ts +9 -0
  5. package/bundled/form/decorator/Services.d.ts +9 -0
  6. package/bundled/form/decorator/Starters.d.ts +9 -0
  7. package/bundled/form/decorator/index.d.ts +3 -0
  8. package/bundled/form/define/FormItem.d.ts +9 -0
  9. package/bundled/form/define/FormItemProperty.d.ts +8 -0
  10. package/bundled/form/define/FormProperty.d.ts +7 -0
  11. package/bundled/form/define/index.d.ts +3 -0
  12. package/bundled/form/index.d.ts +7 -0
  13. package/bundled/form/model/command/index.d.ts +2 -0
  14. package/bundled/form/model/command/item.d.ts +7 -0
  15. package/bundled/form/model/command/service.d.ts +15 -0
  16. package/bundled/form/model/constants/index.d.ts +4 -0
  17. package/bundled/form/model/form/index.d.ts +8 -0
  18. package/bundled/form/model/index.d.ts +8 -0
  19. package/bundled/form/model/item/index.d.ts +25 -0
  20. package/bundled/form/model/reader/index.d.ts +4 -0
  21. package/bundled/form/model/service/index.d.ts +20 -0
  22. package/bundled/form/model/starter/index.d.ts +13 -0
  23. package/bundled/form/model/util/GetItem.d.ts +9 -0
  24. package/bundled/form/model/util/WriteItems.d.ts +8 -0
  25. package/bundled/form/model/util/index.d.ts +2 -0
  26. package/bundled/form/package.json +1 -0
  27. package/bundled/form/reader/decorators/base/index.d.ts +35 -0
  28. package/bundled/form/reader/decorators/readers/FormItemsReader.d.ts +17 -0
  29. package/bundled/form/reader/decorators/readers/ItemDataReader.d.ts +24 -0
  30. package/bundled/form/reader/decorators/readers/ItemInitializerReader.d.ts +16 -0
  31. package/bundled/form/reader/decorators/readers/index.d.ts +3 -0
  32. package/bundled/form/reader/index.d.ts +19 -0
  33. package/bundled/form/reader/reader/Reader.d.ts +13 -0
  34. package/bundled/form/reader/reader/index.d.ts +1 -0
  35. package/bundled/form/register/index.d.ts +43 -0
  36. package/bundled/form/utils/deepCopy.d.ts +8 -0
  37. package/bundled/form/utils/devtools.d.ts +77 -0
  38. package/bundled/form/utils/index.d.ts +2 -0
  39. package/bundled/form-service/clearError/index.d.ts +23 -0
  40. package/bundled/form-service/clearErrors/index.d.ts +22 -0
  41. package/bundled/form-service/getValues/index.d.ts +22 -0
  42. package/bundled/form-service/index.d.ts +9 -0
  43. package/bundled/form-service/package.json +1 -0
  44. package/bundled/form-service/reset/index.d.ts +22 -0
  45. package/bundled/form-service/resetItem/index.d.ts +23 -0
  46. package/bundled/form-service/setValue/index.d.ts +23 -0
  47. package/bundled/form-service/store/index.d.ts +30 -0
  48. package/bundled/form-service/trigger/index.d.ts +22 -0
  49. package/bundled/form-service/validate/index.d.ts +27 -0
  50. package/package.json +46 -3
  51. package/src/create.mjs +128 -0
  52. package/src/guide.md +160 -0
  53. package/src/knowledge.mjs +141 -0
  54. package/src/load.mjs +41 -0
  55. package/src/main.mjs +12 -0
  56. package/src/validate.mjs +98 -0
@@ -0,0 +1,141 @@
1
+ // What a tool needs to know about the public API of the Punica Form packages,
2
+ // read from their type declarations (.d.ts). Pure: it works on file contents,
3
+ // so the server, the build and the tests share it.
4
+
5
+ export const DOCS_URL = 'https://form.punicalab.com';
6
+
7
+ const DECLARATION =
8
+ /^export (?:declare )?(?:abstract )?(class|const|function|type|interface|enum) (\w+)/gm;
9
+
10
+ /** The module a relative specifier points to: `./x.d.ts` or `./x/index.d.ts`. */
11
+ function resolve(files, from, specifier) {
12
+ const base = new URL(specifier, `file:///${from}`).pathname.slice(1);
13
+
14
+ return [`${base}.d.ts`, `${base}/index.d.ts`].find((path) => files.has(path));
15
+ }
16
+
17
+ /** The JSDoc comment that ends right before `index`, if there is one. */
18
+ function commentBefore(source, index) {
19
+ const match = /\/\*\*(?:(?!\*\/)[\s\S])*\*\/\s*$/.exec(source.slice(0, index));
20
+
21
+ return match ? match[0].trimEnd() : '';
22
+ }
23
+
24
+ /** The declaration that starts at `index`: up to its closing brace or semicolon. */
25
+ function declarationAt(source, index) {
26
+ let depth = 0;
27
+
28
+ for (let i = index; i < source.length; i++) {
29
+ const char = source[i];
30
+
31
+ if ('({['.includes(char)) depth++;
32
+ if (')}]'.includes(char)) depth--;
33
+ if (depth === 0 && (char === ';' || char === '}')) {
34
+ return source.slice(index, i + 1);
35
+ }
36
+ }
37
+
38
+ return source.slice(index);
39
+ }
40
+
41
+ function entry(source, index, kind, name) {
42
+ const comment = commentBefore(source, index);
43
+ const summary = (/^\s*\/?\*+\s*([^@*\n][^\n]*)/m.exec(comment) || [])[1] || '';
44
+
45
+ return {
46
+ name,
47
+ kind,
48
+ summary: summary.trim(),
49
+ declaration: [comment, declarationAt(source, index)].filter(Boolean).join('\n')
50
+ };
51
+ }
52
+
53
+ /** Every name a module exports, following its re-exports. */
54
+ function exportsOf(files, path, seen = new Set()) {
55
+ if (!path || seen.has(path)) return new Map();
56
+ seen.add(path);
57
+
58
+ const source = files.get(path);
59
+ const found = new Map();
60
+
61
+ for (const match of source.matchAll(DECLARATION)) {
62
+ found.set(match[2], entry(source, match.index, match[1], match[2]));
63
+ }
64
+
65
+ // export * from './x';
66
+ for (const match of source.matchAll(/^export \* from ['"](.+?)['"];/gm)) {
67
+ const target = exportsOf(files, resolve(files, path, match[1]), seen);
68
+
69
+ for (const [name, value] of target) found.set(name, value);
70
+ }
71
+
72
+ // export { a, default as b } from './x';
73
+ for (const match of source.matchAll(/^export \{([^}]+)\} from ['"](.+?)['"];/gm)) {
74
+ const targetPath = resolve(files, path, match[2]);
75
+ const target = exportsOf(files, targetPath, new Set(seen));
76
+ const targetSource = files.get(targetPath) || '';
77
+
78
+ for (const part of match[1].split(',')) {
79
+ const [original, alias = original] = part.trim().split(/\s+as\s+/);
80
+ let value = target.get(original);
81
+
82
+ if (original === 'default') {
83
+ // declare const x: …; export default x;
84
+ const local = (/^export default (\w+);/m.exec(targetSource) || [])[1];
85
+ const declared = new RegExp(
86
+ `^declare (?:abstract )?(class|const|function) ${local}\\b`,
87
+ 'm'
88
+ ).exec(targetSource);
89
+
90
+ value = declared && entry(targetSource, declared.index, declared[1], alias);
91
+ }
92
+
93
+ if (value) found.set(alias, { ...value, name: alias });
94
+ }
95
+ }
96
+
97
+ return found;
98
+ }
99
+
100
+ /**
101
+ * @param {Array<{ name: string, version: string, files: Map<string, string> }>} packages
102
+ * `files` holds the .d.ts files of the package, keyed by their path
103
+ * relative to its types root (`index.d.ts`, `model/index.d.ts`, …).
104
+ */
105
+ export function createKnowledge(packages) {
106
+ const api = new Map();
107
+
108
+ for (const pkg of packages) {
109
+ for (const [name, value] of exportsOf(pkg.files, 'index.d.ts')) {
110
+ api.set(name, { ...value, package: pkg.name });
111
+ }
112
+ }
113
+
114
+ const names = [...api.keys()].sort();
115
+ const get = (name) => api.get(name);
116
+
117
+ /** Names whose own name or documentation holds every word of the query. */
118
+ function search(query) {
119
+ const words = query.toLowerCase().split(/\W+/).filter(Boolean);
120
+
121
+ return names
122
+ .map((name) => api.get(name))
123
+ .filter((item) => {
124
+ const text = `${item.name} ${item.declaration}`.toLowerCase();
125
+
126
+ return words.every((word) => text.includes(word));
127
+ });
128
+ }
129
+
130
+ function formatMarkdown(name) {
131
+ const item = get(name);
132
+
133
+ if (!item) {
134
+ return `${name} is not exported by ${packages.map((p) => p.name).join(' or ')}. Exports: ${names.join(', ')}`;
135
+ }
136
+
137
+ return `## ${item.name} (${item.kind}, ${item.package})\n\n\`\`\`ts\n${item.declaration}\n\`\`\``;
138
+ }
139
+
140
+ return { packages, names, get, search, formatMarkdown };
141
+ }
package/src/load.mjs ADDED
@@ -0,0 +1,41 @@
1
+ // Reads the type declarations of a Punica Form package from disk: the copy
2
+ // installed in the project the server is started in, so the answers match
3
+ // that version; without one, the copy bundled with this server.
4
+ import { readdirSync, readFileSync } from 'node:fs';
5
+ import { createRequire } from 'node:module';
6
+ import { dirname, join, relative, sep } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ const BUNDLED = fileURLToPath(new URL('../bundled/', import.meta.url));
10
+
11
+ /** Every .d.ts file below `root`, keyed by its path relative to it. */
12
+ export function readTypes(root) {
13
+ const files = new Map();
14
+
15
+ for (const entry of readdirSync(root, { recursive: true, withFileTypes: true })) {
16
+ if (entry.isFile() && entry.name.endsWith('.d.ts')) {
17
+ const path = join(entry.parentPath, entry.name);
18
+
19
+ files.set(relative(root, path).split(sep).join('/'), readFileSync(path, 'utf8'));
20
+ }
21
+ }
22
+
23
+ return files;
24
+ }
25
+
26
+ /** @returns {{ name: string, version: string, files: Map<string, string>, installed: boolean }} */
27
+ export function loadPackage(name, cwd = process.cwd()) {
28
+ try {
29
+ const require = createRequire(join(cwd, 'package.json'));
30
+ const manifestPath = require.resolve(`${name}/package.json`);
31
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
32
+ const root = dirname(join(dirname(manifestPath), manifest.types));
33
+
34
+ return { name, version: manifest.version, files: readTypes(root), installed: true };
35
+ } catch {
36
+ const root = join(BUNDLED, name.split('/')[1]);
37
+ const { version } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
38
+
39
+ return { name, version, files: readTypes(root), installed: false };
40
+ }
41
+ }
package/src/main.mjs ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ // punica-form-mcp: the MCP server over stdio.
3
+ import { readFileSync } from 'node:fs';
4
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
+ import { createPunicaFormServer } from './create.mjs';
6
+ import { loadPackage } from './load.mjs';
7
+
8
+ const packages = ['@punica/form', '@punica/form-service'].map((name) => loadPackage(name));
9
+ const guide = readFileSync(new URL('./guide.md', import.meta.url), 'utf8');
10
+
11
+ const server = createPunicaFormServer({ packages, guide });
12
+ await server.connect(new StdioServerTransport());
@@ -0,0 +1,98 @@
1
+ // Checks code that uses Punica Form for the mistakes models make most often:
2
+ // names the packages do not export and service calls that do not exist.
3
+
4
+ /** The name a service registers under: its class name in camelCase. */
5
+ const serviceName = (className) => className[0].toLowerCase() + className.slice(1);
6
+
7
+ const lineOf = (code, index) => code.slice(0, index).split('\n').length;
8
+
9
+ /** @param {ReturnType<typeof import('./knowledge.mjs').createKnowledge>} knowledge */
10
+ export function createValidator(knowledge) {
11
+ const packageNames = knowledge.packages.map((pkg) => pkg.name);
12
+ const services = knowledge.names
13
+ .map((name) => knowledge.get(name))
14
+ .filter((item) => item.kind === 'class' && item.package.endsWith('-service'))
15
+ .map((item) => item.name);
16
+
17
+ /** Service calls that take the form as an argument do not exist. */
18
+ const formCall = new RegExp(
19
+ `\\.(${services.map(serviceName).join('|')})\\(\\s*(?:this\\.)?(?:form|mockForm)\\b`,
20
+ 'g'
21
+ );
22
+
23
+ /**
24
+ * @param {string} code
25
+ * @returns {Array<{ line: number, rule: string, message: string, fix?: string }>}
26
+ */
27
+ function validate(code) {
28
+ const findings = [];
29
+ const add = (index, rule, message, fix) =>
30
+ findings.push({ line: lineOf(code, index), rule, message, fix });
31
+
32
+ for (const match of code.matchAll(
33
+ /import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g
34
+ )) {
35
+ if (!packageNames.includes(match[2])) continue;
36
+
37
+ for (const part of match[1].split(',')) {
38
+ const name = part.replace(/^\s*type\s+/, '').trim().split(/\s+as\s+/)[0];
39
+ const item = knowledge.get(name);
40
+
41
+ if (!name || item?.package === match[2]) continue;
42
+
43
+ add(
44
+ match.index,
45
+ 'unknown-export',
46
+ `${match[2]} does not export ${name}.`,
47
+ item
48
+ ? `import it from "${item.package}"`
49
+ : 'it is not part of Punica Form: decorators such as Title or FormItemInputText, readers and form item types belong to your own form system'
50
+ );
51
+ }
52
+ }
53
+
54
+ for (const match of code.matchAll(/getServices(?:<[^(\n]*>)?\(([^)]*)\)/g)) {
55
+ for (const [, name] of match[1].matchAll(/['"](\w+)['"]/g)) {
56
+ if (services.includes(name)) {
57
+ add(
58
+ match.index,
59
+ 'service-name',
60
+ `Services are registered in camelCase; "${name}" is not found.`,
61
+ `getServices('${serviceName(name)}')`
62
+ );
63
+ }
64
+ }
65
+ }
66
+
67
+ for (const match of code.matchAll(formCall)) {
68
+ const fix =
69
+ match[1] === 'setValue'
70
+ ? 'await item.setValue(item.property, value) (SetValue adds setValue to every form item)'
71
+ : `await controller.getServices('${match[1]}').run(${/^(clearError|resetItem|trigger)$/.test(match[1]) ? 'property' : ''})`;
72
+
73
+ add(match.index, 'service-call', `There is no ${match[1]}(form, …) method.`, fix);
74
+ }
75
+
76
+ for (const match of code.matchAll(/\.validateItem\(/g)) {
77
+ add(
78
+ match.index,
79
+ 'service-call',
80
+ 'There is no validateItem method.',
81
+ "await controller.getServices('trigger').run(property) (needs new Trigger() in @Services)"
82
+ );
83
+ }
84
+
85
+ for (const match of code.matchAll(/FormItemRegister(?:\.getInstance\(\))?\.getRenderer\(/g)) {
86
+ add(
87
+ match.index,
88
+ 'register',
89
+ 'FormItemRegister has no getRenderer method.',
90
+ 'FormItemRegister.getInstance().getItem(type)'
91
+ );
92
+ }
93
+
94
+ return findings.sort((a, b) => a.line - b.line);
95
+ }
96
+
97
+ return { validate };
98
+ }