nuxt-precognition 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,11 +1,15 @@
1
- <!--
2
- Get your module up and running quickly.
1
+ <!-- Badges -->
2
+ [npm-version-src]: https://img.shields.io/npm/v/nuxt-precognition/latest.svg?style=flat&colorA=020420&colorB=00DC82
3
+ [npm-version-href]: https://npmjs.com/package/nuxt-precognition
4
+
5
+ [npm-downloads-src]: https://img.shields.io/npm/dm/nuxt-precognition.svg?style=flat&colorA=020420&colorB=00DC82
6
+ [npm-downloads-href]: https://npmjs.com/package/nuxt-precognition
3
7
 
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
- -->
8
+ [license-src]: https://img.shields.io/npm/l/nuxt-precognition.svg?style=flat&colorA=020420&colorB=00DC82
9
+ [license-href]: https://npmjs.com/package/nuxt-precognition
10
+
11
+ [nuxt-src]: https://img.shields.io/badge/Nuxt-020420?logo=nuxt.js
12
+ [nuxt-href]: https://nuxt.com
9
13
 
10
14
  # Nuxt Precognition
11
15
 
@@ -14,13 +18,48 @@ Find and replace all on all files (CMD+SHIFT+F):
14
18
  [![License][license-src]][license-href]
15
19
  [![Nuxt][nuxt-src]][nuxt-href]
