@protovalidate-extensions/protovalidate-lingui 1.0.0 → 1.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
@@ -12,22 +12,33 @@ pnpm add @lingui/core
12
12
 
13
13
  Use Protobuf-ES message descriptors generated from `.proto` files with `buf.validate` annotations. This package does not generate descriptors or add validation rules, and does not require Lingui at runtime.
14
14
 
15
- ## Agent skill
15
+ ## Agent skills
16
16
 
17
- The npm package bundles the `protovalidate-lingui` usage skill under `skills/protovalidate-lingui/`. It covers schema adapters, typed message overrides, and Lingui extraction.
17
+ The npm package bundles four skills under `skills/`:
18
18
 
19
- With pnpm 12.11 or later, install the package normally, then run `pnpm approve` and select its skill. To persist that choice explicitly, merge these settings into the consuming project's `pnpm-workspace.yaml`:
19
+ | Skill | Use |
20
+ | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
21
+ | [protovalidate-lingui](skills/protovalidate-lingui/SKILL.md) | Standard Schema adapters, typed message overrides, and Lingui extraction |
22
+ | [protovalidate-lingui-migration](skills/protovalidate-lingui-migration/SKILL.md) | Replace existing manual validation/error mapping while preserving submission behavior |
23
+ | [protovalidate-lingui-tanstack-form](skills/protovalidate-lingui-tanstack-form/SKILL.md) | Bind controls, render issues, and handle submission retries |
24
+ | [protovalidate-lingui-connectrpc](skills/protovalidate-lingui-connectrpc/SKILL.md) | Send and decode canonical validation details with explicit fallbacks |
25
+
26
+ With pnpm 12.11 or later, install the package normally, then run `pnpm approve` and select the skills you need. To persist that choice explicitly, merge these settings into the consuming project's `pnpm-workspace.yaml`:
20
27
 
21
28
  ```yaml
22
29
  permissions:
23
30
  "@protovalidate-extensions/protovalidate-lingui":
24
- skills: [protovalidate-lingui]
31
+ skills:
32
+ - protovalidate-lingui
33
+ - protovalidate-lingui-migration
34
+ - protovalidate-lingui-tanstack-form
35
+ - protovalidate-lingui-connectrpc
25
36
  skills:
26
37
  dirs:
27
38
  - .agents/skills
28
39
  ```
29
40
 
