@omer-x/next-form-actions 1.0.0 → 2.0.0-alpha.2

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
@@ -22,6 +22,10 @@ npm install @omer-x/next-form-actions
22
22
 
23
23
  ## Usage
24
24
 
25
+ > Upgrading from v1? See the [migration guide](MIGRATION.md).
26
+
27
+ ### Defining an action
28
+
25
29
  ```typescript
26
30
  "use server";
27
31
  import { defineFormAction, displayMessage } from "@omer-x/next-form-actions";
@@ -31,24 +35,66 @@ import { authMiddleware } from "./middlewares/session";
31
35
  export const createUser = defineFormAction({
32
36
  middlewares: [authMiddleware],
33
37
  schema: z.object({
34
- foo: z.string(),
38
+ name: z.string().min(3),
39
+ age: z.number(), // "30" from the form is converted to 30
40
+ tags: z.array(z.string()), // repeated keys (checkbox groups, multi-selects) become arrays
41
+ email: z.email().refine(
42
+ async email => !(await emailExists(email)), // async checks are supported
43
+ { params: { customErrorCode: "taken" } },
44
+ ),
35
45
  }),
36
- action: input => (async () => {
37
- console.log(input); // { foo: "bar" }
38
- try {
39
- // try to create a user
40
-
41
- displayMessage("success", "ok!");
42
- } catch (error) {
43
- if (error === "BAD_REQUEST") {
44
- displayMessage("warning", "you are doing something wrong");
45
- }
46
- displayMessage("error", "unknown error");
46
+ action: input => (async (teamId: string) => {
47
+ if (await isTeamFull(teamId)) {
48
+ displayMessage("error", "TEAM_IS_FULL"); // stops the action with a failure state
47
49
  }
50
+ const user = await insertUser(teamId, input);
51
+ return { id: user.id }; // becomes the `data` of the success state
48
52
  }),
49
53
  });
50
54
  ```
51
55
 
56
+ ### Using it in a form
57
+
58
+ ```tsx
59
+ "use client";
60
+ import { useActionState } from "react";
61
+ import { createUser } from "./actions";
62
+
63
+ export function CreateUserForm({ teamId }: { teamId: string }) {
64
+ const [state, formAction] = useActionState(createUser.bind(null, teamId), { status: "idle" });
65
+ // ...
66
+ }
67
+ ```
68
+
69
+ ### The action state
70
+
71
+ Every action resolves to a `FormActionState<Data>`:
72
+
73
+ ```typescript
74
+ // before the first submission
75
+ { status: "idle" }
76
+
77
+ // the action returned normally
78
+ { status: "success", data: { id: "abc123" } }
79
+
80
+ // validation failed
81
+ {
82
+ status: "failure",
83
+ fieldErrors: {
84
+ name: [{ code: "too_small", params: { minimum: 3, origin: "string" } }],
85
+ email: [{ code: "taken" }],
86
+ "tags.1": [{ code: "required" }],
87
+ },
88
+ }
89
+
90
+ // displayMessage("error", "TEAM_IS_FULL") was called
91
+ { status: "failure", fieldErrors: {}, message: { type: "error", text: "TEAM_IS_FULL" } }
92
+ ```
93
+
94
+ - `fieldErrors` keys are full field paths, and each field can have several errors.
95
+ - Error codes are Zod's issue codes (`required`, `too_small`, `too_big`, `invalid_type`, `invalid_value`, `invalid_email`, ...) or the `customErrorCode` of a refinement.
96
+ - `displayMessage` accepts `"error"` and `"warning"`. To signal success, return from the action.
97
+
52
98
  ## License
53
99
 
54
100
  This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
package/dist/index.d.mts CHANGED
@@ -1,8 +1,62 @@
1
1
  import { ZodObject, ZodType } from "zod";
