@diephp/vue-apix 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -114,15 +114,17 @@ interface AttrDto {
114
114
  }
115
115
 
116
116
  // response: {data: {item: {...}}} → model.data = item
117
- const model = apix.getForm<AttrDto>('/api/attribute/123', 'item');
117
+ const model = apix.getForm<AttrDto>('/api/attribute/123', 'data.item');
118
118
  ```
119
119
 
120
120
  Full options:
121
121
 
122
122
  ```ts
123
123
  const model = apix.getForm<AttrDto>('/api/attribute/123', {
124
- // dot-path inside body.data (or inside body when there is no data wrapper)
125
- path: 'item',
124
+ // dot-path against the RAW response body — there is no implicit body.data
125
+ // unwrapping, include `data` yourself when the API wraps its payload
126
+ // (see "Laravel pagination" below)
127
+ path: 'data.item',
126
128
  // used while the request is in flight, and as the reset() fallback
127
129
  default: () => ({ id: null, name: null, description: null }),
128
130
  // default is true; false = no request until reload() or a watch trigger
@@ -136,6 +138,12 @@ const model = apix.getForm<AttrDto>('/api/attribute/123', {
136
138
  onSuccess: (response, model) => {},
137
139
  // called after every failed fill; aborted (superseded) requests are ignored
138
140
  onError: (error, model) => {},
141
+ // never sent by a watch-triggered request or refresh() — see "watch" below
142
+ ignore: ['items'],
143
+ // this field's value survives every watch/refresh response — see "watch" below
144
+ lock: ['trackingNumber'],
145
+ // auto re-fetch when data changes — see "watch() — filters, pagination, live search" below
146
+ watch: { fields: ['name'], debounce: 300 },
139
147
  });
140
148
  ```
141
149
 
@@ -164,6 +172,38 @@ default has an object falls back to the default object, explicit scalar `null`s
164
172
  response are respected, and arrays are always replaced — never merged. The `reset()`
165
173
  snapshot stores the merged state. Opt out with `mergeDefaults: false`.
166
174
 
175
+ ### Laravel pagination — `data` + `links` + `meta`
176
+
177
+ There is no implicit `body.data` unwrapping — `path` is always a dot-path against the
178
+ **raw** response body, and without a `path` the whole body is used as-is. This matters for
179
+ a Laravel paginated collection, which wraps an **array** in `data` with `links`/`meta` as
180
+ siblings:
181
+
182
+ ```json
183
+ { "data": [{ "id": 1 }, { "id": 2 }], "links": { "next": "/?page=2" }, "meta": { "total": 42 } }
184
+ ```
185
+
186
+ Since nothing is auto-unwrapped, `links`/`meta` are never at risk of being silently dropped —
187
+ you decide exactly how much of the body ends up in `model.data`:
188
+
189
+ ```ts
190
+ interface PageDto {
191
+ data: Array<{ id: number; name: string }>;
192
+ links: { next: string | null };
193
+ meta: { current_page: number; total: number };
194
+ }
195
+
196
+ // no `path` at all — model.data becomes the whole body
197
+ const table = apix.getForm<PageDto>('/api/attribute');
198
+
199
+ table.data.data; // the items array
200
+ table.data.meta.total; // pagination meta, fully reachable
201
+ ```
202
+
203
+ If you don't need `links`/`meta` and just want the items array as `model.data`, ask for it
204
+ explicitly: `path: 'data'`. And for the common single-resource convention `{data: {...}}}`,
205
+ include `data` in the path too: `path: 'data.item'` reads `body.data.item`.
206
+
167
207
  ### Edit form — full component
168
208
 
169
209
  ```vue
@@ -177,7 +217,7 @@ interface AttrDto {
177
217
  }
178
218
 
179
219
  const model = apix.getForm<AttrDto>('/api/attribute/1', {
180
- path: 'item',
220
+ path: 'data.item',
181
221
  default: () => ({ id: null, name: null, description: null }),
182
222
  });
183
223
 
@@ -228,9 +268,8 @@ const submit = () =>
228
268
  | `model.setErrors(errors)` / `model.clearErrors(keys?)` | manage errors manually |
229
269
  | `model.reset(keys?)` | restore the snapshot: first server response, else `default()`; `reset(['name'])` for specific paths |
230
270
  | `model.post/put/patch/delete(url?, opts?)` | submit `model.data` (or `opts.data` / `opts.only: ['name']`), returns the response Promise |
231
- | `model.reload(url?)` | re-run the fill request as configured (fresh load — ignores watch payload) |
232
- | `model.refresh()` | re-send the fill request with the CURRENT state — a manual watch trigger for a "Search" button |
233
- | `model.watch(paths?, opts?)` / `model.unwatch()` | auto-refetch on change, see below |
271
+ | `model.reload(url?)` | re-run the fill request as configured — a fresh load, no `ignore`/`lock` applied |
272
+ | `model.refresh(opts?)` | re-send with the CURRENT state — a manual trigger for a "Search" button, see `watch` below |
234
273
  | `model.transformResponse(fn)` / `model.transformRequest(fn)` | reshape server data ↔ model data, see below |
235
274
 
236
275
  Submitting clears previous errors; any **4xx** response carrying an `errors` object in the
@@ -240,7 +279,7 @@ treated as validation errors — only `model.message` is surfaced.
240
279
 
241
280
  **Reserved names.** These model members always win over data keys:
242
281
  `data, errors, message, processing, hasErrors, isDirty, get, error, setData, setErrors,
243
- clearErrors, reset, post, put, patch, delete, reload, refresh, watch, unwatch,
282
+ clearErrors, reset, post, put, patch, delete, reload, refresh,
244
283
  transformRequest, transformResponse`. A data field with such a name is still there —
245
284
  via `model.data.<key>`.
246
285
 
@@ -251,18 +290,18 @@ and reactive. Two equivalent ways:
251
290
 
252
291
  ```ts
253
292
  // ChildForm.vue — via defineModel (parent: <ChildForm v-model="model" />)
254
- import type { Model } from '@diephp/vue-apix';
293
+ import type { ApixModel } from '@diephp/vue-apix';
255
294
 
256
295
  // type it through the macro GENERIC — not a cast on the left side,
257
296
  // otherwise .value loses the model members (errors, processing, data…)
258
- const form = defineModel<Model<AttrDto>>({ required: true });
297
+ const form = defineModel<ApixModel<AttrDto>>({ required: true });
259
298
  ```
260
299
 
261
300
  ```ts
262
301
  // ChildForm.vue — via a plain prop (parent: <ChildForm :form="model" />)
263
- import type { Model } from '@diephp/vue-apix';
302
+ import type { ApixModel } from '@diephp/vue-apix';
264
303
 
265
- const props = defineProps<{ form: Model<AttrDto> }>();
304
+ const props = defineProps<{ form: ApixModel<AttrDto> }>();
266
305
  ```
267
306
 
268
307
  ```html
@@ -279,8 +318,9 @@ is unnecessary — `form.errors` is already reactive inside the child.
279
318
 
280
319
  ## watch() — filters, pagination, live search
281
320
 
282
- The classic SPA page: a table, a filter form and a paginator. One model holds all of it,
283
- `watch()` re-sends the request whenever the watched paths change:
321
+ The classic SPA page: a table, a filter form and a paginator. One model holds all of it;
322
+ `watch` (a `getForm`/`postForm`/`form` option, not a chained method) re-sends the request
323
+ whenever the watched fields change:
284
324
 
285
325
  ```vue
286
326
  <script setup lang="ts">
@@ -298,17 +338,19 @@ interface PageDto {
298
338
  paginator: { page: number; total: number; per_page: number };
299
339
  }
300
340
 
301
- const table = apix
302
- .getForm<PageDto>('/api/attribute', {
303
- default: () => ({
304
- items: [],
305
- filters: { name: null, status: null },
306
- paginator: { page: 1, total: 0, per_page: 15 },
307
- }),
308
- })
309
- // watch paginator.page (not the whole paginator!) so the server-owned
310
- // `total` keeps updating from responses — see the note below
311
- .watch(['filters', 'paginator.page'], { debounce: 300 });
341
+ const table = apix.getForm<PageDto>('/api/attribute', {
342
+ // the API wraps its payload in `data` (see the JSON below) — spell it out,
343
+ // there is no implicit body.data unwrapping
344
+ path: 'data',
345
+ default: () => ({
346
+ items: [],
347
+ filters: { name: null, status: null },
348
+ paginator: { page: 1, total: 0, per_page: 15 },
349
+ }),
350
+ // items is response-only data — it must never round-trip to the server
351
+ ignore: ['items'],
352
+ watch: { fields: ['filters', 'paginator.page'], debounce: 300 },
353
+ });
312
354
 
313
355
  const lastPage = () => Math.max(1, Math.ceil(table.paginator.total / table.paginator.per_page));
314
356
 
@@ -359,25 +401,104 @@ Expected server response shape for the example above (Laravel-style):
359
401
  }
