@punica/form-mcp 0.2.1 → 0.3.1

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/README.md CHANGED
@@ -13,16 +13,16 @@ and validates its answer.
13
13
  | Tool | What it does |
14
14
  | --------------- | ----------------------------------------------------------------------------------------------------------------------------- |
15
15
  | `get_guide` | The rules: what the packages provide and what your application builds, the lifecycle, services, events and a complete example |
16
- | `search_api` | Finds exports of `@punica/form` and `@punica/form-service` by name or documentation |
16
+ | `search_api` | Finds exports of the Punica Form packages (core, services, React hooks, form kit) by name or documentation |
17
17
  | `get_api` | The exact TypeScript declaration and documentation of one or more exports |
18
18
  | `validate_code` | Checks code for imports that do not exist, wrong service names and service calls that do not exist; each problem with a fix |
19
19
 
20
20
  Resources: `punica-form://guide` and `punica-form://api/<name>`.
21
21
 
22
- The API is read from the type declarations of the `@punica/form` and
23
- `@punica/form-service` installed in the project the server is started in, so
24
- the answers match that version. Without them it uses the versions it was
25
- built with.
22
+ The API is read from the type declarations of the Punica Form packages
23
+ installed in the project the server is started in, so the answers match
24
+ those versions. For a package that is not installed it uses the version it
25
+ was built with.
26
26
 
27
27
  ## Set up
28
28
 
