@chepchik/bind-form 0.1.2 → 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/README.md CHANGED
@@ -1,17 +1,27 @@
1
1
  # bind-form
2
2
 
3
- Что: один помощник `bindForm`, который вешает обработчик `submit` на форму,
4
- валидирует поля по схеме (`required` / `pattern` / `minLength` / `maxLength` /
5
- `min` / `max` / `validate`, опционально + `resolver`) и вызывает `onSubmit`
6
- с собранными значениями, если всё валидно. Опционально умеет валидировать
7
- поля "на лету" (`validateOn: "blur" | "input"`), показывать ошибку для
8
- каждого поля отдельно, отслеживать `dirty`/`touched`/`isSubmitting`
9
- (`onStateChange`, `getState`), реагировать на изменения отдельного поля
10
- (`watch`) и блокировать кнопку отправки на время `onSubmit`.
3
+ ![coverage](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/Egortex/spa-toolkit/main/packages/bind-form/coverage-badge.json) ![size](https://img.shields.io/bundlephobia/minzip/@chepchik/bind-form)
4
+
5
+ Что: dependency-free typed form engine поверх настоящего `<form>`/`FormData`.
6
+ Два входа в один и тот же движок:
7
+
8
+ - `createForm({ schema, initialValues })` — `form.values`/`form.errors`
9
+ выводятся из `schema` типами (без ручного `TField`), значения полей могут
10
+ быть не только `string` (`number`/`boolean`/`string[]`), валидация идёт по
11
+ пайплайну `sync → async(на поле) → resolver(на форму) → server`, а сервер
12
+ ошибки `{ field, code }[]` автоматически маппятся в `form.errors`/`form.formError`.
13
+ - `bindForm(form, options)` — прежний API (submit handling, `schema`,
14
+ `resolver`, `validateOn`, `onStateChange`, `watch`...), работает без
15
+ изменений сигнатуры и построен поверх того же движка.
16
+
17
+ Оба API автоматически проставляют accessibility-атрибуты (`aria-invalid`,
18
+ `aria-describedby`, `role="alert"`) и переносят фокус на первое невалидное
19
+ поле после неуспешного submit — это не опция, а поведение "из коробки"
20
+ (см. раздел [Accessibility](#accessibility)).
11
21
 
12
22
  Зачем: чтобы не дублировать в каждой форме одинаковый код —
13
- `preventDefault`, сбор `FormData`, проверку полей и regex,
14
- показ/скрытие текста ошибки. Отправка по Enter работает "из коробки",
23
+ `preventDefault`, сбор `FormData`, проверку полей, показ/скрытие ошибок,
24
+ доступность и фокус-менеджмент. Отправка по Enter работает "из коробки",
15
25
  т.к. используется стандартное поведение `<form>`.
16
26
 
17
27
  ## Установка
@@ -20,7 +30,153 @@
20
30
  npm install @chepchik/bind-form
21
31
  ```
22
32
 
23
- ## Использование
33
+ ## Typed forms
34
+
35
+ ```ts
36
+ import { createForm } from "@chepchik/bind-form";
37
+
38
+ const form = document.querySelector("form")!;
39
+
40
+ const handle = createForm(form, {
41
+ schema: {
42
+ name: { required: "Введите имя" },
43
+ age: { type: "number", min: { value: 18, message: "Минимум 18" } },
44
+ agree: { type: "checkbox", required: "Нужно согласие" },
45
+ },
46
+ initialValues: { age: 18 },
47
+ onSubmit: async (values) => {
48
+ // values.name: string, values.age: number, values.agree: boolean —
49
+ // выведено из schema, без ручного указания generic-параметра.
50
+ await api.register(values);
51
+ },
52
+ });
53
+
54
+ handle.getValues().age; // number
55
+ handle.setValue("age", 21); // типизировано по конкретному полю
56
+
57
+ // позже, при размонтировании:
58
+ handle();
59
+ ```
60
+
61
+ `FieldSchema.type` определяет, как строковое значение `FormData` приводится
62
+ к типу `form.values[field]`:
63
+
64
+ - `"text"` (по умолчанию) → `string`
65
+ - `"number"` → `number` (непарсибельное значение — ошибка валидации, а не `NaN`)
66
+ - `"checkbox"` → `boolean`
67
+ - `"multiselect"` → `string[]` (все значения `name`, например группа чекбоксов)
68
+
69
+ Свой парсинг/сериализация — через `parse`/`serialize` в `FieldSchema` вместо `type`.
70
+
71
+ ## Validation pipeline
72
+
73
+ ```
74
+ submit
75
+ │
76
+ ▼
77
+ sync (required/pattern/minLength/maxLength/min/max) — на каждое поле
78
+ │ ошибка → стоп для этого поля, async не запускается (REQ-006)
79
+ ▼
80
+ async (per field, например uniqueness-проверка)
81
+ │
82
+ ▼
83
+ resolver (form-level, только для полей без ошибок sync/async)
84
+ │
85
+ ▼
86
+ onSubmit(values) — если ошибок нет
87
+ │ бросает FormSubmitError → server-стадия
88
+ ▼
89
+ server errors → form.errors / form.formError
90
+ ```
91
+
92
+ ```ts
93
+ const handle = createForm(form, {
94
+ schema: {
95
+ email: {
96
+ required: "Введите email",
97
+ pattern: { value: /.+@.+/, message: "Неверный формат" },
98
+ // async выполняется, только если email прошёл sync-проверки выше.
99
+ async: async (value) => ((await api.isEmailTaken(value)) ? "Email уже занят" : undefined),
100
+ },
101
+ },
102
+ onSubmit: async (values) => api.register(values),
103
+ });
104
+ ```
105
+
106
+ Если поле не прошло sync-стадию, его `async`-правило не вызывается вообще —
107
+ это можно проверить шпионом/счётчиком вызовов (см. `tests/validation.test.ts`).
108
+
109
+ ## Server errors
110
+
111
+ ```ts
112
+ import { createForm, FormSubmitError } from "@chepchik/bind-form";
113
+
114
+ const handle = createForm(form, {
115
+ schema: { email: {} },
116
+ errorMessages: { EMAIL_EXISTS: "Такой email уже зарегистрирован" },
117
+ onSubmit: async (values) => {
118
+ const res = await fetch("/api/register", { method: "POST", body: JSON.stringify(values) });
119
+ if (res.status === 422) {
120
+ throw new FormSubmitError(await res.json()); // [{ field: "email", code: "EMAIL_EXISTS" }]
121
+ }
122
+ },
123
+ });
124
+ ```
125
+
126
+ - `code` резолвится через `errorMessages`, при отсутствии — фолбэк на `message`,
127
+ затем на сырой `code`, затем на общий fallback-текст.
128
+ - Ошибка с `field`, которого нет в `schema` (или без `field` вообще), попадает
129
+ в `handle.getState().formError`, а не теряется и не бросает исключение.
130
+
131
+ ## Accessibility
132
+
133
+ Применяется автоматически и к `createForm`, и к `bindForm` — не требует
134
+ настройки со стороны потребителя:
135
+
136
+ ```html
137
+ <input name="email" aria-invalid="true" aria-describedby="email-error" />
138
+ <span data-error-for="email" id="email-error" role="alert" aria-live="polite">
139
+ Неверный формат
140
+ </span>
141
+ ```
142
+
143
+ - `aria-invalid="true"` появляется на поле при ошибке и снимается, когда её нет.
144
+ - `[data-error-for="<field>"]` получает `role="alert"`, стабильный `id`
145
+ (генерируется как `${field}-error`, если отсутствует), и этот `id`
146
+ прописывается в `aria-describedby` поля.
147
+ - После неуспешного submit фокус переходит на первое невалидное поле в
148
+ DOM-порядке (`form.elements`, а не порядок ключей `schema`) — обычная
149
+ Tab/Shift+Tab навигация после этого не нарушается (никакого focus trap).
150
+ - В dev-режиме (`process.env.NODE_ENV !== "production"`) в консоль выводится
151
+ предупреждение, если у поля схемы нет связанного `<label>` (`for`/wrapping
152
+ `<label>`/`aria-label`/`aria-labelledby`). Проверка не попадает в
153
+ production-сборку по стоимости выполнения — только вызов вырезается вручную
154
+ через `NODE_ENV`, поэтому убедитесь, что ваш бандлер минифицирует `if (false)`.
155
+
156
+ ## Migrating from `bindForm` to `createForm`
157
+
158
+ `bindForm` продолжает работать без изменений — мигрировать не обязательно.
159
+
160
+ | `bindForm` | `createForm` |
161
+ |---|---|
162
+ | `schema: Record<TField, FieldRule>` | `schema: Record<TField, FieldSchema<TValue>>` (+ `type`/`parse`/`serialize`/`async`) |
163
+ | `values: FormValues<TField>` (всегда `string`) | `values: InferValues<TSchema>` (типы из схемы) |
164
+ | нет серверных ошибок | `errorMessages` + `FormSubmitError` → `form.errors`/`form.formError` |
165
+ | `resolver` — form-level async | тот же `resolver`, плюс per-field `async` в схеме |
166
+ | нет accessibility-контракта | `aria-*`/`role="alert"`/focus management — из коробки (и для `bindForm` тоже) |
167
+
168
+ ## Testing
169
+
170
+ ```sh
171
+ npm run test # tsc --noEmit && vitest run
172
+ npm run test:coverage # то же самое + отчёт покрытия, порог 100% по lines/branches/functions/statements
173
+ ```
174
+
175
+ Любой вклад в пакет должен сохранять 100% покрытие (`vitest.config.ts`,
176
+ `coverage.thresholds`) — `vitest run --coverage` завершается с ненулевым
177
+ кодом, если покрытие `src/**/*.ts` падает ниже 100% хотя бы по одной метрике.
178
+
179
+ ## Пример использования `bindForm`
24
180
 
25
181
  ```ts
26
182
  import { bindForm } from "@chepchik/bind-form";
@@ -51,7 +207,7 @@ formHandle();
51
207
  Для показа ошибки конкретного поля при `validateOn` добавьте рядом с полем
52
208
  элемент `[data-error-for="<name>"]` (`<span data-error-for="email" hidden></span>`).
53
209
 
54
- ## Пример: сложная форма
210
+ ## Пример: сложная форма (`bindForm`)
55
211
 
56
212
  Более развёрнутый пример, использующий все возможности: `resolver` для
57
213
  асинхронной проверки, `onStateChange` для индикации состояния, `watch` для
@@ -117,6 +273,27 @@ resetButton.addEventListener("click", () => handle.reset());
117
273
 
118
274
  ## API
119
275
 
276
+ ### `createForm<TSchema>(form, options): FormHandle<InferValues<TSchema>, keyof TSchema & string>`
277
+
278
+ - `options.schema: Record<TField, FieldSchema<TValue>>` — валидация + типизация.
279
+ - Наследует `required`/`pattern`/`minLength`/`maxLength`/`min`/`max` из `FieldRule`.
280
+ - `type?: "text" | "number" | "checkbox" | "multiselect"` — как приводится значение.
281
+ - `parse?`/`serialize?` — свой парсинг/сериализация вместо `type`.
282
+ - `validate?: (value: TValue, values) => string | undefined` — sync, после built-in правил.
283
+ - `async?: (value: TValue, values) => string | undefined | Promise<...>` — только если sync прошёл (REQ-006).
284
+ - `options.initialValues?: Partial<InferValues<TSchema>>` — записываются в поля формы при вызове `createForm`.
285
+ - `options.errorElement?`, `options.validateOn?`, `options.resolver?`,
286
+ `options.onStateChange?`, `options.disableSubmitWhilePending?`,
287
+ `options.resetOnSuccess?` — как в `bindForm`, но типизированы по `TSchema`.
288
+ - `options.onSubmit(values, form)` — может бросить/вернуть `FormSubmitError`
289
+ для server-стадии пайплайна.
290
+ - `options.errorMessages?: Record<string, string>` — словарь `code → message`
291
+ для `mapServerErrors`.
292
+
293
+ Возвращает `FormHandle`: `getValues()`, `setValue(field, value)`,
294
+ `setError(field, message?)`, `setFormError(message?)`, `reset()`,
295
+ `getState()`, `watch(field, callback)` — все типизированы по `TSchema`.
296
+
120
297
  ### `bindForm<TField>(form, options): BindFormHandle<TField>`
121
298
 
122
299
  - `form: HTMLFormElement` — форма, на которую вешается обработчик `submit`.
@@ -171,3 +348,10 @@ resetButton.addEventListener("click", () => handle.reset());
171
348
  - `getState(): FormState<TField>` — снимок текущего состояния формы.
172
349
  - `watch(field, callback)` — вызывать `callback(value, values)` при каждом
173
350
  изменении значения `field`. Возвращает функцию отписки.
351
+
352
+ ### `mapServerErrors(response, knownFields, errorMessages?)`
353
+
354
+ Превращает `ServerErrorResponse` (`{ field?, code?, message? }[]`) в
355
+ `{ fieldErrors, formError }`. Используется автоматически внутри `createForm`
356
+ при `FormSubmitError`, но экспортируется и для ручного использования (в том
357
+ числе вместе с `bindForm`).
package/dist/index.js CHANGED
@@ -1,127 +1,283 @@
1
- //#region src/index.ts
2
- function e(e, r) {
3
- let i = Object.keys(r.schema), a = {}, o = {}, s = {}, c = !1, l = (e, t) => {
4
- let n = r.schema[e];
5
- if (n.required && !t) return n.required;
6
- if (t) {
7
- if (n.pattern && !n.pattern.value.test(t)) return n.pattern.message;
8
- if (n.minLength && t.length < n.minLength.value) return n.minLength.message;
9
- if (n.maxLength && t.length > n.maxLength.value) return n.maxLength.message;
10
- if (n.min || n.max) {
11
- let e = Number(t);
12
- if (!Number.isNaN(e)) {
13
- if (n.min && e < n.min.value) return n.min.message;
14
- if (n.max && e > n.max.value) return n.max.message;
15
- }
1
+ //#region src/validation.ts
2
+ function e(e, t) {
3
+ if (e.required && !t) return e.required;
4
+ if (t) {
5
+ if (e.pattern && !e.pattern.value.test(t)) return e.pattern.message;
6
+ if (e.minLength && t.length < e.minLength.value) return e.minLength.message;
7
+ if (e.maxLength && t.length > e.maxLength.value) return e.maxLength.message;
8
+ if (e.min || e.max) {
9
+ let n = Number(t);
10
+ if (!Number.isNaN(n)) {
11
+ if (e.min && n < e.min.value) return e.min.message;
12
+ if (e.max && n > e.max.value) return e.max.message;
13
+ }
14
+ }
15
+ }
16
+ }
17
+ async function t(t, n, r, i, a) {
18
+ let o = e(t, n);
19
+ if (o) return o;
20
+ if (a) return a;
21
+ let s = t.validate?.(r, i) || void 0;
22
+ if (s) return s;
23
+ if (t.async) return await t.async(r, i) || void 0;
24
+ }
25
+ async function n(e, n, r, i, a, o) {
26
+ let s = await Promise.all(e.map(async (e) => [e, await t(n(e), r(e), i(e), a, o?.(e))])), c = {};
27
+ for (let [e, t] of s) t && (c[e] = t);
28
+ return c;
29
+ }
30
+ //#endregion
31
+ //#region src/accessibility.ts
32
+ function r(e, t, n, r) {
33
+ if (r ? e.setAttribute("aria-invalid", "true") : e.removeAttribute("aria-invalid"), !n) return;
34
+ n.id ||= `${t}-error`, i(n);
35
+ let a = (e.getAttribute("aria-describedby") ?? "").split(/\s+/).filter(Boolean).filter((e) => e !== n.id);
36
+ r ? e.setAttribute("aria-describedby", [...a, n.id].join(" ")) : a.length > 0 ? e.setAttribute("aria-describedby", a.join(" ")) : e.removeAttribute("aria-describedby");
37
+ }
38
+ function i(e) {
39
+ e.hasAttribute("role") || e.setAttribute("role", "alert"), e.hasAttribute("aria-live") || e.setAttribute("aria-live", "polite");
40
+ }
41
+ function a(e, t) {
42
+ for (let n of Array.from(e.elements)) {
43
+ let e = n.getAttribute("name");
44
+ if (!e || !t[e]) continue;
45
+ let r = n;
46
+ typeof r.focus == "function" && r.focus();
47
+ return;
48
+ }
49
+ }
50
+ function o(e, t) {
51
+ if (typeof process < "u" && process.env.NODE_ENV === "production") return;
52
+ let n = e.elements.namedItem(t);
53
+ if (!n || !(n instanceof HTMLElement)) return;
54
+ let r = n.getAttribute("id"), i = r ? e.querySelector(`label[for="${r}"]`) !== null : !1, a = n.closest("label") !== null, o = n.hasAttribute("aria-label") || n.hasAttribute("aria-labelledby");
55
+ !i && !a && !o && console.warn(`[bind-form] Field "${t}" has no associated <label>. Add <label for="${r ?? t}"> for accessibility.`);
56
+ }
57
+ //#endregion
58
+ //#region src/engine.ts
59
+ var s = (e) => e instanceof HTMLInputElement || e instanceof HTMLTextAreaElement || e instanceof HTMLSelectElement;
60
+ function c(e, c) {
61
+ let d = c.fields.map((e) => e.name), f = new Map(c.fields.map((e) => [e.name, e.schema])), p = (e) => f.get(e), m = {}, h, g = {}, _ = {}, v = !1, y = (t) => String(new FormData(e).get(t) ?? "").trim(), b = (t) => new FormData(e).getAll(t).map((e) => String(e)), x = (e) => {
62
+ if (p(e).type === "multiselect") {
63
+ let t = b(e);
64
+ return t.length > 0 ? t.join(",") : "";
65
+ }
66
+ return y(e);
67
+ }, S = (e) => {
68
+ let t = p(e), n = x(e);
69
+ if (t.type === "number" && n !== "" && Number.isNaN(Number(n))) return "Invalid number value";
70
+ }, C = (e) => {
71
+ let t = p(e), n = y(e);
72
+ if (t.type === "multiselect") return b(e);
73
+ if (t.parse) return t.parse(n);
74
+ switch (t.type) {
75
+ case "number": {
76
+ if (n === "") return;
77
+ let e = Number(n);
78
+ return Number.isNaN(e) ? void 0 : e;
16
79
  }
17
- return n.validate?.(t) || void 0;
80
+ case "checkbox": return n !== "";
81
+ default: return n;
18
82
  }
19
- }, u = (t) => e.querySelector(`[data-error-for="${t}"]`), d = (e, t) => {
20
- a[e] = t;
21
- let n = u(e);
22
- n && (t ? (n.textContent = t, n.removeAttribute("hidden")) : n.setAttribute("hidden", ""));
23
- }, f = (t) => String(new FormData(e).get(t) ?? "").trim(), p = () => {
83
+ }, w = () => {
24
84
  let e = {};
25
- for (let t of i) e[t] = f(t);
85
+ for (let t of d) e[t] = C(t);
26
86
  return e;
27
- }, m = () => {
28
- s = p();
87
+ }, T = () => {
88
+ _ = w();
29
89
  };
30
- m();
31
- let h = () => {
90
+ T();
91
+ let E = () => {
32
92
  let e = {};
33
- for (let t of i) e[t] = f(t) !== s[t];
93
+ for (let t of d) e[t] = y(t) !== D(t);
34
94
  return e;
35
- }, g = () => {
36
- if (!r.onStateChange) return;
37
- let e = h();
38
- r.onStateChange({
39
- values: p(),
40
- errors: { ...a },
41
- touched: { ...o },
95
+ }, D = (e) => u(p(e), _[e]), O = (t) => e.querySelector(`[data-error-for="${t}"]`), k = (t) => {
96
+ let n = e.elements.namedItem(t);
97
+ s(n) && r(n, t, O(t), !!m[t]);
98
+ }, A = (e, t) => {
99
+ m[e] = t;
100
+ let n = O(e);
101
+ n && (t ? (n.textContent = t, n.removeAttribute("hidden")) : n.setAttribute("hidden", "")), k(e);
102
+ }, j = (e) => {
103
+ h = e, l(c.errorElement, e);
104
+ }, M = () => {
105
+ if (!c.onStateChange) return;
106
+ let e = E();
107
+ c.onStateChange({
108
+ values: w(),
109
+ errors: { ...m },
110
+ formError: h,
111
+ touched: { ...g },
42
112
  dirty: e,
43
- isDirty: i.some((t) => e[t]),
44
- isSubmitting: c
113
+ isDirty: d.some((t) => e[t]),
114
+ isSubmitting: v
45
115
  });
46
- }, _ = (t) => {
116
+ }, N = (t) => {
47
117
  let n = e.querySelectorAll("[type=\"submit\"]");
48
118
  for (let e of n) e.disabled = t;
49
- }, v = async () => {
50
- let e = p(), t = {};
51
- for (let n of i) t[n] = l(n, e[n]);
52
- if (r.resolver) {
53
- let n = await r.resolver(e);
54
- for (let e of i) !t[e] && n[e] && (t[e] = n[e]);
119
+ }, P = async () => {
120
+ let e = w(), t = await n(d, p, x, C, e, S);
121
+ if (c.resolver) {
122
+ let n = await c.resolver(e);
123
+ for (let e of d) !t[e] && n[e] && (t[e] = n[e]);
55
124
  }
56
- let n;
57
- for (let e of i) d(e, t[e]), !n && t[e] && (n = t[e]);
125
+ let r, i = !1;
126
+ for (let e of d) A(e, t[e]), t[e] && (i = !0, r ||= t[e]);
58
127
  return {
59
128
  values: e,
60
- firstError: n
129
+ firstError: r,
130
+ hasError: i
61
131
  };
62
- }, y = () => {
63
- for (let e of i) d(e, void 0);
64
- n(r.errorElement);
65
- }, b = (a) => {
66
- a.preventDefault(), (async () => {
67
- let { values: a, firstError: s } = await v();
68
- if (g(), s) {
69
- t(r.errorElement, s);
132
+ }, F = (e) => {
133
+ l(c.errorElement, e);
134
+ }, I = () => {
135
+ for (let e of d) A(e, void 0);
136
+ j(void 0);
137
+ }, L = (t) => {
138
+ t.preventDefault(), (async () => {
139
+ h = void 0;
140
+ let { values: t, firstError: n, hasError: r } = await P();
141
+ if (M(), r) {
142
+ F(n), a(e, m);
70
143
  return;
71
144
  }
72
- n(r.errorElement), c = !0, r.disableSubmitWhilePending !== !1 && _(!0), g();
145
+ F(void 0), v = !0, c.disableSubmitWhilePending !== !1 && N(!0), M();
73
146
  try {
74
- if (await r.onSubmit(a, e), r.resetOnSuccess) {
75
- e.reset(), y();
76
- for (let e of i) o[e] = !1;
77
- m();
147
+ if (await c.onSubmit(t, e), c.resetOnSuccess) {
148
+ e.reset(), I();
149
+ for (let e of d) g[e] = !1;
150
+ T();
78
151
  }
152
+ } catch (t) {
153
+ let n = c.mapSubmitError?.(t);
154
+ if (!n) throw t;
155
+ for (let e of d) A(e, n.fieldErrors[e]);
156
+ j(n.formError), a(e, m);
79
157
  } finally {
80
- c = !1, r.disableSubmitWhilePending !== !1 && _(!1), g();
158
+ v = !1, c.disableSubmitWhilePending !== !1 && N(!1), M();
81
159
  }
82
160
  })();
83
- }, x = (e) => {
84
- let t = e.target;
85
- if (!(t instanceof HTMLElement)) return;
86
- let n = t.getAttribute("name");
87
- !n || !i.includes(n) || (o[n] = !0, d(n, l(n, f(n))), g());
161
+ }, R = (e) => {
162
+ let n = e.target;
163
+ if (!(n instanceof HTMLElement)) return;
164
+ let r = n.getAttribute("name");
165
+ !r || !d.includes(r) || (g[r] = !0, (async () => {
166
+ A(r, await t(p(r), x(r), C(r), w(), S(r))), M();
167
+ })());
88
168
  };
89
- e.addEventListener("submit", b), r.validateOn && e.addEventListener(r.validateOn, x, !0);
90
- let S = (() => {
91
- e.removeEventListener("submit", b), r.validateOn && e.removeEventListener(r.validateOn, x, !0);
169
+ e.addEventListener("submit", L), c.validateOn && e.addEventListener(c.validateOn, R, !0);
170
+ for (let t of d) {
171
+ k(t);
172
+ let n = O(t);
173
+ n && i(n), c.skipLabelWarning || o(e, t);
174
+ }
175
+ let z = (() => {
176
+ e.removeEventListener("submit", L), c.validateOn && e.removeEventListener(c.validateOn, R, !0);
92
177
  });
93
- return S.getValues = p, S.setValue = (t, n) => {
178
+ return z.getValues = w, z.setValue = (t, n) => {
94
179
  let r = e.elements.namedItem(t);
95
- (r instanceof HTMLInputElement || r instanceof HTMLTextAreaElement || r instanceof HTMLSelectElement) && (r.value = n), g();
96
- }, S.setError = (e, t) => {
97
- d(e, t), g();
98
- }, S.reset = () => {
99
- e.reset(), y();
100
- for (let e of i) o[e] = !1;
101
- m(), g();
102
- }, S.getState = () => {
103
- let e = h();
180
+ s(r) && (r.value = n), k(t), M();
181
+ }, z.setError = (e, t) => {
182
+ A(e, t), M();
183
+ }, z.setFormError = (e) => {
184
+ j(e), M();
185
+ }, z.reset = () => {
186
+ e.reset(), I();
187
+ for (let e of d) g[e] = !1;
188
+ T(), M();
189
+ }, z.getState = () => {
190
+ let e = E();
104
191
  return {
105
- values: p(),
106
- errors: { ...a },
107
- touched: { ...o },
192
+ values: w(),
193
+ errors: { ...m },
194
+ formError: h,
195
+ touched: { ...g },
108
196
  dirty: e,
109
- isDirty: i.some((t) => e[t]),
110
- isSubmitting: c
197
+ isDirty: d.some((t) => e[t]),
198
+ isSubmitting: v
111
199
  };
112
- }, S.watch = (t, n) => {
200
+ }, z.watch = (t, n) => {
113
201
  let r = (e) => {
114
202
  let r = e.target;
115
- r instanceof HTMLElement && r.getAttribute("name") === t && n(f(t), p());
203
+ r instanceof HTMLElement && r.getAttribute("name") === t && n(C(t), w());
116
204
  };
117
205
  return e.addEventListener("input", r), () => e.removeEventListener("input", r);
118
- }, S;
206
+ }, z;
207
+ }
208
+ function l(e, t) {
209
+ e && (t ? (e.textContent = t, e.removeAttribute("hidden")) : e.setAttribute("hidden", ""));
210
+ }
211
+ function u(e, t) {
212
+ return e.serialize ? e.serialize(t) : e.type === "number" ? t == null ? "" : String(t) : e.type === "checkbox" ? t ? "on" : "" : e.type === "multiselect" ? Array.isArray(t) ? t.join(",") : "" : typeof t == "string" ? t : String(t ?? "");
213
+ }
214
+ //#endregion
215
+ //#region src/serverErrors.ts
216
+ var d = class extends Error {
217
+ errors;
218
+ constructor(e, t = "Form submit failed") {
219
+ super(t), this.name = "FormSubmitError", this.errors = e;
220
+ }
221
+ };
222
+ function f(e, t, n) {
223
+ let r = {}, i;
224
+ for (let a of e) {
225
+ let e = p(a, n), o = a.field;
226
+ o && t.includes(o) ? r[o] = e : i ||= e;
227
+ }
228
+ return {
229
+ fieldErrors: r,
230
+ formError: i
231
+ };
232
+ }
233
+ function p(e, t) {
234
+ return e.code && t?.[e.code] ? t[e.code] : e.message ? e.message : e.code ? e.code : "Invalid value";
119
235
  }
120
- function t(e, t) {
121
- e && (e.textContent = t, e.removeAttribute("hidden"));
236
+ //#endregion
237
+ //#region src/createForm.ts
238
+ function m(e, t) {
239
+ let n = Object.keys(t.schema);
240
+ if (t.initialValues) for (let r of n) {
241
+ let n = t.initialValues[r];
242
+ if (n === void 0) continue;
243
+ let i = e.elements.namedItem(r);
244
+ (i instanceof HTMLInputElement || i instanceof HTMLTextAreaElement || i instanceof HTMLSelectElement) && (i.value = u(t.schema[r], n));
245
+ }
246
+ let r = c(e, {
247
+ fields: n.map((e) => ({
248
+ name: e,
249
+ schema: t.schema[e]
250
+ })),
251
+ errorElement: t.errorElement,
252
+ validateOn: t.validateOn,
253
+ resolver: t.resolver,
254
+ onStateChange: t.onStateChange,
255
+ disableSubmitWhilePending: t.disableSubmitWhilePending,
256
+ onSubmit: t.onSubmit,
257
+ resetOnSuccess: t.resetOnSuccess,
258
+ mapSubmitError: (e) => {
259
+ if (e instanceof d) return f(e.errors, n, t.errorMessages);
260
+ }
261
+ }), i = (() => r());
262
+ return i.getValues = () => r.getValues(), i.setValue = (e, n) => r.setValue(e, u(t.schema[e], n)), i.setError = (e, t) => r.setError(e, t), i.setFormError = (e) => r.setFormError(e), i.reset = () => r.reset(), i.getState = () => r.getState(), i.watch = (e, t) => r.watch(e, (e, n) => t(e, n)), i;
122
263
  }
123
- function n(e) {
124
- e && e.setAttribute("hidden", "");
264
+ //#endregion
265
+ //#region src/index.ts
266
+ function h(e, t) {
267
+ let n = c(e, {
268
+ fields: Object.keys(t.schema).map((e) => ({
269
+ name: e,
270
+ schema: t.schema[e]
271
+ })),
272
+ errorElement: t.errorElement,
273
+ validateOn: t.validateOn,
274
+ resolver: t.resolver,
275
+ onStateChange: t.onStateChange,
276
+ disableSubmitWhilePending: t.disableSubmitWhilePending,
277
+ onSubmit: t.onSubmit,
278
+ resetOnSuccess: t.resetOnSuccess
279
+ }), r = (() => n());
280
+ return r.getValues = () => n.getValues(), r.setValue = (e, t) => n.setValue(e, t), r.setError = (e, t) => n.setError(e, t), r.reset = () => n.reset(), r.getState = () => n.getState(), r.watch = (e, t) => n.watch(e, (e, n) => t(e, n)), r;
125
281
  }
126
282
  //#endregion
127
- export { e as bindForm };
283
+ export { d as FormSubmitError, r as applyFieldAccessibility, h as bindForm, c as createEngine, m as createForm, i as ensureErrorElementA11y, a as focusFirstInvalidField, f as mapServerErrors, t as runFieldPipeline, n as runFormPipeline, e as runSyncRules, u as serializeFieldValue, o as warnIfLabelMissing };
@@ -0,0 +1,24 @@
1
+ type FieldElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
2
+ /**
3
+ * Applies `aria-invalid` to `input` based on `hasError`, and (when `hasError` is true) links it to
4
+ * `errorElement` via `aria-describedby`, generating a stable `id` for `errorElement` if it doesn't
5
+ * have one yet (`${field}-error`). When `hasError` is false, `aria-invalid` is removed and the
6
+ * `aria-describedby` reference to the error element is removed (without touching other ids the
7
+ * consumer may have added there) (REQ-010/REQ-011).
8
+ */
9
+ export declare function applyFieldAccessibility(input: FieldElement, field: string, errorElement: HTMLElement | null, hasError: boolean): void;
10
+ /** Marks a field's error element as an accessible live region (`role="alert"`, `aria-live="polite"`), once. */
11
+ export declare function ensureErrorElementA11y(errorElement: HTMLElement): void;
12
+ /**
13
+ * Focuses the first field (in DOM order, via `form.elements`, not schema key order) that has an
14
+ * entry in `errors`. Does nothing beyond a single `.focus()` call — it never sets `tabindex` or
15
+ * otherwise affects subsequent Tab/Shift+Tab navigation (REQ-012/REQ-013).
16
+ */
17
+ export declare function focusFirstInvalidField(form: HTMLFormElement, errors: Record<string, string | undefined>): void;
18
+ /**
19
+ * Dev-only check (skipped when `process.env.NODE_ENV === "production"`): warns via `console.warn`
20
+ * if a schema field's input has no associated `<label for="...">` in the form (REQ-014). Intended
21
+ * to be tree-shaken out of production builds together with its call site.
22
+ */
23
+ export declare function warnIfLabelMissing(form: HTMLFormElement, field: string): void;
24
+ export {};
@@ -0,0 +1,49 @@
1
+ import { FieldSchema, FormHandle, InferValues, TypedFormState } from './types';
2
+ export interface CreateFormOptions<TSchema extends Record<string, FieldSchema<any>>> {
3
+ /** Validation + typing schema: keys must match the `name` attributes of the form fields. */
4
+ schema: TSchema;
5
+ /** Initial values written into the form's fields when `createForm` is called. */
6
+ initialValues?: Partial<InferValues<TSchema>>;
7
+ /** Element used to display the form-level error message (must support `hidden`). */
8
+ errorElement?: HTMLElement;
9
+ /**
10
+ * Run validation for a field as the user interacts with it, in addition to on submit.
11
+ * Per-field errors are shown in elements matching `[data-error-for="<field>"]` inside the form.
12
+ */
13
+ validateOn?: "blur" | "input";
14
+ /**
15
+ * Additional form-level async validation, run on submit after each field's own
16
+ * `sync -> async` pipeline. Only consulted for fields that passed their own pipeline.
17
+ */
18
+ resolver?: (values: InferValues<TSchema>) => Partial<Record<keyof TSchema & string, string>> | Promise<Partial<Record<keyof TSchema & string, string>>>;
19
+ /** Called whenever the form's values/errors/formError/touched/dirty/submitting state changes. */
20
+ onStateChange?: (state: TypedFormState<InferValues<TSchema>, keyof TSchema & string>) => void;
21
+ /**
22
+ * Disable `[type="submit"]` elements inside the form while `onSubmit` is pending.
23
+ * Defaults to `true`.
24
+ */
25
+ disableSubmitWhilePending?: boolean;
26
+ /**
27
+ * Called with the validated, typed values after a successful sync/async/resolver pipeline.
28
+ * Throw (or reject with) a `FormSubmitError` to report server-side validation errors — they
29
+ * are mapped through `mapServerErrors`/`errorMessages` automatically instead of propagating
30
+ * as an unhandled exception (REQ-007/TASK-013).
31
+ */
32
+ onSubmit: (values: InferValues<TSchema>, form: HTMLFormElement) => void | Promise<void>;
33
+ /** Reset the form after a successful onSubmit. */
34
+ resetOnSuccess?: boolean;
35
+ /** Maps a server error `code` (see `ServerError`) to a human-readable message (REQ-008). */
36
+ errorMessages?: Record<string, string>;
37
+ }
38
+ /**
39
+ * Creates a typed form engine over a real `<form>`: `form.values`/`form.errors` are inferred
40
+ * from `schema` (REQ-001/REQ-002), field values are parsed/serialized per `FieldSchema.type`
41
+ * (REQ-003), and the `sync -> async(per field) -> resolver(form-level) -> server` validation
42
+ * pipeline (see `validation.ts`) runs on every submit. Accessibility (`aria-invalid`,
43
+ * `aria-describedby`, `role="alert"`, focus management on failed submit) is applied automatically,
44
+ * same as `bindForm` (ASSUMPTION-001).
45
+ *
46
+ * Returns a handle: call it to unsubscribe, or use `getValues`/`setValue`/`setError`/
47
+ * `setFormError`/`reset`/`getState`/`watch`.
48
+ */
49
+ export declare function createForm<TSchema extends Record<string, FieldSchema<any>>>(form: HTMLFormElement, options: CreateFormOptions<TSchema>): FormHandle<InferValues<TSchema>, keyof TSchema & string>;
@@ -0,0 +1,47 @@
1
+ import { FieldSchema, TypedFormState } from './types';
2
+ /** One schema field as seen by the engine: its name and its typed validation/parsing schema. */
3
+ export interface EngineField<TField extends string> {
4
+ name: TField;
5
+ schema: FieldSchema<any>;
6
+ }
7
+ export interface EngineOptions<TValues extends Record<string, unknown>, TField extends string> {
8
+ fields: EngineField<TField>[];
9
+ errorElement?: HTMLElement;
10
+ validateOn?: "blur" | "input";
11
+ resolver?: (values: TValues) => Partial<Record<TField, string>> | Promise<Partial<Record<TField, string>>>;
12
+ onStateChange?: (state: TypedFormState<TValues, TField>) => void;
13
+ disableSubmitWhilePending?: boolean;
14
+ onSubmit: (values: TValues, form: HTMLFormElement) => void | Promise<void>;
15
+ resetOnSuccess?: boolean;
16
+ /**
17
+ * Called when `onSubmit` throws/rejects. Return mapped errors to display them as the "server"
18
+ * pipeline stage (REQ-004); return `undefined` to let the error propagate (e.g. unhandled
19
+ * rejection), matching the behavior of the legacy `bindForm` (which has no such hook).
20
+ */
21
+ mapSubmitError?: (error: unknown) => {
22
+ fieldErrors: Partial<Record<TField, string>>;
23
+ formError?: string;
24
+ } | undefined;
25
+ /** Skip the dev-only missing-`<label>` warning (used internally by tests). */
26
+ skipLabelWarning?: boolean;
27
+ }
28
+ /** Handle shared by `bindForm` and `createForm`; each wraps it with its own public, typed surface. */
29
+ export interface EngineHandle<TValues extends Record<string, unknown>, TField extends string> {
30
+ (): void;
31
+ getValues(): TValues;
32
+ setValue(field: TField, raw: string): void;
33
+ setError(field: TField, message: string | undefined): void;
34
+ setFormError(message: string | undefined): void;
35
+ reset(): void;
36
+ getState(): TypedFormState<TValues, TField>;
37
+ watch(field: TField, callback: (value: unknown, values: TValues) => void): () => void;
38
+ }
39
+ /**
40
+ * Shared internal engine behind both `bindForm` and `createForm`: subscribes to `submit` (and
41
+ * optionally `blur`/`input`), runs the `sync -> async(per field) -> resolver(form-level) -> server`
42
+ * validation pipeline, applies accessibility attributes (REQ-010/011) and focus management
43
+ * (REQ-012/013) to every bound field, and reports state via `onStateChange`.
44
+ */
45
+ export declare function createEngine<TValues extends Record<string, unknown>, TField extends string>(form: HTMLFormElement, options: EngineOptions<TValues, TField>): EngineHandle<TValues, TField>;
46
+ /** Converts a typed field value back into the raw string a DOM field element expects, using `FieldSchema.serialize`/`type`. */
47
+ export declare function serializeFieldValue(schema: FieldSchema<any>, value: unknown): string;
@@ -0,0 +1,35 @@
1
+ import { BindFormHandle, BindFormOptions } from './types';
2
+ export type { FieldRule, FieldSchema, FieldType, SyncFieldRules, FormValues, FormErrors, ValidateTrigger, FormState, TypedFormState, InferValues, InferErrors, BindFormOptions, BindFormHandle, FormHandle, } from './types';
3
+ export type { EngineField, EngineHandle, EngineOptions } from './engine';
4
+ export { createEngine, serializeFieldValue } from './engine';
5
+ export { runSyncRules, runFieldPipeline, runFormPipeline } from './validation';
6
+ export type { ServerError, ServerErrorResponse, MappedServerErrors } from './serverErrors';
7
+ export { FormSubmitError, mapServerErrors } from './serverErrors';
8
+ export { applyFieldAccessibility, ensureErrorElementA11y, focusFirstInvalidField, warnIfLabelMissing, } from './accessibility';
9
+ export type { CreateFormOptions } from './createForm';
10
+ export { createForm } from './createForm';
11
+ /**
12
+ * Subscribes to a form's submit event: prevents the page reload, validates fields
13
+ * against the schema (required/pattern/minLength/maxLength/min/max/validate, then
14
+ * an optional `resolver`) and calls onSubmit with the collected values.
15
+ * Submitting via Enter works out of the box (default <form> behavior).
16
+ *
17
+ * If `validateOn` is set, fields are additionally validated on "blur" or "input"
18
+ * and per-field errors are shown in `[data-error-for="<field>"]` elements.
19
+ *
20
+ * While `onSubmit` is pending, `[type="submit"]` elements are disabled (unless
21
+ * `disableSubmitWhilePending` is `false`) and `isSubmitting` is reported via `onStateChange`.
22
+ *
23
+ * Every bound field automatically gets accessibility wiring (aria-invalid,
24
+ * aria-describedby pointing at its `[data-error-for]` element, role="alert" on that
25
+ * element) and, on a failed submit, focus moves to the first invalid field in DOM
26
+ * order (see `createForm`'s Accessibility section in the README for details).
27
+ *
28
+ * Returns a handle: call it to unsubscribe, or use `getValues`/`setValue`/`setError`/
29
+ * `reset`/`getState`/`watch`.
30
+ *
31
+ * @deprecated Prefer `createForm`, which additionally infers typed `values`/`errors`
32
+ * from the schema and supports non-string field values, async per-field validation and
33
+ * automatic server error mapping. `bindForm` is not going away and keeps working as-is.
34
+ */
35
+ export declare function bindForm<TField extends string>(form: HTMLFormElement, options: BindFormOptions<TField>): BindFormHandle<TField>;
@@ -0,0 +1,34 @@
1
+ /** A single server-side validation error returned after a failed submit (e.g. HTTP 422). */
2
+ export interface ServerError {
3
+ /** Name of the field the error applies to. If it doesn't match a schema field, it becomes `form.formError` (REQ-009). */
4
+ field?: string | null;
5
+ /** Machine-readable error code, resolved through `errorMessages` (REQ-008). */
6
+ code?: string;
7
+ /** Human-readable fallback message, used if `code` has no entry in `errorMessages`. */
8
+ message?: string;
9
+ }
10
+ /** Response shape expected from a failed submit: a list of per-field (or form-level) errors. */
11
+ export type ServerErrorResponse = ServerError[];
12
+ /**
13
+ * Thrown (or returned as a rejected promise) by `onSubmit` to report server-side validation errors.
14
+ * `createForm` catches it and maps `errors` through `mapServerErrors` instead of letting it propagate
15
+ * as an unhandled exception (TASK-013).
16
+ */
17
+ export declare class FormSubmitError extends Error {
18
+ errors: ServerErrorResponse;
19
+ constructor(errors: ServerErrorResponse, message?: string);
20
+ }
21
+ /** Result of `mapServerErrors`: per-field messages plus an optional form-level (non-field) message. */
22
+ export interface MappedServerErrors<TField extends string> {
23
+ fieldErrors: Partial<Record<TField, string>>;
24
+ formError?: string;
25
+ }
26
+ /**
27
+ * Maps a `ServerErrorResponse` into per-field errors plus a form-level error (REQ-007/REQ-009).
28
+ *
29
+ * For each entry: the message is resolved as `errorMessages[code]` (if `code` and a matching entry
30
+ * exist), else the raw `message`, else the raw `code`, else a generic fallback (REQ-008). Entries
31
+ * whose `field` is missing or not part of `knownFields` are collected into `formError` instead
32
+ * (the first one wins, matching the "first error" convention used elsewhere in this package).
33
+ */
34
+ export declare function mapServerErrors<TField extends string>(response: ServerErrorResponse, knownFields: readonly TField[], errorMessages?: Record<string, string>): MappedServerErrors<TField>;
@@ -1,5 +1,5 @@
1
- /** Validation rule for a single form field. */
2
- export interface FieldRule {
1
+ /** Built-in synchronous rules shared by the legacy `FieldRule` and the typed `FieldSchema`. */
2
+ export interface SyncFieldRules {
3
3
  /** Error message shown if the field is empty after trim(). */
4
4
  required?: string;
5
5
  /** Regex and error message checked only when the field is non-empty. */
@@ -27,9 +27,39 @@ export interface FieldRule {
27
27
  value: number;
28
28
  message: string;
29
29
  };
30
+ }
31
+ /** Validation rule for a single form field, as consumed by `bindForm`. */
32
+ export interface FieldRule extends SyncFieldRules {
30
33
  /** Custom validator, run last. Return an error message, or undefined/empty string if valid. */
31
34
  validate?: (value: string) => string | undefined;
32
35
  }
36
+ /** How a field's raw (always-string) FormData value is converted to a typed `form.values[field]`. */
37
+ export type FieldType = "text" | "number" | "checkbox" | "multiselect";
38
+ /**
39
+ * Validation + typing schema for a single field, as consumed by `createForm`.
40
+ * `TValue` is the type exposed on `form.values[field]` (inferred via `InferValues`).
41
+ */
42
+ export interface FieldSchema<TValue = string> extends SyncFieldRules {
43
+ /**
44
+ * How the raw FormData string is converted into `TValue`:
45
+ * - `"text"` (default) -> `string`
46
+ * - `"number"` -> `number` (raw parsed with `Number(...)`)
47
+ * - `"checkbox"` -> `boolean` (`true` if checked/present in FormData)
48
+ * - `"multiselect"` -> `string[]` (all values for fields with the same `name`, e.g. a multi-select or a group of checkboxes)
49
+ */
50
+ type?: FieldType;
51
+ /** Custom parser overriding the default `type`-based conversion. Not used for `type: "multiselect"`. */
52
+ parse?: (raw: string) => TValue;
53
+ /** Custom serializer used by `setValue` to turn a typed value back into a string for the DOM element. */
54
+ serialize?: (value: TValue) => string;
55
+ /** Synchronous custom validator, run after the built-in sync rules. */
56
+ validate?: (value: TValue, values: Record<string, unknown>) => string | undefined;
57
+ /**
58
+ * Asynchronous validator (e.g. a uniqueness check), run only if the field has no sync error
59
+ * (see `runFieldPipeline` / REQ-006).
60
+ */
61
+ async?: (value: TValue, values: Record<string, unknown>) => string | undefined | Promise<string | undefined>;
62
+ }
33
63
  /** Form values: field name -> string value taken from FormData. */
34
64
  export type FormValues<TField extends string> = Record<TField, string>;
35
65
  /** Validation errors keyed by field name. */
@@ -49,6 +79,23 @@ export interface FormState<TField extends string> {
49
79
  /** True while `onSubmit` is pending. */
50
80
  isSubmitting: boolean;
51
81
  }
82
+ /** Infers `form.values` shape from a `createForm` schema: field name -> its `FieldSchema<TValue>`'s `TValue`. */
83
+ export type InferValues<TSchema extends Record<string, FieldSchema<any>>> = {
84
+ [K in keyof TSchema]: TSchema[K] extends FieldSchema<infer TValue> ? TValue : never;
85
+ };
86
+ /** Infers `form.errors` shape from a `createForm` schema: every field maps to an optional error message. */
87
+ export type InferErrors<TSchema extends Record<string, FieldSchema<any>>> = Partial<Record<keyof TSchema & string, string>>;
88
+ /** Snapshot of a typed `createForm` form's current state, passed to `onStateChange`. */
89
+ export interface TypedFormState<TValues extends Record<string, unknown>, TField extends string> {
90
+ values: TValues;
91
+ errors: Partial<Record<TField, string>>;
92
+ /** Form-level error not tied to any known field (see `ServerError`/REQ-009). */
93
+ formError?: string;
94
+ touched: Record<TField, boolean>;
95
+ dirty: Record<TField, boolean>;
96
+ isDirty: boolean;
97
+ isSubmitting: boolean;
98
+ }
52
99
  export interface BindFormOptions<TField extends string> {
53
100
  /** Validation schema: keys must match the `name` attributes of the form fields. */
54
101
  schema: Record<TField, FieldRule>;
@@ -92,19 +139,21 @@ export interface BindFormHandle<TField extends string> {
92
139
  /** Calls `callback` whenever `field`'s value changes. Returns an unsubscribe function. */
93
140
  watch(field: TField, callback: (value: string, values: FormValues<TField>) => void): () => void;
94
141
  }
95
- /**
96
- * Subscribes to a form's submit event: prevents the page reload, validates fields
97
- * against the schema (required/pattern/minLength/maxLength/min/max/validate, then
98
- * an optional `resolver`) and calls onSubmit with the collected values.
99
- * Submitting via Enter works out of the box (default <form> behavior).
100
- *
101
- * If `validateOn` is set, fields are additionally validated on "blur" or "input"
102
- * and per-field errors are shown in `[data-error-for="<field>"]` elements.
103
- *
104
- * While `onSubmit` is pending, `[type="submit"]` elements are disabled (unless
105
- * `disableSubmitWhilePending` is `false`) and `isSubmitting` is reported via `onStateChange`.
106
- *
107
- * Returns a handle: call it to unsubscribe, or use `getValues`/`setValue`/`setError`/
108
- * `reset`/`getState`/`watch`.
109
- */
110
- export declare function bindForm<TField extends string>(form: HTMLFormElement, options: BindFormOptions<TField>): BindFormHandle<TField>;
142
+ /** Handle returned by `createForm`. Calling it directly unsubscribes. */
143
+ export interface FormHandle<TValues extends Record<string, unknown>, TField extends string> {
144
+ (): void;
145
+ /** Reads the current, typed values of all schema fields from the form. */
146
+ getValues(): TValues;
147
+ /** Writes a value into the form field with the given name (serialized via `FieldSchema.serialize` if set). */
148
+ setValue<K extends TField>(field: K, value: TValues[K]): void;
149
+ /** Shows (or, if `message` is undefined, hides) the error for `[data-error-for="<field>"]`. */
150
+ setError(field: TField, message: string | undefined): void;
151
+ /** Sets (or, if `message` is undefined, clears) the form-level error (see REQ-009). */
152
+ setFormError(message: string | undefined): void;
153
+ /** Resets the form, clears all displayed errors and recaptures dirty/touched state. */
154
+ reset(): void;
155
+ /** Returns a snapshot of the current form state (values/errors/formError/touched/dirty/isSubmitting). */
156
+ getState(): TypedFormState<TValues, TField>;
157
+ /** Calls `callback` whenever `field`'s value changes. Returns an unsubscribe function. */
158
+ watch<K extends TField>(field: K, callback: (value: TValues[K], values: TValues) => void): () => void;
159
+ }
@@ -0,0 +1,20 @@
1
+ import { FieldSchema, SyncFieldRules } from './types';
2
+ /**
3
+ * Runs the built-in synchronous rules (`required`/`pattern`/`minLength`/`maxLength`/`min`/`max`)
4
+ * against a field's raw (trimmed) string value. Used as stage 1 of the field pipeline
5
+ * (`sync -> async -> server`, see `runFieldPipeline`).
6
+ */
7
+ export declare function runSyncRules(rule: SyncFieldRules, raw: string): string | undefined;
8
+ /**
9
+ * Runs the full per-field pipeline: built-in sync rules -> `schema.validate` (sync) -> `schema.async`.
10
+ * As soon as a sync stage produces an error, later stages are skipped and that error is returned
11
+ * (REQ-006): the `async` rule never runs for a field that already failed sync validation.
12
+ */
13
+ export declare function runFieldPipeline<TValue>(schema: FieldSchema<TValue>, raw: string, value: TValue, values: Record<string, unknown>,
14
+ /** Error from converting `raw` into `TValue` (e.g. an unparsable number), checked right after the sync rules. */
15
+ coercionError?: string): Promise<string | undefined>;
16
+ /**
17
+ * Runs `runFieldPipeline` for every field in parallel and collects the resulting errors,
18
+ * keyed by field name (stage 2 of `sync -> async(per field) -> resolver(form-level) -> server`).
19
+ */
20
+ export declare function runFormPipeline<TField extends string>(fields: TField[], getSchema: (field: TField) => FieldSchema<any>, getRaw: (field: TField) => string, getValue: (field: TField) => unknown, values: Record<string, unknown>, getCoercionError?: (field: TField) => string | undefined): Promise<Partial<Record<TField, string>>>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ export declare function createForm(html: string): HTMLFormElement;
2
+ export declare function submit(form: HTMLFormElement): void;
3
+ export declare function flush(times?: number): Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@chepchik/bind-form",
3
- "version": "0.1.2",
4
- "description": "Tiny dependency-free form binding helper: submit handling, validation schema and error display.",
3
+ "version": "0.2.0",
4
+ "description": "Dependency-free typed form engine: createForm() with types inferred from schema, sync/async/server validation pipeline, automatic server error mapping and built-in accessibility (aria-invalid, focus management). Also exports the original bindForm() helper.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.js",
@@ -15,18 +15,31 @@
15
15
  "files": [
16
16
  "dist"
17
17
  ],
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/Egortex/spa-toolkit.git",
21
+ "directory": "packages/bind-form"
22
+ },
18
23
  "sideEffects": false,
19
24
  "scripts": {
20
25
  "build": "vite build",
21
- "dev": "vite build --watch"
26
+ "dev": "vite build --watch",
27
+ "test": "tsc --noEmit && vitest run",
28
+ "test:coverage": "tsc --noEmit && vitest run --coverage"
22
29
  },
23
30
  "keywords": [
24
31
  "form",
25
32
  "validation",
26
- "spa"
33
+ "spa",
34
+ "typed-forms",
35
+ "accessibility",
36
+ "form-validation"
27
37
  ],
28
38
  "license": "MIT",
29
39
  "devDependencies": {
40
+ "@vitest/coverage-v8": "^5.0.0",
41
+ "jsdom": "^30.0.1",
42
+ "vitest": "^5.0.0",
30
43
  "typescript": "^6.0.3",
31
44
  "vite": "^8.0.16",
32
45
  "vite-plugin-dts": "^5.0.2"