2
+ /**
3
+ * A single validation error of a field.
4
+ */
5
+ type FieldError = {
6
+ /**
7
+ * The error code, e.g. "required", "too_small", "invalid_email" or a custom code.
8
+ */
9
+ code: string;
10
+ /**
11
+ * Details of the error, e.g. `{ minimum: 3, origin: "string" }` for "too_small".
12
+ */
13
+ params?: Record<string, unknown>;
14
+ };
15
+ /**
16
+ * A form-level message produced by `displayMessage`.
17
+ */
18
+ type FormMessage = {
19
+ type: "error" | "warning";
20
+ /**
21
+ * The display text or a translation key.
22
+ */
23
+ text: string;
24
+ };
25
+ type IdleState = {
26
+ status: "idle";
27
+ };
28
+ type SuccessState<Data> = {
29
+ status: "success";
30
+ /**
31
+ * The value returned by the action.
32
+ */
33
+ data: Data;
34
+ };
35
+ type FailureState = {
36
+ status: "failure";
37
+ /**
38
+ * Validation errors, keyed by the full path of the field (e.g. "tags.1").
39
+ */
40
+ fieldErrors: Record<string, FieldError[]>;
41
+ message?: FormMessage;
42
+ };
43
+ /**
44
+ * The state of a form action, to be used with `useActionState`.
45
+ * Use `{ status: "idle" }` as the initial state.
46
+ */
47
+ type FormActionState<Data = undefined> = IdleState | SuccessState<Data> | FailureState;
48
+ /**
49
+ * A form action, as returned by `defineFormAction`. With its extra arguments bound
50
+ * (e.g. `action.bind(null, id)`), it becomes a `FormAction<Data>` that `useActionState` accepts.
51
+ *
52
+ * The action never reads `previousState`, so it is typed as `unknown`. That keeps `Data` only
53
+ * in the return type, so `FormAction<unknown>` accepts any form action.
54
+ */
55
+ type FormAction<Data = undefined, Args extends unknown[] = []> = (...params: [...Args, previousState: unknown, formData: FormData]) => Promise<FormActionState<Data>>;
2
56
  /**
3
57
  * Describes the definition of a type-safe server action for forms.
4
58
  */