@@ -1 +1 @@
1
- {"version":"2.1.0"}
1
+ {"version":"2.1.1"}
@@ -0,0 +1,42 @@
1
+ import { FormClassDecorator, FormPropertyDecorator, IReader, IService, IStarter } from '@punica/form';
2
+ import { FieldProps } from './types';
3
+ export type FormKitOptions = {
4
+ /** The heading of the form. */
5
+ title?: string;
6
+ /** Text under the heading. */
7
+ description?: string;
8
+ /** Columns the fields are laid out in, 1 by default. */
9
+ columns?: 1 | 2 | 3 | 4;
10
+ /** Services in addition to GetValues, SetValue, Validate, Trigger and Reset. */
11
+ services?: Array<IService | (new () => IService)>;
12
+ /** Readers in addition to the kit's. */
13
+ readers?: Array<IReader<any, any>>;
14
+ starters?: Array<IStarter<any, any>>;
15
+ };
16
+ /**
17
+ * Turns a class into a form of the kit: the built-in services, the kit's
18
+ * reader and the options of the form. It replaces `@Services`, `@Readers`
19
+ * and `@Starters`; pass yours in the options.
20
+ */
21
+ export declare const FormKit: (options?: FormKitOptions) => FormClassDecorator;
22
+ /** The form item types of the kit. */
23
+ export declare const KIT_TYPES: {
24
+ readonly text: "kit:text";
25
+ readonly textarea: "kit:textarea";
26
+ readonly number: "kit:number";
27
+ readonly select: "kit:select";
28
+ readonly checkbox: "kit:checkbox";
29
+ readonly switch: "kit:switch";
30
+ };
31
+ /** A single-line text field. */
32
+ export declare const TextField: (props: FieldProps) => FormPropertyDecorator;
33
+ /** A multi-line text field. */
34
+ export declare const TextAreaField: (props: FieldProps) => FormPropertyDecorator;
35
+ /** A number field; its value is a number, or `undefined` while it is empty. */
36
+ export declare const NumberField: (props: FieldProps) => FormPropertyDecorator;
37
+ /** A select with `options`. */
38
+ export declare const SelectField: (props: FieldProps) => FormPropertyDecorator;
39
+ /** A checkbox; its value is a boolean. `required` means it has to be ticked. */
40
+ export declare const CheckboxField: (props: FieldProps) => FormPropertyDecorator;
41
+ /** A switch; its value is a boolean. */
42
+ export declare const SwitchField: (props: FieldProps) => FormPropertyDecorator;
@@ -0,0 +1,3 @@
1
+ export * from './decorators';
2
+ export type * from './types';
3
+ export { setMessages } from './validation';
@@ -0,0 +1 @@
1
+ {"version":"0.2.0"}
@@ -0,0 +1,19 @@
1
+ import type { ReactNode } from 'react';
2
+ import '@punica/components/components/checkbox/checkbox.js';
3
+ import '@punica/components/components/input/input.js';
4
+ import '@punica/components/components/select/option.js';
5
+ import '@punica/components/components/select/select.js';
6
+ import '@punica/components/components/switch/switch.js';
7
+ import '@punica/components/components/textarea/textarea.js';
8
+ import { KitItem } from '../types';
9
+ /** What a component that renders a form item type receives. */
10
+ export type FieldComponentProps = {
11
+ item: KitItem<any>;
12
+ /** Sets the value of the item. */
13
+ onChange: (value: unknown) => void;
14
+ };
15
+ export type FieldComponent = (props: FieldComponentProps) => ReactNode;
16
+ /** The component of every form item type of the kit. */
17
+ export declare const fieldComponents: Record<string, FieldComponent>;
18
+ /** The types whose component shows the label itself. */
19
+ export declare const SELF_LABELLED: string[];
@@ -0,0 +1,46 @@
1
+ import { type ReactNode } from 'react';
2
+ import '@punica/components/components/button/button.js';
3
+ import '@punica/components/components/field/field.js';
4
+ import '@punica/components/components/formLayout/formLayout.js';
5
+ import { FormController, FormControllerOptions } from '@punica/form';
6
+ import { KitItem } from '../types';
7
+ import { FieldComponent } from './fields';
8
+ export type { FieldComponent, FieldComponentProps } from './fields';
9
+ export { fieldComponents } from './fields';
10
+ type ViewProps<E extends object> = {
11
+ /** Called with the values of a valid form when it is submitted. */
12
+ onSubmit?: (values: E, controller: FormController<E, KitItem<E>>) => void | Promise<void>;
13
+ /**
14
+ * Called with what a validation, a control function or `onSubmit` threw.
15
+ * Without it the error is logged to the console.
16
+ */
17
+ onError?: (error: unknown) => void;
18
+ /** The text of the submit button, `Submit` by default. */
19
+ submitLabel?: string;
20
+ /** The text of the reset button; there is none without it. */
21
+ resetLabel?: string;
22
+ /** Components for your own form item types, or to replace the kit's. */
23
+ components?: Record<string, FieldComponent>;
24
+ };
25
+ export type FormViewProps<E extends object> = ViewProps<E> & {
26
+ controller: FormController<E, KitItem<E>>;
27
+ };
28
+ /**
29
+ * Renders the form of a started controller with `@punica/components`.
30
+ */
31
+ export declare function FormView<E extends object>({ controller, onSubmit, onError, submitLabel, resetLabel, components }: FormViewProps<E>): ReactNode;
32
+ export type KitFormProps<E extends object> = ViewProps<E> & {
33
+ /** Returns the entity of the form, for example `() => new UserForm()`. */
34
+ entity: () => E;
35
+ /** Options of the controller, read when the component mounts. */
36
+ options?: FormControllerOptions;
37
+ /** Shown while the form is being started. */
38
+ loading?: ReactNode;
39
+ /** Shown when the form could not be started; receives what was thrown. */
40
+ failed?: (error: unknown) => ReactNode;
41
+ };
42
+ /**
43
+ * A complete form: creates the controller of the entity, starts it and
44
+ * renders it.
45
+ */
46
+ export declare function KitForm<E extends object>({ entity, options, loading, failed, ...view }: KitFormProps<E>): ReactNode;
@@ -0,0 +1,55 @@
1
+ import { ErrorDetail, FormItem } from '@punica/form';
2
+ /** A choice of a select: its value, or its value and the text to show. */
3
+ export type Option = string | {
4
+ value: string;
5
+ label: string;
6
+ };
7
+ /** How many columns of the form a field takes. */
8
+ export type Span = 1 | 2 | 3 | 4 | 'full';
9
+ /** The rules the kit validates by itself. */
10
+ export type Rules = {
11
+ /** Fewest characters allowed. */
12
+ minLength?: number;
13
+ /** Most characters allowed. */
14
+ maxLength?: number;
15
+ /** What the value has to match. */
16
+ pattern?: RegExp;
17
+ /** Lowest number allowed. */
18
+ min?: number;
19
+ /** Highest number allowed. */
20
+ max?: number;
21
+ };
22
+ /**
23
+ * The form item of the kit: a form item of Punica Form with what the kit's
24
+ * components show and the rules it validates.
25
+ */
26
+ export type KitItem<E> = FormItem<E> & Rules & {
27
+ /** Text under the field. */
28
+ help?: string;
29
+ /** Shown while the field is empty. */
30
+ placeholder?: string;
31
+ /** The type of a text field, `text` by default. */
32
+ inputType?: 'text' | 'email' | 'password' | 'tel' | 'url' | 'date';
33
+ /** The choices of a select. */
34
+ options?: Option[];
35
+ /** Visible lines of a text area. */
36
+ rows?: number;
37
+ /** Columns the field takes in a form with several columns. */
38
+ span?: Span;
39
+ /** Messages of this field, in place of the kit's. */
40
+ messages?: Partial<Messages>;
41
+ };
42
+ /** What a field decorator takes: everything of an item but its property and type. */
43
+ export type FieldProps = Omit<KitItem<any>, 'property' | 'type'>;
44
+ /** The messages of the built-in rules. Each receives the label of the field. */
45
+ export type Messages = {
46
+ required: (label: string) => string;
47
+ minLength: (label: string, length: number) => string;
48
+ maxLength: (label: string, length: number) => string;
49
+ pattern: (label: string) => string;
50
+ min: (label: string, value: number) => string;
51
+ max: (label: string, value: number) => string;
52
+ };
53
+ /** A validation of an item. */
54
+ export type Validation = NonNullable<FieldProps['validation']>;
55
+ export type { ErrorDetail };
@@ -0,0 +1,11 @@
1
+ import { FieldProps, Messages, Validation } from './types';
2
+ /**
3
+ * Replaces messages of the built-in rules for every form, for example with
4
+ * translations. A field can still have its own with `messages`.
5
+ */
6
+ export declare const setMessages: (custom: Partial<Messages>) => void;
7
+ /**
8
+ * The validation of a field: its rules first, then its own `validation`
9
+ * function, which only runs for a value that passed the rules.
10
+ */
11
+ export declare const createValidation: (props: FieldProps) => Validation;
@@ -0,0 +1,2 @@
1
+ export * from './useForm';
2
+ export * from './useFormController';
@@ -0,0 +1 @@
1
+ {"version":"0.1.1"}
@@ -0,0 +1,6 @@
1
+ import { Form, FormController, FormItem } from '@punica/form';
2
+ /**
3
+ * The current form of a controller. The component renders again after
4
+ * every change of the form.
5
+ */
6
+ export declare const useForm: <E extends object, F extends FormItem<E>>(controller: FormController<E, F>) => Form<E, F>;
@@ -0,0 +1,13 @@
1
+ import { FormController, FormControllerOptions, FormItem } from '@punica/form';
2
+ export type FormControllerState<E extends object, F extends FormItem<E>> = {
3
+ /** The started controller; `undefined` while the form is being started. */
4
+ controller?: FormController<E, F>;
5
+ /** What a reader, a starter or a service threw while the form was started. */
6
+ error?: unknown;
7
+ };
8
+ /**
9
+ * Creates the controller of a form when the component mounts and starts it.
10
+ * @param createEntity - Returns the entity of the form, for example `() => new UserForm()`
11
+ * @param options - Options of the controller, read when the component mounts
12
+ */
13
+ export declare const useFormController: <E extends object, F extends FormItem<E> = FormItem<E>>(createEntity: () => E, options?: FormControllerOptions) => FormControllerState<E, F>;
@@ -1 +1 @@
1
- {"version":"2.1.0"}
1
+ {"version":"2.1.1"}
@@ -1,13 +1,16 @@
1
1
  import { CommandService, ErrorDetail, FormItem } from '@punica/form';