360
402
  ```
361
403
 
362
- How `watch()` behaves:
404
+ ### `watch` — the auto-refetch trigger
405
+
406
+ ```ts
407
+ apix.getForm(url, {
408
+ watch: true, // watch every field except `ignore`, no debounce
409
+ // or, explicitly:
410
+ watch: {
411
+ fields: ['filters', 'paginator.page'], // omit to watch everything except `ignore`
412
+ debounce: 300, // default 0
413
+ deep: false, // default false, see below
414
+ },
415
+ });
416
+ ```
363
417
 
364
- - **Only the watched paths are sent.** GET → PHP-style query
365
- (`filters[name]=x&paginator[page]=2`), postForm → JSON body. Override with `payload: [...]`.
366
- - **The response updates everything except the watched paths**, so a slow response never
367
- clobbers what the user is typing. Opt out with `refreshWatched: true`.
368
- - **A new trigger aborts the previous in-flight request** (AbortController) — the last
418
+ - `fields` only controls what **triggers** an auto-refetch. It never limits what gets
419
+ **sent** — every fill request (auto-triggered or via `refresh()`) always sends every
420
+ field except `ignore`, regardless of `fields`. This is what lets a field be sent (and
421
+ available to a "Search" button) without auto-firing on every keystroke — see `ignore`
422
+ below.
423
+ - Omit `fields` to watch every field except `ignore` (arrays are always skipped
424
+ automatically — see `ignore`).
425
+ - A field pointing at a **plain object** (`'paginator'`) is watched leaf-by-leaf
426
+ automatically when `fields` is omitted, so `paginator.page++` triggers without `deep`.
427
+ When you list an object bare in explicit `fields`, `deep` decides whether ANY of its
428
+ nested changes trigger (`true`) or only a full reassignment of that object does
429
+ (`false`, the default) — list the specific leaf (`'paginator.page'`) instead of the
430
+ whole object for precise, `deep`-independent reactivity.
431
+ - A new trigger **aborts the previous in-flight request** (AbortController) — the last
369
432
  change wins, out-of-order responses can't overwrite fresh data.
370
- - **Debounce** (`debounce: 300`) collapses fast typing into one request.
371
- - `reset()` restores the first-response snapshot; if that actually changes watched data,
372
- the request is re-sent — reset filters, the table refreshes itself.
373
- - **A "Search" button is `model.refresh()`** — it re-sends the request with the current
374
- watched values (and cancels a pending debounce). `model.reload()` is different: it
375
- re-runs the ORIGINAL fill request without the watch payload, i.e. it resets the view.
376
- - **Watch server-owned fields precisely**: `['filters', 'paginator.page']`, not
377
- `['paginator']` — a watched path is preserved from responses, so watching the whole
378
- `paginator` would freeze `paginator.total` at its first value.
379
- - Created inside `setup()`, the watcher is bound to the component scope and stops on
380
- unmount. Module-level models live until `model.unwatch()`.
433
+ - `reset()` restores the first-response snapshot; if that actually changes a watched
434
+ field, the request is re-sent — reset filters, the table refreshes itself.
435
+
436
+ ### `ignore` — never sent, never watched by default
437
+
438
+ ```ts
439
+ apix.getForm(url, {
440
+ ignore: ['items'], // response-only data: never sent, never auto-watched
441
+ watch: true,
442
+ });
443
+ ```
444
+
445
+ - Fields in `ignore` are **never sent** by a watch-triggered request or `refresh()`, no
446
+ matter what. Use it for response-only data (a fetched list, pagination `total`/`meta`
447
+ you don't want echoed back).
448
+ - When `watch.fields` is **omitted**, `ignore` also removes the field from the default
449
+ "watch everything" set. Arrays are excluded from that default set automatically, even
450
+ without `ignore` — an accidentally un-ignored fetched list would otherwise get
451
+ serialized into the query string on every request.
452
+ - A field listed in **both** `ignore` and `watch.fields` still triggers (fields wins for
453
+ triggering) but is still never sent (ignore always wins for sending) — a rare but
454
+ supported combination.
455
+
456
+ ### `lock` — protect a field from being overwritten by the response
457
+
458
+ By default a fill response **fully overwrites** the model (merged with `default()` for
459
+ anything the response didn't return, exactly like any other fill — see "Responses are
460
+ merged over `default()`" above). Nothing about a field being watched or sent protects it
461
+ from this. `lock` is the explicit opt-in when that's not what you want:
462
+
463
+ ```ts
464
+ apix.getForm(url, {
465
+ lock: ['trackingNumber'], // this field's local value survives every response
466
+ watch: { fields: ['filters'], debounce: 300 }, // doesn't auto-fire on trackingNumber
467
+ });
468
+ ```
469
+
470
+ This is the fix for a field the user is typing into that the backend doesn't echo back:
471
+ without `lock`, the very next watch-triggered request (fired by some *other* field
472
+ changing) would merge `trackingNumber` back to its `default()` value mid-edit. `lock` only
473
+ affects watch-triggered and `refresh()`-triggered fills — the very first load is
474
+ unaffected (there's nothing local to protect yet), and `reset()` is unaffected too (it's
475
+ an explicit, direct action, not a server response).
476
+
477
+ ### `refresh()` — the "Search" button
478
+
479
+ ```ts
480
+ model.refresh();
481
+ // or, for this one call only (not persisted, not merged into future calls):
482
+ model.refresh({ ignore: ['paginator.page'], lock: ['trackingNumber'] });
483
+ ```
484
+
485
+ - Sends every field except `ignore` (same rule as a watch-triggered request), applies
486
+ `lock`, and cancels a pending debounce.
487
+ - `options.ignore`/`options.lock` **extend** the form-level lists for this call only —
488
+ handy for "Search resets to page 1": omit `paginator.page` for just this click so the
489
+ server defaults to page 1, without changing the form's permanent configuration.
490
+ - `model.reload()` is different: it re-runs the *original* fill request with no
491
+ field-derived payload at all — it resets the view rather than searching with the
492
+ current state.
493
+ - Without `watch` configured, `refresh()` simply behaves like `reload()`.
494
+
495
+ ### Cleanup — no `unwatch()` needed inside a component
496
+
497
+ Vue automatically stops a `watch()` effect created synchronously inside a component's
498
+ `setup()` (which is exactly when `apix.getForm(...)` runs in `<script setup>`) once that
499
+ component unmounts — no manual cleanup call exists or is needed. This only matters if you
500
+ create a `watch`-enabled model **outside** any component (e.g. a module-level store shared
501
+ across the whole app) — there it lives for as long as the module does, by design.
381
502
 
382
503
  ### Live search (minimal)
383
504
 
@@ -387,13 +508,12 @@ interface SearchDto {
387
508
  query: string | null;
388
509
  }
389
510
 
390
- const search = apix
391
- .getForm<SearchDto>('/api/search', {
392
- default: () => ({ results: [], query: null }),
393
- // don't hit the API until the user types something
394
- immediate: false,
395
- })
396
- .watch(['query'], { debounce: 400 });
511
+ const search = apix.getForm<SearchDto>('/api/search', {
512
+ default: () => ({ results: [], query: null }),
513
+ // don't hit the API until the user types something
514
+ immediate: false,
515
+ watch: { fields: ['query'], debounce: 400 },
516
+ });
397
517
 
398
518
  // template: <input v-model="search.query" /> — that's the whole feature
399
519
  ```
@@ -430,9 +550,9 @@ When the API shape is awkward (nested, legacy), unwrap it into a comfortable mod
430
550
  shape and wrap it back on submit:
431
551
 
432
552
  ```ts
433
- // server shape: {attr: {name: {value: 'x'}}} ↔ model shape: {name: 'x'}
553
+ // response: {data: {item: {attr: {name: {value: 'x'}}}}} ↔ model shape: {name: 'x'}
434
554
  const model = apix
435
- .getForm<{ name: string | null }>('/api/attribute/1', 'item')
555
+ .getForm<{ name: string | null }>('/api/attribute/1', 'data.item')
436
556
  .transformResponse((data) => ({ name: data?.attr?.name?.value ?? null }))
437
557
  .transformRequest((data) => ({ attr: { name: { value: data.name } } }));
438
558
 
@@ -453,15 +573,15 @@ model.put();
453
573
  ## TypeScript
454
574
 
455
575
  ```ts
456
- const model = apix.getForm<AttrDto>('/api/attribute/1', 'item');
576
+ const model = apix.getForm<AttrDto>('/api/attribute/1', 'data.item');
457
577
 
458
- // typed via magic props: Model<AttrDto> = ApixModel<AttrDto> & AttrDto
578
+ // typed via magic props: ApixModel<AttrDto> = ApixFormModel<AttrDto> & AttrDto
459
579
  model.name;
460
580
 
461
581
  // full escape hatch
462
582
  model.data?.description;
463
583
 
464
- const list = apix.getForm<ItemDto[]>('/api/attribute', 'items');
584
+ const list = apix.getForm<ItemDto[]>('/api/attribute', 'data.items');
465
585
 
466
586
  // arrays: no magic props, iterate .data directly
467
587
  list.data?.map((item) => item.name);