16
20
 
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.
21
+ Nuxt Precognition is a validation module for Nuxt that implements the [Precognition protocol](https://laravel.com/docs/10.x/precognition) in a backend-agnostic way. It supports any backend or validation library, and is not tied to Laravel.
22
+
23
+ ## Table of Contents
24
+
25
+ - [Nuxt Precognition](#nuxt-precognition)
26
+ - [Table of Contents](#table-of-contents)
27
+ - [Requirements](#requirements)
28
+ - [Why Nuxt Precognition?](#why-nuxt-precognition)
29
+ - [Quick Example](#quick-example)
30
+ - [Features](#features)
31
+ - [Installation](#installation)
32
+ - [How It Works](#how-it-works)
33
+ - [Define Zod Error Parser](#define-zod-error-parser)
34
+ - [Client Side Validation](#client-side-validation)
35
+ - [Server Side Validation](#server-side-validation)
36
+ - [Precognition Protocol](#precognition-protocol)
37
+ - [Configuration](#configuration)
38
+ - [Options](#options)
39
+ - [Status Handlers](#status-handlers)
40
+ - [Laravel Integration](#laravel-integration)
41
+ - [Contributing](#contributing)
42
+ - [License](#license)
43
+
44
+ ## Requirements
45
+
46
+ - Nuxt >= 3.x
47
+ - Node.js >= 18
18
48
 
19
- Instead of supporting only _$fetch_ and _Laravel_, it works with simple promises, targeting any backend that implements the base Precognition protocol. These promises will receive the form `payload` and protocol `Headers`.
49
+ ## Why Nuxt Precognition?
50
+
51
+ - **Backend agnostic:** Works with any backend that supports the Precognition protocol.
52
+ - **Validation library agnostic:** Use Zod, Yup, or any other validation library.
53
+ - **Client & server side validation:** Seamless validation on both ends.
54
+ - **Optimal TypeScript support:** Typesafe forms and error handling.
55
+ - **Highly customizable:** Plug in your own error parsers and status handlers.
56
+
57
+ ---
58
+
59
+ ## Quick Example
20
60
 
21
- #### Example
22
61
  ```ts
23
- interface User = {
62
+ interface User {
24
63
  email: string
25
64
  password: string
26
65
  }
@@ -31,27 +70,32 @@ const form = useForm(
31
70
  )
32
71
  ```
33
72
 
34
- This module comes with native __Nitro__ integration, but will work with other backend as well.
73
+ ---
35
74
 
36
- Are you using only __Lambda__? You are covered with [Lambda Precognition](https://www.npmjs.com/package/lambda-precognition)!!
75
+ ## Features
37
76
 
38
- It supports any validation library (_who said [__Zod__](https://zod.dev/)??_) server or client side. You will need only to configure specific `Error parsers`.
77
+ - Laravel compliant
78
+ - Validation library agnostic
79
+ - Client and server side validation
80
+ - TypeScript support
81
+ - Customizable error parsing and status handling
39
82
 
40
- - [✨ &nbsp;Release Notes](/CHANGELOG.md)
41
- <!-- - [🏀 Online playground](https://stackblitz.com/github/your-org/nuxt-precognition?file=playground%2Fapp.vue) -->
42
- <!-- - [📖 &nbsp;Documentation](https://example.com) -->
83
+ ---
43
84
 
44
- ### Features
85
+ ## Installation
45
86
 
46
- <!-- Highlight some of the features your module provide here -->
47
- - &nbsp;Laravel compliant
48
- - &nbsp;Validation library agnostic
49
- - &nbsp;Client and server side validation
50
- - &nbsp;Optimal Typescript support
51
- - &nbsp;Highly customizable
87
+ Install the module in your Nuxt app:
88
+
89
+ ```bash
90
+ npx nuxi module add nuxt-precognition
91
+ ```
92
+
93
+ ---
94
+
95
+ ## How It Works
96
+
97
+ The core concept is **error parsers**: functions that extract validation errors from thrown errors.
52
98
 
53
- ### How it works
54
- Everything turns around `errorParsers`(_user defined function to read validation errors from_ `Error` _payload_):
55
99
  ```ts
56
100
  type ValidationErrors = Record<string, string | string[]>
57
101
 
@@ -63,84 +107,160 @@ interface ValidationErrorsData {
63
107
  type ValidationErrorParser = (error: Error) => ValidationErrorsData | undefined | null
64
108
  ```
65
109
 
66
- You can define them globally (in `Nuxt Plugin` or custom `eventHandler`), or per `form` instance.
67
-
68
- Imagine you are working with [__Zod__](https://zod.dev/).
69
- Just create a __nuxt plugin__ and define the "_Zod error parser_":
110
+ ### Define Zod Error Parser
70
111
 
71
112
  ```ts
72
- // plugins/precognition.ts
113
+ // app/utils/precognition.ts or shared/utils/precognition.ts
114
+ import { ZodError } from 'zod'
73
115
 
116
+ export const zodErrorParser: ValidationErrorParser = (error) => {
117
+ if (error instanceof ZodError) {
118
+ const errors = {} as Record<string, string[]>
119
+ error.errors.forEach((e) => {
120
+ const key = e.path.join('.')
121
+ if (key in errors) {
122
+ errors[key].push(e.message)
123
+ return
124
+ }
125
+ errors[key] = [e.message]
126
+ })
127
+ return { errors, message: 'Validation error' }
128
+ }
129
+ return null
130
+ }
131
+ ```
132
+
133
+ > **Note:**
134
+ > For Server side validation, place this file in `shared/utils` folder.
135
+
136
+ ### Client Side Validation
137
+
138
+ Add the parser client side globally.
139
+
140
+ ```ts
141
+ // app/plugins/precognition.ts
74
142
  export default defineNuxtPlugin(() => {
75
143
  const { $precognition } = useNuxtApp()
76
144
 
77
- $precognition.errorParsers.push(
78
- (error) => {
79
- if (error instanceof ZodError) {
80
- const errors = {} as Record<string, string[]>
81
- error.errors.forEach((e) => {
82
- const key = e.path.join('.')
83
- if (key in errors) {
84
- errors[key].push(e.message)
85
- return
86
- }
87
- errors[key] = [e.message]
88
- })
89
- return { errors, message: 'Validation error' }
90
- }
91
- return null
92
- },
93
- )
145
+ $precognition.errorParsers.push(zodErrorParser)
146
+
147
+ // ..
94
148
  })
95
149
  ```
96
- From now on, everytime the `useForm` will catch the error, it will run our parses, and capture and assign any validation errors.
97
150
 
98
- If you want to reuse the same options over multiple pages, you can create your __custom composable__ by `useForm.create` factory function.
151
+ Use the composable in setup method.
152
+ ```ts
153
+ const UserSchema = z.object({
154
+ email: z.string().email(),
155
+ password: z.string().min(8),
156
+ })
157
+
158
+ const form = useForm(
159
+ (): z.infer<typeof UserSchema> => ({
160
+ email: '',
161
+ password: '',
162
+ }),
163
+ (body, headers) => $fetch('/api/login', {
164
+ method: 'POST',
165
+ headers,
166
+ body,
167
+ }),
168
+ {
169
+ clientValidation(data) {
170
+ UserSchema.parse(data)
171
+ },
172
+ },
173
+ )
174
+
175
+ function login() {
176
+ form.submit()
177
+ }
178
+
179
+ function reset() {
180
+ form.reset()
181
+ document.getElementById('email')?.focus()
182
+ }
183
+ ```
184
+
185
+ ```vue
186
+ <form
187
+ @submit.prevent="login"
188
+ @reset.prevent="reset"
189
+ >
190
+ <div>
191
+ <label for="email">Email address</label>
192
+ <input
193
+ id="email"
194
+ v-model="form.email"
195
+ name="email"
196
+ type="email"
197
+ @change="form.validate('email')"
198
+ >
199
+ <span v-if="form.valid('email')">OK!!</span>
200
+ <span v-if="form.invalid('email')">{{ form.errors.email }}</span>
201
+ </div>
202
+
203
+ <div>
204
+ <label for="password">Password</label>
205
+ <input
206
+ id="password"
207
+ v-model="form.password"
208
+ name="password"
209
+ type="password"
210
+ autocomplete="current-password"
211
+ required
212
+ @change="form.validate('password')"
213
+ >
214
+ <span v-if="form.valid('password')">OK!!</span>
215
+ <span v-if="form.invalid('password')">{{ form.errors.password }}</span>
216
+ </div>
217
+
218
+ <div>
219
+ <button type="submit">Sign in</button>
220
+ <button type="reset">Reset</button>
221
+ </div>
222
+ </form>
223
+ ```
99
224
 
100
- ### How about server side
101
- Same idea, creating a nitro plugin:
225
+ ### Server Side Validation
102
226
 
227
+ 1. update the default configuration.
103
228
  ```ts
104
- // server/plugins/precognition.ts
229
+ // nuxt.config.ts
105
230
 
231
+ export default defineNuxtConfig({
232
+ modules: [
233
+ 'nuxt-precognition'
234
+ ],
235
+ precognition: {
236
+ backendValidation: true,
237
+ enableNuxtClientErrorParser: true,
238
+ },
239
+ })
240
+ ```
241
+ 2. Create a Nitro plugin to parse server errors:
242
+ ```ts
243
+ // server/plugins/precognition.ts
106
244
  import { ZodError } from 'zod'
107
245
 
108
246
  export default defineNitroPlugin((nitroApp) => {
109
247
  nitroApp.hooks.hook('request', (event) => {
110
248
  event.context.$precognition.errorParsers = [
111
- (error) => {
112
- if (error instanceof ZodError) {
113
- const errors: Record<string, string[]> = {}
114
- error.errors.forEach((e) => {
115
- const key = e.path.join('.')
116
- if (key in errors) {
117
- errors[key].push(e.message)
118
- return
119
- }
120
- errors[key] = [e.message]
121
- })
122
- const message = error.errors.at(0)?.message ?? 'Validation error'
123
- return { errors, message }
124
- }
125
- },
249
+ zodErrorParser
126
250
  ]
127
251
  })
128
252
  })
129
253
  ```
130
- If you don't like hooking on every request, you can create your custom eventHandler by `definePrecognitiveEventHandler.create` factory function.
131
-
132
- Make your validation logic inside the `onRequest` handler of the `definePrecognitiveEventHandler`.
133
254
 
255
+ 3. Use `definePrecognitiveEventHandler` in the _object_ way and add validation in the `onRequest` hook.
134
256
  ```ts
135
257
  // server/api/login.post.ts
136
258
  import { z } from 'zod'
137
259
  import { definePrecognitiveEventHandler, readBody } from '#imports'
138
260
 
139
261
  const loginSchema = z.object({
140
- email: z.string().email().refine(_email => // Check for email uniqueness
141
- true, { message: 'Email is already in use' },
142
- ),
143
- password: z.string(),
262
+ email: z.string().email(),
263
+ password: z.string()
144
264
  }).refine((_data) => {
145
265
  // Check for email and password match
146
266
  // ...
@@ -164,65 +284,59 @@ export default definePrecognitiveEventHandler({
164
284
  },
165
285
  })
166
286
  ```
287
+ ---
167
288
 
168
- This time the error will be converted to `NuxtServerValidationError` and captured client side, if we enable the predefined parsers in the nuxt configuration file:
169
-
170
- ```ts
171
- // nuxt.config.ts
172
-
173
- export default defineNuxtConfig({
174
- modules: ['nuxt-precognitiion'],
175
- precognition: {
176
- backendValidation: true,
177
- enableNuxtClientErrorParser: true,
178
- }
179
- })
180
- ```
181
- __Remember to throw the `ValidationError` only in the `onRequest` handler (using the `object notation`)__.
182
- Any logic in the base `handler` won't be process during `precognitiveRequests`.
183
-
184
- * Each `event.context` include also a flag (`{ precognitive: boolean }`), indicating if request is precognitive or not, looking at presence of _Precognitive header_.
289
+ ## Precognition Protocol
185
290
 
186
- ### Precognition Protocol
187
- In case you need to define your own backend logic outside nitro (_AWS Lamba_), respect following list of requirements.
291
+ If you need to define your own backend logic outside Nitro, follow these requirements.
188
292
 
189
293
  - Precognitive Requests must have:
190
294
  1. Precognitive Header `{ 'Precognitive': 'true' }`
191
295
  - To validate specific variables, each keys must be specified inside the ValidateOnly Header, comma separated and leveraging dot notation `{ 'Precognition-Validate-Only': 'name,age,address.street,address.number' }`
192
296
  - To validate the full Form the ValidateOnly Header should be omitted or define as an empty string.
193
- - Successfull validation response must have:
297
+ - Successful validation response must have:
194
298
  1. Precognitive Header `{ 'Precognitive': 'true' }`
195
- 2. Precognitive Successfull Header `{ 'Precognition-Success': 'true' }`
196
- 3. Precognitve Successfull status code: `204`
299
+ 2. Precognitive Successful Header `{ 'Precognition-Success': 'true' }`
300
+ 3. Precognitive Successful status code: `204`
197
301
  - Error validation response must have:
198
302
  1. Precognitive Header `{ 'Precognitive': 'true' }`
199
- 2. ValidationOnly header if needed `{ 'Precognition-Validate-Only': 'name,age,address.street,address.number' }`
303
+ 2. Precognition-Validate-Only header if needed `{ 'Precognition-Validate-Only': 'name,age,address.street,address.number' }`
200
304
  3. Validation Error status code: `422`
201
305
  4. Validation Errors and Message will be parsed as per your define logic, or using standard `errorParsers`:
202
306
  - NuxtErrorParsers: `NuxtPrecognitiveErrorResponse`: `Response & { _data: { data: ValidationErrorsData }}`
203
307
  - LaravelErrorParsers: `LaravelPrecognitiveErrorResponse`: `Response & { _data: ValidationErrorsData }`
204
308
 
309
+ ---
205
310
 
206
- ## Quick Setup
311
+ ## Configuration
207
312
 
208
- Install the module to your Nuxt application with one command:
313
+ Add to your `nuxt.config.ts`:
209
314
 
210
- ```bash
211
- npx nuxi module add nuxt-precognition
315
+ ```ts
316
+ export default defineNuxtConfig({
317
+ modules: ['nuxt-precognition'],
318
+ precognition: {
319
+ backendValidation: true,
320
+ enableNuxtClientErrorParser: true,
321
+ // ...other options
322
+ }
323
+ })
212
324
  ```
213
325
 
214
- ### Configure
215
-
326
+ ### Options
216
327
  | name | type | default | description |
217
328
  |---|---|---|---|
218
329
  |validationTimeout|_number_|`1500`|Debounce time, in milliseconds, between two precognitive validation requests.|
219
330
  |backendValidation|_boolean_|`false`|Flag to enable the precognitive validation.|
220
331
  |validateFiles|_boolean_|`false`|Flag to enable files validation on precognitive requests.|
221
- |enableNuxtClientErrorParser|_boolean_|`false`|Flag to enable _nuxtErrorParsers_ @ client side (in `form.validate` and `form.submit`).|
222
- |enableLaravelClientErrorParser|_boolean_|`false`|Flag to enable _laravelErrorParsers_ @ client side (in `form.validate` and `form.submit`).|
223
- |enableLaravelServerErrorParser|_boolean_|`false`|Flag to enable _laravelErrorParsers_ @ client side (in `definePrecognitiveEventHandler`).|
332
+ |enableNuxtClientErrorParser|_boolean_|`false`|Flag to enable _nuxtErrorParsers_ on client side (in `form.validate` and `form.submit`).|
333
+ |enableLaravelClientErrorParser|_boolean_|`false`|Flag to enable _laravelErrorParsers_ on client side (in `form.validate` and `form.submit`).|
334
+ |enableLaravelServerErrorParser|_boolean_|`false`|Flag to enable _laravelErrorParsers_ on server side (in `definePrecognitiveEventHandler`).|
335
+
224
336
 
225
- #### Status Handlers
337
+ ---
338
+
339
+ ### Status Handlers
226
340
  Like in [official package](https://github.com/laravel/precognition), you can define globally, or @instance level, custom handlers for specific error codes:
227
341
 
228
342
  ```ts
@@ -243,14 +357,31 @@ export default defineNuxtPlugin(() => {
243
357
  })
244
358
  ```
245
359
 
246
- That's it! You can now use Nuxt Precognition in your Nuxt app ✨
360
+ ---
361
+
362
+ ## Laravel Integration
247
363
 
248
- #### Working with Laravel
364
+ If you want to use Laravel, you won't need nuxt nitro integration.
365
+
366
+ 1. **Enable Backend Validation and Error Parsers:**
249
367
 
250
- 1. Define a plugin like this
251
368
  ```ts
252
- // plugins/api.ts
369
+ // nuxt.config.ts
370
+ export default defineNuxtConfig({
371
+ modules: ['nuxt-precognition'],
372
+ precognition: {
373
+ backendValidation: true,
374
+ enableLaravelClientErrorParser: true,
375
+ }
376
+ })
377
+ ```
378
+
379
+ 2. **Plugin Example:**
380
+
381
+ Add Sanctum token prefetch and ensure proper handling of all precognitive requests.
253
382
 
383
+ ```ts
384
+ // plugins/laravel.ts
254
385
  export default defineNuxtPlugin((app) => {
255
386
  const { $precognition } = useNuxtApp()
256
387
  const token = useCookie('XSRF-TOKEN')
@@ -263,7 +394,6 @@ export default defineNuxtPlugin((app) => {
263
394
  'Content-Type': 'application/json',
264
395
  },
265
396
  onRequest: ({ options }) => {
266
- // Setup csrf protection for every requests if available
267
397
  if (token.value) {
268
398
  const headers = new Headers(options.headers)
269
399
  headers.set('X-XSRF-TOKEN', token.value)
@@ -271,7 +401,7 @@ export default defineNuxtPlugin((app) => {
271
401
  }
272
402
  },
273
403
  onResponse: (context) => {
274
- // ensure that all precognitive requests will receive precognitive responses
404
+ // ensure non false positive validations
275
405
  $precognition.assertSuccessfulPrecognitiveResponses(context)
276
406
  },
277
407
  })
@@ -280,12 +410,8 @@ export default defineNuxtPlugin((app) => {
280
410
  try {
281
411
  await api('/sanctum/csrf-cookie')
282
412
  token.value = useCookie('XSRF-TOKEN').value
283
-
284
- if (!token.value) {
285
- throw new Error('Failed to get CSRF token')
286
- }
287
- }
288
- catch (e) {
413
+ if (!token.value) throw new Error('Failed to get CSRF token')
414
+ } catch (e) {
289
415
  console.error(e)
290
416
  }
291
417
  }
@@ -303,102 +429,66 @@ export default defineNuxtPlugin((app) => {
303
429
  }
304
430
  })
305
431
  ```
306
- 2. Enable backend validation and native Laravel Error parsers client or server side
307
- ```ts
308
- // nuxt.config.ts
309
- export default defineNuxtConfig({
310
- modules: ['nuxt-precognition'],
311
- precognition: {
312
- backendValidation: true,
313
- enableLaravelClientErrorParser: true,
314
- },
315
- /*
316
- ...
317
- */
318
- })
319
- ```
320
- \* If you `enableLaravelServerErrorParser`, you must also `enableNuxtClientErrorParser`
321
432
 
322
- 3. Setup Laravel Cors configuration file
433
+ 3. **Laravel CORS Configuration:**
434
+
435
+ Ensure Precognitive headers will be shared with Nuxt application.
436
+
323
437
  ```php
324
438
  // config/cors.php
325
-
326
439
  return [
327
-
328
- /*
329
- |--------------------------------------------------------------------------
330
- | Cross-Origin Resource Sharing (CORS) Configuration
331
- |--------------------------------------------------------------------------
332
- |
333
- */
334
-
335
- 'paths' => ['*'],
336
-
337
- 'allowed_methods' => ['*'],
338
-
339
- 'allowed_origins' => ['*'],
340
-
341
- 'allowed_origins_patterns' => [env('FRONTEND_URL', 'http://localhost:3000')],
342
-
343
- 'allowed_headers' => ['*'],
344
-
345
- 'exposed_headers' => ['Precognition', 'Precognition-Success'],
346
-
347
- 'max_age' => 0,
348
-
349
- 'supports_credentials' => true,
350
-
440
+ 'paths' => ['*'],
441
+ 'allowed_methods' => ['*'],
442
+ 'allowed_origins' => ['*'],
443
+ 'allowed_origins_patterns' => [env('FRONTEND_URL', 'http://localhost:3000')],
444
+ 'allowed_headers' => ['*'],
445
+ 'exposed_headers' => ['Precognition', 'Precognition-Success'],
446
+ 'max_age' => 0,
447
+ 'supports_credentials' => true,
351
448
  ];
352
449
  ```
353
- 3. Enable the Precognition Middleware where needed
450
+
451
+ 4. **Enable Precognition Middleware:**
452
+
453
+ Apply precognitive middleware where needed.
354
454
 
355
455
  ```php
356
456
  // routes/api.php
357
-
358
457
  Route::middleware('precognitive')->group(function () {
359
458
  Route::apiResource('posts', \App\Http\Controllers\PostController::class);
360
459
  });
361
460
  ```
362
- ## Contribution
363
-
364
- <details>
365
- <summary>Local development</summary>
366
461
 
367
- ```bash
368
- # Install dependencies
369
- npm install
462
+ That's it. Nuxt validation will be in sync with Laravel!!.
370
463
 
371
- # Generate type stubs
372
- npm run dev:prepare
464
+ ---
373
465
 
374
- # Develop with the playground
375
- npm run dev
466
+ ## Contributing
376
467
 
377
- # Build the playground
378
- npm run dev:build
468
+ ```bash
469
+ # Install dependencies
470
+ npm install
379
471
 
380
- # Run ESLint
381
- npm run lint
472
+ # Generate type stubs
473
+ npm run dev:prepare
382
474
 
383
- # Run Vitest
384
- npm run test
385
- npm run test:watch
475
+ # Develop with the playground
476
+ npm run dev
386
477
 
387
- # Release new version
388
- npm run release
389
- ```
478
+ # Build the playground
479
+ npm run dev:build
390
480
 
391
- </details>
481
+ # Run ESLint
482
+ npm run lint
392
483
 
393
- <!-- Badges -->
394
- [npm-version-src]: https://img.shields.io/npm/v/nuxt-precognition/latest.svg?style=flat&colorA=020420&colorB=00DC82
395
- [npm-version-href]: https://npmjs.com/package/nuxt-precognition
484
+ # Run Vitest
485
+ npm run test
486
+ npm run test:watch
396
487
 
397
- [npm-downloads-src]: https://img.shields.io/npm/dm/nuxt-precognition.svg?style=flat&colorA=020420&colorB=00DC82
398
- [npm-downloads-href]: https://npmjs.com/package/nuxt-precognition
488
+ # Release new version
489
+ npm run release
490
+ ```
399
491
 
400
- [license-src]: https://img.shields.io/npm/l/nuxt-precognition.svg?style=flat&colorA=020420&colorB=00DC82
401
- [license-href]: https://npmjs.com/package/nuxt-precognition
492
+ ## License
402
493
 
403
- [nuxt-src]: https://img.shields.io/badge/Nuxt-020420?logo=nuxt.js
404
- [nuxt-href]: https://nuxt.com
494
+ MIT © [sot1986]
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=3.9.0"
6
6
  },
7
- "version": "0.0.7",
7
+ "version": "0.0.8",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "0.8.3",
10
10
  "unbuild": "2.0.0"
@@ -10,6 +10,17 @@ export declare function isFile(value: unknown): value is Blob | File | FileList;
10
10
  export declare function resolveValidationErrorData(error: Error, parsers: ValidationErrorParser[]): ValidationErrorsData | null | undefined;
11
11
  export declare function makeNuxtValidationErrorParser(): ValidationErrorParser;
12
12
  export declare function makeLaravelValidationErrorParser(): ValidationErrorParser;
13
+ /**
14
+ * Asserts that the response is a successful precognitive response.
15
+ * It runs check only if the response is OK (status 200-299) and the precognition header is set to true.
16
+ * Use this function to prevent false positives when the response is not a precognitive response.
17
+ *
18
+ * @param ctx The context object.
19
+ * @param ctx.options The options object containing headers.
20
+ * @param ctx.options.headers Optional headers for the request.
21
+ * @param ctx.response The response object to validate.
22
+ * @throws {Error} If the response does not have the expected precognition headers or status.
23
+ */
13
24
  export declare function assertSuccessfulPrecognitiveResponses(ctx: {
14
25
  options: {
15
26
  headers?: HeadersInit;
@@ -62,15 +62,20 @@ export function makeLaravelValidationErrorParser() {
62
62
  return (error) => hasResponse(error) && hasValidationStatusCode(error.response) && hasLaravelValidationErrorsData(error.response) ? error.response._data : null;
63
63
  }
64
64
  export function assertSuccessfulPrecognitiveResponses(ctx) {
65
+ if (!ctx.response.ok) {
66
+ return;
67
+ }
65
68
  if (new Headers(ctx.options.headers).get("Precognition") !== "true") {
66
69
  return;
67
70
  }
68
71
  const { status, headers } = ctx.response;
69
72
  const hasPrecognitionHeader = headers.get("Precognition") === "true";
70
73
  const hasPrecognitionSuccessHeader = headers.get("Precognition-Success") === "true";
71
- const isSuccess = hasPrecognitionHeader && hasPrecognitionSuccessHeader && status === 204;
72
- const isValidationError = hasPrecognitionHeader && status === 422;
73
- if (!(isSuccess || isValidationError)) {
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 });
74
+ const hasNoContentStatus = status === 204;
75
+ const isSuccess = hasPrecognitionHeader && hasPrecognitionSuccessHeader && hasNoContentStatus;
76
+ if (!isSuccess) {
77
+ const 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.";
78
+ console.error(message, { ctx, response: ctx.response });
79
+ throw createError({ message, statusCode: 500 });
75
80
  }
76
81
  }
@@ -0,0 +1,2 @@
1
+ import type { NestedKeyOf } from './types/utils.js';
2
+ export declare function getKeyValue<T extends object, K extends NestedKeyOf<T>>(obj: T, key: K): T[keyof T] | null;
@@ -0,0 +1,41 @@
1
+ const model = {
2
+ id: "1",
3
+ name: "John Doe",
4
+ age: 30,
5
+ address: {
6
+ street: "123 Main St",
7
+ city: "Anytown"
8
+ },
9
+ tags: ["developer", "blogger"],
10
+ websites: [
11
+ {
12
+ url: "https://example.com",
13
+ description: "My personal blog",
14
+ followers: 1e3
15
+ }
16
+ ],
17
+ favorites: [
18
+ { site: "https://favorite.com" },
19
+ { site: "https://another-favorite.com" }
20
+ ]
21
+ };
22
+ export function getKeyValue(obj, key) {
23
+ const firstKey = key.split(".")[0];
24
+ if (key === firstKey) {
25
+ return obj[firstKey];
26
+ }
27
+ if (typeof firstKey !== "string") {
28
+ throw new TypeError(`Key must be a string, received: ${typeof firstKey}`);
29
+ }
30
+ if (!(firstKey in obj)) {
31
+ throw new Error(`Key "${firstKey}" does not exist in the object.`);
32
+ }
33
+ if (typeof obj[firstKey] !== "object") {
34
+ throw new TypeError(`Value at key "${firstKey}" is not an object or is null.`);
35
+ }
36
+ if (!obj[firstKey]) {
37
+ return null;
38
+ }
39
+ const restKey = key.slice(firstKey.length + 1);
40
+ return getKeyValue(obj[firstKey], restKey);
41
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-precognition",
3
3
  "type": "module",
4
- "version": "0.0.7",
4
+ "version": "0.0.8",
5
5
  "description": "Nuxt module implementing Precognition protocol (inspired by official Laravel Precognition) for backend precognitive validation.",
6
6
  "author": {
7
7
  "name": "sot1986",