2
2
  /**
3
- * Runs the validation of an item.
4
- * @returns The result of the validation, or `undefined` when the item is not
5
- * validated (no validation function, or hidden)
3
+ * Tells the validations of a form that are still running that their results
4
+ * are stale: of one property, or of every property.
6
5
  */
7
- export declare const validateItem: <E, F extends FormItem<E>>(command: CommandService<E, F>, item: F) => Promise<ErrorDetail | undefined>;
6
+ export declare const dropValidations: <E, F extends FormItem<E>>(command: CommandService<E, F>, property?: keyof E) => void;
8
7
  /**
9
- * Writes validation results onto the items as they are now: an item may
10
- * have changed while the form was validated, and only its error state is
11
- * what the validation knows.
8
+ * Validates items one after the other and writes the results onto the items
9
+ * as they are now: an item may have changed while it was validated, and only
10
+ * its error state is what the validation knows. A result is not written when
11
+ * it is stale: the value changed, the item was validated again or reset.
12
+ * Items without a validation function, hidden items and disabled items are
13
+ * not validated.
14
+ * @returns The results, by the property of the validated items
12
15
  */
13
- export declare const writeResults: <E, F extends FormItem<E>>(command: CommandService<E, F>, results: Map<keyof E, ErrorDetail>) => void;
16
+ export declare const validateItems: <E, F extends FormItem<E>>(command: CommandService<E, F>, items: F[]) => Promise<Map<keyof E, ErrorDetail>>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@punica/form-mcp",
3
- "version": "0.2.1",
4
- "description": "MCP server for Punica Form: look up the exact API, read the rules and check code that uses it.",
3
+ "version": "0.3.1",
4
+ "description": "MCP server for Punica Form: look up the exact API of its packages, read the rules and check code that uses them.",
5
5
  "keywords": [
6
6
  "mcp",
7
7
  "model-context-protocol",
@@ -39,8 +39,10 @@
39
39
  "zod": "^4.6.7"
40
40
  },