5
- type ActionDefinition<Shape extends Record<string, ZodType>, SchemaI, SchemaO, Args extends unknown[]> = {
59
+ type ActionDefinition<Shape extends Record<string, ZodType>, SchemaI, SchemaO, Args extends unknown[], Data> = {
6
60
  /**
7
61
  * An array of middleware functions to execute before the action. (Optional)
8
62
  */
@@ -13,20 +67,24 @@ type ActionDefinition<Shape extends Record<string, ZodType>, SchemaI, SchemaO, A
13
67
  schema: ZodType<SchemaO, SchemaI> & ZodObject<Shape>;
14
68
  /**
15
69
  * The function to execute if validation succeeds. Receives parsed data and returns a function for additional arguments.
70
+ * Its return value becomes the `data` of the success state.
16
71
  */
17
- action: (input: SchemaO) => ((...args: [...Args]) => Promise<Partial<Record<string, string>>>);
72
+ action: (input: SchemaO) => ((...args: [...Args]) => Data | Promise<Data>);
18
73
  };
19
- type FormAction<Args extends unknown[]> = (...allParams: [...Args, initialState: unknown, formData: FormData]) => Promise<Record<string, string>>;
20
74
  /**
21
75
  * Defines a type-safe React server action for forms, validating form data with Zod and handling errors internally.
22
76
  *
23
77
  * @param definition - The form action definition object.
24
- * @param definition.name - The unique name of the action.
25
78
  * @param definition.middleware - An array of middleware functions to execute before the action. (Optional)
26
79
  * @param definition.schema - The Zod schema used to validate form data.
27
80
  * @param definition.action - The function to execute if validation succeeds.
28
- * @returns An object containing the server action handler keyed by the action name.
81
+ * @returns The server action, which resolves to a `FormActionState`.
82
+ */
83
+ export declare function defineFormAction<Shape extends Record<string, ZodType>, SchemaI, SchemaO, Args extends unknown[], Data = undefined>(definition: ActionDefinition<Shape, SchemaI, SchemaO, Args, Data>): FormAction<Data, Args>;
84
+ /**
85
+ * Stops the action and returns a failure state with a form-level message.
86
+ * @param type - The type of the message.
87
+ * @param text - The display text or a translation key.
29
88
  */
30
- export declare function defineFormAction<Shape extends Record<string, ZodType>, SchemaI, SchemaO, Args extends unknown[]>(definition: ActionDefinition<Shape, SchemaI, SchemaO, Args>): FormAction<Args>;
31
- export declare function displayMessage(messageType: "error" | "warning" | "success" | (string & {}), message: string): never;
32
- export {};
89
+ export declare function displayMessage(type: FormMessage["type"], text: string): never;
90
+ export type { FieldError, FormAction, FormActionState, FormMessage };
package/dist/index.mjs CHANGED
@@ -1,101 +1,189 @@
1
+ // src/utils/formDataToObject.ts
2
+ function formDataToObject(formData) {
3
+ const result = {};
4
+ for (const [key, value] of formData.entries()) if (key in result) {
5
+ const existing = result[key];
6
+ if (Array.isArray(existing)) existing.push(value);
7
+ else result[key] = [existing, value];
8
+ } else result[key] = value;
9
+ return result;
10
+ }
1
11
  // src/core/bundleErrors.ts
2
12
  /**
3
- * Maps a Zod issue to a string error code or message.
13
+ * Maps a Zod issue to a field error.
4
14
  * @param issue - The Zod issue object.
5
- * @returns The error code or message for the issue.
15
+ * @returns The error code and the parameters of the issue.
6
16
  */
7
- function handleZodIssue(issue) {
17
+ function toFieldError(issue) {
8
18
  switch (issue.code) {
9
19
  case "custom": {
10
- const params = issue.params ?? {};
11
- if ("customErrorCode" in params && typeof params.customErrorCode === "string") return params.customErrorCode;
12
- return issue.message;
20
+ const { customErrorCode, ...params } = issue.params ?? {};
21
+ const code = typeof customErrorCode === "string" ? customErrorCode : issue.message;
22
+ return Object.keys(params).length ? {
23
+ code,
24
+ params
25
+ } : { code };
13
26
  }
14
- case "invalid_format": return `invalid_${issue.format}`;
27
+ case "invalid_format": return { code: `invalid_${issue.format}` };
15
28
  case "invalid_type":
16
- if (/expected .+?, received undefined/.test(issue.message)) return "required";
17
- return issue.code;
18
- case "too_small":
19
- case "too_big": return issue.code;
20
- default: return "unknown_error";
29
+ if (/expected .+?, received undefined/.test(issue.message)) return { code: "required" };
30
+ return {
31
+ code: issue.code,
32
+ params: { expected: issue.expected }
33
+ };
34
+ case "too_small": return {
35
+ code: issue.code,
36
+ params: {
37
+ minimum: issue.minimum,
38
+ origin: issue.origin
39
+ }
40
+ };
41
+ case "too_big": return {
42
+ code: issue.code,
43
+ params: {
44
+ maximum: issue.maximum,
45
+ origin: issue.origin
46
+ }
47
+ };
48
+ case "invalid_value": return {
49
+ code: issue.code,
50
+ params: { values: issue.values }
51
+ };
52
+ case "not_multiple_of": return {
53
+ code: issue.code,
54
+ params: { divisor: issue.divisor }
55
+ };
56
+ default: return { code: issue.code };
21
57
  }
22
58
  }
23
59
  /**
24
- * Bundles an array of Zod issues into a record mapping field locations to error codes/messages.
60
+ * Groups Zod issues by the full path of their field.
25
61
  * @param issues - Array of Zod issues.
26
- * @returns An object mapping field names to error codes/messages.
62
+ * @returns An object mapping field paths (e.g. "tags.1") to their errors.
27
63
  */
28
64
  function bundleErrors(issues) {
29
- return issues.reduce((bundle, issue) => {
30
- const [location] = issue.path;
31
- return {
32
- ...bundle,
33
- [location]: handleZodIssue(issue).toUpperCase()
34
- };
35
- }, {});
65
+ const fieldErrors = {};
66
+ for (const issue of issues) {
67
+ const path = issue.path.map(String).join(".");
68
+ fieldErrors[path] ??= [];
69
+ fieldErrors[path].push(toFieldError(issue));
70
+ }
71
+ return fieldErrors;
36
72
  }
37
- // src/core/solveKnownIssues.ts
38
- function solveKnownIssues(schema, input) {
39
- const validation = schema.safeParse(input);
40
- if (!validation.success) {
41
- for (const issue of validation.error.issues) if (issue.code === "invalid_type") {
42
- if (issue.expected === "number" && issue.message.includes("expected number, received string")) {
43
- const [location] = issue.path;
44
- return solveKnownIssues(schema, {
45
- ...input,
46
- [location]: parseFloat(input[location])
47
- });
48
- }
49
- if (issue.expected === "boolean" && issue.message.includes("expected boolean, received string")) {
50
- const [location] = issue.path;
51
- const value = input[location];
52
- if (value === "true" || value === "false") return solveKnownIssues(schema, {
53
- ...input,
54
- [location]: value === "true"
55
- });
56
- }
57
- }
73
+ // src/core/coerceFormInput.ts
74
+ /**
75
+ * Strips wrappers (optional, default, pipe, ...) to find the schema that decides the value's type.
76
+ * @param schema - The schema of a single field.
77
+ * @returns The innermost schema.
78
+ */
79
+ function unwrap(schema) {
80
+ const def = schema._zod.def;
81
+ switch (def.type) {
82
+ case "optional":
83
+ case "nullable":
84
+ case "default":
85
+ case "prefault":
86
+ case "catch":
87
+ case "readonly":
88
+ case "nonoptional": return def.innerType ? unwrap(def.innerType) : schema;
89
+ case "pipe": return def.in ? unwrap(def.in) : schema;
90
+ case "lazy": return def.getter ? unwrap(def.getter()) : schema;
91
+ default: return schema;
92
+ }
93
+ }
94
+ /**
95
+ * Converts a single form value to the type its schema expects. Values that can't be converted are left as they are,
96
+ * so the schema can report them.
97
+ * @param schema - The schema of the field.
98
+ * @param value - The raw form value.
99
+ * @returns The converted value.
100
+ */
101
+ function coerceValue(schema, value) {
102
+ const def = unwrap(schema)._zod.def;
103
+ if (def.type === "array") {
104
+ if (value === void 0) return value;
105
+ const items = Array.isArray(value) ? value : [value];
106
+ return def.element ? items.map((item) => coerceValue(def.element, item)) : items;
107
+ }
108
+ if (Array.isArray(value)) return coerceValue(schema, value.at(-1));
109
+ switch (def.type) {
110
+ case "number": return typeof value === "string" ? parseFloat(value) : value;
111
+ case "boolean":
112
+ if (value === "true") return true;
113
+ if (value === "false") return false;
114
+ return value;
115
+ default: return value;
116
+ }
117
+ }
118
+ /**
119
+ * Converts form values to the types the schema expects (e.g. "12" to 12, "true" to true) before validation,
120
+ * so the schema only has to run once.
121
+ * @param shape - The shape of the object schema.
122
+ * @param input - The raw form values.
123
+ * @returns The converted form values.
124
+ */
125
+ function coerceFormInput(shape, input) {
126
+ return Object.fromEntries(Object.entries(input).map(([key, value]) => {
127
+ const fieldSchema = Object.hasOwn(shape, key) ? shape[key] : void 0;
128
+ return [key, fieldSchema ? coerceValue(fieldSchema, value) : value];
129
+ }));
130
+ }
131
+ // src/core/displayMessage.ts
132
+ /**
133
+ * Thrown by `displayMessage`. Deliberately not an `Error`, so `catch` blocks that only handle errors
134
+ * (e.g. `if (Error.isError(error))`) let it pass through.
135
+ */
136
+ var DisplayMessage = class {
137
+ constructor(message) {
138
+ this.message = message;
58
139
  }
59
- return validation;
140
+ };
141
+ /**
142
+ * Stops the action and returns a failure state with a form-level message.
143
+ * @param type - The type of the message.
144
+ * @param text - The display text or a translation key.
145
+ */
146
+ function displayMessage(type, text) {
147
+ throw new DisplayMessage({
148
+ type,
149
+ text
150
+ });
60
151
  }
61
152
  // src/core/defineFormAction.ts
62
153
  /**
63
154
  * Defines a type-safe React server action for forms, validating form data with Zod and handling errors internally.
64
155
  *
65
156
  * @param definition - The form action definition object.
66
- * @param definition.name - The unique name of the action.
67
157
  * @param definition.middleware - An array of middleware functions to execute before the action. (Optional)
68
158
  * @param definition.schema - The Zod schema used to validate form data.
69
159
  * @param definition.action - The function to execute if validation succeeds.
70
- * @returns An object containing the server action handler keyed by the action name.
160
+ * @returns The server action, which resolves to a `FormActionState`.
71
161
  */
72
162
  function defineFormAction(definition) {
73
163
  async function handler(...allParams) {
74
164
  if (definition.middlewares) await Promise.all(definition.middlewares.map((middleware) => middleware()));
75
165
  const formData = allParams[allParams.length - 1];
76
166
  const customArgs = allParams.slice(0, allParams.length - 2);
77
- const validation = solveKnownIssues(definition.schema, Object.fromEntries(formData.entries()));
78
- if (!validation.success) return bundleErrors(validation.error.issues);
167
+ const input = coerceFormInput(definition.schema.shape, formDataToObject(formData));
168
+ const validation = await definition.schema.safeParseAsync(input);
169
+ if (!validation.success) return {
170
+ status: "failure",
171
+ fieldErrors: bundleErrors(validation.error.issues)
172
+ };
79
173
  try {
80
- return await definition.action(validation.data)(...customArgs);
174
+ return {
175
+ status: "success",
176
+ data: await definition.action(validation.data)(...customArgs)
177
+ };
81
178
  } catch (error) {
82
- if (error && typeof error === "object" && "isDisplayMessage" in error && "messageType" in error && "message" in error) return { [error.messageType]: error.message };
179
+ if (error instanceof DisplayMessage) return {
180
+ status: "failure",
181
+ fieldErrors: {},
182
+ message: error.message
183
+ };
83
184
  throw error;
84
185
  }
85
186
  }
86
187
  return handler;
87
188
  }
88
- // src/core/displayMessage.ts
89
- function displayMessage(messageType, message) {
90
- if (messageType === "error" || messageType === "warning" || messageType === "success") throw {
91
- isDisplayMessage: true,
92
- messageType: `[${messageType}]`,
93
- message
94
- };
95
- throw {
96
- isDisplayMessage: true,
97
- messageType,
98
- message
99
- };
100
- }
101
189
  export { defineFormAction, displayMessage };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omer-x/next-form-actions",
3
- "version": "1.0.0",
3
+ "version": "2.0.0-alpha.2",
4
4
  "description": "Provides helper functions to define a type-safe React server action for forms, validating form data with Zod and handling errors internally.",
5
5
  "keywords": [
6
6
  "nextjs",