nuxt-precognition 0.0.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/LICENSE +22 -0
- package/README.md +337 -0
- package/dist/module.cjs +5 -0
- package/dist/module.d.mts +22 -0
- package/dist/module.d.ts +22 -0
- package/dist/module.json +8 -0
- package/dist/module.mjs +77 -0
- package/dist/runtime/core.d.ts +18 -0
- package/dist/runtime/core.mjs +76 -0
- package/dist/runtime/plugin.d.ts +2 -0
- package/dist/runtime/plugin.mjs +15 -0
- package/dist/runtime/server/definePrecognitiveEventHandler.d.ts +18 -0
- package/dist/runtime/server/definePrecognitiveEventHandler.mjs +116 -0
- package/dist/runtime/server/plugin.d.ts +2 -0
- package/dist/runtime/server/plugin.mjs +12 -0
- package/dist/runtime/server/tsconfig.json +3 -0
- package/dist/runtime/types/config.d.ts +15 -0
- package/dist/runtime/types/config.mjs +1 -0
- package/dist/runtime/types/core.d.ts +7 -0
- package/dist/runtime/types/core.mjs +1 -0
- package/dist/runtime/types/eventHandler.d.ts +12 -0
- package/dist/runtime/types/eventHandler.mjs +1 -0
- package/dist/runtime/types/form.d.ts +46 -0
- package/dist/runtime/types/form.mjs +1 -0
- package/dist/runtime/types/utils.d.ts +9 -0
- package/dist/runtime/types/utils.mjs +1 -0
- package/dist/runtime/useForm.d.ts +2 -0
- package/dist/runtime/useForm.mjs +135 -0
- package/dist/runtime/validator.d.ts +11 -0
- package/dist/runtime/validator.mjs +86 -0
- package/dist/types.d.mts +16 -0
- package/dist/types.d.ts +16 -0
- package/package.json +73 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Copyright (c) <year> <copyright holders>
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person
|
|
4
|
+
obtaining a copy of this software and associated documentation
|
|
5
|
+
files (the "Software"), to deal in the Software without
|
|
6
|
+
restriction, including without limitation the rights to use,
|
|
7
|
+
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the
|
|
9
|
+
Software is furnished to do so, subject to the following
|
|
10
|
+
conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be
|
|
13
|
+
included in all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
16
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
17
|
+
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
18
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
19
|
+
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
20
|
+
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
21
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
22
|
+
OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
Get your module up and running quickly.
|
|
3
|
+
|
|
4
|
+
Find and replace all on all files (CMD+SHIFT+F):
|
|
5
|
+
- Name: Nuxt Precognition
|
|
6
|
+
- Package name: nuxt-precognition
|
|
7
|
+
- Description: My new Nuxt module
|
|
8
|
+
-->
|
|
9
|
+
|
|
10
|
+
# Nuxt Precognition
|
|
11
|
+
|
|
12
|
+
[![npm version][npm-version-src]][npm-version-href]
|
|
13
|
+
[![npm downloads][npm-downloads-src]][npm-downloads-href]
|
|
14
|
+
[![License][license-src]][license-href]
|
|
15
|
+
[![Nuxt][nuxt-src]][nuxt-href]
|
|
16
|
+
|
|
17
|
+
This is a new version of [nuxt-laravel-precognition](https://www.npmjs.com/package/nuxt-laravel-precognition). It offers same features, but being not dependent on Laravel.
|
|
18
|
+
|
|
19
|
+
Instead of supporting only _$fetch_ and _Laravel_, it works with simple promises, targetting any backend that implements the base Precognition protocol. These promises will receive the form `payload` and protocol `Headers`.
|
|
20
|
+
|
|
21
|
+
#### Example
|
|
22
|
+
```ts
|
|
23
|
+
interface User = {
|
|
24
|
+
email: string
|
|
25
|
+
password: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const form = useForm(
|
|
29
|
+
(): User => ({ email: '', password: '' }),
|
|
30
|
+
(body, headers) => $fetch('/api/login', { method: 'POST', headers, body })
|
|
31
|
+
)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
This moudules comes with native __Nitro__ integration, but will work with other backend as weel, even properly configured _aws lambda_.
|
|
35
|
+
It supports any validation library (_who said [__Zod__](https://zod.dev/)??_) server or client side. You will need only to configure specific `Error parsers`.
|
|
36
|
+
|
|
37
|
+
- [✨ Release Notes](/CHANGELOG.md)
|
|
38
|
+
<!-- - [🏀 Online playground](https://stackblitz.com/github/your-org/nuxt-precognition?file=playground%2Fapp.vue) -->
|
|
39
|
+
<!-- - [📖 Documentation](https://example.com) -->
|
|
40
|
+
|
|
41
|
+
### Features
|
|
42
|
+
|
|
43
|
+
<!-- Highlight some of the features your module provide here -->
|
|
44
|
+
- Laravel compliant
|
|
45
|
+
- Validation library agnostic
|
|
46
|
+
- Client and server side validation
|
|
47
|
+
- Optimal Typescript support
|
|
48
|
+
- Highly customizable
|
|
49
|
+
|
|
50
|
+
### How it works
|
|
51
|
+
Everything turns around `errorParsers`(_user defined function to read validation errors from_ `Error` _payload_):
|
|
52
|
+
```ts
|
|
53
|
+
type ValidationErrors = Record<string, string | string[]>
|
|
54
|
+
|
|
55
|
+
interface ValidationErrorsData {
|
|
56
|
+
message: string
|
|
57
|
+
errors: ValidationErrors
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
type ValidationErrorParser = (error: Error) => ValidationErrorsData | undefined | null
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
You can define them globally (in `Nuxt Plugin` or custom `eventHandler`), or per `form` instance.
|
|
64
|
+
|
|
65
|
+
Imagine you are working with [__Zod__](https://zod.dev/).
|
|
66
|
+
Just create a __nuxt plugin__ and define the "_Zod error parser_":
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
// plugins/precognition.ts
|
|
70
|
+
|
|
71
|
+
export default defineNuxtPlugin(() => {
|
|
72
|
+
const { $precognition } = useNuxtApp()
|
|
73
|
+
|
|
74
|
+
$precognition.errorParsers.push(
|
|
75
|
+
(error) => {
|
|
76
|
+
if (error instanceof ZodError) {
|
|
77
|
+
const errors = {} as Record<string, string[]>
|
|
78
|
+
error.errors.forEach((e) => {
|
|
79
|
+
const key = e.path.join('.')
|
|
80
|
+
if (key in errors) {
|
|
81
|
+
errors[key].push(e.message)
|
|
82
|
+
return
|
|
83
|
+
}
|
|
84
|
+
errors[key] = [e.message]
|
|
85
|
+
})
|
|
86
|
+
return { errors, message: 'Validation error' }
|
|
87
|
+
}
|
|
88
|
+
return null
|
|
89
|
+
},
|
|
90
|
+
)
|
|
91
|
+
})
|
|
92
|
+
```
|
|
93
|
+
From now on, everytime the `useForm` will catch the error, it will run our parses, and capture and assign any validation errors.
|
|
94
|
+
|
|
95
|
+
### How about server side
|
|
96
|
+
Same idea, but can create a __custom eventHandler__ around the base `definePrecognitiveEventHandler`. Create a new `utils` like that:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
// server/utils/precognition.ts
|
|
100
|
+
|
|
101
|
+
import { ZodError } from 'zod'
|
|
102
|
+
|
|
103
|
+
export const defineZodPrecognitiveEventHandler = definePrecognitiveEventHandler.create(
|
|
104
|
+
{
|
|
105
|
+
errorParsers: [
|
|
106
|
+
(error) => {
|
|
107
|
+
if (error instanceof ZodError) {
|
|
108
|
+
const errors: Record<string, string[]> = {}
|
|
109
|
+
error.errors.forEach((e) => {
|
|
110
|
+
const key = e.path.join('.')
|
|
111
|
+
if (key in errors) {
|
|
112
|
+
errors[key].push(e.message)
|
|
113
|
+
return
|
|
114
|
+
}
|
|
115
|
+
errors[key] = [e.message]
|
|
116
|
+
})
|
|
117
|
+
const message = error.errors.at(0)?.message ?? 'Validation error'
|
|
118
|
+
return { errors, message }
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
]
|
|
122
|
+
})
|
|
123
|
+
```
|
|
124
|
+
This time the error will be converted to `NuxtServerValidationError` and captured client side, if we enable the predefined parsers in the nuxt configuration file:
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
// nuxt.config.ts
|
|
128
|
+
|
|
129
|
+
export default defineNuxtConfig({
|
|
130
|
+
modules: ['nuxt-precognitiion'],
|
|
131
|
+
precognition: {
|
|
132
|
+
backendValidation: true,
|
|
133
|
+
enableNuxtClientErrorParser: true,
|
|
134
|
+
}
|
|
135
|
+
})
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
## Quick Setup
|
|
140
|
+
|
|
141
|
+
Install the module to your Nuxt application with one command:
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
npx nuxi module add nuxt-precognition
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### Configure
|
|
148
|
+
|
|
149
|
+
| name | type | default | description |
|
|
150
|
+
|---|---|---|---|
|
|
151
|
+
|validationTimeout|_number_|`1500`|Debounce time, in milliseconds, between two precognitive validation requests.|
|
|
152
|
+
|backendValidation|_boolean_|`false`|Flag to enable the precognitive validation.|
|
|
153
|
+
|validateFiles|_boolean_|`false`|Flag to enable files validation on precognitive requests.|
|
|
154
|
+
|enableNuxtClientErrorParser|_boolean_|`false`|Flag to enable _nuxtErrorParsers_ @ client side (in `form.validate` and `form.submit`).|
|
|
155
|
+
|enableLaravelClientErrorParser|_boolean_|`false`|Flag to enable _laravelErrorParsers_ @ client side (in `form.validate` and `form.submit`).|
|
|
156
|
+
|enableLaravelServerErrorParser|_boolean_|`false`|Flag to enable _laravelErrorParsers_ @ client side (in `definePrecognitiveEventHandler`).|
|
|
157
|
+
|
|
158
|
+
#### Status Handlers
|
|
159
|
+
Like in [official package](https://github.com/laravel/precognition), you can define globally, or @instance level, custom handlers for specific error codes:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
// plugins/precognition.ts
|
|
163
|
+
|
|
164
|
+
export default defineNuxtPlugin(() => {
|
|
165
|
+
const { $precognition } = useNuxtApp()
|
|
166
|
+
|
|
167
|
+
$precognition.statusHandlers = {
|
|
168
|
+
401: async (error, form) => {
|
|
169
|
+
form.error = createError('Unauthorized')
|
|
170
|
+
await navigateTo('/login')
|
|
171
|
+
},
|
|
172
|
+
403: async (error, form) => {
|
|
173
|
+
form.error = createError('Forbidden')
|
|
174
|
+
},
|
|
175
|
+
}
|
|
176
|
+
})
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
That's it! You can now use Nuxt Precognition in your Nuxt app ✨
|
|
180
|
+
|
|
181
|
+
#### Working with Laravel
|
|
182
|
+
|
|
183
|
+
1. Define a plugin like this
|
|
184
|
+
```ts
|
|
185
|
+
// plugins/api.ts
|
|
186
|
+
|
|
187
|
+
export default defineNuxtPlugin((app) => {
|
|
188
|
+
const { $precognition } = useNuxtApp()
|
|
189
|
+
const token = useCookie('XSRF-TOKEN')
|
|
190
|
+
|
|
191
|
+
const api = $fetch.create({
|
|
192
|
+
baseURL: 'http://localhost',
|
|
193
|
+
credentials: 'include',
|
|
194
|
+
headers: {
|
|
195
|
+
'Accept': 'application/json',
|
|
196
|
+
'Content-Type': 'application/json',
|
|
197
|
+
},
|
|
198
|
+
onRequest: ({ options }) => {
|
|
199
|
+
// Setup csrf protection for every requests if available
|
|
200
|
+
if (token.value) {
|
|
201
|
+
const headers = new Headers(options.headers)
|
|
202
|
+
headers.set('X-XSRF-TOKEN', token.value)
|
|
203
|
+
options.headers = headers
|
|
204
|
+
}
|
|
205
|
+
},
|
|
206
|
+
onResponse: (context) => {
|
|
207
|
+
// ensure that all precognitive requests will receive precognitive responses
|
|
208
|
+
$precognition.assertSuccessfulPrecognitiveResponses(context)
|
|
209
|
+
},
|
|
210
|
+
})
|
|
211
|
+
|
|
212
|
+
async function fetchSanctumToken() {
|
|
213
|
+
try {
|
|
214
|
+
await api('/sanctum/csrf-cookie')
|
|
215
|
+
token.value = useCookie('XSRF-TOKEN').value
|
|
216
|
+
|
|
217
|
+
if (!token.value) {
|
|
218
|
+
throw new Error('Failed to get CSRF token')
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
catch (e) {
|
|
222
|
+
console.error(e)
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
app.hook('app:mounted', fetchSanctumToken)
|
|
227
|
+
|
|
228
|
+
return {
|
|
229
|
+
provide: {
|
|
230
|
+
api,
|
|
231
|
+
sanctum: {
|
|
232
|
+
fetchToken: fetchSanctumToken,
|
|
233
|
+
token,
|
|
234
|
+
},
|
|
235
|
+
},
|
|
236
|
+
}
|
|
237
|
+
})
|
|
238
|
+
```
|
|
239
|
+
2. Enable backend validation and native Laravel Error parsers client or server side
|
|
240
|
+
```ts
|
|
241
|
+
// nuxt.config.ts
|
|
242
|
+
export default defineNuxtConfig({
|
|
243
|
+
modules: ['nuxt-precognition'],
|
|
244
|
+
precognition: {
|
|
245
|
+
backendValidation: true,
|
|
246
|
+
enableLaravelClientErrorParser: true,
|
|
247
|
+
},
|
|
248
|
+
/*
|
|
249
|
+
...
|
|
250
|
+
*/
|
|
251
|
+
})
|
|
252
|
+
```
|
|
253
|
+
\* If you `enableLaravelServerErrorParser`, you must also `enableNuxtClientErrorParser`
|
|
254
|
+
|
|
255
|
+
3. Setup Laravel Cors configuration file
|
|
256
|
+
```php
|
|
257
|
+
// config/cors.php
|
|
258
|
+
|
|
259
|
+
return [
|
|
260
|
+
|
|
261
|
+
/*
|
|
262
|
+
|--------------------------------------------------------------------------
|
|
263
|
+
| Cross-Origin Resource Sharing (CORS) Configuration
|
|
264
|
+
|--------------------------------------------------------------------------
|
|
265
|
+
|
|
|
266
|
+
*/
|
|
267
|
+
|
|
268
|
+
'paths' => ['*'],
|
|
269
|
+
|
|
270
|
+
'allowed_methods' => ['*'],
|
|
271
|
+
|
|
272
|
+
'allowed_origins' => ['*'],
|
|
273
|
+
|
|
274
|
+
'allowed_origins_patterns' => [env('FRONTEND_URL', 'http://localhost:3000')],
|
|
275
|
+
|
|
276
|
+
'allowed_headers' => ['*'],
|
|
277
|
+
|
|
278
|
+
'exposed_headers' => ['Precognition', 'Precognition-Success'],
|
|
279
|
+
|
|
280
|
+
'max_age' => 0,
|
|
281
|
+
|
|
282
|
+
'supports_credentials' => true,
|
|
283
|
+
|
|
284
|
+
];
|
|
285
|
+
```
|
|
286
|
+
3. Enable the Precognition Middleware where needed
|
|
287
|
+
|
|
288
|
+
```php
|
|
289
|
+
// routes/api.php
|
|
290
|
+
|
|
291
|
+
Route::middleware('precognitive')->group(function () {
|
|
292
|
+
Route::apiResource('posts', \App\Http\Controllers\PostController::class);
|
|
293
|
+
});
|
|
294
|
+
```
|
|
295
|
+
## Contribution
|
|
296
|
+
|
|
297
|
+
<details>
|
|
298
|
+
<summary>Local development</summary>
|
|
299
|
+
|
|
300
|
+
```bash
|
|
301
|
+
# Install dependencies
|
|
302
|
+
npm install
|
|
303
|
+
|
|
304
|
+
# Generate type stubs
|
|
305
|
+
npm run dev:prepare
|
|
306
|
+
|
|
307
|
+
# Develop with the playground
|
|
308
|
+
npm run dev
|
|
309
|
+
|
|
310
|
+
# Build the playground
|
|
311
|
+
npm run dev:build
|
|
312
|
+
|
|
313
|
+
# Run ESLint
|
|
314
|
+
npm run lint
|
|
315
|
+
|
|
316
|
+
# Run Vitest
|
|
317
|
+
npm run test
|
|
318
|
+
npm run test:watch
|
|
319
|
+
|
|
320
|
+
# Release new version
|
|
321
|
+
npm run release
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
</details>
|
|
325
|
+
|
|
326
|
+
<!-- Badges -->
|
|
327
|
+
[npm-version-src]: https://img.shields.io/npm/v/nuxt-precognition/latest.svg?style=flat&colorA=020420&colorB=00DC82
|
|
328
|
+
[npm-version-href]: https://npmjs.com/package/nuxt-precognition
|
|
329
|
+
|
|
330
|
+
[npm-downloads-src]: https://img.shields.io/npm/dm/nuxt-precognition.svg?style=flat&colorA=020420&colorB=00DC82
|
|
331
|
+
[npm-downloads-href]: https://npmjs.com/package/nuxt-precognition
|
|
332
|
+
|
|
333
|
+
[license-src]: https://img.shields.io/npm/l/nuxt-precognition.svg?style=flat&colorA=020420&colorB=00DC82
|
|
334
|
+
[license-href]: https://npmjs.com/package/nuxt-precognition
|
|
335
|
+
|
|
336
|
+
[nuxt-src]: https://img.shields.io/badge/Nuxt-020420?logo=nuxt.js
|
|
337
|
+
[nuxt-href]: https://nuxt.com
|
package/dist/module.cjs
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import * as _nuxt_schema from '@nuxt/schema';
|
|
2
|
+
|
|
3
|
+
interface Config {
|
|
4
|
+
/** base validation timeout, @default 1500 ms */
|
|
5
|
+
validationTimeout: number;
|
|
6
|
+
/** enable backend validation @default false */
|
|
7
|
+
backendValidation: boolean;
|
|
8
|
+
/** precognitive files validation, @default false */
|
|
9
|
+
validateFiles: boolean;
|
|
10
|
+
/** enable Nuxt precognitive error parser client side, @default false */
|
|
11
|
+
enableNuxtClientErrorParser: boolean;
|
|
12
|
+
/** enable Laravel precognitive error parser client side, @default false */
|
|
13
|
+
enableLaravelClientErrorParser: boolean;
|
|
14
|
+
/** enable Laravel precognitive error parsers server side, @default false */
|
|
15
|
+
enableLaravelServerErrorParser: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface ModuleOptions extends Config {
|
|
19
|
+
}
|
|
20
|
+
declare const _default: _nuxt_schema.NuxtModule<ModuleOptions>;
|
|
21
|
+
|
|
22
|
+
export { type ModuleOptions, _default as default };
|
package/dist/module.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import * as _nuxt_schema from '@nuxt/schema';
|
|
2
|
+
|
|
3
|
+
interface Config {
|
|
4
|
+
/** base validation timeout, @default 1500 ms */
|
|
5
|
+
validationTimeout: number;
|
|
6
|
+
/** enable backend validation @default false */
|
|
7
|
+
backendValidation: boolean;
|
|
8
|
+
/** precognitive files validation, @default false */
|
|
9
|
+
validateFiles: boolean;
|
|
10
|
+
/** enable Nuxt precognitive error parser client side, @default false */
|
|
11
|
+
enableNuxtClientErrorParser: boolean;
|
|
12
|
+
/** enable Laravel precognitive error parser client side, @default false */
|
|
13
|
+
enableLaravelClientErrorParser: boolean;
|
|
14
|
+
/** enable Laravel precognitive error parsers server side, @default false */
|
|
15
|
+
enableLaravelServerErrorParser: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface ModuleOptions extends Config {
|
|
19
|
+
}
|
|
20
|
+
declare const _default: _nuxt_schema.NuxtModule<ModuleOptions>;
|
|
21
|
+
|
|
22
|
+
export { type ModuleOptions, _default as default };
|
package/dist/module.json
ADDED
package/dist/module.mjs
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { defineNuxtModule, createResolver, addPlugin, addImports, addServerImports, addServerPlugin, addTemplate } from '@nuxt/kit';
|
|
2
|
+
import defu from 'defu';
|
|
3
|
+
|
|
4
|
+
const module = defineNuxtModule({
|
|
5
|
+
meta: {
|
|
6
|
+
name: "nuxt-precognition",
|
|
7
|
+
configKey: "precognition",
|
|
8
|
+
compatibility: {
|
|
9
|
+
nuxt: "^3.9.0"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
// Default configuration options of the Nuxt module
|
|
13
|
+
defaults: {
|
|
14
|
+
validationTimeout: 1500,
|
|
15
|
+
backendValidation: false,
|
|
16
|
+
validateFiles: false,
|
|
17
|
+
enableNuxtClientErrorParser: false,
|
|
18
|
+
enableLaravelClientErrorParser: false,
|
|
19
|
+
enableLaravelServerErrorParser: false
|
|
20
|
+
},
|
|
21
|
+
setup(options, nuxt) {
|
|
22
|
+
nuxt.options.runtimeConfig.public.precognition = defu(
|
|
23
|
+
nuxt.options.runtimeConfig.public.precognition,
|
|
24
|
+
{
|
|
25
|
+
validationTimeout: options.validationTimeout,
|
|
26
|
+
backendValidation: options.backendValidation,
|
|
27
|
+
validateFiles: options.validateFiles,
|
|
28
|
+
enableNuxtClientErrorParser: options.enableNuxtClientErrorParser,
|
|
29
|
+
enableLaravelClientErrorParser: options.enableLaravelClientErrorParser,
|
|
30
|
+
enableLaravelServerErrorParser: options.enableLaravelServerErrorParser
|
|
31
|
+
}
|
|
32
|
+
);
|
|
33
|
+
const resolver = createResolver(import.meta.url);
|
|
34
|
+
nuxt.options.nitro.plugins = nuxt.options.nitro.plugins || [];
|
|
35
|
+
addPlugin(resolver.resolve("./runtime/plugin"));
|
|
36
|
+
addImports({
|
|
37
|
+
name: "useForm",
|
|
38
|
+
from: resolver.resolve("./runtime/useForm"),
|
|
39
|
+
as: "useForm"
|
|
40
|
+
});
|
|
41
|
+
addServerImports([
|
|
42
|
+
{
|
|
43
|
+
from: resolver.resolve("./runtime/server/definePrecognitiveEventHandler"),
|
|
44
|
+
name: "definePrecognitiveEventHandler"
|
|
45
|
+
}
|
|
46
|
+
]);
|
|
47
|
+
addServerPlugin(resolver.resolve("./runtime/server/plugin"));
|
|
48
|
+
const template = addTemplate({
|
|
49
|
+
filename: "types/nuxt-precognition.d.ts",
|
|
50
|
+
getContents: () => `// Generated by nuxt-precognition
|
|
51
|
+
import type {ValidationErrorParser} from '${resolver.resolve("./runtime/types/core")}'
|
|
52
|
+
import type {ClientStatusHandlers} from '${resolver.resolve("./runtime/types/form")}'
|
|
53
|
+
|
|
54
|
+
interface NuxtPrecognition {
|
|
55
|
+
$precognition: {
|
|
56
|
+
errorParsers: ValidationErrorParser[],
|
|
57
|
+
statusHandlers: ClientStatusHandlers
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
declare module '#app' {
|
|
62
|
+
interface NuxtApp extends NuxtPrecognition {}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
declare module 'vue' {
|
|
66
|
+
interface ComponentCustomProperties extends NuxtPrecognition {}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export {}`
|
|
70
|
+
});
|
|
71
|
+
nuxt.hook("prepare:types", ({ references }) => {
|
|
72
|
+
references.push({ path: template.dst });
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
export { module as default };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ValidationErrorsData, ValidationErrorParser } from './types/core';
|
|
2
|
+
import type { NestedKeyOf } from './types/utils';
|
|
3
|
+
export declare function hasResponse(error: Error): error is Error & {
|
|
4
|
+
response: Response;
|
|
5
|
+
};
|
|
6
|
+
export declare function resolveDynamicObject<T extends object>(object: T | (() => T)): T;
|
|
7
|
+
export declare function requestPrecognitiveHeaders(headers?: HeadersInit, keys?: string[]): Headers;
|
|
8
|
+
export declare function getAllNestedKeys<TData extends object, TPrefix extends string | undefined = undefined>(obj: TData, prefix?: TPrefix, keys?: string[]): TPrefix extends undefined ? NestedKeyOf<TData>[] : string[];
|
|
9
|
+
export declare function isFile(value: unknown): value is Blob | File | FileList;
|
|
10
|
+
export declare function resolveValidationErrorData(error: Error, parsers: ValidationErrorParser[]): ValidationErrorsData | null | undefined;
|
|
11
|
+
export declare function makeNuxtValidationErrorParser(): ValidationErrorParser;
|
|
12
|
+
export declare function makeLaravelValidationErrorParser(): ValidationErrorParser;
|
|
13
|
+
export declare function assertSuccessfulPrecognitiveResponses(ctx: {
|
|
14
|
+
options: {
|
|
15
|
+
headers?: HeadersInit;
|
|
16
|
+
};
|
|
17
|
+
response: Response;
|
|
18
|
+
}): void;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { createError } from "#imports";
|
|
2
|
+
export function hasResponse(error) {
|
|
3
|
+
return "response" in error && error.response instanceof Response;
|
|
4
|
+
}
|
|
5
|
+
function hasValidationStatusCode(response) {
|
|
6
|
+
return response.status === 422;
|
|
7
|
+
}
|
|
8
|
+
function hasNuxtValidationErrorsData(response) {
|
|
9
|
+
return hasResponseData(response) && "data" in response._data && typeof response._data.data === "object" && !!response._data.data && hasErrorMessage(response._data.data) && hasValidationErrors(response._data.data);
|
|
10
|
+
}
|
|
11
|
+
function hasResponseData(response) {
|
|
12
|
+
return "_data" in response && typeof response._data === "object" && !!response._data;
|
|
13
|
+
}
|
|
14
|
+
function hasLaravelValidationErrorsData(response) {
|
|
15
|
+
return hasResponseData(response) && hasErrorMessage(response._data) && hasValidationErrors(response._data);
|
|
16
|
+
}
|
|
17
|
+
function hasErrorMessage(data) {
|
|
18
|
+
return "message" in data && typeof data.message === "string";
|
|
19
|
+
}
|
|
20
|
+
function hasValidationErrors(data) {
|
|
21
|
+
if (!("errors" in data) || typeof data.errors !== "object" || !data.errors)
|
|
22
|
+
return false;
|
|
23
|
+
const allObjectKeysAreStrings = Object.keys(data.errors).every((key) => typeof key === "string");
|
|
24
|
+
const allObjectValuesAreStringsOrArrays = Object.values(data.errors).every((value) => typeof value === "string" || Array.isArray(value) && value.every((item) => typeof item === "string"));
|
|
25
|
+
return allObjectKeysAreStrings && allObjectValuesAreStringsOrArrays;
|
|
26
|
+
}
|
|
27
|
+
export function resolveDynamicObject(object) {
|
|
28
|
+
return typeof object === "function" ? object() : object;
|
|
29
|
+
}
|
|
30
|
+
export function requestPrecognitiveHeaders(headers, keys) {
|
|
31
|
+
const h = new Headers(headers);
|
|
32
|
+
h.set("Precognition", "true");
|
|
33
|
+
if (keys?.length)
|
|
34
|
+
h.set("Precognition-Validate-Only", keys.join(","));
|
|
35
|
+
return h;
|
|
36
|
+
}
|
|
37
|
+
export function getAllNestedKeys(obj, prefix, keys = []) {
|
|
38
|
+
Object.keys(obj).forEach((key) => {
|
|
39
|
+
const path = prefix ? `${prefix}.${key}` : key;
|
|
40
|
+
keys.push(path);
|
|
41
|
+
const value = obj[key];
|
|
42
|
+
if (typeof value === "object" && value !== null)
|
|
43
|
+
getAllNestedKeys(value, path, keys);
|
|
44
|
+
});
|
|
45
|
+
return keys;
|
|
46
|
+
}
|
|
47
|
+
export function isFile(value) {
|
|
48
|
+
if (value instanceof Blob)
|
|
49
|
+
return true;
|
|
50
|
+
return import.meta.server ? value instanceof File || value instanceof FileList : false;
|
|
51
|
+
}
|
|
52
|
+
export function resolveValidationErrorData(error, parsers) {
|
|
53
|
+
return parsers.reduce(
|
|
54
|
+
(errors, parser) => errors ?? parser(error),
|
|
55
|
+
null
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
export function makeNuxtValidationErrorParser() {
|
|
59
|
+
return (error) => hasResponse(error) && hasValidationStatusCode(error.response) && hasNuxtValidationErrorsData(error.response) ? error.response._data.data : null;
|
|
60
|
+
}
|
|
61
|
+
export function makeLaravelValidationErrorParser() {
|
|
62
|
+
return (error) => hasResponse(error) && hasValidationStatusCode(error.response) && hasLaravelValidationErrorsData(error.response) ? error.response._data : null;
|
|
63
|
+
}
|
|
64
|
+
export function assertSuccessfulPrecognitiveResponses(ctx) {
|
|
65
|
+
if (new Headers(ctx.options.headers).get("Precognition") !== "true") {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const check = [
|
|
69
|
+
(res) => res?.headers?.get("Precognition") === "true",
|
|
70
|
+
(res) => res?.headers?.get("Precognition-Success") === "true",
|
|
71
|
+
(res) => res.status === 204
|
|
72
|
+
].reduce((acc, fn) => acc && fn({ status: ctx.response.status, headers: ctx.response.headers }), true);
|
|
73
|
+
if (check === false) {
|
|
74
|
+
throw createError({ message: "Did not receive a Precognition response. Ensure you have the Precognition middleware in place for the route and Precognitive headers have been enabled in config/cors.php.", statusCode: 500 });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { assertSuccessfulPrecognitiveResponses } from "./core.mjs";
|
|
2
|
+
import { defineNuxtPlugin } from "#imports";
|
|
3
|
+
export default defineNuxtPlugin(() => {
|
|
4
|
+
const errorParsers = [];
|
|
5
|
+
const statusHandlers = {};
|
|
6
|
+
return {
|
|
7
|
+
provide: {
|
|
8
|
+
precognition: {
|
|
9
|
+
errorParsers,
|
|
10
|
+
statusHandlers,
|
|
11
|
+
assertSuccessfulPrecognitiveResponses
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
});
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { EventHandler, EventHandlerObject, EventHandlerRequest, H3Event } from 'h3';
|
|
2
|
+
import type { ValidationErrorParser } from '../types/core';
|
|
3
|
+
import type { ServerStatusHandlers } from '../types/eventHandler';
|
|
4
|
+
import type { ErrorStatusCode } from '../types/utils';
|
|
5
|
+
declare function definePrecognitiveEventHandler<TRequest extends EventHandlerRequest, TResponse>(handler: EventHandlerObject<TRequest, TResponse>, options?: {
|
|
6
|
+
errorParsers?: ValidationErrorParser[];
|
|
7
|
+
statusHandlers?: ServerStatusHandlers;
|
|
8
|
+
}): EventHandler<TRequest, TResponse>;
|
|
9
|
+
declare namespace definePrecognitiveEventHandler {
|
|
10
|
+
var create: <TRequest extends EventHandlerRequest, TResponse>(options: {
|
|
11
|
+
errorParsers?: ValidationErrorParser[] | undefined;
|
|
12
|
+
statusHandlers?: Partial<Record<ErrorStatusCode, <TRequest_1 extends EventHandlerRequest>(error: Error, event: H3Event<TRequest_1>) => void | Promise<void>>> | undefined;
|
|
13
|
+
}) => (handler: EventHandlerObject<TRequest, TResponse>, options?: {
|
|
14
|
+
errorParsers?: ValidationErrorParser[] | undefined;
|
|
15
|
+
statusHandlers?: Partial<Record<ErrorStatusCode, <TRequest_1 extends EventHandlerRequest>(error: Error, event: H3Event<TRequest_1>) => void | Promise<void>>> | undefined;
|
|
16
|
+
} | undefined) => EventHandler<TRequest, TResponse>;
|
|
17
|
+
}
|
|
18
|
+
export { definePrecognitiveEventHandler };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { hasResponse, makeLaravelValidationErrorParser, resolveValidationErrorData } from "../core.mjs";
|
|
2
|
+
import { useRuntimeConfig, defineEventHandler, setResponseHeader, createError, setResponseStatus } from "#imports";
|
|
3
|
+
function definePrecognitiveEventHandler(handler, options) {
|
|
4
|
+
return defineEventHandler({
|
|
5
|
+
onRequest: onPrecognitiveRequest(handler.onRequest, options),
|
|
6
|
+
handler: onPrecognitiveHandler(handler.handler),
|
|
7
|
+
onBeforeResponse: handler.onBeforeResponse
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
function onPrecognitiveRequest(onRequest, options) {
|
|
11
|
+
if (!onRequest)
|
|
12
|
+
return void 0;
|
|
13
|
+
const config = useRuntimeConfig().public.precognition;
|
|
14
|
+
const baseParsers = [];
|
|
15
|
+
if (config.enableLaravelServerErrorParser)
|
|
16
|
+
baseParsers.push(makeLaravelValidationErrorParser());
|
|
17
|
+
if (typeof onRequest === "function")
|
|
18
|
+
return onPrecognitiveRequestWrapper(
|
|
19
|
+
onRequest,
|
|
20
|
+
{
|
|
21
|
+
errorParsers: [...baseParsers, ...options?.errorParsers ?? []],
|
|
22
|
+
statusHandlers: options?.statusHandlers
|
|
23
|
+
}
|
|
24
|
+
);
|
|
25
|
+
return onRequest.map((middleware) => onPrecognitiveRequestWrapper(
|
|
26
|
+
middleware,
|
|
27
|
+
{
|
|
28
|
+
errorParsers: [...baseParsers, ...options?.errorParsers ?? []],
|
|
29
|
+
statusHandlers: options?.statusHandlers
|
|
30
|
+
}
|
|
31
|
+
));
|
|
32
|
+
}
|
|
33
|
+
function onPrecognitiveRequestWrapper(middleware, options) {
|
|
34
|
+
return async (event) => {
|
|
35
|
+
try {
|
|
36
|
+
await middleware(event);
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (!(error instanceof Error)) {
|
|
39
|
+
throw createError({
|
|
40
|
+
message: "Unknown server error",
|
|
41
|
+
statusCode: 500,
|
|
42
|
+
data: { message: "Unknown server error" }
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
const statusHandler = hasResponse(error) && options.statusHandlers ? options.statusHandlers[`${error.response.status}`] ?? event.context.precognition.statusHandlers[`${error.response.status}`] : void 0;
|
|
46
|
+
if (statusHandler) {
|
|
47
|
+
return statusHandler(error, event);
|
|
48
|
+
}
|
|
49
|
+
setResponseHeader(event, "Content-Type", "application/json");
|
|
50
|
+
const errorsData = resolveValidationErrorData(error, [
|
|
51
|
+
...event.context.precognition.errorParsers,
|
|
52
|
+
...options.errorParsers
|
|
53
|
+
]);
|
|
54
|
+
if (!errorsData) {
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
handleValidationErrorsData(errorsData, event);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function handleValidationErrorsData(errorsData, event) {
|
|
62
|
+
setResponseStatus(event, 422);
|
|
63
|
+
setResponseHeader(event, "Content-Type", "application/json");
|
|
64
|
+
if (!event.headers.has("Precognition")) {
|
|
65
|
+
throw createError({
|
|
66
|
+
message: errorsData.message,
|
|
67
|
+
data: errorsData
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
setResponseHeader(event, "Precognition", "true");
|
|
71
|
+
const validateOnly = event.headers.get("Precognition-Validate-Only");
|
|
72
|
+
if (!validateOnly) {
|
|
73
|
+
throw createError({
|
|
74
|
+
status: 422,
|
|
75
|
+
message: errorsData.message,
|
|
76
|
+
data: errorsData
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
setResponseHeader(event, "Precognition-Validate-Only", validateOnly);
|
|
80
|
+
const errors = Object.keys(errorsData.errors).filter((e) => validateOnly.split(",").includes(e));
|
|
81
|
+
if (!errors.length)
|
|
82
|
+
return;
|
|
83
|
+
const precognitveErrors = {};
|
|
84
|
+
errors.forEach((key) => {
|
|
85
|
+
const value = errorsData.errors[key];
|
|
86
|
+
precognitveErrors[key] = Array.isArray(value) ? value : [value];
|
|
87
|
+
});
|
|
88
|
+
throw createError({
|
|
89
|
+
status: 422,
|
|
90
|
+
data: {
|
|
91
|
+
message: errorsData.message,
|
|
92
|
+
errors: precognitveErrors
|
|
93
|
+
},
|
|
94
|
+
message: errorsData.message
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
function onPrecognitiveHandler(handler) {
|
|
98
|
+
return (event) => {
|
|
99
|
+
if (event.headers.get("Precognition") !== "true")
|
|
100
|
+
return handler(event);
|
|
101
|
+
setResponseHeader(event, "Content-Type", "application/json");
|
|
102
|
+
setResponseHeader(event, "Precognition", "true");
|
|
103
|
+
setResponseHeader(event, "Precognition-Success", "true");
|
|
104
|
+
const validateOnlyKey = event.headers.get("Precognition-Validate-Only");
|
|
105
|
+
if (validateOnlyKey)
|
|
106
|
+
setResponseHeader(event, "Precognition-Validate-Only", validateOnlyKey);
|
|
107
|
+
setResponseStatus(event, 200);
|
|
108
|
+
return null;
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
definePrecognitiveEventHandler.create = function(options) {
|
|
112
|
+
const baseErrorParsers = [...options.errorParsers ?? []];
|
|
113
|
+
const baseStatusHandlers = { ...options.statusHandlers };
|
|
114
|
+
return (handler, options2) => definePrecognitiveEventHandler(handler, { errorParsers: [...baseErrorParsers, ...options2?.errorParsers ?? []], statusHandlers: { ...baseStatusHandlers, ...options2?.statusHandlers } });
|
|
115
|
+
};
|
|
116
|
+
export { definePrecognitiveEventHandler };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { defineNitroPlugin } from "#imports";
|
|
2
|
+
export default defineNitroPlugin((nitroApp) => {
|
|
3
|
+
const errorParsers = [];
|
|
4
|
+
const statusHandlers = {};
|
|
5
|
+
nitroApp.hooks.hook("request", (event) => {
|
|
6
|
+
event.context.precognition = {
|
|
7
|
+
errorParsers,
|
|
8
|
+
statusHandlers
|
|
9
|
+
};
|
|
10
|
+
event.context.precognitive = event.headers.get("Precognition") === "true";
|
|
11
|
+
});
|
|
12
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface Config {
|
|
2
|
+
/** base validation timeout, @default 1500 ms */
|
|
3
|
+
validationTimeout: number;
|
|
4
|
+
/** enable backend validation @default false */
|
|
5
|
+
backendValidation: boolean;
|
|
6
|
+
/** precognitive files validation, @default false */
|
|
7
|
+
validateFiles: boolean;
|
|
8
|
+
/** enable Nuxt precognitive error parser client side, @default false */
|
|
9
|
+
enableNuxtClientErrorParser: boolean;
|
|
10
|
+
/** enable Laravel precognitive error parser client side, @default false */
|
|
11
|
+
enableLaravelClientErrorParser: boolean;
|
|
12
|
+
/** enable Laravel precognitive error parsers server side, @default false */
|
|
13
|
+
enableLaravelServerErrorParser: boolean;
|
|
14
|
+
}
|
|
15
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export type ValidationErrors = Record<string, string | string[]>;
|
|
2
|
+
export interface ValidationErrorsData {
|
|
3
|
+
message: string;
|
|
4
|
+
errors: ValidationErrors;
|
|
5
|
+
}
|
|
6
|
+
export type ValidationErrorParser = (error: Error) => ValidationErrorsData | undefined | null;
|
|
7
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { H3Event, EventHandlerRequest } from 'h3';
|
|
2
|
+
import type { ErrorStatusCode } from './utils';
|
|
3
|
+
import type { ValidationErrorParser } from './core';
|
|
4
|
+
export type ServerStatusHandlers = Partial<Record<ErrorStatusCode, <TRequest extends EventHandlerRequest>(error: Error, event: H3Event<TRequest>) => void | Promise<void>>>;
|
|
5
|
+
export interface PrecognitionEventContext {
|
|
6
|
+
precognition: {
|
|
7
|
+
errorParsers: ValidationErrorParser[];
|
|
8
|
+
statusHandlers: ServerStatusHandlers;
|
|
9
|
+
};
|
|
10
|
+
precognitive: boolean;
|
|
11
|
+
}
|
|
12
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ValidationErrorParser, ValidationErrorsData } from './core';
|
|
2
|
+
import type { NestedKeyOf, ErrorStatusCode } from './utils';
|
|
3
|
+
interface SubmitOptions<TData extends object, TResp> {
|
|
4
|
+
headers?: Headers;
|
|
5
|
+
onError?: (error: Error, data: TData) => Promise<void> | void;
|
|
6
|
+
onBefore?: (data: TData) => Promise<boolean> | boolean;
|
|
7
|
+
onStart?: (data: TData) => Promise<void> | void;
|
|
8
|
+
onSuccess?: (resp: TResp, data: TData) => Promise<void> | void;
|
|
9
|
+
}
|
|
10
|
+
export interface Form<TData extends object, Tresp> {
|
|
11
|
+
data: () => TData;
|
|
12
|
+
setData: (data: TData) => TData & Form<TData, Tresp>;
|
|
13
|
+
error: Error | null;
|
|
14
|
+
errors: Partial<Record<NestedKeyOf<TData>, string>>;
|
|
15
|
+
validatedKeys: NestedKeyOf<TData>[];
|
|
16
|
+
processing: boolean;
|
|
17
|
+
validating: boolean;
|
|
18
|
+
disabled: () => boolean;
|
|
19
|
+
validate: (...keys: NestedKeyOf<TData>[]) => TData & Form<TData, Tresp>;
|
|
20
|
+
reset: () => TData & Form<TData, Tresp>;
|
|
21
|
+
submit: (options?: SubmitOptions<TData, Tresp>) => Promise<void>;
|
|
22
|
+
valid: (...keys: (NestedKeyOf<TData>)[]) => boolean;
|
|
23
|
+
invalid: (...keys: (NestedKeyOf<TData>)[]) => boolean;
|
|
24
|
+
touched: (...keys: (NestedKeyOf<TData>)[]) => boolean;
|
|
25
|
+
touch: (...key: (NestedKeyOf<TData>)[]) => TData & Form<TData, Tresp>;
|
|
26
|
+
forgetErrors: (...keys: (NestedKeyOf<TData>)[]) => TData & Form<TData, Tresp>;
|
|
27
|
+
setErrors: (errors: ValidationErrorsData) => TData & Form<TData, Tresp>;
|
|
28
|
+
validateFiles(): TData & Form<TData, Tresp>;
|
|
29
|
+
}
|
|
30
|
+
export type ClientStatusHandlers = Partial<Record<ErrorStatusCode, <TData extends object, TResp>(error: Error & {
|
|
31
|
+
response: Response;
|
|
32
|
+
}, form: TData & Form<TData, TResp>) => void | Promise<void>>>;
|
|
33
|
+
export interface UseFormOptions<TData extends object> {
|
|
34
|
+
validationHeaders?: Headers;
|
|
35
|
+
validationTimeout?: number;
|
|
36
|
+
backendValidation?: boolean;
|
|
37
|
+
validateFiles?: boolean;
|
|
38
|
+
onBeforeValidation?: (data: TData) => boolean;
|
|
39
|
+
onValidationStart?: (data: TData) => Promise<void> | void;
|
|
40
|
+
clientValidation?: (data: TData) => Promise<void> | void;
|
|
41
|
+
onValidationError?: (error: Error, data: TData, keys: NestedKeyOf<TData>[]) => Promise<void> | void;
|
|
42
|
+
onValidationSuccess?: (data: TData) => Promise<void> | void;
|
|
43
|
+
clientErrorParsers?: ValidationErrorParser[];
|
|
44
|
+
statusHandlers?: ClientStatusHandlers;
|
|
45
|
+
}
|
|
46
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
type ArrayKeys<T extends unknown[]> = T extends [unknown, ...unknown[]] ? T extends Record<infer Index, unknown> ? Index extends `${number}` ? Index : never : never : `${number}`;
|
|
2
|
+
type ObjectKeys<T extends object> = T extends unknown[] ? ArrayKeys<T> : keyof T & string;
|
|
3
|
+
interface HasConstructor {
|
|
4
|
+
new (...args: unknown[]): unknown;
|
|
5
|
+
}
|
|
6
|
+
export type NestedKeyOf<T> = T extends Record<infer Key, unknown> ? T extends HasConstructor ? never : T extends CallableFunction ? never : Key extends string | number ? (ObjectKeys<T> | (T[Key] extends object ? `${ObjectKeys<Pick<T, Key>>}.${NestedKeyOf<T[Key]>}` : T extends unknown[] ? T extends [unknown, ...unknown[]] ? never : T[number] extends object ? `${number}.${NestedKeyOf<T[number]>}` : never : never)) : never : never;
|
|
7
|
+
type SingleDigit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
|
|
8
|
+
export type ErrorStatusCode = `4${SingleDigit}${SingleDigit}` | `5${SingleDigit}${SingleDigit}`;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type { Form, UseFormOptions } from './types/form';
|
|
2
|
+
export declare function useForm<TData extends object, TResp>(init: TData | (() => TData), cb: (form: TData, precognitiveHeaders: Headers) => Promise<TResp>, options?: UseFormOptions<TData>): TData & Form<TData, TResp>;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { cloneDeep } from "lodash-es";
|
|
2
|
+
import { getAllNestedKeys, hasResponse, resolveDynamicObject, resolveValidationErrorData } from "./core.mjs";
|
|
3
|
+
import { makeValidator } from "./validator.mjs";
|
|
4
|
+
import { reactive, toRaw } from "#imports";
|
|
5
|
+
export function useForm(init, cb, options) {
|
|
6
|
+
const keys = Object.keys(resolveDynamicObject(init));
|
|
7
|
+
function getInitialData() {
|
|
8
|
+
return cloneDeep(toRaw(resolveDynamicObject(init)));
|
|
9
|
+
}
|
|
10
|
+
const validator = makeValidator(cb, options);
|
|
11
|
+
const form = reactive({
|
|
12
|
+
...getInitialData(),
|
|
13
|
+
data: () => {
|
|
14
|
+
const data = cloneDeep(toRaw(form));
|
|
15
|
+
Object.keys(data).forEach((key) => {
|
|
16
|
+
if (keys.includes(key))
|
|
17
|
+
return;
|
|
18
|
+
delete data[key];
|
|
19
|
+
});
|
|
20
|
+
return data;
|
|
21
|
+
},
|
|
22
|
+
processing: false,
|
|
23
|
+
validating: false,
|
|
24
|
+
disabled: () => form.processing || form.validating,
|
|
25
|
+
setData: (data) => {
|
|
26
|
+
Object.assign(form, data);
|
|
27
|
+
return form;
|
|
28
|
+
},
|
|
29
|
+
validatedKeys: [],
|
|
30
|
+
errors: {},
|
|
31
|
+
error: null,
|
|
32
|
+
validate(...keys2) {
|
|
33
|
+
if (form.validating)
|
|
34
|
+
return form;
|
|
35
|
+
validator.validate(form, ...keys2);
|
|
36
|
+
return form;
|
|
37
|
+
},
|
|
38
|
+
reset() {
|
|
39
|
+
Object.assign(this, getInitialData());
|
|
40
|
+
form.error = null;
|
|
41
|
+
form.errors = {};
|
|
42
|
+
form.validatedKeys = [];
|
|
43
|
+
return form;
|
|
44
|
+
},
|
|
45
|
+
async submit(o) {
|
|
46
|
+
if (form.processing)
|
|
47
|
+
return;
|
|
48
|
+
const data = form.data();
|
|
49
|
+
try {
|
|
50
|
+
const onBefore = o?.onBefore ? await o.onBefore(data) : true;
|
|
51
|
+
if (!onBefore)
|
|
52
|
+
return;
|
|
53
|
+
form.processing = true;
|
|
54
|
+
form.error = null;
|
|
55
|
+
if (o?.onStart)
|
|
56
|
+
await o.onStart(data);
|
|
57
|
+
const resp = await cb(data, o?.headers ?? new Headers());
|
|
58
|
+
if (o?.onSuccess)
|
|
59
|
+
await o.onSuccess(resp, data);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
const err = error instanceof Error ? error : new Error("Invalid form");
|
|
62
|
+
const statusHandler = hasResponse(err) ? validator.statusHandlers[`${err.response.status}`] : void 0;
|
|
63
|
+
if (statusHandler) {
|
|
64
|
+
return statusHandler(err, form);
|
|
65
|
+
}
|
|
66
|
+
form.error = err;
|
|
67
|
+
const errorsData = resolveValidationErrorData(err, validator.errorParsers);
|
|
68
|
+
if (errorsData) {
|
|
69
|
+
form.setErrors(errorsData);
|
|
70
|
+
form.touch();
|
|
71
|
+
}
|
|
72
|
+
if (o?.onError)
|
|
73
|
+
return o.onError(err, data);
|
|
74
|
+
} finally {
|
|
75
|
+
form.processing = false;
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
valid: (...keys2) => {
|
|
79
|
+
if (keys2.length === 0)
|
|
80
|
+
return Object.values(form.errors).reduce((acc, error) => acc && !!error, true);
|
|
81
|
+
return keys2.reduce((acc, key) => acc && (form.validatedKeys.includes(key) && !form.errors[key]), true);
|
|
82
|
+
},
|
|
83
|
+
invalid: (...keys2) => {
|
|
84
|
+
if (keys2.length === 0)
|
|
85
|
+
return Object.values(form.errors).reduce((acc, error) => acc || !!error, false);
|
|
86
|
+
return keys2.reduce((acc, key) => acc || form.validatedKeys.includes(key) && !!form.errors[key], false);
|
|
87
|
+
},
|
|
88
|
+
touched: (...keys2) => {
|
|
89
|
+
if (keys2.length === 0)
|
|
90
|
+
return form.validatedKeys.length > 0;
|
|
91
|
+
return keys2.reduce((acc, key) => acc && form.validatedKeys.includes(key), true);
|
|
92
|
+
},
|
|
93
|
+
touch(...keys2) {
|
|
94
|
+
if (keys2.length === 0) {
|
|
95
|
+
getAllNestedKeys(form.data()).forEach((key) => form.touch(key));
|
|
96
|
+
return form;
|
|
97
|
+
}
|
|
98
|
+
keys2.forEach((key) => {
|
|
99
|
+
if (!form.validatedKeys.includes(key))
|
|
100
|
+
form.validatedKeys.push(key);
|
|
101
|
+
});
|
|
102
|
+
return form;
|
|
103
|
+
},
|
|
104
|
+
forgetErrors(...keys2) {
|
|
105
|
+
if (keys2.length === 0) {
|
|
106
|
+
form.errors = {};
|
|
107
|
+
form.error = null;
|
|
108
|
+
form.validatedKeys = [];
|
|
109
|
+
return form;
|
|
110
|
+
}
|
|
111
|
+
keys2.forEach((key) => {
|
|
112
|
+
if (key in form.errors)
|
|
113
|
+
form.errors[key] = void 0;
|
|
114
|
+
const index = form.validatedKeys.indexOf(key);
|
|
115
|
+
if (index > -1)
|
|
116
|
+
form.validatedKeys.splice(index, 1);
|
|
117
|
+
});
|
|
118
|
+
return form;
|
|
119
|
+
},
|
|
120
|
+
setErrors(data) {
|
|
121
|
+
form.errors = {};
|
|
122
|
+
form.error = new Error(data.message);
|
|
123
|
+
Object.keys(data.errors).forEach((key) => {
|
|
124
|
+
const error = data.errors[key];
|
|
125
|
+
form.errors[key] = Array.isArray(error) ? error[0] : error;
|
|
126
|
+
});
|
|
127
|
+
return form;
|
|
128
|
+
},
|
|
129
|
+
validateFiles() {
|
|
130
|
+
validator.setValidateFiles(true);
|
|
131
|
+
return form;
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
return form;
|
|
135
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { DebouncedFuncLeading } from 'lodash';
|
|
2
|
+
import type { NestedKeyOf } from './types/utils';
|
|
3
|
+
import type { ValidationErrorParser } from './types/core';
|
|
4
|
+
import type { ClientStatusHandlers, Form, UseFormOptions } from './types/form';
|
|
5
|
+
export declare function makeValidator<TData extends object, TResp>(cb: (data: TData, precognitiveHeaders: Headers) => Promise<TResp>, options?: UseFormOptions<TData>): {
|
|
6
|
+
validate: DebouncedFuncLeading<(form: Form<TData, TResp>, ...keys: NestedKeyOf<TData>[]) => Promise<void>>;
|
|
7
|
+
errorParsers: ValidationErrorParser[];
|
|
8
|
+
setValidateFiles: (value: boolean) => void;
|
|
9
|
+
statusHandlers: ClientStatusHandlers;
|
|
10
|
+
};
|
|
11
|
+
export declare function withoutFiles<TData extends object>(data: TData): TData;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { debounce } from "lodash-es";
|
|
2
|
+
import defu from "defu";
|
|
3
|
+
import { isFile, requestPrecognitiveHeaders, resolveValidationErrorData, makeLaravelValidationErrorParser, makeNuxtValidationErrorParser, hasResponse } from "./core.mjs";
|
|
4
|
+
import { useNuxtApp, useRuntimeConfig } from "#imports";
|
|
5
|
+
export function makeValidator(cb, options) {
|
|
6
|
+
const { $precognition } = useNuxtApp();
|
|
7
|
+
const config = useRuntimeConfig().public.precognition;
|
|
8
|
+
const validateOptions = defu(options, config);
|
|
9
|
+
const errorParsers = [
|
|
10
|
+
...$precognition.errorParsers,
|
|
11
|
+
...validateOptions?.clientErrorParsers ?? []
|
|
12
|
+
];
|
|
13
|
+
if (validateOptions.enableLaravelClientErrorParser)
|
|
14
|
+
errorParsers.push(makeLaravelValidationErrorParser());
|
|
15
|
+
if (validateOptions.enableNuxtClientErrorParser)
|
|
16
|
+
errorParsers.push(makeNuxtValidationErrorParser());
|
|
17
|
+
const statusHandlers = { ...$precognition.statusHandlers, ...options?.statusHandlers };
|
|
18
|
+
const validate = debounce(
|
|
19
|
+
async function(form, ...keys) {
|
|
20
|
+
const headers = requestPrecognitiveHeaders(validateOptions.validationHeaders, keys);
|
|
21
|
+
const data = form.data();
|
|
22
|
+
try {
|
|
23
|
+
const onBefore = (validateOptions?.onBeforeValidation ?? (() => true))(data);
|
|
24
|
+
if (!onBefore)
|
|
25
|
+
return;
|
|
26
|
+
form.validating = true;
|
|
27
|
+
form.error = null;
|
|
28
|
+
const onValidationStart = validateOptions.onValidationStart ?? (() => Promise.resolve());
|
|
29
|
+
await onValidationStart(data);
|
|
30
|
+
const clientValidation = validateOptions?.clientValidation ?? (() => Promise.resolve());
|
|
31
|
+
await clientValidation(data);
|
|
32
|
+
const backendValidation = validateOptions.backendValidation ? cb : () => Promise.resolve();
|
|
33
|
+
await backendValidation(
|
|
34
|
+
validateOptions.validateFiles ? data : withoutFiles(data),
|
|
35
|
+
headers
|
|
36
|
+
);
|
|
37
|
+
form.forgetErrors(...keys);
|
|
38
|
+
form.touch(...keys);
|
|
39
|
+
const onSuccess = validateOptions?.onValidationSuccess ?? (() => void 0);
|
|
40
|
+
return onSuccess(data);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
const err = error instanceof Error ? error : new Error("An error occurred while validating the form. Please try again.");
|
|
43
|
+
const statusHandler = hasResponse(err) && statusHandlers ? statusHandlers[`${err.response.status}`] : void 0;
|
|
44
|
+
if (statusHandler)
|
|
45
|
+
return statusHandler(err, form);
|
|
46
|
+
form.error = err;
|
|
47
|
+
const errorData = resolveValidationErrorData(err, errorParsers);
|
|
48
|
+
if (errorData) {
|
|
49
|
+
form.setErrors(errorData);
|
|
50
|
+
form.touch(...keys);
|
|
51
|
+
}
|
|
52
|
+
const onError = validateOptions?.onValidationError ?? (() => void 0);
|
|
53
|
+
return onError(err, data, keys);
|
|
54
|
+
} finally {
|
|
55
|
+
form.validating = false;
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
validateOptions.validationTimeout,
|
|
59
|
+
{ leading: true, trailing: true }
|
|
60
|
+
);
|
|
61
|
+
function setValidateFiles(value) {
|
|
62
|
+
validateOptions.validateFiles = value;
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
validate,
|
|
66
|
+
errorParsers,
|
|
67
|
+
statusHandlers,
|
|
68
|
+
setValidateFiles
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
export function withoutFiles(data) {
|
|
72
|
+
const copy = Array.isArray(data) ? [] : {};
|
|
73
|
+
Object.keys(data).forEach((key) => {
|
|
74
|
+
const value = data[key];
|
|
75
|
+
if (isFile(value)) {
|
|
76
|
+
copy[key] = null;
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (typeof value === "object" && value !== null) {
|
|
80
|
+
copy[key] = withoutFiles(value);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
copy[key] = value;
|
|
84
|
+
});
|
|
85
|
+
return copy;
|
|
86
|
+
}
|
package/dist/types.d.mts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
|
|
2
|
+
import type { ModuleOptions } from './module.js'
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
declare module '@nuxt/schema' {
|
|
6
|
+
interface NuxtConfig { ['precognition']?: Partial<ModuleOptions> }
|
|
7
|
+
interface NuxtOptions { ['precognition']?: ModuleOptions }
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
declare module 'nuxt/schema' {
|
|
11
|
+
interface NuxtConfig { ['precognition']?: Partial<ModuleOptions> }
|
|
12
|
+
interface NuxtOptions { ['precognition']?: ModuleOptions }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
export type { ModuleOptions, default } from './module.js'
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
|
|
2
|
+
import type { ModuleOptions } from './module'
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
declare module '@nuxt/schema' {
|
|
6
|
+
interface NuxtConfig { ['precognition']?: Partial<ModuleOptions> }
|
|
7
|
+
interface NuxtOptions { ['precognition']?: ModuleOptions }
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
declare module 'nuxt/schema' {
|
|
11
|
+
interface NuxtConfig { ['precognition']?: Partial<ModuleOptions> }
|
|
12
|
+
interface NuxtOptions { ['precognition']?: ModuleOptions }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
export type { ModuleOptions, default } from './module'
|
package/package.json
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "nuxt-precognition",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.0.2",
|
|
5
|
+
"description": "Nuxt module implementing Precognition protocol (inspired by official Laravel Precognition) for backend precognitive validation.",
|
|
6
|
+
"author": {
|
|
7
|
+
"name": "sot1986",
|
|
8
|
+
"email": "sot@8dplus.com"
|
|
9
|
+
},
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"homepage": "https://github.com/sot1986/nuxt-precognition",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "https://github.com/sot1986/nuxt-laravel-precognition"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"precognition",
|
|
18
|
+
"nuxt",
|
|
19
|
+
"laravel",
|
|
20
|
+
"zod"
|
|
21
|
+
],
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./dist/types.d.ts",
|
|
25
|
+
"import": "./dist/module.mjs",
|
|
26
|
+
"require": "./dist/module.cjs"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"main": "./dist/module.cjs",
|
|
30
|
+
"types": "./dist/types.d.ts",
|
|
31
|
+
"files": [
|
|
32
|
+
"dist"
|
|
33
|
+
],
|
|
34
|
+
"scripts": {
|
|
35
|
+
"prepack": "nuxt-module-build build",
|
|
36
|
+
"dev": "nuxi dev playground",
|
|
37
|
+
"dev:build": "nuxi build playground",
|
|
38
|
+
"dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
|
|
39
|
+
"release": "npm run lint && npm run test && npm run prepack && changelogen --release && npm publish && git push --follow-tags",
|
|
40
|
+
"release:locally": "npm run lint && npm run test && npm run prepack && npm pack && mv ./nuxt-precognition-*.tgz ../Released",
|
|
41
|
+
"lint": "eslint .",
|
|
42
|
+
"lint:fix": "eslint . --fix",
|
|
43
|
+
"test": "vitest run",
|
|
44
|
+
"test:watch": "vitest watch"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@nuxt/kit": "^3.11.2",
|
|
48
|
+
"defu": "^6.1.4",
|
|
49
|
+
"lodash-es": "^4.17.21"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@nuxt/devtools": "latest",
|
|
53
|
+
"@nuxt/eslint-config": "^0.3.12",
|
|
54
|
+
"@nuxt/module-builder": "^0.5.5",
|
|
55
|
+
"@nuxt/schema": "^3.11.2",
|
|
56
|
+
"@nuxt/test-utils": "^3.12.1",
|
|
57
|
+
"@tailwindcss/forms": "^0.5.7",
|
|
58
|
+
"@types/lodash-es": "^4.17.12",
|
|
59
|
+
"@types/node": "^20.12.11",
|
|
60
|
+
"autoprefixer": "^10.4.19",
|
|
61
|
+
"changelogen": "^0.5.5",
|
|
62
|
+
"eslint": "^8.57.0",
|
|
63
|
+
"h3": "^1.11.1",
|
|
64
|
+
"nuxt": "^3.11.2",
|
|
65
|
+
"playwright-core": "^1.44.0",
|
|
66
|
+
"postcss": "^8.4.38",
|
|
67
|
+
"tailwindcss": "^3.4.3",
|
|
68
|
+
"typescript": "^5.4.5",
|
|
69
|
+
"vitest": "^1.6.0",
|
|
70
|
+
"vue-tsc": "^2.0.17",
|
|
71
|
+
"zod": "^3.23.8"
|
|
72
|
+
}
|
|
73
|
+
}
|