30
- Subsequent installs link the approved skill automatically. See [pnpm agent skills](https://pnpm.io/agent-skills). Other package managers still install the bundled files; copy `node_modules/@protovalidate-extensions/protovalidate-lingui/skills/protovalidate-lingui` into your agent's skill directory and refresh the copy when updating the package.
41
+ Enable only the entries needed by your application. Subsequent installs link the approved skills automatically. See [pnpm agent skills](https://pnpm.io/agent-skills). Other package managers still install the bundled files; copy the desired folders from `node_modules/@protovalidate-extensions/protovalidate-lingui/skills/` into your agent's skill directory and refresh them when updating the package.
31
42
 
32
43
  ## Validate and translate
33
44
 
@@ -211,3 +222,186 @@ Both `createStandardSchema` and `createStandardSchemaInit` accept `SchemaOptions
211
222
  `createStandardSchema` infers `MessageShape` input; `createStandardSchemaInit` infers `MessageInitShape` input. Both infer `MessageValidType` output, including stronger required-field types when generated with Protobuf-ES valid types. The package exports `StandardSchemaV1`, `ValidatorOptions`, `SchemaOptions`, and `MessageOverrides` types. The adapters supply Protobuf defaults during construction; they do not parse Protobuf JSON. Malformed message construction can throw.
212
223
 
213
224
  Issue paths use JavaScript field names, numeric list indices, map keys, and `[oneofName, "value"]` for oneof member fields. Message-level issues omit the path.
225
+
226
+ ## ConnectRPC errors in TanStack Form
227
+
228
+ The optional integrations decode `Code.InvalidArgument` errors containing canonical `buf.validate.Violations` details. They return translation IDs and preserve every violation, including multiple violations for one field. No server English text is displayed and no validation rules are evaluated again.
229
+
230
+ ```sh
231
+ pnpm add @connectrpc/connect@^2.3.0 @tanstack/react-form@^1.33.5
232
+ ```
233
+
234
+ Connect and `@tanstack/form-core` are optional peers. React Form supplies Form Core; use matching TanStack versions. The main entry point needs neither integration installed and has no Lingui runtime dependency.
235
+
236
+ ```tsx
237
+ import type { MessageInitShape } from "@bufbuild/protobuf";
238
+ import { useForm } from "@tanstack/react-form";
239
+ import { useLingui } from "@lingui/react";
240
+ import { msg } from "@lingui/core/macro";
241
+ import { createStandardSchemaInit } from "@protovalidate-extensions/protovalidate-lingui";
242
+ import {
243
+ toFormErrors,
244
+ submitWithFormErrors,
245
+ } from "@protovalidate-extensions/protovalidate-lingui/connect/tanstack-form";
246
+
247
+ const defaultValues: MessageInitShape<typeof CreateProjectRequestSchema> = {
248
+ displayName: "",
249
+ };
250
+ const submitErrorMessage = msg`We couldn't save the project. Please try again.`;
251
+ const schema = createStandardSchemaInit(CreateProjectRequestSchema, {
252
+ messages,
253
+ });
254
+
255
+ // Inside the component, with the application's defaultValues, mutation and navigate:
256
+ const { i18n } = useLingui();
257
+ const form = useForm({
258
+ defaultValues,
259
+ validators: {
260
+ onChange: schema,
261
+ onSubmitAsync: async ({ value }) => {
262
+ try {
263
+ await mutation.mutateAsync(value);
264
+ return undefined;
265
+ } catch (error) {
266
+ return toFormErrors(error, {
267
+ schema: CreateProjectRequestSchema,
268
+ messages,
269
+ fallback: submitErrorMessage,
270
+ mapMessageViolation: ({ messageType, ruleId }) => {
271
+ if (
272
+ messageType === CreateProjectRequestSchema.typeName &&
273
+ ruleId === "project.name_available"
274
+ ) {
275
+ return { fields: [["displayName"]] };
276
+ }
277
+ return undefined;
278
+ },
279
+ });
280
+ }
281
+ },
282
+ },
283
+ onSubmit: async () => {
284
+ await navigate({ to: ".." });
285
+ },
286
+ });
287
+
288
+ return (
289
+ <form
290
+ onSubmit={(event) => {
291
+ event.preventDefault();
292
+ event.stopPropagation();
293
+ void submitWithFormErrors(form);
294
+ }}
295
+ >
296
+ <form.Field name="displayName">
297
+ {(field) => (
298
+ <>
299
+ <input
300
+ value={field.state.value}
301
+ onChange={(event) => field.handleChange(event.target.value)}
302
+ onBlur={field.handleBlur}
303
+ />
304
+ {field.state.meta.errors.map((issue, index) => (
305
+ <p key={index}>{i18n._(issue.message)}</p>
306
+ ))}
307
+ </>
308
+ )}
309
+ </form.Field>
310
+ <form.Subscribe selector={(state) => state.errorMap.onSubmit}>
311
+ {(issues) =>
312
+ issues?.map((issue, index) => (
313
+ <p role="alert" key={index}>
314
+ {i18n._(issue.message)}
315
+ </p>
316
+ ))
317
+ }
318
+ </form.Subscribe>
319
+ <form.Subscribe
320
+ selector={(state) => state.isSubmitting || state.isValidating}
321
+ >
322
+ {(pending) => (
323
+ <button type="submit" disabled={pending}>
324
+ Save
325
+ </button>
326
+ )}
327
+ </form.Subscribe>
328
+ </form>
329
+ );
330
+ ```
331
+
332
+ Keep `messages` checked with the existing generated `CreateProjectRequestMessages` type. `fallback` is required: pass a nonempty translation ID or a static Lingui descriptor with an ID. Do not translate it before conversion. Existing errors, including fallbacks, follow locale changes when rendered through the active `useLingui()` instance. The fallback descriptor and any unknown rule IDs still need normal Lingui extraction/catalog setup.
333
+
334
+ `toFormErrors` returns `{ fields, form? }`. `fields` is always present because TanStack v1 uses that property to recognize a form/field error result. Field values and `form` are arrays of `ValidationIssue` objects with `message` (an ID), optional initializer `path`, and `target`. Field names follow `MessageInitShape`: nested names such as `project.displayName`, arrays such as `members[2].emailAddress`, maps such as `labels.home.displayName`, and oneof members such as `contact.value`. The `target` describes the normalized issue; a field issue can also appear in `form` when TanStack cannot represent its path.
335
+
336
+ Use `submitWithFormErrors(form)` as the submission handler. On TanStack Form 1.33.5, stale server field errors can block `handleSubmit()` before its async validator runs, even when values are unchanged. The helper removes only this integration's previous `onSubmit` issues, preserves other validators' errors, and then lets TanStack validate the new attempt. It coalesces simultaneous helper calls and accepts the form's optional submit metadata as a second argument. Do not disable retry solely because `canSubmit` is false; disable while submission/validation is pending. The helper tracks the original issue objects in memory; it does not restore or clear serialized errors across processes or different copies of this integration.
337
+
338
+ Keep the mutation exclusively in `onSubmitAsync`, which also runs during explicit submit validation. Standard Schema does not transform TanStack's stored values: the mutation receives the initializer, even though the schema's successful result is a complete protobuf message. Build a message explicitly if your mutation requires one. The helper prevents concurrent calls through itself; application/server idempotency remains appropriate for uncertain network outcomes. Transport cancellation, mutation retry policy, and edits during an in-flight request remain application concerns.
339
+
340
+ ### Message rules and fallback policy
341
+
342
+ Message-level rules remain form errors unless explicitly mapped. Descriptor annotations identify nested message CEL rules and message-oneof rules. `mapMessageViolation` is also called at message-valued locations so callers can explicitly register a server-only message rule absent from the client descriptor. Match both `messageType` and `ruleId`; nothing is inferred from rule-ID spelling or English text.
343
+
344
+ Routing destinations are arrays of **relative initializer path segments**. A violation at `members[2]` mapped to `["displayName"]` becomes `members[2].displayName`; callers do not traverse the original path. Return several destinations to show the same issue on several fields. Message overrides resolve in their original `$message` scope before routing. An empty or invalid destination list uses the form fallback. The callback is application code; exceptions from it propagate as configuration/programming errors.
345
+
346
+ A field CEL rule and its child message CEL rule can share both location and ID. Canonical details cannot distinguish them. Without explicit routing, that ambiguity uses the form fallback. Avoid such collisions in schemas where possible.
347
+
348
+ | Condition | Result |
349
+ | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
350
+ | Known path and rule override | Override descriptor's ID |
351
+ | Nonempty unknown/unmapped rule ID | Original rule ID, never server English |
352
+ | Root/nested message rule | Form issue, unless explicitly routed |
353
+ | Map-key violation | Form issue; initializer objects have no separate key field |
354
+ | Missing/empty rule ID, unknown field, conflicting descriptor names/types, invalid traversal/subscript | Form fallback |
355
+ | Missing, empty, or malformed validation details | Form fallback |
356
+ | Non-`InvalidArgument` Connect error or any non-Connect failure | Form fallback |
357
+ | Mixed usable and unusable violations/details | Usable issues plus a form fallback |
358
+
359
+ All canonical details are processed. Other detail types are ignored. Order and duplicates are preserved within each field/form list. Invalid `fallback` configuration throws a `TypeError` rather than silently treating a failed submission as successful.
360
+
361
+ Field numbers are authoritative when present; proto names are accepted when numbers are absent. JSON names and guessed camel-case names are never used to resolve wire paths. Repeated indices must fit JavaScript array indices. Integer map keys retain exact decimal strings, including signed/unsigned 64-bit keys; boolean keys use `"true"`/`"false"`.
362
+
363
+ TanStack's string path syntax cannot escape map keys containing `.`, `[` or `]`, or empty keys. These violations are promoted to `form` with their structured path retained. Prototype-traversal keys are promoted too. Do not render the structured path as a TanStack field name yourself.
364
+
365
+ Singular well-known wrapper values use their unwrapped initializer field (for example, `title`, rather than `title.value`). Internal protobuf paths inside `google.protobuf.Struct` fields use the form fallback: those fields have JSON object initializer shapes rather than a protobuf `fields` map.
366
+
367
+ The adapter does not carry interpolation values, rule parameters, or dynamic English messages. It expects protobuf initializer shapes, not custom UI models or Protobuf JSON. Recursive descriptors work at runtime; TanStack's `DeepKeys` types may require a finite application form type for recursive TypeScript message types.
368
+
369
+ ### Lower-level integrations and generator boundary
370
+
371
+ | Import suffix | Export | Purpose |
372
+ | ------------------------ | ---------------------------------------------- | --------------------------------------------------------------------------------- |
373
+ | `/violations` | `violationsToIssues` | Convert decoded canonical violation arrays with descriptors and message overrides |
374
+ | `/connect` | `connectErrorToIssues` | Decode a caught Connect failure into normalized issues |
375
+ | `/tanstack-form` | `toTanStackFormErrors`, `submitWithFormErrors` | Group normalized issues and handle submit retries without Connect |
376
+ | `/connect/tanstack-form` | `toFormErrors`, `submitWithFormErrors` | Combined consumer API |
377
+
378
+ The root adapter and these normalizers share message resolution and initializer-path conversion. Server conversion uses descriptor reflection; it does not instantiate a validator or evaluate CEL. A strict path walker handles collection shape checks, proto2 field presence, index bounds and signed 64-bit map keys that the installed upstream path converter does not fully handle. The protoc plugin remains unchanged: existing override types and message descriptors are sufficient. No generated routing tables, Connect dependencies, or TanStack dependencies are added to generated modules.
379
+
380
+ ### Migrating a manually mapped form
381
+
382
+ For an existing submit validator with manual mapping:
383
+
384
+ ```ts
385
+ // Before: app-specific decoding/mapping, one translated string per field.
386
+ catch (error) {
387
+ const violations = decodeValidationDetails(error);
388
+ const nameError = violations.find((v) => v.fieldName === "display_name");
389
+ return {
390
+ fields: { displayName: nameError ? i18n._(nameError.ruleId) : undefined },
391
+ form: nameError ? undefined : i18n._(submitErrorMessage),
392
+ };
393
+ }
394
+
395
+ // After: keep IDs, preserve all violations, and convert structured paths.
396
+ catch (error) {
397
+ return toFormErrors(error, {
398
+ schema: CreateProjectRequestSchema,
399
+ messages,
400
+ fallback: submitErrorMessage,
401
+ });
402
+ }
403
+ ```
404
+
405
+ Replace the catch block that decodes details, switches on proto names, translates messages, and calls `setFieldMeta` with `return toFormErrors(error, { schema, messages, fallback })` in `validators.onSubmitAsync`, as shown above. Move success-only navigation into `onSubmit` and replace the form's `handleSubmit()` call with `submitWithFormErrors(form)`. Replace a single translated field error with iteration over `issue.message` IDs. Move message-rule-to-field choices from your switch into `mapMessageViolation`; do not reproduce collection-path traversal.
406
+
407
+ The server must send canonical `buf.validate.Violations` as structured error details. `google.rpc.BadRequest`, legacy display-path strings, and plain JSON application errors are not decoded by this integration and use the fallback.
@@ -0,0 +1,8 @@
1
+ import type { DescMessage } from "@bufbuild/protobuf";
2
+ import { type FormErrors } from "../tanstack-form.js";
3
+ import type { ViolationOptions } from "../violations.js";
4
+ export { submitWithFormErrors } from "../tanstack-form.js";
5
+ export type { FormErrors } from "../tanstack-form.js";
6
+ export type { ViolationOptions, ValidationIssue, MessageViolationContext, } from "../violations.js";
7
+ /** Return server validation errors or a required form fallback for any caught failure. */
8
+ export declare function toFormErrors<Desc extends DescMessage>(error: unknown, options: ViolationOptions<Desc>): FormErrors<Desc>;
@@ -0,0 +1,7 @@
1
+ import { connectErrorToIssues } from "../connect.js";
2
+ import { toTanStackFormErrors } from "../tanstack-form.js";
3
+ export { submitWithFormErrors } from "../tanstack-form.js";
4
+ /** Return server validation errors or a required form fallback for any caught failure. */
5
+ export function toFormErrors(error, options) {
6
+ return toTanStackFormErrors(connectErrorToIssues(error, options));
7
+ }
@@ -0,0 +1,4 @@
1
+ import type { DescMessage } from "@bufbuild/protobuf";
2
+ import { type ValidationIssue, type ViolationOptions } from "./violations.js";
3
+ /** Decode only InvalidArgument errors with canonical buf.validate.Violations details. */
4
+ export declare function connectErrorToIssues<Desc extends DescMessage>(error: unknown, options: ViolationOptions<Desc>): ValidationIssue[];
@@ -0,0 +1,43 @@
1
+ import { Code, ConnectError } from "@connectrpc/connect";
2
+ import { ViolationsSchema } from "@bufbuild/protovalidate/gen/buf/validate/validate_pb.js";
3
+ import { fallbackIssue, violationsToIssues, } from "./violations.js";
4
+ /** Decode only InvalidArgument errors with canonical buf.validate.Violations details. */
5
+ export function connectErrorToIssues(error, options) {
6
+ const fallback = fallbackIssue(options.fallback);
7
+ let malformed = false;
8
+ const violations = [];
9
+ try {
10
+ const connect = ConnectError.from(error);
11
+ if (connect.code !== Code.InvalidArgument)
12
+ return [fallback];
13
+ // Decode separately: findDetails silently skips malformed binary details. We
14
+ // must preserve valid siblings and still report malformed validation data.
15
+ for (const detail of connect.details) {
16
+ const type = "desc" in detail ? detail.desc.typeName : detail.type;
17
+ if (type !== ViolationsSchema.typeName)
18
+ continue;
19
+ try {
20
+ const isolated = new ConnectError("", Code.InvalidArgument);
21
+ isolated.details = [detail];
22
+ const decoded = isolated.findDetails(ViolationsSchema);
23
+ if (!decoded.length || !decoded[0].violations.length)
24
+ malformed = true;
25
+ for (const batch of decoded)
26
+ violations.push(...batch.violations);
27
+ }
28
+ catch {
29
+ malformed = true;
30
+ }
31
+ }
32
+ }
33
+ catch {
34
+ return [fallback];
35
+ }
36
+ const issues = violationsToIssues(violations, options);
37
+ if (malformed &&
38
+ !issues.some((issue) => issue.target === "form" &&
39
+ !issue.path &&
40
+ issue.message === fallback.message))
41
+ issues.push(fallback);
42
+ return issues;
43
+ }
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { type DescMessage, type MessageInitShape, type MessageShape, type MessageValidType } from "@bufbuild/protobuf";
2
2
  import { type ValidatorOptions } from "@bufbuild/protovalidate";
3
3
  import type { StandardSchemaV1 } from "@standard-schema/spec";
4
+ import { type MessageOverrides } from "./issues.js";
4
5
  export type { ValidatorOptions } from "@bufbuild/protovalidate";
5
6
  export type { StandardSchemaV1 } from "@standard-schema/spec";
6
- /** Use the plugin-generated message type with `satisfies` for exact rule checks. */
7
- export type MessageOverrides = Readonly<Record<string, Readonly<Record<string, unknown>> | undefined>>;
7
+ export type { MessageOverrides } from "./issues.js";
8
8
  export interface SchemaOptions extends ValidatorOptions {
9
9
  messages?: MessageOverrides;
10
10
  }
package/dist/index.js CHANGED
@@ -1,88 +1,6 @@
1
1
  import { create, } from "@bufbuild/protobuf";
2
2
  import { createValidator, CompilationError, } from "@bufbuild/protovalidate";
3
- function ownObject(value, key) {
4
- if (typeof value !== "object" ||
5
- value === null ||
6
- !Object.hasOwn(value, key)) {
7
- return undefined;
8
- }
9
- const child = value[key];
10
- return typeof child === "object" && child !== null
11
- ? child
12
- : undefined;
13
- }
14
- function overrideId(violation, messages) {
15
- let scope = messages;
16
- let field;
17
- let first = true;
18
- for (const segment of violation.field) {
19
- if (segment.kind !== "field" && segment.kind !== "oneof")
20
- continue;
21
- if (!first)
22
- scope = ownObject(field, "$fields");
23
- first = false;
24
- // Escape reserved properties even for oneof members, where Protobuf-ES
25
- // keeps the unescaped name. Optional `constructor` keys conflict with
26
- // Object.constructor in TypeScript otherwise.
27
- const name = ["constructor", "toString", "toJSON", "valueOf"].includes(segment.localName)
28
- ? `${segment.localName}$`
29
- : segment.localName;
30
- field = ownObject(scope, name);
31
- }
32
- const descriptor = violation.field.length === 0
33
- ? ownObject(ownObject(scope, "$message"), violation.ruleId)
34
- : (ownObject(field, violation.ruleId) ??
35
- ownObject(ownObject(ownObject(field, "$fields"), "$message"), violation.ruleId));
36
- return typeof descriptor?.id === "string" && descriptor.id.length > 0
37
- ? descriptor.id
38
- : violation.ruleId;
39
- }
40
- /**
41
- * Convert a Violation to a StandardSchemaV1.Issue.
42
- */
43
- function violationToIssue(violation, messages) {
44
- const path = [];
45
- for (const segment of violation.field) {
46
- switch (segment.kind) {
47
- case "field":
48
- if (segment.oneof !== undefined) {
49
- path.push(segment.oneof.localName);
50
- path.push("value");
51
- }
52
- else {
53
- path.push(segment.localName);
54
- }
55
- continue;
56
- case "oneof":
57
- path.push(segment.localName);
58
- continue;
59
- case "list_sub":
60
- path.push(segment.index);
61
- continue;
62
- case "map_sub":
63
- const key = segment.key;
64
- if (typeof key === "string" || typeof key === "number") {
65
- path.push(key);
66
- }
67
- else {
68
- path.push(String(key));
69
- }
70
- continue;
71
- case "extension":
72
- // Extensions are represented as field names with brackets
73
- path.push(`[${segment.typeName}]`);
74
- }
75
- }
76
- if (path.length > 0) {
77
- return {
78
- message: overrideId(violation, messages),
79
- path: path,
80
- };
81
- }
82
- return {
83
- message: overrideId(violation, messages),
84
- };
85
- }
3
+ import { violationToIssue } from "./issues.js";
86
4
  /**
87
5
  * Create a Standard Schema validator whose issue messages are Lingui IDs.
88
6
  *
@@ -0,0 +1,15 @@
1
+ import type { Path } from "@bufbuild/protobuf/reflect";
2
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
3
+ /** Use the plugin-generated message type with `satisfies` for exact rule checks. */
4
+ export type MessageOverrides = Readonly<Record<string, Readonly<Record<string, unknown>> | undefined>>;
5
+ export declare function overrideId(violation: {
6
+ field: Path;
7
+ ruleId: string;
8
+ }, messages?: MessageOverrides, messageScope?: boolean): string;
9
+ /**
10
+ * Convert a Violation to a StandardSchemaV1.Issue.
11
+ */
12
+ export declare function violationToIssue(violation: {
13
+ field: Path;
14
+ ruleId: string;
15
+ }, messages?: MessageOverrides): StandardSchemaV1.Issue;
package/dist/issues.js ADDED
@@ -0,0 +1,83 @@
1
+ function ownObject(value, key) {
2
+ if (typeof value !== "object" ||
3
+ value === null ||
4
+ !Object.hasOwn(value, key)) {
5
+ return undefined;
6
+ }
7
+ const child = value[key];
8
+ return typeof child === "object" && child !== null
9
+ ? child
10
+ : undefined;
11
+ }
12
+ export function overrideId(violation, messages, messageScope = false) {
13
+ let scope = messages;
14
+ let field;
15
+ let first = true;
16
+ for (const segment of violation.field) {
17
+ if (segment.kind !== "field" && segment.kind !== "oneof")
18
+ continue;
19
+ if (!first)
20
+ scope = ownObject(field, "$fields");
21
+ first = false;
22
+ // Escape reserved properties even for oneof members, where Protobuf-ES
23
+ // keeps the unescaped name. Optional `constructor` keys conflict with
24
+ // Object.constructor in TypeScript otherwise.
25
+ const name = ["constructor", "toString", "toJSON", "valueOf"].includes(segment.localName)
26
+ ? `${segment.localName}$`
27
+ : segment.localName;
28
+ field = ownObject(scope, name);
29
+ }
30
+ const descriptor = violation.field.length === 0
31
+ ? ownObject(ownObject(scope, "$message"), violation.ruleId)
32
+ : ((!messageScope ? ownObject(field, violation.ruleId) : undefined) ??
33
+ ownObject(ownObject(ownObject(field, "$fields"), "$message"), violation.ruleId));
34
+ return typeof descriptor?.id === "string" && descriptor.id.length > 0
35
+ ? descriptor.id
36
+ : violation.ruleId;
37
+ }
38
+ /**
39
+ * Convert a Violation to a StandardSchemaV1.Issue.
40
+ */
41
+ export function violationToIssue(violation, messages) {
42
+ const path = [];
43
+ for (const segment of violation.field) {
44
+ switch (segment.kind) {
45
+ case "field":
46
+ if (segment.oneof !== undefined) {
47
+ path.push(segment.oneof.localName);
48
+ path.push("value");
49
+ }
50
+ else {
51
+ path.push(segment.localName);
52
+ }
53
+ continue;
54
+ case "oneof":
55
+ path.push(segment.localName);
56
+ continue;
57
+ case "list_sub":
58
+ path.push(segment.index);
59
+ continue;
60
+ case "map_sub":
61
+ const key = segment.key;
62
+ if (typeof key === "string" || typeof key === "number") {
63
+ path.push(key);
64
+ }
65
+ else {
66
+ path.push(String(key));
67
+ }
68
+ continue;
69
+ case "extension":
70
+ // Extensions are represented as field names with brackets
71
+ path.push(`[${segment.typeName}]`);
72
+ }
73
+ }
74
+ if (path.length > 0) {
75
+ return {
76
+ message: overrideId(violation, messages),
77
+ path: path,
78
+ };
79
+ }
80
+ return {
81
+ message: overrideId(violation, messages),
82
+ };
83
+ }
@@ -0,0 +1,20 @@
1
+ import type { DescMessage, MessageInitShape } from "@bufbuild/protobuf";
2
+ import type { AnyFormApi, DeepKeys } from "@tanstack/form-core";
3
+ import type { ValidationIssue } from "./violations.js";
4
+ export interface FormErrors<Desc extends DescMessage = DescMessage> {
5
+ form?: ValidationIssue[];
6
+ fields: Partial<Record<DeepKeys<MessageInitShape<Desc>>, ValidationIssue[]>>;
7
+ }
8
+ /** Group issues without mutating form state. Unrepresentable paths stay visible on the form. */
9
+ export declare function toTanStackFormErrors<Desc extends DescMessage = DescMessage>(issues: readonly ValidationIssue[]): FormErrors<Desc>;
10
+ /**
11
+ * Retry submissions without stale adapter errors blocking TanStack's field validation.
12
+ * Preserves other validators' errors and coalesces concurrent calls for this form.
13
+ */
14
+ export declare function submitWithFormErrors<SubmitMeta>(form: {
15
+ state: Pick<AnyFormApi["state"], "isSubmitting" | "fieldMeta" | "errorMap">;
16
+ getFieldMeta(...args: Parameters<AnyFormApi["getFieldMeta"]>): ReturnType<AnyFormApi["getFieldMeta"]>;
17
+ setFieldMeta(...args: Parameters<AnyFormApi["setFieldMeta"]>): ReturnType<AnyFormApi["setFieldMeta"]>;
18
+ setErrorMap(...args: Parameters<AnyFormApi["setErrorMap"]>): void;
19
+ handleSubmit(submitMeta?: SubmitMeta): Promise<void>;
20
+ }, submitMeta?: SubmitMeta): Promise<void>;
@@ -0,0 +1,88 @@
1
+ const adapterIssues = new WeakSet();
2
+ function fieldName(path) {
3
+ if (!path?.length)
4
+ return undefined;
5
+ let name = "";
6
+ for (const segment of path) {
7
+ if (typeof segment === "number") {
8
+ if (!Number.isInteger(segment) || segment < 0 || segment > 4294967294)
9
+ return undefined;
10
+ name += `[${segment}]`;
11
+ }
12
+ else {
13
+ // TanStack has no escaping for path delimiters. Reject prototype traversal
14
+ // keys too: its field metadata dictionaries are ordinary objects.
15
+ if (!segment ||
16
+ /[.\[\]]/.test(segment) ||
17
+ ["__proto__", "constructor", "prototype"].includes(segment))
18
+ return undefined;
19
+ name += (name ? "." : "") + segment;
20
+ }
21
+ }
22
+ return name;
23
+ }
24
+ /** Group issues without mutating form state. Unrepresentable paths stay visible on the form. */
25
+ export function toTanStackFormErrors(issues) {
26
+ const form = [];
27
+ const fields = Object.create(null);
28
+ for (const issue of issues) {
29
+ adapterIssues.add(issue);
30
+ const name = issue.target === "field" ? fieldName(issue.path) : undefined;
31
+ if (name === undefined)
32
+ form.push(issue);
33
+ else
34
+ (fields[name] ??= []).push(issue);
35
+ }
36
+ return {
37
+ ...(form.length ? { form } : {}),
38
+ fields: fields,
39
+ };
40
+ }
41
+ const pendingSubmissions = new WeakMap();
42
+ function withoutAdapterIssues(error) {
43
+ if (!Array.isArray(error))
44
+ return error;
45
+ const remaining = error.filter((issue) => typeof issue !== "object" || issue === null || !adapterIssues.has(issue));
46
+ return remaining.length === error.length
47
+ ? error
48
+ : remaining.length
49
+ ? remaining
50
+ : undefined;
51
+ }
52
+ /**
53
+ * Retry submissions without stale adapter errors blocking TanStack's field validation.
54
+ * Preserves other validators' errors and coalesces concurrent calls for this form.
55
+ */
56
+ export function submitWithFormErrors(form, submitMeta) {
57
+ const pending = pendingSubmissions.get(form);
58
+ if (pending)
59
+ return pending;
60
+ const submission = Promise.resolve()
61
+ .then(async () => {
62
+ if (form.state.isSubmitting)
63
+ return;
64
+ for (const name of Object.keys(form.state.fieldMeta)) {
65
+ const meta = form.getFieldMeta(name);
66
+ if (meta?.errorSourceMap.onSubmit !== "form")
67
+ continue;
68
+ const error = withoutAdapterIssues(meta.errorMap.onSubmit);
69
+ if (error !== meta.errorMap.onSubmit) {
70
+ form.setFieldMeta(name, (previous) => ({
71
+ ...previous,
72
+ errorMap: { ...previous.errorMap, onSubmit: error },
73
+ errorSourceMap: {
74
+ ...previous.errorSourceMap,
75
+ onSubmit: error === undefined ? undefined : "form",
76
+ },
77
+ }));
78
+ }
79
+ }
80
+ const error = withoutAdapterIssues(form.state.errorMap.onSubmit);
81
+ if (error !== form.state.errorMap.onSubmit)
82
+ form.setErrorMap({ onSubmit: error });
83
+ await form.handleSubmit(submitMeta);
84
+ })
85
+ .finally(() => pendingSubmissions.delete(form));
86
+ pendingSubmissions.set(form, submission);
87
+ return submission;
88
+ }
@@ -0,0 +1,33 @@
1
+ import { type DescMessage } from "@bufbuild/protobuf";
2
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
3
+ import { type Violation } from "@bufbuild/protovalidate/gen/buf/validate/validate_pb.js";
4
+ import { type MessageOverrides } from "./issues.js";
5
+ export type FieldPathSegments = readonly (string | number)[];
6
+ export type MessageId = string | {
7
+ readonly id?: string;
8
+ };
9
+ /** An issue retains its translation ID and initializer path until rendering. */
10
+ export interface ValidationIssue extends StandardSchemaV1.Issue {
11
+ readonly path?: FieldPathSegments;
12
+ readonly target: "form" | "field";
13
+ }
14
+ export interface MessageViolationContext {
15
+ readonly messageType: string;
16
+ readonly schema: DescMessage;
17
+ readonly ruleId: string;
18
+ /** Path of this message instance, including collection indices and keys. */
19
+ readonly messagePath: FieldPathSegments;
20
+ }
21
+ export interface ViolationOptions<Desc extends DescMessage = DescMessage> {
22
+ schema: Desc;
23
+ messages?: MessageOverrides;
24
+ /** A translation ID or static Lingui descriptor, never translated text. */
25
+ fallback: MessageId;
26
+ /** Explicitly identify and route a message rule. Targets are relative initializer paths. */
27
+ mapMessageViolation?: (context: MessageViolationContext) => {
28
+ fields: readonly FieldPathSegments[];
29
+ } | undefined;
30
+ }
31
+ export declare function fallbackIssue(fallback: MessageId): ValidationIssue;
32
+ /** Convert decoded canonical violations without evaluating any validation rules. */
33
+ export declare function violationsToIssues<Desc extends DescMessage>(violations: readonly Violation[], options: ViolationOptions<Desc>): ValidationIssue[];
@@ -0,0 +1,245 @@
1
+ import { getExtension, isFieldSet, ScalarType, } from "@bufbuild/protobuf";
2
+ import { isWrapperDesc } from "@bufbuild/protobuf/wkt";
3
+ import { message as messageRules, field as fieldRules, FieldPathElementSchema, } from "@bufbuild/protovalidate/gen/buf/validate/validate_pb.js";
4
+ import { overrideId, violationToIssue, } from "./issues.js";
5
+ export function fallbackIssue(fallback) {
6
+ const id = typeof fallback === "string" ? fallback : fallback.id;
7
+ if (typeof id !== "string" || id.trim().length === 0) {
8
+ throw new TypeError("fallback must contain a nonempty translation ID");
9
+ }
10
+ return { message: id, target: "form" };
11
+ }
12
+ function mapKey(field, sub) {
13
+ const key = field.mapKey;
14
+ if (sub.case === "stringKey" && key === ScalarType.STRING)
15
+ return sub.value;
16
+ if (sub.case === "boolKey" && key === ScalarType.BOOL)
17
+ return String(sub.value);
18
+ const signed32 = [
19
+ ScalarType.INT32,
20
+ ScalarType.SINT32,
21
+ ScalarType.SFIXED32,
22
+ ].includes(key);
23
+ const signed64 = [
24
+ ScalarType.INT64,
25
+ ScalarType.SINT64,
26
+ ScalarType.SFIXED64,
27
+ ].includes(key);
28
+ const unsigned32 = [ScalarType.UINT32, ScalarType.FIXED32].includes(key);
29
+ const unsigned64 = [ScalarType.UINT64, ScalarType.FIXED64].includes(key);
30
+ if ((sub.case === "intKey" && (signed32 || signed64)) ||
31
+ (sub.case === "uintKey" && (unsigned32 || unsigned64))) {
32
+ const min = signed32 ? -(2n ** 31n) : signed64 ? -(2n ** 63n) : 0n;
33
+ const max = signed32
34
+ ? 2n ** 31n - 1n
35
+ : signed64
36
+ ? 2n ** 63n - 1n
37
+ : unsigned32
38
+ ? 2n ** 32n - 1n
39
+ : 2n ** 64n - 1n;
40
+ if (sub.value >= min && sub.value <= max)
41
+ return String(sub.value);
42
+ }
43
+ throw new Error("invalid map subscript");
44
+ }
45
+ /** Strict reflection avoids name guessing, lossy indices, and upstream int64-key limitations. */
46
+ function resolvePath(schema, proto) {
47
+ const path = [];
48
+ let parent = schema;
49
+ for (const element of proto?.elements ?? []) {
50
+ if (!parent)
51
+ throw new Error("path traverses a scalar or unselected collection");
52
+ const field = element.fieldNumber !== 0
53
+ ? parent.fields.find((f) => f.number === element.fieldNumber)
54
+ : parent.fields.find((f) => f.name === element.fieldName);
55
+ if (!field) {
56
+ const oneof = element.fieldNumber === 0
57
+ ? parent.oneofs.find((o) => o.name === element.fieldName)
58
+ : undefined;
59
+ if (!oneof || element.subscript.case !== undefined)
60
+ throw new Error("unknown field");
61
+ path.push(oneof);
62
+ parent = undefined;
63
+ continue;
64
+ }
65
+ if (element.fieldName && element.fieldName !== field.name)
66
+ throw new Error("conflicting field name");
67
+ if (isFieldSet(element, FieldPathElementSchema.field.fieldType) &&
68
+ element.fieldType !== field.proto.type)
69
+ throw new Error("conflicting field type");
70
+ const previous = path[path.length - 1];
71
+ const unwrapped = previous?.kind === "field" &&
72
+ previous.fieldKind === "message" &&
73
+ !previous.oneof &&
74
+ isWrapperDesc(previous.message) &&
75
+ field.parent === previous.message;
76
+ // Struct is represented as JsonObject in fields, rather than its protobuf
77
+ // fields map. Do not attach internal protobuf paths to fictitious UI fields.
78
+ const previousField = [...path]
79
+ .reverse()
80
+ .find((segment) => segment.kind === "field");
81
+ if (field.parent.typeName === "google.protobuf.Struct" &&
82
+ previousField?.kind === "field" &&
83
+ previousField.parent.typeName !== "google.protobuf.Value")
84
+ throw new Error("opaque Struct initializer");
85
+ if (!unwrapped)
86
+ path.push(field);
87
+ const sub = element.subscript;
88
+ if (field.fieldKind === "list" && sub.case === "index") {
89
+ if (sub.value < 0n || sub.value > 4294967294n)
90
+ throw new Error("invalid array index");
91
+ path.push({ kind: "list_sub", index: Number(sub.value) });
92
+ parent = field.message;
93
+ }
94
+ else if (field.fieldKind === "map" && sub.case !== undefined) {
95
+ path.push({ kind: "map_sub", key: mapKey(field, sub) });
96
+ parent = field.message;
97
+ }
98
+ else {
99
+ if (sub.case !== undefined)
100
+ throw new Error("invalid subscript");
101
+ parent = field.fieldKind === "message" ? field.message : undefined;
102
+ }
103
+ }
104
+ return { path, message: parent };
105
+ }
106
+ /** Check explicit routing destinations against initializer shapes, including oneof value branches. */
107
+ function isInitializerPath(schema, path) {
108
+ if (!path.length)
109
+ return false;
110
+ const [head, ...tail] = path;
111
+ const oneof = schema.oneofs.find((o) => o.localName === head);
112
+ if (oneof) {
113
+ if (!tail.length)
114
+ return true;
115
+ if (tail[0] !== "value")
116
+ return false;
117
+ return (tail.length === 1 ||
118
+ oneof.fields.some((f) => f.message && isInitializerPath(f.message, tail.slice(1))));
119
+ }
120
+ const field = schema.fields.find((f) => !f.oneof && f.localName === head);
121
+ if (!field)
122
+ return false;
123
+ if (!tail.length)
124
+ return true;
125
+ if (field.fieldKind === "list") {
126
+ if (typeof tail[0] !== "number" ||
127
+ !Number.isInteger(tail[0]) ||
128
+ tail[0] < 0 ||
129
+ tail[0] > 4294967294)
130
+ return false;
131
+ return (tail.length === 1 ||
132
+ (!!field.message && isInitializerPath(field.message, tail.slice(1))));
133
+ }
134
+ if (field.fieldKind === "map") {
135
+ if (typeof tail[0] !== "string")
136
+ return false;
137
+ const key = tail[0];
138
+ if (field.mapKey === ScalarType.BOOL && key !== "true" && key !== "false")
139
+ return false;
140
+ if (field.mapKey !== ScalarType.STRING &&
141
+ field.mapKey !== ScalarType.BOOL) {
142
+ const signed = [
143
+ ScalarType.INT32,
144
+ ScalarType.SINT32,
145
+ ScalarType.SFIXED32,
146
+ ScalarType.INT64,
147
+ ScalarType.SINT64,
148
+ ScalarType.SFIXED64,
149
+ ].includes(field.mapKey);
150
+ try {
151
+ if (mapKey(field, {
152
+ case: signed ? "intKey" : "uintKey",
153
+ value: BigInt(key),
154
+ }) !== key)
155
+ return false;
156
+ }
157
+ catch {
158
+ return false;
159
+ }
160
+ }
161
+ return (tail.length === 1 ||
162
+ (!!field.message && isInitializerPath(field.message, tail.slice(1))));
163
+ }
164
+ return (!!field.message &&
165
+ !isWrapperDesc(field.message) &&
166
+ isInitializerPath(field.message, tail));
167
+ }
168
+ /** Convert decoded canonical violations without evaluating any validation rules. */
169
+ export function violationsToIssues(violations, options) {
170
+ const fallback = fallbackIssue(options.fallback);
171
+ const issues = [];
172
+ let unusable = violations.length === 0;
173
+ for (const violation of violations) {
174
+ let resolved;
175
+ try {
176
+ if (!violation.ruleId.trim())
177
+ throw new Error("missing rule ID");
178
+ resolved = resolvePath(options.schema, violation.field);
179
+ }
180
+ catch {
181
+ unusable = true;
182
+ continue;
183
+ }
184
+ const issue = violationToIssue({ field: resolved.path, ruleId: violation.ruleId }, options.messages);
185
+ const path = (issue.path ?? []);
186
+ const mapping = resolved.message &&
187
+ options.mapMessageViolation?.({
188
+ messageType: resolved.message.typeName,
189
+ schema: resolved.message,
190
+ ruleId: violation.ruleId,
191
+ messagePath: path,
192
+ });
193
+ const rules = resolved.message?.proto.options &&
194
+ getExtension(resolved.message.proto.options, messageRules);
195
+ const isMessageRule = path.length === 0 ||
196
+ !!mapping ||
197
+ (!!rules &&
198
+ (rules.cel.some((rule) => rule.id === violation.ruleId) ||
199
+ (violation.ruleId === "message.oneof" && rules.oneof.length > 0)));
200
+ const lastField = [...resolved.path]
201
+ .reverse()
202
+ .find((segment) => segment.kind === "field");
203
+ const containingRules = lastField?.kind === "field" && lastField.proto.options
204
+ ? getExtension(lastField.proto.options, fieldRules)
205
+ : undefined;
206
+ const containers = [containingRules];
207
+ if (containingRules?.type.case === "repeated")
208
+ containers.push(containingRules.type.value.items);
209
+ if (containingRules?.type.case === "map")
210
+ containers.push(containingRules.type.value.values);
211
+ if (!mapping &&
212
+ isMessageRule &&
213
+ containers.some((rules) => rules?.cel.some((rule) => rule.id === violation.ruleId))) {
214
+ // Canonical details cannot distinguish a field CEL rule from the child
215
+ // message CEL rule at the same location with the same ID.
216
+ unusable = true;
217
+ continue;
218
+ }
219
+ // A message rule's dictionary is the child $fields.$message scope, even if a
220
+ // containing field has an identically named rule. Explicit mapping selects it.
221
+ const message = isMessageRule
222
+ ? overrideId({ field: resolved.path, ruleId: violation.ruleId }, options.messages, true)
223
+ : issue.message;
224
+ if (mapping) {
225
+ if (!mapping.fields.length ||
226
+ !mapping.fields.every((p) => isInitializerPath(resolved.message, p))) {
227
+ unusable = true;
228
+ continue;
229
+ }
230
+ for (const target of mapping.fields) {
231
+ issues.push({ message, path: [...path, ...target], target: "field" });
232
+ }
233
+ }
234
+ else {
235
+ issues.push({
236
+ message,
237
+ ...(path.length ? { path } : {}),
238
+ target: isMessageRule || violation.forKey ? "form" : "field",
239
+ });
240
+ }
241
+ }
242
+ if (unusable)
243
+ issues.push(fallback);
244
+ return issues;
245
+ }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@protovalidate-extensions/protovalidate-lingui",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Standard Schema validation with Lingui message IDs for Protovalidate.",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/comradesharf/protovalidate-extensions.git",
8
8
  "directory": "packages/protovalidate-lingui"
9
9
  },
10
- "homepage": "https://github.com/comradesharf/protovalidate-extensions/tree/master/packages/protovalidate-lingui#readme",
10
+ "homepage": "https://github.com/comradesharf/protovalidate-extensions/tree/main/packages/protovalidate-lingui#readme",
11
11
  "bugs": "https://github.com/comradesharf/protovalidate-extensions/issues",
12
12
  "publishConfig": {
13
13
  "access": "public",
@@ -27,12 +27,16 @@
27
27
  "type": "module",
28
28
  "peerDependencies": {
29
29
  "@bufbuild/protobuf": "^2.8.0",
30
- "@bufbuild/protovalidate": "^1.3.0"
30
+ "@bufbuild/protovalidate": "^1.3.0",
31
+ "@connectrpc/connect": "^2.3.0",
32
+ "@tanstack/form-core": "^1.33.5"
31
33
  },
32
34
  "devDependencies": {
33
35
  "@bufbuild/protobuf": "^2.17.0",
34
36
  "@bufbuild/protovalidate": "^1.3.0",
35
- "@lingui/core": "^6.12.0"
37
+ "@connectrpc/connect": "^2.3.0",
38
+ "@lingui/core": "^6.12.0",
39
+ "@tanstack/form-core": "1.33.5"
36
40
  },
37
41
  "sideEffects": false,
38
42
  "main": "./dist/index.js",
@@ -45,6 +49,22 @@
45
49
  "./messages": {
46
50
  "types": "./dist/messages.d.ts",
47
51
  "import": "./dist/messages.js"
52
+ },
53
+ "./violations": {
54
+ "types": "./dist/violations.d.ts",
55
+ "import": "./dist/violations.js"
56
+ },
57
+ "./connect": {
58
+ "types": "./dist/connect.d.ts",
59
+ "import": "./dist/connect.js"
60
+ },
61
+ "./tanstack-form": {
62
+ "types": "./dist/tanstack-form.d.ts",
63
+ "import": "./dist/tanstack-form.js"
64
+ },
65
+ "./connect/tanstack-form": {
66
+ "types": "./dist/connect/tanstack-form.d.ts",
67
+ "import": "./dist/connect/tanstack-form.js"
48
68
  }
49
69
  },
50
70
  "files": [
@@ -54,5 +74,13 @@
54
74
  ],
55
75
  "dependencies": {
56
76
  "@standard-schema/spec": "^1.1.0"
77
+ },
78
+ "peerDependenciesMeta": {
79
+ "@connectrpc/connect": {
80
+ "optional": true
81
+ },
82
+ "@tanstack/form-core": {
83
+ "optional": true
84
+ }
57
85
  }
58
86
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: protovalidate-lingui
3
- description: Integrate @protovalidate-extensions/protovalidate-lingui into TypeScript applications and Standard Schema forms, including Lingui extraction, translation, and plugin-generated message overrides. Use when installing, using, or troubleshooting this package.
3
+ description: Integrate @protovalidate-extensions/protovalidate-lingui into TypeScript applications and Standard Schema forms, including Lingui extraction, translation, and plugin-generated message overrides. Use when installing or troubleshooting the core adapter and localization setup; dedicated integration skills cover manual error migration, TanStack submission handling, and ConnectRPC details.
4
4
  ---
5
5
 
6
6
  # Protovalidate Lingui
@@ -0,0 +1,92 @@
1
+ ---
2
+ name: protovalidate-lingui-connectrpc
3
+ description: Decode or troubleshoot canonical buf.validate.Violations details in ConnectRPC failures using @protovalidate-extensions/protovalidate-lingui, including descriptor paths, message overrides, and fallbacks. Use for this package's transport integration; add TanStack handling only when the application uses it.
4
+ ---
5
+
6
+ # Protovalidate Lingui with ConnectRPC
7
+
8
+ Separate decoding from form-library binding. Use canonical validation details and Protobuf-ES descriptors; avoid ad hoc JSON decoders, English-message parsing, and manual path traversal.
9
+
10
+ ## Match the installed API and transport
11
+
12
+ Inspect the installed package's exports, declarations, peer versions, and README. The Connect integration is an optional peer dependency; the root Standard Schema adapter does not import it. Verify `/connect` exists before relying on a source checkout's new API.
13
+
14
+ The decoder processes `Code.InvalidArgument` errors containing `buf.validate.Violations`, using the canonical schema from `@bufbuild/protovalidate/gen/buf/validate/validate_pb.js`. It accepts caught `unknown` failures and produces issues or the required form fallback. Do not treat another status code as validation simply because it carries a detail with a familiar type name.
15
+
16
+ `google.rpc.BadRequest`, legacy display-path strings, and plain application JSON errors do not satisfy this contract. When the server's payload differs, establish whether changing that contract is in scope; otherwise retain explicit fallback handling.
17
+
18
+ ## Choose the consumer layer
19
+
20
+ Without TanStack Form:
21
+
22
+ ```ts
23
+ import { connectErrorToIssues } from "@protovalidate-extensions/protovalidate-lingui/connect";
24
+
25
+ const issues = connectErrorToIssues(error, {
26
+ schema: CreateProjectRequestSchema,
27
+ messages,
28
+ fallback: submitErrorMessage,
29
+ });
30
+ ```
31
+
32
+ For TanStack Form, use `toFormErrors(error, options)` from `/connect/tanstack-form` instead. That entry point also exports `submitWithFormErrors` for retries. For already decoded canonical violation arrays, use `violationsToIssues` from `/violations`; do not manufacture a ConnectError solely to call the decoder.
33
+
34
+ Options require the request's descriptor and a fallback translation ID or static descriptor with a nonempty `id`. Reuse client-side `messages` checked with the generated request override type. Conversion returns IDs and never evaluates the request's rules again. Translate with the active Lingui instance during rendering, not in the catch handler.
35
+
36
+ ## Keep the canonical server detail
37
+
38
+ When implementing a TypeScript Connect server already using Protovalidate, attach the actual validation result rather than rebuilding violations from English text:
39
+
40
+ ```ts
41
+ import { Code, ConnectError } from "@connectrpc/connect";
42
+ import { violationsToProto } from "@bufbuild/protovalidate";
43
+
44
+ // Inside the existing validation-result branch:
45
+ if (result.kind === "invalid") {
46
+ const [value, desc] = violationsToProto(result.violations);
47
+ throw new ConnectError("Validation failed", Code.InvalidArgument, undefined, [
48
+ { desc, value },
49
+ ]);
50
+ }
51
+ ```
52
+
53
+ For Rust or another server language, preserve its validation library and existing Connect stack. Send the same canonical `buf.validate.Violations` detail with structured field elements, rule IDs, and the correct status. Do not introduce a JavaScript validator or another validation pass into an existing backend.
54
+
55
+ The Lingui protoc plugin extracts static messages and generates override types. Existing output is sufficient for this integration; transport decoding and path reflection do not require generated runtime routing tables or server-side Lingui dependencies.
56
+
57
+ ## Interpret paths and route message rules
58
+
59
+ The package resolves canonical `field.elements` against the descriptor, using field numbers when present and proto names when absent. It checks conflicting names/types and collection subscripts, then emits Protobuf-ES initializer names. JSON names are not wire-path aliases. Preserve numeric list indices and exact decimal map-key strings, including 64-bit keys. Oneof members bind through the group's `.value` shape.
60
+
61
+ Use explicit `mapMessageViolation` registration for message-rule destinations:
62
+
63
+ ```ts
64
+ mapMessageViolation: ({ messageType, ruleId }) => {
65
+ if (
66
+ messageType === CreateProjectRequestSchema.typeName &&
67
+ ruleId === "project.name_available"
68
+ ) {
69
+ return { fields: [["displayName"]] };
70
+ }
71
+ return undefined;
72
+ };
73
+ ```
74
+
75
+ The callback receives the message descriptor and instance path. Its destinations are relative initializer paths; the adapter applies enclosing list indices and map keys. Match actual message types and IDs rather than inferring fields from ID spelling or human-readable messages. Returning `undefined` retains default placement. The callback can explicitly identify a server-only message rule at a message-valued location.
76
+
77
+ Nested message rules resolve their original `$fields.$message` override before routing. Without explicit routing, an ambiguous field-CEL/child-message-CEL ID collision uses fallback. Invalid or empty destinations also use fallback; application callback exceptions propagate as programming/configuration errors.
78
+
79
+ ## Preserve fallback behavior
80
+
81
+ - Known overrides return descriptor IDs; other nonempty rule IDs remain unchanged and need catalog entries.
82
+ - Missing/empty rule IDs, unknown fields, incompatible paths/subscripts, empty or malformed details, and non-validation failures leave visible form fallbacks.
83
+ - Every canonical detail is considered; unrelated detail types are ignored. Usable siblings survive malformed validation data, with a fallback alongside them.
84
+ - Multiple violations and their order within each field/form list are retained. Do not replace arrays with a last-error-wins dictionary.
85
+ - Map-key violations stay form-level. TanStack cannot safely encode empty map keys, path delimiters, or prototype-traversal segments; the integration promotes those issues to the form with the structured path retained.
86
+ - Singular scalar wrappers use unwrapped initializer fields. Internal protobuf paths inside `Struct` fields use fallback because their initializer is a JSON object.
87
+
88
+ Do not expose `ConnectError.message`, `rawMessage`, a violation's English text, or a pretranslated fallback as the validation message. Existing special application policies for authentication or cancellation can run before conversion; the package itself falls back for those failures.
89
+
90
+ ## Verify the contract
91
+
92
+ Use real canonical messages serialized with Protobuf-ES in transport tests. Exercise incoming binary and outgoing in-process details, multiple matching details, malformed and unrelated details, wrong status codes, absent IDs, unknown fields/rules, and large integer map keys. Compare local and wire-round-tripped issue IDs and paths for the same invalid request. Confirm retained issues retranslate after a locale switch. For TanStack consumers, also verify an unchanged-value retry through `submitWithFormErrors` and success-only navigation.
@@ -0,0 +1,3 @@
1
+ interface:
2
+ display_name: "Protovalidate Lingui ConnectRPC"
3
+ short_description: "Decode canonical ConnectRPC validation error details"
@@ -0,0 +1,79 @@
1
+ ---
2
+ name: protovalidate-lingui-migration
3
+ description: Migrate existing TypeScript validation and manual server-error mapping to @protovalidate-extensions/protovalidate-lingui, preserving application behavior, Lingui messages, and form submission retries. Use for replacing ad hoc ConnectRPC/TanStack Form error handling, not unrelated framework or schema migrations.
4
+ ---
5
+
6
+ # Migrate Protovalidate Lingui integrations
7
+
8
+ Replace application-owned error decoding and path traversal with the package adapters. Preserve the existing form library, mutation, navigation, validation rules, translations, and unrelated error handling.
9
+
10
+ ## Inspect the installed contract
11
+
12
+ Read the installed package's exports, declarations, peer dependencies, and README. An older published version may lack `/connect/tanstack-form`, `toFormErrors`, or `submitWithFormErrors`; do not assume the source checkout's version number proves these exports exist. Upgrade only as needed for the requested migration and use the application's package manager.
13
+
14
+ Locate the request's Protobuf-ES descriptor, generated message override type, default-value type, validators, submit handler, field/form error rendering, and Lingui catalog sources. Identify manual `findDetails`, proto-name switches, path joining, `setFieldMeta`/`setErrorMap`, translated error strings, and submit-button guards. Distinguish validation handling from intentional authentication, authorization, or cancellation behavior before replacing a catch block.
15
+
16
+ ## Replace the manual mapping
17
+
18
+ For a TanStack Form using ConnectRPC, import the combined optional integration:
19
+
20
+ ```ts
21
+ import {
22
+ toFormErrors,
23
+ submitWithFormErrors,
24
+ } from "@protovalidate-extensions/protovalidate-lingui/connect/tanstack-form";
25
+
26
+ // In validators.onSubmitAsync, keep the application's mutation:
27
+ onSubmitAsync: async ({ value }) => {
28
+ try {
29
+ await mutation.mutateAsync(value);
30
+ return undefined;
31
+ } catch (error) {
32
+ return toFormErrors(error, {
33
+ schema: CreateProjectRequestSchema,
34
+ messages,
35
+ fallback: submitErrorMessage,
36
+ });
37
+ }
38
+ };
39
+ ```
40
+
41
+ `fallback` must be a nonempty translation ID or static Lingui descriptor, not `i18n._(...)` or `t` output. Keep special application error branches where needed; the converter otherwise produces a fallback for non-validation failures.
42
+
43
+ Use `createStandardSchemaInit(RequestSchema, { messages })` for plain initializers. Explicitly type default values as `MessageInitShape<typeof RequestSchema>` or the schema's inferred input so TanStack and Standard Schema agree on the input type. Keep existing compatible client validators. A Standard Schema's validated output does not replace TanStack's stored initializer; construct a protobuf message explicitly if the mutation needs one.
44
+
45
+ Move success-only navigation to `onSubmit` when using this submission pattern. Remove the mutation from its former submit handler so it runs once per attempt. `onSubmitAsync` also runs on explicit submit validation; avoid adding additional calls that validate by executing the mutation.
46
+
47
+ ## Preserve routing decisions and translations
48
+
49
+ Replace hardcoded message-rule switches with `mapMessageViolation`:
50
+
51
+ ```ts
52
+ mapMessageViolation: ({ messageType, ruleId }) => {
53
+ if (
54
+ messageType === CreateProjectRequestSchema.typeName &&
55
+ ruleId === "project.name_available"
56
+ ) {
57
+ return { fields: [["displayName"]] };
58
+ }
59
+ return undefined;
60
+ };
61
+ ```
62
+
63
+ Use actual application rule IDs. Destinations are relative initializer paths; the package retains nested message, list-index, and map-key prefixes. Do not reconstruct them or infer a field from ID spelling or English messages. Returning `undefined` keeps a message rule at form level. Preserve wording through the existing generated `...Messages` type and scoped `$message`/`$fields` overrides.
64
+
65
+ Change renderers from a single translated string to arrays of issue objects. Translate each `issue.message` through the active `useLingui()` instance during rendering. Preserve every violation per field. Render server form errors from `state.errorMap.onSubmit`; they are issue arrays. Existing custom validators may return other error types, so preserve appropriate handling for those types rather than assuming all application errors have `.message`.
66
+
67
+ ## Migrate the submission boundary
68
+
69
+ Replace the DOM handler's `form.handleSubmit()` call with `submitWithFormErrors(form)`, retaining `preventDefault` and the application's event handling. Pass existing submit metadata as the optional second argument.
70
+
71
+ TanStack v1 can stop a retry on stale server field errors before its async validator runs. The helper clears this integration's previous submit issues, preserves unrelated validators, and coalesces concurrent helper calls. Disable the submit button while `isSubmitting || isValidating`; an unconditional `!canSubmit` guard can prevent unchanged-value retries. Do not clear all errors or reset the form to force a retry.
72
+
73
+ The helper tracks original issue objects within one package instance. It does not manage serialized errors, transport retries, mutation cancellation, or server idempotency. Preserve existing policies for those concerns.
74
+
75
+ ## Verify the migration
76
+
77
+ Typecheck the actual form and exercise: client-invalid input without a mutation; server field and form failures; multiple violations on one field; unchanged-value retry after field/fallback errors; corrected-value success with navigation once; and preservation of other validators. Switch locale with stored errors and confirm they retranslate without a request or revalidation.
78
+
79
+ Use canonical binary `buf.validate.Violations` details in transport tests. Missing/malformed details, unknown fields, and non-validation failures must leave a visible fallback. Unmapped nonempty rule IDs remain IDs and need catalog entries. Unrepresentable TanStack map keys and map-key violations appear at form level; do not restore guessed field paths to hide this limitation.
@@ -0,0 +1,3 @@
1
+ interface:
2
+ display_name: "Protovalidate Lingui Migration"
3
+ short_description: "Migrate manual validation errors to package adapters"
@@ -0,0 +1,119 @@
1
+ ---
2
+ name: protovalidate-lingui-tanstack-form
3
+ description: Integrate @protovalidate-extensions/protovalidate-lingui with TanStack Form for client validation, structured server errors, Lingui rendering, and submission retries. Use when wiring or troubleshooting this package's TanStack integration, not general TanStack Router or Query work.
4
+ ---
5
+
6
+ # Protovalidate Lingui with TanStack Form
7
+
8
+ Use the root Standard Schema adapter for local validation and optional integration entry points for server issues. Keep the application's existing framework and mutation tools.
9
+
10
+ ## Select the entry points and input type
11
+
12
+ Inspect the installed exports, declarations, README, and peer versions. The integration targets TanStack Form v1, with retry behavior tested against Form Core 1.33.5; do not apply alpha APIs or assume a newer checkout's exports exist in an older installation. Keep React Form and Form Core versions aligned with the application's dependency setup.
13
+
14
+ - Root: `createStandardSchemaInit` for initializer inputs, or `createStandardSchema` for complete protobuf messages.
15
+ - `/connect/tanstack-form`: `toFormErrors` plus `submitWithFormErrors` for caught ConnectRPC failures.
16
+ - `/tanstack-form`: `toTanStackFormErrors` plus `submitWithFormErrors` for already normalized issues, without requiring ConnectRPC.
17
+
18
+ ConnectRPC and Form Core are optional peers. Do not add React, TanStack Query, or ConnectRPC when the requested use does not require them. The core adapter needs no form-library integration dependency.
19
+
20
+ ```ts
21
+ import type { MessageInitShape } from "@bufbuild/protobuf";
22
+ import { createStandardSchemaInit } from "@protovalidate-extensions/protovalidate-lingui";
23
+ import {
24
+ toFormErrors,
25
+ submitWithFormErrors,
26
+ } from "@protovalidate-extensions/protovalidate-lingui/connect/tanstack-form";
27
+
28
+ const schema = createStandardSchemaInit(CreateProjectRequestSchema, {
29
+ messages,
30
+ });
31
+ const defaultValues: MessageInitShape<typeof CreateProjectRequestSchema> = {
32
+ displayName: "",
33
+ };
34
+
35
+ const form = useForm({
36
+ defaultValues,
37
+ validators: {
38
+ onChange: schema,
39
+ onSubmitAsync: async ({ value }) => {
40
+ try {
41
+ await mutation.mutateAsync(value);
42
+ return undefined;
43
+ } catch (error) {
44
+ return toFormErrors(error, {
45
+ schema: CreateProjectRequestSchema,
46
+ messages,
47
+ fallback: submitErrorMessage,
48
+ });
49
+ }
50
+ },
51
+ },
52
+ onSubmit: async () => {
53
+ await navigate({ to: ".." });
54
+ },
55
+ });
56
+ ```
57
+
58
+ The descriptor, messages, mutation, and navigation above are application values. Check `messages` against the generated request message override type. Keep the schema instance stable when its descriptor and options are stable.
59
+
60
+ TanStack keeps the original initializer even though a successful Standard Schema result contains a constructed protobuf message. Do not assume validation transforms form values. Recursive descriptors work at runtime, but recursive TypeScript messages may require a finite application form type to avoid TanStack `DeepKeys` expansion limits.
61
+
62
+ ## Bind and render errors
63
+
64
+ The server adapter returns `{ fields, form? }`. Keep `fields` even for a form-only failure: TanStack v1 uses that property to recognize this error structure. Each populated value is an array of issues, with a translation ID in `message`, an optional structured initializer `path`, and a `target`.
65
+
66
+ Bind controls to Protobuf-ES initializer names: `displayName`, `members[2].emailAddress`, `labels.home.displayName`, and `contact.value` for a oneof member. A required oneof targets its group, such as `contact`. Do not use proto snake-case or JSON names to bind controls, and do not join structured paths yourself.
67
+
68
+ Use the active Lingui instance from `useLingui()` in the rendering component:
69
+
70
+ ```tsx
71
+ {
72
+ field.state.meta.errors.map((issue, index) => (
73
+ <p key={index}>{i18n._(issue.message)}</p>
74
+ ));
75
+ }
76
+ ```
77
+
78
+ Render server form issues from `state.errorMap.onSubmit` using the same ID-based approach. Standard Schema form errors for other events can instead be records of issue arrays; respect the event's inferred type. If custom validators return strings or other objects, retain their existing rendering paths.
79
+
80
+ Do not translate inside validators or keep only the first violation. Override descriptors and fallback descriptors must have IDs; their interpolation values are not carried. Supply catalog entries and normal extraction/loading for every displayed ID.
81
+
82
+ ## Handle submit retries
83
+
84
+ Use this DOM boundary with the application's form instance:
85
+
86
+ ```tsx
87
+ <form
88
+ onSubmit={(event) => {
89
+ event.preventDefault();
90
+ event.stopPropagation();
91
+ void submitWithFormErrors(form);
92
+ }}
93
+ >
94
+ {/* Existing controls and translated field/form issues. */}
95
+ <form.Subscribe
96
+ selector={(state) => state.isSubmitting || state.isValidating}
97
+ >
98
+ {(pending) => (
99
+ <button type="submit" disabled={pending}>
100
+ Save
101
+ </button>
102
+ )}
103
+ </form.Subscribe>
104
+ </form>
105
+ ```
106
+
107
+ Retained server field errors can stop plain `handleSubmit()` before `onSubmitAsync` runs again. The helper clears only its own previous submit issue objects, preserves other validators, forwards optional submit metadata, and coalesces concurrent calls. Avoid disabling retry solely through `!canSubmit`, resetting values, or clearing unrelated error maps.
108
+
109
+ Keep the mutation exclusively in `onSubmitAsync`; success-only work belongs in `onSubmit`. Explicit submit validation can also run the mutation, so do not add such calls as a retry workaround. The helper does not manage serialized error state, cancellation, mutations submitted outside it, or network idempotency.
110
+
111
+ ## Handle unbound errors explicitly
112
+
113
+ Use `mapMessageViolation` when the application deliberately binds a message-level rule to one or more fields. Match the message type and rule ID, then return relative initializer path arrays. The package keeps collection prefixes and resolves the message in its original override scope before routing. Never infer a target from ID spelling or English text.
114
+
115
+ Render form issues: missing/malformed details and non-validation failures use the required fallback; unknown nonempty rule IDs retain their IDs. Message rules remain at form level unless mapped. Map-key violations and paths containing unrepresentable map keys also stay visible there. Do not force them onto a guessed control.
116
+
117
+ ## Verify behavior
118
+
119
+ Typecheck the real form. Test client-invalid values preventing mutation, multiple server issues per field, form/fallback display, nested and oneof bindings, unchanged-value retry, corrected-value success, duplicate submit coalescing, and unrelated validators remaining effective. Confirm locale changes update stored errors without revalidation or a new request. Use mocked/disposable transport responses appropriate to the application's test setup.
@@ -0,0 +1,3 @@
1
+ interface:
2
+ display_name: "Protovalidate Lingui TanStack Form"
3
+ short_description: "Wire validation IDs, form errors, and submit retries"