package/dist/apix.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ApixConfig, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, Model, ProcessingHook, RequestOptions } from './types';
1
+ import { ApixConfig, ApixModel, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, ProcessingHook, RequestOptions } from './types';
2
2
  export declare class Apix {
3
3
  private baseUrl;
4
4
  private headers;
@@ -34,11 +34,11 @@ export declare class Apix {
34
34
  /** DELETE with an optional body. */
35
35
  delete<T = any>(url: string, data?: unknown, options?: RequestOptions): Promise<T>;
36
36
  /** Create a form model without any request (like Inertia's useForm). */
37
- form<T extends object>(defaults: T | (() => T), options?: Omit<FormOptions<T>, 'default'>): Model<T>;
37
+ form<T extends object>(defaults: T | (() => T), options?: Omit<FormOptions<T>, 'default'>): ApixModel<T>;
38
38
  /** Create a form model and fill it with a GET request. */
39
- getForm<T = any>(url: string, pathOrOptions?: string | FormOptions<T>): Model<T>;
39
+ getForm<T = any>(url: string, options?: string | FormOptions<T>): ApixModel<T>;
40
40
  /** Same as getForm, but the fill request is a POST (complex search endpoints etc.). */
41
- postForm<T = any>(url: string, pathOrOptions?: string | FormOptions<T>): Model<T>;
41
+ postForm<T = any>(url: string, options?: string | FormOptions<T>): ApixModel<T>;
42
42
  private createFormModel;
43
43
  private trackStart;
44
44
  private trackEnd;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  export { Apix, createApix } from './apix';
2
2
  export { ApixError } from './client';
3
- export { ApixModel } from './model';
4
- export type { ApixConfig, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, MagicData, Model, ProcessingHook, RequestContext, RequestOptions, SubmitOptions, WatchOptions, } from './types';
3
+ /** The underlying model class (advanced use, e.g. `instanceof` checks). Prefer the `ApixModel<T>` type for annotations. */
4
+ export { ApixFormModel } from './model';
5
+ export type { ApixConfig, ApixModel, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, MagicData, ProcessingHook, RefreshOptions, RequestContext, RequestOptions, SubmitOptions, WatchConfig, } from './types';
5
6
  /** Shared default instance — configure it once (e.g. in your api.ts) and import everywhere. */
6
7
  export declare const apix: import('./apix').Apix;
7
8
  export default apix;
package/dist/model.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Apix } from './apix';
2
- import { FillSource, FormOptions, Model, SubmitOptions, WatchOptions } from './types';
2
+ import { ApixModel, FillSource, FormOptions, RefreshOptions, SubmitOptions } from './types';
3
3
  interface ModelState {
4
4
  data: any;
5
5
  errors: Record<string, string>;
@@ -14,21 +14,23 @@ interface ModelState {
14
14
  * Reserved members (always win over data keys, use `model.data.<key>` for those):
15
15
  * data, errors, message, processing, hasErrors, isDirty,
16
16
  * get, error, setData, setErrors, clearErrors, reset,
17
- * post, put, patch, delete, reload, refresh, watch, unwatch,
17
+ * post, put, patch, delete, reload, refresh,
18
18
  * transformRequest, transformResponse.
19
19
  */
20
- export declare class ApixModel<T = any> {
20
+ export declare class ApixFormModel<T = any> {
21
21
  /** @internal */ _apix: Apix;
22
22
  /** @internal */ _options: FormOptions<T>;
23
23
  /** @internal */ _state: ModelState;
24
24
  /** @internal */ _source: FillSource | null;
25
25
  /** @internal */ _snapshot: any;
26
26
  /** @internal */ _snapshotLocked: boolean;
27
- /** @internal */ _proxy: Model<T>;
28
- /** @internal */ _stopWatch: (() => void) | null;
27
+ /** @internal */ _proxy: ApixModel<T>;
28
+ /** @internal */ _ignore: string[];
29
+ /** @internal */ _lock: string[];
30
+ /** @internal */ _triggerFields: string[] | null;
31
+ /** @internal */ _sendFields: string[] | null;
32
+ /** @internal */ _debounce: number;
29
33
  /** @internal */ _debounceTimer: ReturnType<typeof setTimeout> | null;
30
- /** @internal */ _watched: string[] | null;
31
- /** @internal */ _watchOptions: WatchOptions;
32
34
  /** @internal */ _lastSent: string | null;
33
35
  /** @internal */ _fillAbort: AbortController | null;
34
36
  /** @internal */ _transformResponse: ((data: any, response: any) => any) | null;
@@ -50,56 +52,49 @@ export declare class ApixModel<T = any> {
50
52
  */
51
53
  get(path: string): any;
52
54
  /** Replace data entirely (object or array). A detached clone is stored. */
53
- setData(data: T): Model<T>;
55
+ setData(data: T): ApixModel<T>;
54
56
  /**
55
57
  * First error for the key. Falls back to the first `key.*` sub-error,
56
58
  * so `error('name')` also surfaces `name.en.label` messages.
57
59
  */
58
60
  error(key: string): string | undefined;
59
- setErrors(errors: Record<string, string | string[]>): Model<T>;
61
+ setErrors(errors: Record<string, string | string[]>): ApixModel<T>;
60
62
  /** Clear all errors, or only the given keys (including their `key.*` sub-errors). */
61
- clearErrors(keys?: string[]): Model<T>;
63
+ clearErrors(keys?: string[]): ApixModel<T>;
62
64
  /**
63
65
  * Restore data to the snapshot: the first server response, or `default()`
64
66
  * if nothing was loaded yet. Pass keys to reset only those dot-paths.
65
- * An active watch() reacts to the change as usual (the request is re-sent).
67
+ * An active `watch` reacts to the change as usual (the request is re-sent).
66
68
  */
67
- reset(keys?: string | string[]): Model<T>;
69
+ reset(keys?: string | string[]): ApixModel<T>;
68
70
  post(url?: string, options?: SubmitOptions): Promise<any>;
69
71
  put(url?: string, options?: SubmitOptions): Promise<any>;
70
72
  patch(url?: string, options?: SubmitOptions): Promise<any>;
71
73
  delete(url?: string, options?: SubmitOptions): Promise<any>;
72
- /** Re-run the fill request (or set a new source URL and run it). */
74
+ /** Re-run the fill request (or set a new source URL and run it). Resets the view — no ignore/lock applied. */
73
75
  reload(url?: string): Promise<any>;
74
76
  /**
75
- * Re-send the fill request with the CURRENT state — a manual watch trigger
76
- * (a "Search" button next to filters). Sends the watched paths as payload and
77
- * preserves them in the response, exactly like a watch-triggered request; any
78
- * pending debounce is cancelled. Without an active watch() it equals reload().
77
+ * Re-send the fill request with the CURRENT state — a manual trigger for a
78
+ * "Search" button. Sends every watched field except `ignore`, and protects
79
+ * `lock` fields from being overwritten by the response, exactly like an
80
+ * auto watch-triggered request; any pending debounce is cancelled.
81
+ * `options.ignore`/`options.lock` extend the form-level lists for this one
82
+ * call only. Without `watch` configured, this equals `reload()`.
79
83
  */
80
- refresh(): Promise<any>;
84
+ refresh(options?: RefreshOptions): Promise<any>;
81
85
  /**
82
86
  * Map server data into the model shape. Runs on every fill (initial, reload,
83
87
  * watch) AFTER path extraction and BEFORE the reactive data is touched — so it
84
88
  * never causes a false watch trigger. The snapshot for reset() stores the
85
89
  * transformed shape. Return the new data (or mutate in place and return nothing).
86
90
  */
87
- transformResponse(transformer: ((data: any, response: any) => any) | null): Model<T>;
91
+ transformResponse(transformer: ((data: any, response: any) => any) | null): ApixModel<T>;
88
92
  /**
89
93
  * Map model data back into the server shape. Runs on the payload of
90
94
  * post/put/patch/delete (unless an explicit `data` option is passed) and on
91
95
  * watch payloads. Receives a detached clone — mutations never touch the model.
92
96
  */
93
- transformRequest(transformer: ((data: any) => any) | null): Model<T>;
94
- /**
95
- * Re-send the fill request whenever data changes.
96
- * `paths` limits both what is observed and what is sent
97
- * (GET → PHP-style query params, POST → JSON body).
98
- * The response updates everything except the watched paths (see WatchOptions).
99
- * A new trigger aborts the previous in-flight watch request.
100
- */
101
- watch(paths?: string[] | WatchOptions, options?: WatchOptions): Model<T>;
102
- unwatch(): Model<T>;
97
+ transformRequest(transformer: ((data: any) => any) | null): ApixModel<T>;
103
98
  /** @internal */
104
99
  _fill(extra?: {
105
100
  params?: Record<string, unknown>;
@@ -109,13 +104,15 @@ export declare class ApixModel<T = any> {
109
104
  private _applyFill;
110
105
  private _applyError;
111
106
  private _submit;
107
+ /** @internal Configures auto-refetch-on-change, once, at construction time. */
108
+ private _setupWatch;
112
109
  private _onWatchTrigger;
113
110
  private _sendWatchRequest;
114
- /** Build the fill() extra for a watch-shaped request from the current state. */
115
- private _watchExtra;
111
+ /** Build the fill() extra for a watch/refresh request from the current state. */
112
+ private _buildFillExtra;
116
113
  private _payloadJson;
117
114
  private _syncLastSent;
118
115
  }
119
116
  /** @internal Factory: wraps the model in the magic Proxy and fires the initial fill. */
120
- export declare function createModel<T>(apix: Apix, options?: FormOptions<T>, source?: FillSource | null): Model<T>;
117
+ export declare function createModel<T>(apix: Apix, options?: FormOptions<T>, source?: FillSource | null): ApixModel<T>;
121
118
  export {};
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ApixModel } from './model';
1
+ import { ApixFormModel } from './model';
2
2
  /** Header value: a plain string or a lazy callback resolved on every request. */
3
3
  export type HeaderValue = string | null | undefined | (() => string | null | undefined);
4
4
  export interface ApixConfig {
@@ -41,9 +41,12 @@ export type ErrorHook = (error: unknown, context: RequestContext) => Error | voi
41
41
  export type BodyTransformer = (body: any, context: RequestContext) => any;
42
42
  export interface FormOptions<T = any> {
43
43
  /**
44
- * Dot-path to the payload inside the response. Resolved against `body.data`
45
- * when it exists, otherwise against the body itself.
46
- * No path → `body.data ?? body`.
44
+ * Dot-path to the payload, resolved against the RAW response body — there is
45
+ * no implicit `body.data` unwrapping. Include `data` yourself when the API
46
+ * wraps its payload: `path: 'data.item'` for `{data: {item: {...}}}`,
47
+ * `path: 'data'` for a paginated collection. No path → the whole body, so a
48
+ * Laravel paginator's `links`/`meta` (`{data: [...], links, meta}`) are
49
+ * always reachable, e.g. via `model.data.meta`.
47
50
  */
48
51
  path?: string;
49
52
  /** Factory for the initial data used while the request is in flight (and as reset() fallback). */
@@ -63,27 +66,61 @@ export interface FormOptions<T = any> {
63
66
  /** Body for `postForm` fill requests. */
64
67
  data?: unknown;
65
68
  /** Called after every successful fill request (initial, reload(), watch-triggered). */
66
- onSuccess?: (response: any, model: Model<T>) => void;
69
+ onSuccess?: (response: any, model: ApixModel<T>) => void;
67
70
  /** Called after every failed fill request. Aborted (superseded) requests are ignored. */
68
- onError?: (error: unknown, model: Model<T>) => void;
71
+ onError?: (error: unknown, model: ApixModel<T>) => void;
69
72
  /** See model.transformResponse(). */
70
73
  transformResponse?: (data: any, response: any) => any;
71
74
  /** See model.transformRequest(). */
72
75
  transformRequest?: (data: any) => any;
76
+ /**
77
+ * Dot-paths NEVER sent to the server (by a watch trigger or `refresh()`) and,
78
+ * when `watch.fields` is omitted, never auto-watched either — for
79
+ * response-only data like a fetched list (`ignore: ['items']`). Arrays are
80
+ * already excluded from the default watch set automatically; `ignore` is
81
+ * mainly for fields you still want reachable but never round-tripped.
82
+ * A path explicitly listed in `watch.fields` still triggers even if it's
83
+ * also in `ignore` — it's simply left out of what gets sent.
84
+ */
85
+ ignore?: string[];
86
+ /**
87
+ * Dot-paths whose local value a watch/`refresh()` response may NEVER
88
+ * overwrite (the very first fill is unaffected — there's nothing to protect
89
+ * yet). Use this for a field the user is actively editing that the backend
90
+ * doesn't echo back, so it never gets reset to `default()` mid-edit.
91
+ */
92
+ lock?: string[];
93
+ /**
94
+ * Auto re-fetch when data changes. `true` = watch everything except
95
+ * `ignore`, no debounce. Or configure explicitly — see WatchConfig.
96
+ */
97
+ watch?: boolean | WatchConfig;
73
98
  }
74
- export interface WatchOptions {
75
- /** Deep-watch the observed paths (default: true). */
76
- deep?: boolean;
99
+ export interface WatchConfig {
100
+ /**
101
+ * Dot-paths that trigger a re-fetch when changed. Omit to watch every field
102
+ * except `ignore` (arrays excluded automatically). A path pointing at a
103
+ * plain object is watched leaf-by-leaf automatically — `'pagination'`
104
+ * behaves like listing each of its properties — so nested changes
105
+ * (`pagination.page++`) are caught without `deep`. `deep` only matters for
106
+ * an explicitly listed object path when you want ANY of its nested changes
107
+ * to trigger without enumerating each leaf yourself.
108
+ */
109
+ fields?: string[];
77
110
  /** Debounce in milliseconds before sending the request (default: 0). */
78
111
  debounce?: number;
79
112
  /**
80
- * By default the response updates everything EXCEPT the watched paths,
81
- * so user input is never clobbered by a stale response.
82
- * Set true to let the response overwrite watched paths too.
113
+ * Deep-watch object paths explicitly listed in `fields` (default: false).
114
+ * Irrelevant to the default (fields omitted) case, which is always
115
+ * leaf-precise regardless of this flag.
83
116
  */
84
- refreshWatched?: boolean;
85
- /** Dot-paths of `data` to send instead of the watched paths. */
86
- payload?: string[];
117
+ deep?: boolean;
118
+ }
119
+ export interface RefreshOptions {
120
+ /** Merged with the form-level `ignore` for this call only (not persisted). */
121
+ ignore?: string[];
122
+ /** Merged with the form-level `lock` for this call only (not persisted). */
123
+ lock?: string[];
87
124
  }
88
125
  export interface SubmitOptions {
89
126
  /** Explicit body; overrides model data. */
@@ -104,5 +141,6 @@ export interface FillSource {
104
141
  * model member — those stay reachable via `model.data.<key>`.
105
142
  * Arrays get no magic props — iterate `model.data` directly.
106
143
  */
107
- export type MagicData<T> = T extends readonly unknown[] ? {} : T extends object ? Omit<T, keyof ApixModel> : {};
108
- export type Model<T = any> = ApixModel<T> & MagicData<T>;
144
+ export type MagicData<T> = T extends readonly unknown[] ? {} : T extends object ? Omit<T, keyof ApixFormModel> : {};
145
+ /** Public type of a vue-apix model: `apix.form()` / `apix.getForm()` / `apix.postForm()` all return this. */
146
+ export type ApixModel<T = any> = ApixFormModel<T> & MagicData<T>;
package/dist/utils.d.ts CHANGED
@@ -22,9 +22,25 @@ export declare function pick(source: any, paths: string[]): any;
22
22
  /** Laravel sends `{field: [messages]}`; keep the first message per field. */
23
23
  export declare function flattenErrors(errors: Record<string, unknown>): Record<string, string>;
24
24
  export declare function extractMessage(body: unknown): string | null;
25
+ /** True when `path` is exactly ignored, or nested inside an ignored (whole-object) path. */
26
+ export declare function isIgnoredPath(path: string, ignore: string[]): boolean;
27
+ /**
28
+ * Recursively expand `value` (typically a form's `default()` shape) into leaf
29
+ * dot-paths: nested plain objects are walked into their own properties, so a
30
+ * bare object field is watched/sent leaf-by-leaf without needing `deep`.
31
+ * Arrays are never auto-included (watching/sending a whole array by default
32
+ * is rarely useful and an easy mistake to forget excluding) — list them in
33
+ * `watch.fields` explicitly if you really need to. A path matched by
34
+ * `ignore` (exact match or as a parent prefix) is skipped entirely.
35
+ */
36
+ export declare function collectLeafPaths(value: any, ignore: string[], prefix?: string): string[];
25
37
  /**
26
38
  * Pull the payload out of a response body.
27
- * Root is `body.data` when present (Laravel resources), otherwise the body itself;
28
- * `path` is a dot-path inside that root.
39
+ *
40
+ * There is no implicit `body.data` unwrapping — `path` is a dot-path against
41
+ * the RAW body, and you include `data` in it yourself when the API wraps its
42
+ * payload: `path: 'data.item'` for `{data: {item: {...}}}`, `path: 'data'` for
43
+ * a paginated collection. Without a `path`, the whole body is returned as-is,
44
+ * so a Laravel paginator's `links`/`meta` are never silently dropped.
29
45
  */
30
46
  export declare function extractData(body: any, path?: string): any;
package/dist/vue-apix.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const d=require("vue");function c(i){const t=d.toRaw(i);if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(s=>c(s));if(t instanceof Date)return new Date(t.getTime());const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const s={};for(const r of Object.keys(t))s[r]=c(t[r]);return s}return t}function b(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function A(i,t){if(!b(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!b(i))return i;for(const e of Object.keys(t))i[e]=e in i?A(i[e],t[e]):c(t[e]);return i}function f(i,t){if(i==null)return;let e=i;for(const s of t.split(".")){if(e==null)return;e=e[s]}return e}function m(i,t,e){const s=t.split(".");let r=i;for(let o=0;o<s.length-1;o++){const a=s[o];(r[a]===null||typeof r[a]!="object")&&(r[a]={}),r=r[a]}r[s[s.length-1]]=e}function w(i,t){const e={};for(const s of t){const r=f(i,s);r!==void 0&&m(e,s,c(r))}return e}function x(i){const t={};for(const[e,s]of Object.entries(i??{}))s!=null&&(t[e]=Array.isArray(s)?String(s[0]):String(s));return t}function _(i){return i&&typeof i=="object"&&typeof i.message=="string"?i.message:null}function T(i,t){const e=i&&typeof i=="object"&&!Array.isArray(i)&&"data"in i?i.data:i;return t?f(e,t):e}class y extends Error{constructor(t,e,s){super(_(e)??`Request failed with status ${t}`),this.name="ApixError",this.status=t,this.body=e,this.response=s,this.errors=e&&typeof e=="object"&&e.errors&&typeof e.errors=="object"?e.errors:{}}get isValidationError(){return this.status>=400&&this.status<500&&Object.keys(this.errors).length>0}}function E(i){return i instanceof Error&&i.name==="AbortError"}function S(i){const t=[],e=(r,o)=>{t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`)},s=(r,o)=>{if(r!=null){if(typeof r=="boolean")return e(o,r?"1":"0");if(r instanceof Date)return e(o,r.toISOString());if(Array.isArray(r)){r.forEach((a,n)=>s(a,`${o}[${n}]`));return}if(typeof r=="object"){for(const[a,n]of Object.entries(r))s(n,`${o}[${a}]`);return}e(o,String(r))}};for(const[r,o]of Object.entries(i))s(o,r);return t.join("&")}async function k(i){if(i.status===204)return null;const t=await i.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}class R{constructor(t,e={},s=null){this._snapshot=null,this._snapshotLocked=!1,this._stopWatch=null,this._debounceTimer=null,this._watched=null,this._watchOptions={},this._lastSent=null,this._fillAbort=null,this._transformResponse=null,this._transformRequest=null,this._apix=t,this._options=e,this._source=s,this._transformResponse=e.transformResponse??null,this._transformRequest=e.transformRequest??null;const r=e.default?e.default():null;this._state=d.reactive({data:r,errors:{},message:null,processing:!1}),this._snapshot=c(r)}get data(){return this._state.data}set data(t){this._state.data=t}get errors(){return this._state.errors}get message(){return this._state.message}get processing(){return this._state.processing}get hasErrors(){return Object.keys(this._state.errors).length>0}get isDirty(){return JSON.stringify(this._state.data)!==JSON.stringify(this._snapshot)}get(t){return c(f(this._state.data,t))}setData(t){return this._state.data=c(t),this._proxy}error(t){const e=this._state.errors;if(e[t]!==void 0)return e[t];const s=`${t}.`;for(const r of Object.keys(e))if(r.startsWith(s))return e[r]}setErrors(t){return this._state.errors=x(t),this._proxy}clearErrors(t){if(!t)return this._state.errors={},this._proxy;for(const e of t){const s=`${e}.`;for(const r of Object.keys(this._state.errors))(r===e||r.startsWith(s))&&delete this._state.errors[r]}return this._proxy}reset(t){if(t===void 0||Array.isArray(t)&&t.length===0)return this._state.data=c(this._snapshot),this._state.errors={},this._state.message=null,this._proxy;const e=Array.isArray(t)?t:[t];if(this._state.data&&typeof this._state.data=="object")for(const s of e)m(this._state.data,s,c(f(this._snapshot,s)));return this.clearErrors(e),this._proxy}post(t,e){return this._submit("post",t,e)}put(t,e){return this._submit("put",t,e)}patch(t,e){return this._submit("patch",t,e)}delete(t,e){return this._submit("delete",t,e)}reload(t){var e;return t&&(this._source={url:t,method:((e=this._source)==null?void 0:e.method)??"get"}),this._source?this._fill():Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."))}refresh(){return this._source?this._stopWatch?(this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._lastSent=this._payloadJson(),this._fill(this._watchExtra())):this._fill():Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."))}transformResponse(t){return this._transformResponse=t,this._proxy}transformRequest(t){return this._transformRequest=t,this._proxy}watch(t,e){let s=null,r;Array.isArray(t)?(s=t,r=e??{}):r=t??e??{},this._source||console.warn("[vue-apix] model.watch() has no effect until the model has a source URL (getForm/postForm/reload)."),this.unwatch(),this._watched=s,this._watchOptions=r,this._syncLastSent();const o=s&&s.length?s.map(a=>()=>f(this._state.data,a)):()=>this._state.data;return this._stopWatch=d.watch(o,()=>this._onWatchTrigger(),{deep:r.deep??!0}),this._proxy}unwatch(){var t;return(t=this._stopWatch)==null||t.call(this),this._stopWatch=null,this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._proxy}async _fill(t={}){var o,a,n,h,u;const e=this._source;(o=this._fillAbort)==null||o.abort();const s=new AbortController;this._fillAbort=s,this._state.processing=!0;const r={signal:s.signal};e.method==="get"?r.params={...this._options.params,...t.params}:(r.params=this._options.params,r.data=t.data!==void 0?t.data:this._options.data);try{const l=await this._apix.request(e.method,e.url,r);let p=T(l,this._options.path);if(this._transformResponse){const g=c(p);p=this._transformResponse(g,l)??g}return this._applyFill(p,t.preserve??null),this._state.message=_(l),this._state.errors={},(n=(a=this._options).onSuccess)==null||n.call(a,l,this._proxy),l}catch(l){throw E(l)||(this._applyError(l),(u=(h=this._options).onError)==null||u.call(h,l,this._proxy)),l}finally{this._fillAbort===s&&(this._fillAbort=null,this._state.processing=!1)}}_applyFill(t,e){let s=c(t);this._options.mergeDefaults!==!1&&this._options.default&&(s=A(s,this._options.default()));const r=this._snapshotLocked?null:c(s);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const o of e){const a=f(this._state.data,o);a!==void 0&&m(s,o,c(a))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof y&&(this._state.message=_(t.body)??t.message,t.isValidationError&&(this._state.errors=x(t.errors)))}async _submit(t,e,s={}){var a;const r=e??((a=this._source)==null?void 0:a.url);if(!r)throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);let o=s.data!==void 0?s.data:s.only?w(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&o!==void 0){const n=c(o);o=this._transformRequest(n)??n}this._state.processing=!0,this._state.errors={},this._state.message=null;try{const n=await this._apix.request(t,r,{data:o,params:s.params,headers:s.headers});return this._state.message=_(n),n}catch(n){throw this._applyError(n),n}finally{this._state.processing=!1}}_onWatchTrigger(){if(this._payloadJson()===this._lastSent)return;this._debounceTimer&&clearTimeout(this._debounceTimer);const t=this._watchOptions.debounce??0;t>0?this._debounceTimer=setTimeout(()=>this._sendWatchRequest(),t):this._sendWatchRequest()}_sendWatchRequest(){this._debounceTimer=null,this._source&&(this._lastSent=this._payloadJson(),this._fill(this._watchExtra()).catch(()=>{}))}_watchExtra(){const t=this._watched,e=this._watchOptions.payload??t;let s=e&&e.length?w(this._state.data,e):c(this._state.data);this._transformRequest&&(s=this._transformRequest(s)??s);const r=this._watchOptions.refreshWatched?null:t;return this._source.method==="get"?{params:s,preserve:r}:{data:s,preserve:r}}_payloadJson(){const t=this._watched,e=t&&t.length?t.map(s=>f(this._state.data,s)):this._state.data;return JSON.stringify(e)??"undefined"}_syncLastSent(){this._lastSent=this._payloadJson()}}function j(i,t={},e=null){const s=new R(i,t,e),r=new Proxy(s,{get(o,a){if(typeof a=="symbol"||a in o)return Reflect.get(o,a);const n=o._state.data;if(n&&typeof n=="object")return n[a]},set(o,a,n){if(typeof a=="symbol"||a in o)return Reflect.set(o,a,n);const h=o._state.data;return h&&typeof h=="object"?(h[a]=n,!0):(o._state.data={[a]:n},!0)},has(o,a){if(a in o)return!0;const n=o._state.data;return!!n&&typeof n=="object"&&a in n}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().catch(()=>{}),r}class v{constructor(t={}){this.baseUrl="",this.headers={},this.processingHooks=[],this.errorHooks=[],this.bodyTransformer=null,this.active=0,t.baseUrl&&this.setBaseUrl(t.baseUrl),t.headers&&this.setHeader(t.headers),t.credentials&&(this.credentials=t.credentials)}setBaseUrl(t){return this.baseUrl=t.replace(/\/+$/,""),this}setHeader(t){return Object.assign(this.headers,t),this}setCredentials(t){return this.credentials=t,this}onProcessing(t){return this.processingHooks.push(t),()=>{this.processingHooks=this.processingHooks.filter(e=>e!==t)}}onError(t){return this.errorHooks.push(t),()=>{this.errorHooks=this.errorHooks.filter(e=>e!==t)}}transformResponse(t){return this.bodyTransformer=t,this}async request(t,e,s={}){let r=/^https?:\/\//i.test(e)?e:this.baseUrl+e;if(s.params){const h=S(s.params);h&&(r+=(r.includes("?")?"&":"?")+h)}const o={accept:"application/json","x-requested-with":"XMLHttpRequest"};for(const[h,u]of Object.entries(this.headers)){const l=typeof u=="function"?u():u;l!=null&&(o[h.toLowerCase()]=l)}for(const[h,u]of Object.entries(s.headers??{}))o[h.toLowerCase()]=u;const a={method:t.toUpperCase(),headers:o,signal:s.signal};this.credentials&&(a.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?(delete o["content-type"],a.body=s.data):(o["content-type"]??(o["content-type"]="application/json"),a.body=JSON.stringify(s.data)));const n={method:t,url:r,options:s};this.trackStart();try{const h=await fetch(r,a);let u=await k(h);if(this.bodyTransformer&&(u=this.bodyTransformer(u,n)??u),!h.ok)throw new y(h.status,u,h);return u}catch(h){throw E(h)?h:this.emitError(h,n)}finally{this.trackEnd()}}get(t,e,s={}){return this.request("get",t,e?{...s,params:e}:s)}post(t,e,s={}){return this.request("post",t,e!==void 0?{...s,data:e}:s)}put(t,e,s={}){return this.request("put",t,e!==void 0?{...s,data:e}:s)}patch(t,e,s={}){return this.request("patch",t,e!==void 0?{...s,data:e}:s)}delete(t,e,s={}){return this.request("delete",t,e!==void 0?{...s,data:e}:s)}form(t,e={}){return j(this,{...e,default:typeof t=="function"?t:()=>c(t)})}getForm(t,e){return this.createFormModel("get",t,e)}postForm(t,e){return this.createFormModel("post",t,e)}createFormModel(t,e,s){const r=typeof s=="string"?{path:s}:{...s??{}};return j(this,r,{url:e,method:t})}trackStart(){++this.active===1&&this.emitProcessing(!0)}trackEnd(){--this.active===0&&this.emitProcessing(!1)}emitProcessing(t){for(const e of this.processingHooks)try{e(t)}catch{}}emitError(t,e){let s=t;for(const r of this.errorHooks)try{const o=r(s,e);o instanceof Error&&(s=o)}catch{}return s}}function O(i={}){return new v(i)}const q=O();exports.Apix=v;exports.ApixError=y;exports.ApixModel=R;exports.apix=q;exports.createApix=O;exports.default=q;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const p=require("vue");function c(i){const t=p.toRaw(i);if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(s=>c(s));if(t instanceof Date)return new Date(t.getTime());const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const s={};for(const r of Object.keys(t))s[r]=c(t[r]);return s}return t}function m(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function E(i,t){if(!m(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!m(i))return i;for(const e of Object.keys(t))i[e]=e in i?E(i[e],t[e]):c(t[e]);return i}function f(i,t){if(i==null)return;let e=i;for(const s of t.split(".")){if(e==null)return;e=e[s]}return e}function y(i,t,e){const s=t.split(".");let r=i;for(let o=0;o<s.length-1;o++){const n=s[o];(r[n]===null||typeof r[n]!="object")&&(r[n]={}),r=r[n]}r[s[s.length-1]]=e}function x(i,t){const e={};for(const s of t){const r=f(i,s);r!==void 0&&y(e,s,c(r))}return e}function j(i){const t={};for(const[e,s]of Object.entries(i??{}))s!=null&&(t[e]=Array.isArray(s)?String(s[0]):String(s));return t}function d(i){return i&&typeof i=="object"&&typeof i.message=="string"?i.message:null}function R(i,t){return t.some(e=>e===i||i.startsWith(`${e}.`))}function w(i,t,e=""){if(e&&R(e,t))return[];if(m(i)){const s=[];for(const r of Object.keys(i))s.push(...w(i[r],t,e?`${e}.${r}`:r));return s}return Array.isArray(i)||!e?[]:[e]}function S(i,t){return t&&i&&typeof i=="object"?f(i,t):i}class g extends Error{constructor(t,e,s){super(d(e)??`Request failed with status ${t}`),this.name="ApixError",this.status=t,this.body=e,this.response=s,this.errors=e&&typeof e=="object"&&e.errors&&typeof e.errors=="object"?e.errors:{}}get isValidationError(){return this.status>=400&&this.status<500&&Object.keys(this.errors).length>0}}function F(i){return i instanceof Error&&i.name==="AbortError"}function T(i){const t=[],e=(r,o)=>{t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`)},s=(r,o)=>{if(r!=null){if(typeof r=="boolean")return e(o,r?"1":"0");if(r instanceof Date)return e(o,r.toISOString());if(Array.isArray(r)){r.forEach((n,a)=>s(n,`${o}[${a}]`));return}if(typeof r=="object"){for(const[n,a]of Object.entries(r))s(a,`${o}[${n}]`);return}e(o,String(r))}};for(const[r,o]of Object.entries(i))s(o,r);return t.join("&")}async function U(i){if(i.status===204)return null;const t=await i.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}class A{constructor(t,e={},s=null){this._snapshot=null,this._snapshotLocked=!1,this._ignore=[],this._lock=[],this._triggerFields=null,this._sendFields=null,this._debounce=0,this._debounceTimer=null,this._lastSent=null,this._fillAbort=null,this._transformResponse=null,this._transformRequest=null,this._apix=t,this._options=e,this._source=s,this._transformResponse=e.transformResponse??null,this._transformRequest=e.transformRequest??null;const r=e.default?e.default():null;this._state=p.reactive({data:r,errors:{},message:null,processing:!1}),this._snapshot=c(r),this._ignore=e.ignore??[],this._lock=e.lock??[],this._setupWatch(e.watch,r)}get data(){return this._state.data}set data(t){this._state.data=t}get errors(){return this._state.errors}get message(){return this._state.message}get processing(){return this._state.processing}get hasErrors(){return Object.keys(this._state.errors).length>0}get isDirty(){return JSON.stringify(this._state.data)!==JSON.stringify(this._snapshot)}get(t){return c(f(this._state.data,t))}setData(t){return this._state.data=c(t),this._proxy}error(t){const e=this._state.errors;if(e[t]!==void 0)return e[t];const s=`${t}.`;for(const r of Object.keys(e))if(r.startsWith(s))return e[r]}setErrors(t){return this._state.errors=j(t),this._proxy}clearErrors(t){if(!t)return this._state.errors={},this._proxy;for(const e of t){const s=`${e}.`;for(const r of Object.keys(this._state.errors))(r===e||r.startsWith(s))&&delete this._state.errors[r]}return this._proxy}reset(t){if(t===void 0||Array.isArray(t)&&t.length===0)return this._state.data=c(this._snapshot),this._state.errors={},this._state.message=null,this._proxy;const e=Array.isArray(t)?t:[t];if(this._state.data&&typeof this._state.data=="object")for(const s of e)y(this._state.data,s,c(f(this._snapshot,s)));return this.clearErrors(e),this._proxy}post(t,e){return this._submit("post",t,e)}put(t,e){return this._submit("put",t,e)}patch(t,e){return this._submit("patch",t,e)}delete(t,e){return this._submit("delete",t,e)}reload(t){var e;return t&&(this._source={url:t,method:((e=this._source)==null?void 0:e.method)??"get"}),this._source?this._fill():Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."))}refresh(t={}){if(!this._source)return Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."));if(this._triggerFields===null)return this._fill();this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null);const e=this._buildFillExtra(t);return this._lastSent=this._payloadJson(),this._fill(e)}transformResponse(t){return this._transformResponse=t,this._proxy}transformRequest(t){return this._transformRequest=t,this._proxy}async _fill(t={}){var o,n,a,h,l;const e=this._source;(o=this._fillAbort)==null||o.abort();const s=new AbortController;this._fillAbort=s,this._state.processing=!0;const r={signal:s.signal};e.method==="get"?r.params={...this._options.params,...t.params}:(r.params=this._options.params,r.data=t.data!==void 0?t.data:this._options.data);try{const u=await this._apix.request(e.method,e.url,r);let _=S(u,this._options.path);if(this._transformResponse){const b=c(_);_=this._transformResponse(b,u)??b}return this._applyFill(_,t.preserve??null),this._state.message=d(u),this._state.errors={},(a=(n=this._options).onSuccess)==null||a.call(n,u,this._proxy),u}catch(u){throw F(u)||(this._applyError(u),(l=(h=this._options).onError)==null||l.call(h,u,this._proxy)),u}finally{this._fillAbort===s&&(this._fillAbort=null,this._state.processing=!1)}}_applyFill(t,e){let s=c(t);this._options.mergeDefaults!==!1&&this._options.default&&(s=E(s,this._options.default()));const r=this._snapshotLocked?null:c(s);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const o of e){const n=f(this._state.data,o);n!==void 0&&y(s,o,c(n))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof g&&(this._state.message=d(t.body)??t.message,t.isValidationError&&(this._state.errors=j(t.errors)))}async _submit(t,e,s={}){var n;const r=e??((n=this._source)==null?void 0:n.url);if(!r)throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);let o=s.data!==void 0?s.data:s.only?x(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&o!==void 0){const a=c(o);o=this._transformRequest(a)??a}this._state.processing=!0,this._state.errors={},this._state.message=null;try{const a=await this._apix.request(t,r,{data:o,params:s.params,headers:s.headers});return this._state.message=d(a),a}catch(a){throw this._applyError(a),a}finally{this._state.processing=!1}}_setupWatch(t,e){if(!t)return;if(!this._source){console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");return}const s=t===!0?{}:t,r=s.fields;this._sendFields=w(e??{},this._ignore),this._triggerFields=r??this._sendFields,this._debounce=s.debounce??0,this._syncLastSent();const o=this._triggerFields.map(a=>()=>f(this._state.data,a)),n=r?s.deep??!1:!0;p.watch(o,()=>this._onWatchTrigger(),{deep:n})}_onWatchTrigger(){this._payloadJson()!==this._lastSent&&(this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounce>0?this._debounceTimer=setTimeout(()=>this._sendWatchRequest(),this._debounce):this._sendWatchRequest())}_sendWatchRequest(){this._debounceTimer=null,this._source&&(this._lastSent=this._payloadJson(),this._fill(this._buildFillExtra()).catch(()=>{}))}_buildFillExtra(t={}){const e=t.lock?[...this._lock,...t.lock]:this._lock,s=t.ignore?(this._sendFields??[]).filter(o=>!R(o,t.ignore)):this._sendFields??[];let r=x(this._state.data,s);return this._transformRequest&&(r=this._transformRequest(r)??r),this._source.method==="get"?{params:r,preserve:e}:{data:r,preserve:e}}_payloadJson(){const e=(this._triggerFields??[]).map(s=>f(this._state.data,s));return JSON.stringify(e)??"undefined"}_syncLastSent(){this._lastSent=this._payloadJson()}}function k(i,t={},e=null){const s=new A(i,t,e),r=new Proxy(s,{get(o,n){if(typeof n=="symbol"||n in o)return Reflect.get(o,n);const a=o._state.data;if(a&&typeof a=="object")return a[n]},set(o,n,a){if(typeof n=="symbol"||n in o)return Reflect.set(o,n,a);const h=o._state.data;return h&&typeof h=="object"?(h[n]=a,!0):(o._state.data={[n]:a},!0)},has(o,n){if(n in o)return!0;const a=o._state.data;return!!a&&typeof a=="object"&&n in a}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().catch(()=>{}),r}class v{constructor(t={}){this.baseUrl="",this.headers={},this.processingHooks=[],this.errorHooks=[],this.bodyTransformer=null,this.active=0,t.baseUrl&&this.setBaseUrl(t.baseUrl),t.headers&&this.setHeader(t.headers),t.credentials&&(this.credentials=t.credentials)}setBaseUrl(t){return this.baseUrl=t.replace(/\/+$/,""),this}setHeader(t){return Object.assign(this.headers,t),this}setCredentials(t){return this.credentials=t,this}onProcessing(t){return this.processingHooks.push(t),()=>{this.processingHooks=this.processingHooks.filter(e=>e!==t)}}onError(t){return this.errorHooks.push(t),()=>{this.errorHooks=this.errorHooks.filter(e=>e!==t)}}transformResponse(t){return this.bodyTransformer=t,this}async request(t,e,s={}){let r=/^https?:\/\//i.test(e)?e:this.baseUrl+e;if(s.params){const h=T(s.params);h&&(r+=(r.includes("?")?"&":"?")+h)}const o={accept:"application/json","x-requested-with":"XMLHttpRequest"};for(const[h,l]of Object.entries(this.headers)){const u=typeof l=="function"?l():l;u!=null&&(o[h.toLowerCase()]=u)}for(const[h,l]of Object.entries(s.headers??{}))o[h.toLowerCase()]=l;const n={method:t.toUpperCase(),headers:o,signal:s.signal};this.credentials&&(n.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?(delete o["content-type"],n.body=s.data):(o["content-type"]??(o["content-type"]="application/json"),n.body=JSON.stringify(s.data)));const a={method:t,url:r,options:s};this.trackStart();try{const h=await fetch(r,n);let l=await U(h);if(this.bodyTransformer&&(l=this.bodyTransformer(l,a)??l),!h.ok)throw new g(h.status,l,h);return l}catch(h){throw F(h)?h:this.emitError(h,a)}finally{this.trackEnd()}}get(t,e,s={}){return this.request("get",t,e?{...s,params:e}:s)}post(t,e,s={}){return this.request("post",t,e!==void 0?{...s,data:e}:s)}put(t,e,s={}){return this.request("put",t,e!==void 0?{...s,data:e}:s)}patch(t,e,s={}){return this.request("patch",t,e!==void 0?{...s,data:e}:s)}delete(t,e,s={}){return this.request("delete",t,e!==void 0?{...s,data:e}:s)}form(t,e={}){return k(this,{...e,default:typeof t=="function"?t:()=>c(t)})}getForm(t,e){return this.createFormModel("get",t,e)}postForm(t,e){return this.createFormModel("post",t,e)}createFormModel(t,e,s){const r=typeof s=="string"?{path:s}:{...s??{}};return k(this,r,{url:e,method:t})}trackStart(){++this.active===1&&this.emitProcessing(!0)}trackEnd(){--this.active===0&&this.emitProcessing(!1)}emitProcessing(t){for(const e of this.processingHooks)try{e(t)}catch{}}emitError(t,e){let s=t;for(const r of this.errorHooks)try{const o=r(s,e);o instanceof Error&&(s=o)}catch{}return s}}function O(i={}){return new v(i)}const q=O();exports.Apix=v;exports.ApixError=g;exports.ApixFormModel=A;exports.apix=q;exports.createApix=O;exports.default=q;
package/dist/vue-apix.js CHANGED
@@ -1,6 +1,6 @@
1
- import { toRaw as E, reactive as v, watch as A } from "vue";
1
+ import { toRaw as F, reactive as O, watch as q } from "vue";
2
2
  function c(i) {
3
- const t = E(i);
3
+ const t = F(i);
4
4
  if (t === null || typeof t != "object") return t;
5
5
  if (Array.isArray(t)) return t.map((s) => c(s));
6
6
  if (t instanceof Date) return new Date(t.getTime());
@@ -12,16 +12,16 @@ function c(i) {
12
12
  }
13
13
  return t;
14
14
  }
15
- function y(i) {
15
+ function p(i) {
16
16
  if (i === null || typeof i != "object") return !1;
17
17
  const t = Object.getPrototypeOf(i);
18
18
  return t === Object.prototype || t === null;
19
19
  }
20
20
  function x(i, t) {
21
- if (!y(t))
21
+ if (!p(t))
22
22
  return i === void 0 ? c(t) : i;
23
23
  if (i == null) return c(t);
24
- if (!y(i)) return i;
24
+ if (!p(i)) return i;
25
25
  for (const e of Object.keys(t))
26
26
  i[e] = e in i ? x(i[e], t[e]) : c(t[e]);
27
27
  return i;
@@ -35,12 +35,12 @@ function f(i, t) {
35
35
  }
36
36
  return e;
37
37
  }
38
- function d(i, t, e) {
38
+ function m(i, t, e) {
39
39
  const s = t.split(".");
40
40
  let r = i;
41
41
  for (let o = 0; o < s.length - 1; o++) {
42
- const a = s[o];
43
- (r[a] === null || typeof r[a] != "object") && (r[a] = {}), r = r[a];
42
+ const n = s[o];
43
+ (r[n] === null || typeof r[n] != "object") && (r[n] = {}), r = r[n];
44
44
  }
45
45
  r[s[s.length - 1]] = e;
46
46
  }
@@ -48,7 +48,7 @@ function g(i, t) {
48
48
  const e = {};
49
49
  for (const s of t) {
50
50
  const r = f(i, s);
51
- r !== void 0 && d(e, s, c(r));
51
+ r !== void 0 && m(e, s, c(r));
52
52
  }
53
53
  return e;
54
54
  }
@@ -58,16 +58,28 @@ function b(i) {
58
58
  s != null && (t[e] = Array.isArray(s) ? String(s[0]) : String(s));
59
59
  return t;
60
60
  }
61
- function _(i) {
61
+ function d(i) {
62
62
  return i && typeof i == "object" && typeof i.message == "string" ? i.message : null;
63
63
  }
64
- function O(i, t) {
65
- const e = i && typeof i == "object" && !Array.isArray(i) && "data" in i ? i.data : i;
66
- return t ? f(e, t) : e;
64
+ function k(i, t) {
65
+ return t.some((e) => e === i || i.startsWith(`${e}.`));
67
66
  }
68
- class j extends Error {
67
+ function R(i, t, e = "") {
68
+ if (e && k(e, t)) return [];
69
+ if (p(i)) {
70
+ const s = [];
71
+ for (const r of Object.keys(i))
72
+ s.push(...R(i[r], t, e ? `${e}.${r}` : r));
73
+ return s;
74
+ }
75
+ return Array.isArray(i) || !e ? [] : [e];
76
+ }
77
+ function v(i, t) {
78
+ return t && i && typeof i == "object" ? f(i, t) : i;
79
+ }
80
+ class w extends Error {
69
81
  constructor(t, e, s) {
70
- super(_(e) ?? `Request failed with status ${t}`), this.name = "ApixError", this.status = t, this.body = e, this.response = s, this.errors = e && typeof e == "object" && e.errors && typeof e.errors == "object" ? e.errors : {};
82
+ super(d(e) ?? `Request failed with status ${t}`), this.name = "ApixError", this.status = t, this.body = e, this.response = s, this.errors = e && typeof e == "object" && e.errors && typeof e.errors == "object" ? e.errors : {};
71
83
  }
72
84
  /**
73
85
  * True for any 4xx response whose body carries an `errors` object
@@ -78,10 +90,10 @@ class j extends Error {
78
90
  return this.status >= 400 && this.status < 500 && Object.keys(this.errors).length > 0;
79
91
  }
80
92
  }
81
- function R(i) {
93
+ function E(i) {
82
94
  return i instanceof Error && i.name === "AbortError";
83
95
  }
84
- function q(i) {
96
+ function A(i) {
85
97
  const t = [], e = (r, o) => {
86
98
  t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`);
87
99
  }, s = (r, o) => {
@@ -89,11 +101,11 @@ function q(i) {
89
101
  if (typeof r == "boolean") return e(o, r ? "1" : "0");
90
102
  if (r instanceof Date) return e(o, r.toISOString());
91
103
  if (Array.isArray(r)) {
92
- r.forEach((a, n) => s(a, `${o}[${n}]`));
104
+ r.forEach((n, a) => s(n, `${o}[${a}]`));
93
105
  return;
94
106
  }
95
107
  if (typeof r == "object") {
96
- for (const [a, n] of Object.entries(r)) s(n, `${o}[${a}]`);
108
+ for (const [n, a] of Object.entries(r)) s(a, `${o}[${n}]`);
97
109
  return;
98
110
  }
99
111
  e(o, String(r));
@@ -102,7 +114,7 @@ function q(i) {
102
114
  for (const [r, o] of Object.entries(i)) s(o, r);
103
115
  return t.join("&");
104
116
  }
105
- async function T(i) {
117
+ async function S(i) {
106
118
  if (i.status === 204) return null;
107
119
  const t = await i.text();
108
120
  if (!t) return null;
@@ -112,11 +124,11 @@ async function T(i) {
112
124
  return t;
113
125
  }
114
126
  }
115
- class S {
127
+ class T {
116
128
  constructor(t, e = {}, s = null) {
117
- this._snapshot = null, this._snapshotLocked = !1, this._stopWatch = null, this._debounceTimer = null, this._watched = null, this._watchOptions = {}, this._lastSent = null, this._fillAbort = null, this._transformResponse = null, this._transformRequest = null, this._apix = t, this._options = e, this._source = s, this._transformResponse = e.transformResponse ?? null, this._transformRequest = e.transformRequest ?? null;
129
+ this._snapshot = null, this._snapshotLocked = !1, this._ignore = [], this._lock = [], this._triggerFields = null, this._sendFields = null, this._debounce = 0, this._debounceTimer = null, this._lastSent = null, this._fillAbort = null, this._transformResponse = null, this._transformRequest = null, this._apix = t, this._options = e, this._source = s, this._transformResponse = e.transformResponse ?? null, this._transformRequest = e.transformRequest ?? null;
118
130
  const r = e.default ? e.default() : null;
119
- this._state = v({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r);
131
+ this._state = O({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r), this._ignore = e.ignore ?? [], this._lock = e.lock ?? [], this._setupWatch(e.watch, r);
120
132
  }
121
133
  // --- reactive state ---------------------------------------------------------
122
134
  get data() {
@@ -183,7 +195,7 @@ class S {
183
195
  /**
184
196
  * Restore data to the snapshot: the first server response, or `default()`
185
197
  * if nothing was loaded yet. Pass keys to reset only those dot-paths.
186
- * An active watch() reacts to the change as usual (the request is re-sent).
198
+ * An active `watch` reacts to the change as usual (the request is re-sent).
187
199
  */
188
200
  reset(t) {
189
201
  if (t === void 0 || Array.isArray(t) && t.length === 0)
@@ -191,7 +203,7 @@ class S {
191
203
  const e = Array.isArray(t) ? t : [t];
192
204
  if (this._state.data && typeof this._state.data == "object")
193
205
  for (const s of e)
194
- d(this._state.data, s, c(f(this._snapshot, s)));
206
+ m(this._state.data, s, c(f(this._snapshot, s)));
195
207
  return this.clearErrors(e), this._proxy;
196
208
  }
197
209
  // --- HTTP ------------------------------------------------------------------------
@@ -207,7 +219,7 @@ class S {
207
219
  delete(t, e) {
208
220
  return this._submit("delete", t, e);
209
221
  }
210
- /** Re-run the fill request (or set a new source URL and run it). */
222
+ /** Re-run the fill request (or set a new source URL and run it). Resets the view — no ignore/lock applied. */
211
223
  reload(t) {
212
224
  var e;
213
225
  return t && (this._source = { url: t, method: ((e = this._source) == null ? void 0 : e.method) ?? "get" }), this._source ? this._fill() : Promise.reject(
@@ -215,15 +227,22 @@ class S {
215
227
  );
216
228
  }
217
229
  /**
218
- * Re-send the fill request with the CURRENT state — a manual watch trigger
219
- * (a "Search" button next to filters). Sends the watched paths as payload and
220
- * preserves them in the response, exactly like a watch-triggered request; any
221
- * pending debounce is cancelled. Without an active watch() it equals reload().
230
+ * Re-send the fill request with the CURRENT state — a manual trigger for a
231
+ * "Search" button. Sends every watched field except `ignore`, and protects
232
+ * `lock` fields from being overwritten by the response, exactly like an
233
+ * auto watch-triggered request; any pending debounce is cancelled.
234
+ * `options.ignore`/`options.lock` extend the form-level lists for this one
235
+ * call only. Without `watch` configured, this equals `reload()`.
222
236
  */
223
- refresh() {
224
- return this._source ? this._stopWatch ? (this._debounceTimer && (clearTimeout(this._debounceTimer), this._debounceTimer = null), this._lastSent = this._payloadJson(), this._fill(this._watchExtra())) : this._fill() : Promise.reject(
225
- new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url).")
226
- );
237
+ refresh(t = {}) {
238
+ if (!this._source)
239
+ return Promise.reject(
240
+ new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url).")
241
+ );
242
+ if (this._triggerFields === null) return this._fill();
243
+ this._debounceTimer && (clearTimeout(this._debounceTimer), this._debounceTimer = null);
244
+ const e = this._buildFillExtra(t);
245
+ return this._lastSent = this._payloadJson(), this._fill(e);
227
246
  }
228
247
  // --- transformers -------------------------------------------------------------------
229
248
  /**
@@ -243,30 +262,10 @@ class S {
243
262
  transformRequest(t) {
244
263
  return this._transformRequest = t, this._proxy;
245
264
  }
246
- // --- watch ------------------------------------------------------------------------
247
- /**
248
- * Re-send the fill request whenever data changes.
249
- * `paths` limits both what is observed and what is sent
250
- * (GET → PHP-style query params, POST → JSON body).
251
- * The response updates everything except the watched paths (see WatchOptions).
252
- * A new trigger aborts the previous in-flight watch request.
253
- */
254
- watch(t, e) {
255
- let s = null, r;
256
- Array.isArray(t) ? (s = t, r = e ?? {}) : r = t ?? e ?? {}, this._source || console.warn("[vue-apix] model.watch() has no effect until the model has a source URL (getForm/postForm/reload)."), this.unwatch(), this._watched = s, this._watchOptions = r, this._syncLastSent();
257
- const o = s && s.length ? s.map((a) => () => f(this._state.data, a)) : () => this._state.data;
258
- return this._stopWatch = A(o, () => this._onWatchTrigger(), {
259
- deep: r.deep ?? !0
260
- }), this._proxy;
261
- }
262
- unwatch() {
263
- var t;
264
- return (t = this._stopWatch) == null || t.call(this), this._stopWatch = null, this._debounceTimer && (clearTimeout(this._debounceTimer), this._debounceTimer = null), this._proxy;
265
- }
266
265
  // --- internals ----------------------------------------------------------------------
267
266
  /** @internal */
268
267
  async _fill(t = {}) {
269
- var o, a, n, h, u;
268
+ var o, n, a, h, l;
270
269
  const e = this._source;
271
270
  (o = this._fillAbort) == null || o.abort();
272
271
  const s = new AbortController();
@@ -274,15 +273,15 @@ class S {
274
273
  const r = { signal: s.signal };
275
274
  e.method === "get" ? r.params = { ...this._options.params, ...t.params } : (r.params = this._options.params, r.data = t.data !== void 0 ? t.data : this._options.data);
276
275
  try {
277
- const l = await this._apix.request(e.method, e.url, r);
278
- let p = O(l, this._options.path);
276
+ const u = await this._apix.request(e.method, e.url, r);
277
+ let _ = v(u, this._options.path);
279
278
  if (this._transformResponse) {
280
- const m = c(p);
281
- p = this._transformResponse(m, l) ?? m;
279
+ const y = c(_);
280
+ _ = this._transformResponse(y, u) ?? y;
282
281
  }
283
- return this._applyFill(p, t.preserve ?? null), this._state.message = _(l), this._state.errors = {}, (n = (a = this._options).onSuccess) == null || n.call(a, l, this._proxy), l;
284
- } catch (l) {
285
- throw R(l) || (this._applyError(l), (u = (h = this._options).onError) == null || u.call(h, l, this._proxy)), l;
282
+ return this._applyFill(_, t.preserve ?? null), this._state.message = d(u), this._state.errors = {}, (a = (n = this._options).onSuccess) == null || a.call(n, u, this._proxy), u;
283
+ } catch (u) {
284
+ throw E(u) || (this._applyError(u), (l = (h = this._options).onError) == null || l.call(h, u, this._proxy)), u;
286
285
  } finally {
287
286
  this._fillAbort === s && (this._fillAbort = null, this._state.processing = !1);
288
287
  }
@@ -293,86 +292,93 @@ class S {
293
292
  const r = this._snapshotLocked ? null : c(s);
294
293
  if (e && e.length && s && typeof s == "object" && this._state.data && typeof this._state.data == "object")
295
294
  for (const o of e) {
296
- const a = f(this._state.data, o);
297
- a !== void 0 && d(s, o, c(a));
295
+ const n = f(this._state.data, o);
296
+ n !== void 0 && m(s, o, c(n));
298
297
  }
299
298
  this._state.data = s, this._snapshotLocked || (this._snapshot = r, this._snapshotLocked = !0), this._syncLastSent();
300
299
  }
301
300
  _applyError(t) {
302
- t instanceof j && (this._state.message = _(t.body) ?? t.message, t.isValidationError && (this._state.errors = b(t.errors)));
301
+ t instanceof w && (this._state.message = d(t.body) ?? t.message, t.isValidationError && (this._state.errors = b(t.errors)));
303
302
  }
304
303
  async _submit(t, e, s = {}) {
305
- var a;
306
- const r = e ?? ((a = this._source) == null ? void 0 : a.url);
304
+ var n;
305
+ const r = e ?? ((n = this._source) == null ? void 0 : n.url);
307
306
  if (!r)
308
307
  throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);
309
308
  let o = s.data !== void 0 ? s.data : s.only ? g(this._state.data, s.only) : this._state.data ?? void 0;
310
309
  if (s.data === void 0 && this._transformRequest && o !== void 0) {
311
- const n = c(o);
312
- o = this._transformRequest(n) ?? n;
310
+ const a = c(o);
311
+ o = this._transformRequest(a) ?? a;
313
312
  }
314
313
  this._state.processing = !0, this._state.errors = {}, this._state.message = null;
315
314
  try {
316
- const n = await this._apix.request(t, r, {
315
+ const a = await this._apix.request(t, r, {
317
316
  data: o,
318
317
  params: s.params,
319
318
  headers: s.headers
320
319
  });
321
- return this._state.message = _(n), n;
322
- } catch (n) {
323
- throw this._applyError(n), n;
320
+ return this._state.message = d(a), a;
321
+ } catch (a) {
322
+ throw this._applyError(a), a;
324
323
  } finally {
325
324
  this._state.processing = !1;
326
325
  }
327
326
  }
327
+ /** @internal Configures auto-refetch-on-change, once, at construction time. */
328
+ _setupWatch(t, e) {
329
+ if (!t) return;
330
+ if (!this._source) {
331
+ console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");
332
+ return;
333
+ }
334
+ const s = t === !0 ? {} : t, r = s.fields;
335
+ this._sendFields = R(e ?? {}, this._ignore), this._triggerFields = r ?? this._sendFields, this._debounce = s.debounce ?? 0, this._syncLastSent();
336
+ const o = this._triggerFields.map((a) => () => f(this._state.data, a)), n = r ? s.deep ?? !1 : !0;
337
+ q(o, () => this._onWatchTrigger(), { deep: n });
338
+ }
328
339
  _onWatchTrigger() {
329
- if (this._payloadJson() === this._lastSent) return;
330
- this._debounceTimer && clearTimeout(this._debounceTimer);
331
- const t = this._watchOptions.debounce ?? 0;
332
- t > 0 ? this._debounceTimer = setTimeout(() => this._sendWatchRequest(), t) : this._sendWatchRequest();
340
+ this._payloadJson() !== this._lastSent && (this._debounceTimer && clearTimeout(this._debounceTimer), this._debounce > 0 ? this._debounceTimer = setTimeout(() => this._sendWatchRequest(), this._debounce) : this._sendWatchRequest());
333
341
  }
334
342
  _sendWatchRequest() {
335
- this._debounceTimer = null, this._source && (this._lastSent = this._payloadJson(), this._fill(this._watchExtra()).catch(() => {
343
+ this._debounceTimer = null, this._source && (this._lastSent = this._payloadJson(), this._fill(this._buildFillExtra()).catch(() => {
336
344
  }));
337
345
  }
338
- /** Build the fill() extra for a watch-shaped request from the current state. */
339
- _watchExtra() {
340
- const t = this._watched, e = this._watchOptions.payload ?? t;
341
- let s = e && e.length ? g(this._state.data, e) : c(this._state.data);
342
- this._transformRequest && (s = this._transformRequest(s) ?? s);
343
- const r = this._watchOptions.refreshWatched ? null : t;
344
- return this._source.method === "get" ? { params: s, preserve: r } : { data: s, preserve: r };
346
+ /** Build the fill() extra for a watch/refresh request from the current state. */
347
+ _buildFillExtra(t = {}) {
348
+ const e = t.lock ? [...this._lock, ...t.lock] : this._lock, s = t.ignore ? (this._sendFields ?? []).filter((o) => !k(o, t.ignore)) : this._sendFields ?? [];
349
+ let r = g(this._state.data, s);
350
+ return this._transformRequest && (r = this._transformRequest(r) ?? r), this._source.method === "get" ? { params: r, preserve: e } : { data: r, preserve: e };
345
351
  }
346
352
  _payloadJson() {
347
- const t = this._watched, e = t && t.length ? t.map((s) => f(this._state.data, s)) : this._state.data;
353
+ const e = (this._triggerFields ?? []).map((s) => f(this._state.data, s));
348
354
  return JSON.stringify(e) ?? "undefined";
349
355
  }
350
356
  _syncLastSent() {
351
357
  this._lastSent = this._payloadJson();
352
358
  }
353
359
  }
354
- function w(i, t = {}, e = null) {
355
- const s = new S(i, t, e), r = new Proxy(s, {
356
- get(o, a) {
357
- if (typeof a == "symbol" || a in o) return Reflect.get(o, a);
358
- const n = o._state.data;
359
- if (n && typeof n == "object") return n[a];
360
+ function j(i, t = {}, e = null) {
361
+ const s = new T(i, t, e), r = new Proxy(s, {
362
+ get(o, n) {
363
+ if (typeof n == "symbol" || n in o) return Reflect.get(o, n);
364
+ const a = o._state.data;
365
+ if (a && typeof a == "object") return a[n];
360
366
  },
361
- set(o, a, n) {
362
- if (typeof a == "symbol" || a in o) return Reflect.set(o, a, n);
367
+ set(o, n, a) {
368
+ if (typeof n == "symbol" || n in o) return Reflect.set(o, n, a);
363
369
  const h = o._state.data;
364
- return h && typeof h == "object" ? (h[a] = n, !0) : (o._state.data = { [a]: n }, !0);
370
+ return h && typeof h == "object" ? (h[n] = a, !0) : (o._state.data = { [n]: a }, !0);
365
371
  },
366
- has(o, a) {
367
- if (a in o) return !0;
368
- const n = o._state.data;
369
- return !!n && typeof n == "object" && a in n;
372
+ has(o, n) {
373
+ if (n in o) return !0;
374
+ const a = o._state.data;
375
+ return !!a && typeof a == "object" && n in a;
370
376
  }
371
377
  });
372
378
  return s._proxy = r, e && t.immediate !== !1 && r.reload().catch(() => {
373
379
  }), r;
374
380
  }
375
- class k {
381
+ class U {
376
382
  constructor(t = {}) {
377
383
  this.baseUrl = "", this.headers = {}, this.processingHooks = [], this.errorHooks = [], this.bodyTransformer = null, this.active = 0, t.baseUrl && this.setBaseUrl(t.baseUrl), t.headers && this.setHeader(t.headers), t.credentials && (this.credentials = t.credentials);
378
384
  }
@@ -415,30 +421,30 @@ class k {
415
421
  async request(t, e, s = {}) {
416
422
  let r = /^https?:\/\//i.test(e) ? e : this.baseUrl + e;
417
423
  if (s.params) {
418
- const h = q(s.params);
424
+ const h = A(s.params);
419
425
  h && (r += (r.includes("?") ? "&" : "?") + h);
420
426
  }
421
427
  const o = {
422
428
  accept: "application/json",
423
429
  "x-requested-with": "XMLHttpRequest"
424
430
  };
425
- for (const [h, u] of Object.entries(this.headers)) {
426
- const l = typeof u == "function" ? u() : u;
427
- l != null && (o[h.toLowerCase()] = l);
431
+ for (const [h, l] of Object.entries(this.headers)) {
432
+ const u = typeof l == "function" ? l() : l;
433
+ u != null && (o[h.toLowerCase()] = u);
428
434
  }
429
- for (const [h, u] of Object.entries(s.headers ?? {}))
430
- o[h.toLowerCase()] = u;
431
- const a = { method: t.toUpperCase(), headers: o, signal: s.signal };
432
- this.credentials && (a.credentials = this.credentials), s.data !== void 0 && t !== "get" && (typeof FormData < "u" && s.data instanceof FormData ? (delete o["content-type"], a.body = s.data) : (o["content-type"] ?? (o["content-type"] = "application/json"), a.body = JSON.stringify(s.data)));
433
- const n = { method: t, url: r, options: s };
435
+ for (const [h, l] of Object.entries(s.headers ?? {}))
436
+ o[h.toLowerCase()] = l;
437
+ const n = { method: t.toUpperCase(), headers: o, signal: s.signal };
438
+ this.credentials && (n.credentials = this.credentials), s.data !== void 0 && t !== "get" && (typeof FormData < "u" && s.data instanceof FormData ? (delete o["content-type"], n.body = s.data) : (o["content-type"] ?? (o["content-type"] = "application/json"), n.body = JSON.stringify(s.data)));
439
+ const a = { method: t, url: r, options: s };
434
440
  this.trackStart();
435
441
  try {
436
- const h = await fetch(r, a);
437
- let u = await T(h);
438
- if (this.bodyTransformer && (u = this.bodyTransformer(u, n) ?? u), !h.ok) throw new j(h.status, u, h);
439
- return u;
442
+ const h = await fetch(r, n);
443
+ let l = await S(h);
444
+ if (this.bodyTransformer && (l = this.bodyTransformer(l, a) ?? l), !h.ok) throw new w(h.status, l, h);
445
+ return l;
440
446
  } catch (h) {
441
- throw R(h) ? h : this.emitError(h, n);
447
+ throw E(h) ? h : this.emitError(h, a);
442
448
  } finally {
443
449
  this.trackEnd();
444
450
  }
@@ -462,7 +468,7 @@ class k {
462
468
  // --- form models -----------------------------------------------------------
463
469
  /** Create a form model without any request (like Inertia's useForm). */
464
470
  form(t, e = {}) {
465
- return w(this, { ...e, default: typeof t == "function" ? t : () => c(t) });
471
+ return j(this, { ...e, default: typeof t == "function" ? t : () => c(t) });
466
472
  }
467
473
  /** Create a form model and fill it with a GET request. */
468
474
  getForm(t, e) {
@@ -474,7 +480,7 @@ class k {
474
480
  }
475
481
  createFormModel(t, e, s) {
476
482
  const r = typeof s == "string" ? { path: s } : { ...s ?? {} };
477
- return w(this, r, { url: e, method: t });
483
+ return j(this, r, { url: e, method: t });
478
484
  }
479
485
  // --- internals --------------------------------------------------------------
480
486
  trackStart() {
@@ -502,15 +508,15 @@ class k {
502
508
  return s;
503
509
  }
504
510
  }
505
- function U(i = {}) {
506
- return new k(i);
511
+ function L(i = {}) {
512
+ return new U(i);
507
513
  }
508
- const F = U();
514
+ const P = L();
509
515
  export {
510
- k as Apix,
511
- j as ApixError,
512
- S as ApixModel,
513
- F as apix,
514
- U as createApix,
515
- F as default
516
+ U as Apix,
517
+ w as ApixError,
518
+ T as ApixFormModel,
519
+ P as apix,
520
+ L as createApix,
521
+ P as default
516
522
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diephp/vue-apix",
3
- "version": "0.1.4",
3
+ "version": "0.3.0",
4
4
  "description": "Tiny form/model/api toolkit for Vue 3 — fetch-based, Laravel-friendly, zero dependencies",
5
5
  "type": "module",
6
6
  "license": "MIT",