@punica/form-mcp 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +49 -2
- package/bundled/form/controller/index.d.ts +63 -0
- package/bundled/form/decorator/Readers.d.ts +9 -0
- package/bundled/form/decorator/Services.d.ts +9 -0
- package/bundled/form/decorator/Starters.d.ts +9 -0
- package/bundled/form/decorator/index.d.ts +3 -0
- package/bundled/form/define/FormItem.d.ts +15 -0
- package/bundled/form/define/FormItemProperty.d.ts +8 -0
- package/bundled/form/define/FormProperty.d.ts +8 -0
- package/bundled/form/define/decorator.d.ts +16 -0
- package/bundled/form/define/index.d.ts +4 -0
- package/bundled/form/index.d.ts +8 -0
- package/bundled/form/metadata/index.d.ts +20 -0
- package/bundled/form/model/command/index.d.ts +2 -0
- package/bundled/form/model/command/item.d.ts +13 -0
- package/bundled/form/model/command/service.d.ts +24 -0
- package/bundled/form/model/constants/index.d.ts +15 -0
- package/bundled/form/model/form/index.d.ts +12 -0
- package/bundled/form/model/index.d.ts +7 -0
- package/bundled/form/model/item/index.d.ts +40 -0
- package/bundled/form/model/reader/index.d.ts +8 -0
- package/bundled/form/model/service/index.d.ts +38 -0
- package/bundled/form/model/starter/index.d.ts +13 -0
- package/bundled/form/package.json +1 -0
- package/bundled/form/reader/index.d.ts +11 -0
- package/bundled/form/register/index.d.ts +30 -0
- package/bundled/form/utils/deepCopy.d.ts +8 -0
- package/bundled/form/utils/devtools.d.ts +18 -0
- package/bundled/form/utils/index.d.ts +2 -0
- package/bundled/form-service/clearError/index.d.ts +13 -0
- package/bundled/form-service/clearErrors/index.d.ts +10 -0
- package/bundled/form-service/getValues/index.d.ts +14 -0
- package/bundled/form-service/index.d.ts +30 -0
- package/bundled/form-service/package.json +1 -0
- package/bundled/form-service/reset/index.d.ts +13 -0
- package/bundled/form-service/resetItem/index.d.ts +13 -0
- package/bundled/form-service/setValue/index.d.ts +14 -0
- package/bundled/form-service/store/index.d.ts +18 -0
- package/bundled/form-service/trigger/index.d.ts +13 -0
- package/bundled/form-service/validate/index.d.ts +13 -0
- package/bundled/form-service/validateItem.d.ts +7 -0
- package/package.json +46 -3
- package/src/create.mjs +128 -0
- package/src/guide.md +184 -0
- package/src/knowledge.mjs +141 -0
- package/src/load.mjs +41 -0
- package/src/main.mjs +12 -0
- package/src/validate.mjs +111 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { CommandService, FormItem, IServiceControl, IServiceInitialize } from '@punica/form';
|
|
2
|
+
/**
|
|
3
|
+
* Sets the value of an item and runs its control function.
|
|
4
|
+
*/
|
|
5
|
+
export declare class SetValue<E, F extends FormItem<E> = FormItem<E>> implements IServiceInitialize<E, F>, IServiceControl {
|
|
6
|
+
#private;
|
|
7
|
+
get name(): string;
|
|
8
|
+
initialize(command: CommandService<E, F>): void;
|
|
9
|
+
/**
|
|
10
|
+
* Fires UPDATE_ITEM with the changed item and the items its control returned.
|
|
11
|
+
* @throws When the form has no item for the property
|
|
12
|
+
*/
|
|
13
|
+
run(property: keyof E, value: unknown): Promise<void>;
|
|
14
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { IServiceCommand } from '@punica/form';
|
|
2
|
+
/**
|
|
3
|
+
* What `Store` adds to the command of the functions of form items:
|
|
4
|
+
* `validation: ({ readStoreItem }: CommandItem<E, F, StoreCommand>) => …`
|
|
5
|
+
*/
|
|
6
|
+
export type StoreCommand = {
|
|
7
|
+
readStoreItem: (key: string) => unknown;
|
|
8
|
+
writeStoreItem: (key: string, value: unknown) => void;
|
|
9
|
+
deleteStoreItem: (key: string) => void;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* A key-value store the functions of the form items share.
|
|
13
|
+
*/
|
|
14
|
+
export declare class Store implements IServiceCommand {
|
|
15
|
+
#private;
|
|
16
|
+
get name(): string;
|
|
17
|
+
addCustomFeaturesForCommandItem(): StoreCommand;
|
|
18
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { CommandService, FormItem, IServiceControl, IServiceInitialize } from '@punica/form';
|
|
2
|
+
/**
|
|
3
|
+
* Validates one item of the form.
|
|
4
|
+
*/
|
|
5
|
+
export declare class Trigger<E, F extends FormItem<E> = FormItem<E>> implements IServiceInitialize<E, F>, IServiceControl {
|
|
6
|
+
#private;
|
|
7
|
+
get name(): string;
|
|
8
|
+
initialize(command: CommandService<E, F>): void;
|
|
9
|
+
/**
|
|
10
|
+
* @throws When the form has no item for the property
|
|
11
|
+
*/
|
|
12
|
+
run(property: keyof E): Promise<void>;
|
|
13
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { CommandService, FormItem, IServiceControl, IServiceInitialize } from '@punica/form';
|
|
2
|
+
/**
|
|
3
|
+
* Validates every item of the form.
|
|
4
|
+
*/
|
|
5
|
+
export declare class Validate<E, F extends FormItem<E> = FormItem<E>> implements IServiceInitialize<E, F>, IServiceControl {
|
|
6
|
+
#private;
|
|
7
|
+
get name(): string;
|
|
8
|
+
initialize(command: CommandService<E, F>): void;
|
|
9
|
+
/**
|
|
10
|
+
* @returns Whether every validated item is valid
|
|
11
|
+
*/
|
|
12
|
+
run(): Promise<boolean>;
|
|
13
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { CommandService, FormItem } from '@punica/form';
|
|
2
|
+
/**
|
|
3
|
+
* Runs the validation of an item.
|
|
4
|
+
* @returns The item with the result of the validation, or `undefined` when
|
|
5
|
+
* the item is not validated (no validation function, or hidden)
|
|
6
|
+
*/
|
|
7
|
+
export declare const validateItem: <E, F extends FormItem<E>>(command: CommandService<E, F>, item: F) => Promise<F | undefined>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@punica/form-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "MCP server for Punica Form: look up the exact API, read the rules and check code that uses it.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"mcp",
|
|
7
|
+
"model-context-protocol",
|
|
8
|
+
"form",
|
|
9
|
+
"punica"
|
|
10
|
+
],
|
|
11
|
+
"homepage": "https://form.punicalab.com",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/punicalab/punica-form/issues"
|
|
14
|
+
},
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/punicalab/punica-form.git",
|
|
18
|
+
"directory": "packages/mcp"
|
|
19
|
+
},
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"author": "PunicaLab",
|
|
22
|
+
"type": "module",
|
|
23
|
+
"bin": {
|
|
24
|
+
"punica-form-mcp": "src/main.mjs"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"src",
|
|
28
|
+
"bundled"
|
|
29
|
+
],
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=20.12"
|
|
32
|
+
},
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
38
|
+
"zod": "^4.6.7"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@punica/form": "^2.0.0",
|
|
42
|
+
"@punica/form-service": "^2.0.0"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "node build.mjs",
|
|
46
|
+
"clean": "rimraf bundled",
|
|
47
|
+
"test": "node --test test/*.test.mjs"
|
|
48
|
+
}
|
|
6
49
|
}
|
package/src/create.mjs
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// The MCP server: tools and resources over the public API of Punica Form,
|
|
2
|
+
// its rules and the code validator. Transport-free, so tests connect it to
|
|
3
|
+
// an in-memory client.
|
|
4
|
+
import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { createKnowledge } from './knowledge.mjs';
|
|
7
|
+
import { createValidator } from './validate.mjs';
|
|
8
|
+
|
|
9
|
+
const text = (value) => ({ content: [{ type: 'text', text: value }] });
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @param {{ packages: Array<Parameters<typeof createKnowledge>[0][number] & { installed?: boolean }>, guide: string }} options
|
|
13
|
+
* `installed` says whether the declarations come from the project or from
|
|
14
|
+
* the copy bundled with the server; the instructions tell the model.
|
|
15
|
+
*/
|
|
16
|
+
export function createPunicaFormServer({ packages, guide }) {
|
|
17
|
+
const knowledge = createKnowledge(packages);
|
|
18
|
+
const { validate } = createValidator(knowledge);
|
|
19
|
+
const versions = packages
|
|
20
|
+
.map((pkg) => `${pkg.name} ${pkg.version} (${pkg.installed ? 'installed in this project' : 'not installed, bundled copy'})`)
|
|
21
|
+
.join(', ');
|
|
22
|
+
|
|
23
|
+
const server = new McpServer(
|
|
24
|
+
{ name: 'punica-form', version: '0.2.0' },
|
|
25
|
+
{
|
|
26
|
+
instructions: `${versions}. Punica Form is a headless form engine and is rarely in training data: never write an import, a service name or a method from memory. Read get_guide first, look names up with search_api and get_api, and check the code with validate_code before handing it over.`
|
|
27
|
+
}
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
server.registerTool(
|
|
31
|
+
'get_guide',
|
|
32
|
+
{
|
|
33
|
+
title: 'How to use Punica Form',
|
|
34
|
+
description:
|
|
35
|
+
'The rules of Punica Form: what the packages provide and what the application builds itself, the lifecycle, the immutable state, the services and how to call them, events, and a complete working example.',
|
|
36
|
+
inputSchema: {},
|
|
37
|
+
annotations: { readOnlyHint: true }
|
|
38
|
+
},
|
|
39
|
+
async () => text(guide)
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
server.registerTool(
|
|
43
|
+
'search_api',
|
|
44
|
+
{
|
|
45
|
+
title: 'Find Punica Form exports',
|
|
46
|
+
description:
|
|
47
|
+
'Finds exports of @punica/form and @punica/form-service by name or by words in their documentation ("validate", "reader", "event"). Without a query: every export.',
|
|
48
|
+
inputSchema: { query: z.string().optional().describe('Words to look for') },
|
|
49
|
+
annotations: { readOnlyHint: true }
|
|
50
|
+
},
|
|
51
|
+
async ({ query }) => {
|
|
52
|
+
const results = knowledge.search(query || '');
|
|
53
|
+
|
|
54
|
+
if (!results.length) {
|
|
55
|
+
return text(`Nothing matches "${query}". Exports: ${knowledge.names.join(', ')}`);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return text(
|
|
59
|
+
results
|
|
60
|
+
.map((item) => `${item.name} (${item.kind}, ${item.package})${item.summary ? `: ${item.summary}` : ''}`)
|
|
61
|
+
.join('\n')
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
server.registerTool(
|
|
67
|
+
'get_api',
|
|
68
|
+
{
|
|
69
|
+
title: 'The declaration of an export',
|
|
70
|
+
description:
|
|
71
|
+
'The exact TypeScript declaration and documentation of one or more exports, such as FormController, Validate, FormItem or IReader, read from the installed packages.',
|
|
72
|
+
inputSchema: { names: z.array(z.string()).min(1).max(12).describe('Export names') },
|
|
73
|
+
annotations: { readOnlyHint: true }
|
|
74
|
+
},
|
|
75
|
+
async ({ names }) => text(names.map((name) => knowledge.formatMarkdown(name)).join('\n\n'))
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
server.registerTool(
|
|
79
|
+
'validate_code',
|
|
80
|
+
{
|
|
81
|
+
title: 'Check code that uses Punica Form',
|
|
82
|
+
description:
|
|
83
|
+
'Checks TypeScript or JavaScript that uses Punica Form: imports the packages do not export and calls that do not exist, such as the 1.x API. Returns each problem with its line and a fix.',
|
|
84
|
+
inputSchema: { code: z.string().describe('The code to check') },
|
|
85
|
+
annotations: { readOnlyHint: true }
|
|
86
|
+
},
|
|
87
|
+
async ({ code }) => {
|
|
88
|
+
const findings = validate(code);
|
|
89
|
+
|
|
90
|
+
if (!findings.length) {
|
|
91
|
+
return text('No problems: every import exists and no removed API is used.');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return text(
|
|
95
|
+
[
|
|
96
|
+
`${findings.length} problem${findings.length === 1 ? '' : 's'}:`,
|
|
97
|
+
...findings.map((f) => `line ${f.line} ${f.rule}: ${f.message} [fix: ${f.fix}]`)
|
|
98
|
+
].join('\n')
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
server.registerResource(
|
|
104
|
+
'guide',
|
|
105
|
+
'punica-form://guide',
|
|
106
|
+
{ title: 'The rules of Punica Form', mimeType: 'text/markdown' },
|
|
107
|
+
async (uri) => ({ contents: [{ uri: uri.href, mimeType: 'text/markdown', text: guide }] })
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
server.registerResource(
|
|
111
|
+
'api',
|
|
112
|
+
new ResourceTemplate('punica-form://api/{name}', {
|
|
113
|
+
list: async () => ({
|
|
114
|
+
resources: knowledge.names.map((name) => ({
|
|
115
|
+
uri: `punica-form://api/${name}`,
|
|
116
|
+
name,
|
|
117
|
+
mimeType: 'text/markdown'
|
|
118
|
+
}))
|
|
119
|
+
})
|
|
120
|
+
}),
|
|
121
|
+
{ title: 'The declaration of an export', mimeType: 'text/markdown' },
|
|
122
|
+
async (uri, { name }) => ({
|
|
123
|
+
contents: [{ uri: uri.href, mimeType: 'text/markdown', text: knowledge.formatMarkdown(String(name)) }]
|
|
124
|
+
})
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
return server;
|
|
128
|
+
}
|
package/src/guide.md
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# Punica Form 2: the rules
|
|
2
|
+
|
|
3
|
+
Punica Form is a headless form engine. `@punica/form` holds the engine,
|
|
4
|
+
`@punica/form-service` the built-in services. There are no UI components.
|
|
5
|
+
|
|
6
|
+
## What the packages provide, and what they do not
|
|
7
|
+
|
|
8
|
+
- `@punica/form`: `FormController`, the class decorators `@Services`,
|
|
9
|
+
`@Readers` and `@Starters`, the helpers `defineFormItem`,
|
|
10
|
+
`defineFormItemProperty` and `defineFormProperty`, the metadata readers
|
|
11
|
+
`getFormProperty` and `getFormItemProperties`, the form item register,
|
|
12
|
+
`deepCopy`, the DevTools switches and the types. Use `search_api` for the
|
|
13
|
+
exact list.
|
|
14
|
+
- `@punica/form-service`: `Validate`, `GetValues`, `SetValue`, `Reset`,
|
|
15
|
+
`ResetItem`, `Trigger`, `ClearError`, `ClearErrors`, `Store`.
|
|
16
|
+
- NOT provided: `@Title`, `@Description`, `@Layout`, `@FormItemInputText` or
|
|
17
|
+
any other form item decorator, a `Reader` class, a base form item. These
|
|
18
|
+
belong to the application's own form system. Build them with the `define*`
|
|
19
|
+
helpers and by implementing `IReader`; import them from the application's
|
|
20
|
+
own module, never from `@punica/form`.
|
|
21
|
+
- Decorators work with both the legacy implementation of TypeScript
|
|
22
|
+
(`"experimentalDecorators": true`) and the standard one. There is no
|
|
23
|
+
`reflect-metadata`: never call `Reflect.getMetadata`.
|
|
24
|
+
|
|
25
|
+
## Lifecycle
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
const controller = await FormController.fromEntity(new UserForm());
|
|
29
|
+
const form = await controller.start();
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
`fromEntity` creates the form items from the decorated properties of the
|
|
33
|
+
entity (only properties with an initializer, such as `name = ""`).
|
|
34
|
+
`start()` then fires `REGISTER_ITEMS`, runs the readers of `@Readers` in
|
|
35
|
+
order, runs the starters of `@Starters` (each returns the form, possibly a
|
|
36
|
+
new one), initializes the services of `@Services` and returns the form.
|
|
37
|
+
Both calls are asynchronous and reject when a reader, starter or service
|
|
38
|
+
throws. `FormController.fromForm(form)` starts from a form written as data.
|
|
39
|
+
|
|
40
|
+
## State
|
|
41
|
+
|
|
42
|
+
The form is immutable. Every change produces a new form object; items that
|
|
43
|
+
did not change keep their identity.
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
controller.getForm(); // the current form
|
|
47
|
+
const unsubscribe = controller.subscribe(() => {}); // after every change
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
In React: `useSyncExternalStore(controller.subscribe, controller.getForm)`.
|
|
51
|
+
Never change a form or an item in place; use the services.
|
|
52
|
+
|
|
53
|
+
## Services
|
|
54
|
+
|
|
55
|
+
Services are read by class and executed with `run`. They are bound to the
|
|
56
|
+
entity of the form, so property names and results are type-checked.
|
|
57
|
+
|
|
58
|
+
| Class | Call |
|
|
59
|
+
|---|---|
|
|
60
|
+
| `Validate` | `run(): Promise<boolean>`, validates every visible item |
|
|
61
|
+
| `Trigger` | `run(property): Promise<void>`, validates one item |
|
|
62
|
+
| `GetValues` | `run(): Promise<E>`, a copy of the entity filled with the item values |
|
|
63
|
+
| `SetValue` | `run(property, value): Promise<void>`, then runs the `control` function of the item |
|
|
64
|
+
| `Reset` | `run(): Promise<void>` |
|
|
65
|
+
| `ResetItem` | `run(property): Promise<void>` |
|
|
66
|
+
| `ClearError` | `run(property): Promise<void>` |
|
|
67
|
+
| `ClearErrors` | `run(): Promise<void>` |
|
|
68
|
+
| `Store` | no `run`: it adds `readStoreItem`, `writeStoreItem`, `deleteStoreItem` to the command passed to item functions (`CommandItem<E, F, StoreCommand>`) |
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { GetValues, SetValue, Trigger, Validate } from "@punica/form-service";
|
|
72
|
+
|
|
73
|
+
await controller.getService(SetValue).run("name", "Jane");
|
|
74
|
+
await controller.getService(Trigger).run("name");
|
|
75
|
+
|
|
76
|
+
if (await controller.getService(Validate).run()) {
|
|
77
|
+
const values = await controller.getService(GetValues).run();
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
- A service works only when it is listed in `@Services([...])`;
|
|
82
|
+
`getService` throws for a class that is not.
|
|
83
|
+
- There is no `getServices('name')`, no `validate(form)`, no
|
|
84
|
+
`item.setValue(…)` and no `validateItem(…)`.
|
|
85
|
+
- `Validate.run()` returns `false` when the form is invalid. Other failures
|
|
86
|
+
(an unknown property, an error thrown by a validation function) reject.
|
|
87
|
+
- Setting a value does not validate it. Run `Trigger` for that.
|
|
88
|
+
|
|
89
|
+
## Form items
|
|
90
|
+
|
|
91
|
+
A form item is a plain object: `property`, `label`, `type`, `value`,
|
|
92
|
+
`required`, `disabled`, `hidden`, `error`, `errorMessages`. Add the
|
|
93
|
+
properties of your form system with a type of your own:
|
|
94
|
+
`type AppItem<E> = FormItem<E> & { layout?: Layout }`, then use
|
|
95
|
+
`FormController<UserForm, AppItem<UserForm>>`.
|
|
96
|
+
|
|
97
|
+
The functions of an item receive a command `{ formItem, initialEntity,
|
|
98
|
+
getItem }` holding copies, and return items instead of changing them:
|
|
99
|
+
|
|
100
|
+
- `validation(command): Promise<{ error: boolean, errorMessages?: string[] }>`
|
|
101
|
+
- `control(command): Promise<FormItem[]>`, run after its value is set; the
|
|
102
|
+
returned items are written to the form
|
|
103
|
+
- `initialize(command): Promise<FormItem[]>`, run once while the form is created
|
|
104
|
+
|
|
105
|
+
## Events
|
|
106
|
+
|
|
107
|
+
`controller.on(event, handler)` returns the function that removes the
|
|
108
|
+
handler. Payloads are typed.
|
|
109
|
+
|
|
110
|
+
| Event | Payload |
|
|
111
|
+
|---|---|
|
|
112
|
+
| `UPDATE_FORM` | the form; fired after every change |
|
|
113
|
+
| `UPDATE_ITEM` | an array: the changed item, then the items its `control` returned |
|
|
114
|
+
| `RESET` | the form; fired by `Reset`, after `UPDATE_FORM` |
|
|
115
|
+
| `REGISTER_ITEMS` | `string[]` of registered form item types; fired at the start of `start()` |
|
|
116
|
+
|
|
117
|
+
## A complete example
|
|
118
|
+
|
|
119
|
+
The application's form system:
|
|
120
|
+
|
|
121
|
+
```tsx
|
|
122
|
+
import {
|
|
123
|
+
defineFormItem,
|
|
124
|
+
defineFormProperty,
|
|
125
|
+
getFormProperty,
|
|
126
|
+
type Form,
|
|
127
|
+
type FormItem,
|
|
128
|
+
type IReader,
|
|
129
|
+
} from "@punica/form";
|
|
130
|
+
|
|
131
|
+
export const Title = defineFormProperty<string>("app:title");
|
|
132
|
+
|
|
133
|
+
export class Reader<E extends object, F extends FormItem<E>> implements IReader<E, F> {
|
|
134
|
+
public read(entity: E, form: Form<E, F>): void {
|
|
135
|
+
form.title = getFormProperty<string>(entity, "app:title");
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// The second argument is the renderer; defaultFormItemRegister.getItem(item.type) returns it
|
|
140
|
+
export const FormItemInputText = defineFormItem<Omit<FormItem<any>, "property">>(
|
|
141
|
+
"app:input-text",
|
|
142
|
+
InputText
|
|
143
|
+
);
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
A business form:
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
import { Readers, Services } from "@punica/form";
|
|
150
|
+
import { GetValues, SetValue, Trigger, Validate } from "@punica/form-service";
|
|
151
|
+
import { FormItemInputText, Reader, Title } from "./formSystem";
|
|
152
|
+
|
|
153
|
+
@Title("Create User")
|
|
154
|
+
@Readers([new Reader()])
|
|
155
|
+
@Services([new GetValues(), new SetValue(), new Validate(), new Trigger()])
|
|
156
|
+
export class UserForm {
|
|
157
|
+
@FormItemInputText({
|
|
158
|
+
label: "Name",
|
|
159
|
+
required: true,
|
|
160
|
+
validation: async ({ formItem }) => ({
|
|
161
|
+
error: !formItem.value,
|
|
162
|
+
errorMessages: formItem.value ? [] : ["Name is required"],
|
|
163
|
+
}),
|
|
164
|
+
})
|
|
165
|
+
name = "";
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Using it:
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
const controller = await FormController.fromEntity(new UserForm());
|
|
173
|
+
|
|
174
|
+
controller.subscribe(() => render(controller.getForm()));
|
|
175
|
+
await controller.start();
|
|
176
|
+
|
|
177
|
+
await controller.getService(SetValue).run("name", "Jane");
|
|
178
|
+
|
|
179
|
+
if (await controller.getService(Validate).run()) {
|
|
180
|
+
const values = await controller.getService(GetValues).run(); // UserForm
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Documentation: https://form.punicalab.com
|
|
@@ -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'; export type { a } from './x';
|
|
73
|
+
for (const match of source.matchAll(/^export (?:type )?\{([^}]+)\} 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());
|