41
41
  "devDependencies": {
42
- "@punica/form": "^2.1.0",
43
- "@punica/form-service": "^2.1.0"
42
+ "@punica/form": "^2.1.1",
43
+ "@punica/form-service": "^2.1.1",
44
+ "@punica/form-react": "^0.1.1",
45
+ "@punica/form-kit": "^0.2.0"
44
46
  },
45
47
  "scripts": {
46
48
  "build": "node build.mjs",
package/src/create.mjs CHANGED
@@ -21,13 +21,15 @@ export function createPunicaFormServer({ packages, guide }) {
21
21
  .join(', ');
22
22
 
23
23
  // The guide describes 2.x; a project on 1.x must not be steered into it
24
- const legacy = packages.find((pkg) => parseInt(pkg.version) < 2);
24
+ const legacy = packages.find(
25
+ (pkg) => pkg.name === '@punica/form' && parseInt(pkg.version) < 2
26
+ );
25
27
  const legacyNote = legacy
26
28
  ? `This project has ${legacy.name} ${legacy.version} installed, but this server documents Punica Form 2. search_api and get_api show the installed 1.x API and are correct; get_guide describes 2.x and applies only after upgrading. Do not rewrite 1.x code to the 2.x API unless the user asks to upgrade.\n\n`
27
29
  : '';
28
30
 
29
31
  const server = new McpServer(
30
- { name: 'punica-form', version: '0.2.0' },
32
+ { name: 'punica-form', version: '0.3.0' },
31
33
  {
32
34
  instructions: `${legacyNote}${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.`
33
35
  }
@@ -50,7 +52,7 @@ export function createPunicaFormServer({ packages, guide }) {
50
52
  {
51
53
  title: 'Find Punica Form exports',
52
54
  description:
53
- '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.',
55
+ 'Finds exports of the Punica Form packages (@punica/form, @punica/form-service, @punica/form-react, @punica/form-kit) by name or by words in their documentation ("validate", "reader", "field"). Without a query: every export.',
54
56
  inputSchema: { query: z.string().optional().describe('Words to look for') },
55
57
  annotations: { readOnlyHint: true }
56
58
  },
@@ -74,7 +76,7 @@ export function createPunicaFormServer({ packages, guide }) {
74
76
  {
75
77
  title: 'The declaration of an export',
76
78
  description:
77
- 'The exact TypeScript declaration and documentation of one or more exports, such as FormController, Validate, FormItem or IReader, read from the installed packages.',
79
+ 'The exact TypeScript declaration and documentation of one or more exports, such as FormController, Validate, TextField or KitForm, read from the installed packages.',
78
80
  inputSchema: { names: z.array(z.string()).min(1).max(12).describe('Export names') },
79
81
  annotations: { readOnlyHint: true }
80
82
  },
package/src/guide.md CHANGED
@@ -22,6 +22,17 @@ Punica Form is a headless form engine. `@punica/form` holds the engine,
22
22
  (`"experimentalDecorators": true`) and the standard one. There is no
23
23
  `reflect-metadata`: never call `Reflect.getMetadata`.
24
24
 
25
+ ## The ready-made form system
26
+
27
+ `@punica/form-kit` provides what the application would otherwise build:
28
+ `@FormKit({ title, columns })` on the class, the field decorators `TextField`,
29
+ `NumberField`, `TextAreaField`, `SelectField`, `CheckboxField` and
30
+ `SwitchField` with the rules `required`, `minLength`, `maxLength`, `pattern`,
31
+ `min` and `max`, and from `@punica/form-kit/react` the component
32
+ `<KitForm entity={() => new UserForm()} onSubmit={…} />`, which renders the
33
+ form with `@punica/components`. Use it when the project has it installed;
34
+ otherwise build the form system as described below.
35
+
25
36
  ## Lifecycle
26
37
 
27
38
  ```ts
package/src/knowledge.mjs CHANGED
@@ -62,8 +62,8 @@ function exportsOf(files, path, seen = new Set()) {
62
62
  found.set(match[2], entry(source, match.index, match[1], match[2]));
63
63
  }
64
64
 
65
- // export * from './x';
66
- for (const match of source.matchAll(/^export \* from ['"](.+?)['"];/gm)) {
65
+ // export * from './x'; export type * from './x';
66
+ for (const match of source.matchAll(/^export (?:type )?\* from ['"](.+?)['"];/gm)) {
67
67
  const target = exportsOf(files, resolve(files, path, match[1]), seen);
68
68
 
69
69
  for (const [name, value] of target) found.set(name, value);
package/src/load.mjs CHANGED
@@ -23,19 +23,27 @@ export function readTypes(root) {
23
23
  return files;
24
24
  }
25
25
 
26
- /** @returns {{ name: string, version: string, files: Map<string, string>, installed: boolean }} */
27
- export function loadPackage(name, cwd = process.cwd()) {
26
+ /**
27
+ * @param {string} name - The package
28
+ * @param {string} [cwd] - The project to look for the package in
29
+ * @param {string} [entry] - A second entry point of the package, such as
30
+ * `react` for `@punica/form-kit/react`
31
+ * @returns {{ name: string, version: string, files: Map<string, string>, installed: boolean }}
32
+ */
33
+ export function loadPackage(name, cwd = process.cwd(), entry = '') {
34
+ const entryName = entry ? `${name}/${entry}` : name;
35
+
28
36
  try {
29
37
  const require = createRequire(join(cwd, 'package.json'));
30
38
  const manifestPath = require.resolve(`${name}/package.json`);
31
39
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
32
- const root = dirname(join(dirname(manifestPath), manifest.types));
40
+ const root = join(dirname(join(dirname(manifestPath), manifest.types)), entry);
33
41
 
34
- return { name, version: manifest.version, files: readTypes(root), installed: true };
42
+ return { name: entryName, version: manifest.version, files: readTypes(root), installed: true };
35
43
  } catch {
36
44
  const root = join(BUNDLED, name.split('/')[1]);
37
45
  const { version } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
38
46
 
39
- return { name, version, files: readTypes(root), installed: false };
47
+ return { name: entryName, version, files: readTypes(join(root, entry)), installed: false };
40
48
  }
41
49
  }
package/src/main.mjs CHANGED
@@ -5,7 +5,13 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
5
5
  import { createPunicaFormServer } from './create.mjs';
6
6
  import { loadPackage } from './load.mjs';
7
7
 
8
- const packages = ['@punica/form', '@punica/form-service'].map((name) => loadPackage(name));
8
+ const packages = [
9
+ loadPackage('@punica/form'),
10
+ loadPackage('@punica/form-service'),
11
+ loadPackage('@punica/form-react'),
12
+ loadPackage('@punica/form-kit'),
13
+ loadPackage('@punica/form-kit', process.cwd(), 'react')
14
+ ];
9
15
  const guide = readFileSync(new URL('./guide.md', import.meta.url), 'utf8');
10
16
 
11
17
  const server = createPunicaFormServer({ packages, guide });
package/src/validate.mjs CHANGED
@@ -69,7 +69,9 @@ export function createValidator(knowledge) {
69
69
 
70
70
  // The rules name what 2.0 removed; for a project that still has 1.x
71
71
  // installed that API is correct, so only its imports are checked
72
- const isLegacy = knowledge.packages.some((pkg) => parseInt(pkg.version) < 2);
72
+ const isLegacy = knowledge.packages.some(
73
+ (pkg) => pkg.name === '@punica/form' && parseInt(pkg.version) < 2
74
+ );
73
75
 
74
76
  /**
75
77
  * @param {string} code