@diephp/vue-apix 0.2.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +131 -44
- package/dist/index.d.ts +1 -1
- package/dist/model.d.ts +35 -23
- package/dist/types.d.ts +43 -9
- package/dist/utils.d.ts +12 -0
- package/dist/vue-apix.cjs +1 -1
- package/dist/vue-apix.js +150 -125
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -138,6 +138,12 @@ const model = apix.getForm<AttrDto>('/api/attribute/123', {
|
|
|
138
138
|
onSuccess: (response, model) => {},
|
|
139
139
|
// called after every failed fill; aborted (superseded) requests are ignored
|
|
140
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 },
|
|
141
147
|
});
|
|
142
148
|
```
|
|
143
149
|
|
|
@@ -262,9 +268,8 @@ const submit = () =>
|
|
|
262
268
|
| `model.setErrors(errors)` / `model.clearErrors(keys?)` | manage errors manually |
|
|
263
269
|
| `model.reset(keys?)` | restore the snapshot: first server response, else `default()`; `reset(['name'])` for specific paths |
|
|
264
270
|
| `model.post/put/patch/delete(url?, opts?)` | submit `model.data` (or `opts.data` / `opts.only: ['name']`), returns the response Promise |
|
|
265
|
-
| `model.reload(url?)` | re-run the fill request as configured
|
|
266
|
-
| `model.refresh()` | re-send
|
|
267
|
-
| `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 |
|
|
268
273
|
| `model.transformResponse(fn)` / `model.transformRequest(fn)` | reshape server data ↔ model data, see below |
|
|
269
274
|
|
|
270
275
|
Submitting clears previous errors; any **4xx** response carrying an `errors` object in the
|
|
@@ -274,7 +279,7 @@ treated as validation errors — only `model.message` is surfaced.
|
|
|
274
279
|
|
|
275
280
|
**Reserved names.** These model members always win over data keys:
|
|
276
281
|
`data, errors, message, processing, hasErrors, isDirty, get, error, setData, setErrors,
|
|
277
|
-
clearErrors, reset, post, put, patch, delete, reload, refresh,
|
|
282
|
+
clearErrors, reset, post, put, patch, delete, reload, refresh,
|
|
278
283
|
transformRequest, transformResponse`. A data field with such a name is still there —
|
|
279
284
|
via `model.data.<key>`.
|
|
280
285
|
|
|
@@ -313,8 +318,9 @@ is unnecessary — `form.errors` is already reactive inside the child.
|
|
|
313
318
|
|
|
314
319
|
## watch() — filters, pagination, live search
|
|
315
320
|
|
|
316
|
-
The classic SPA page: a table, a filter form and a paginator. One model holds all of it
|
|
317
|
-
`watch(
|
|
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:
|
|
318
324
|
|
|
319
325
|
```vue
|
|
320
326
|
<script setup lang="ts">
|
|
@@ -332,20 +338,19 @@ interface PageDto {
|
|
|
332
338
|
paginator: { page: number; total: number; per_page: number };
|
|
333
339
|
}
|
|
334
340
|
|
|
335
|
-
const table = apix
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
.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
|
+
});
|
|
349
354
|
|
|
350
355
|
const lastPage = () => Math.max(1, Math.ceil(table.paginator.total / table.paginator.per_page));
|
|
351
356
|
|
|
@@ -396,25 +401,108 @@ Expected server response shape for the example above (Laravel-style):
|
|
|
396
401
|
}
|
|
397
402
|
```
|
|
398
403
|
|
|
399
|
-
|
|
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
|
+
```
|
|
400
417
|
|
|
401
|
-
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
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
|
|
406
432
|
change wins, out-of-order responses can't overwrite fresh data.
|
|
407
|
-
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
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 inside a component's `setup()` once that
|
|
498
|
+
component unmounts — no manual cleanup call exists or is needed. This only matters if you
|
|
499
|
+
create a `watch`-enabled model **outside** any component (e.g. a module-level store shared
|
|
500
|
+
across the whole app) — there it lives for as long as the module does, by design.
|
|
501
|
+
|
|
502
|
+
With an automatic initial fill (`immediate` not `false`), the underlying `watch()` is
|
|
503
|
+
registered only once that fill settles — not at construction — so its own response is
|
|
504
|
+
never mistaken for a change to react to. The component's effect scope is still captured
|
|
505
|
+
synchronously at construction, so auto-cleanup on unmount works exactly the same either way.
|
|
418
506
|
|
|
419
507
|
### Live search (minimal)
|
|
420
508
|
|
|
@@ -424,13 +512,12 @@ interface SearchDto {
|
|
|
424
512
|
query: string | null;
|
|
425
513
|
}
|
|
426
514
|
|
|
427
|
-
const search = apix
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
.watch(['query'], { debounce: 400 });
|
|
515
|
+
const search = apix.getForm<SearchDto>('/api/search', {
|
|
516
|
+
default: () => ({ results: [], query: null }),
|
|
517
|
+
// don't hit the API until the user types something
|
|
518
|
+
immediate: false,
|
|
519
|
+
watch: { fields: ['query'], debounce: 400 },
|
|
520
|
+
});
|
|
434
521
|
|
|
435
522
|
// template: <input v-model="search.query" /> — that's the whole feature
|
|
436
523
|
```
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ export { Apix, createApix } from './apix';
|
|
|
2
2
|
export { ApixError } from './client';
|
|
3
3
|
/** The underlying model class (advanced use, e.g. `instanceof` checks). Prefer the `ApixModel<T>` type for annotations. */
|
|
4
4
|
export { ApixFormModel } from './model';
|
|
5
|
-
export type { ApixConfig, ApixModel, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, MagicData, ProcessingHook, RequestContext, RequestOptions, SubmitOptions,
|
|
5
|
+
export type { ApixConfig, ApixModel, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, MagicData, ProcessingHook, RefreshOptions, RequestContext, RequestOptions, SubmitOptions, WatchConfig, } from './types';
|
|
6
6
|
/** Shared default instance — configure it once (e.g. in your api.ts) and import everywhere. */
|
|
7
7
|
export declare const apix: import('./apix').Apix;
|
|
8
8
|
export default apix;
|
package/dist/model.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Apix } from './apix';
|
|
2
|
-
import { ApixModel, FillSource, FormOptions,
|
|
2
|
+
import { ApixModel, FillSource, FormOptions, RefreshOptions, SubmitOptions } from './types';
|
|
3
3
|
interface ModelState {
|
|
4
4
|
data: any;
|
|
5
5
|
errors: Record<string, string>;
|
|
@@ -14,7 +14,7 @@ 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,
|
|
17
|
+
* post, put, patch, delete, reload, refresh,
|
|
18
18
|
* transformRequest, transformResponse.
|
|
19
19
|
*/
|
|
20
20
|
export declare class ApixFormModel<T = any> {
|
|
@@ -25,14 +25,25 @@ export declare class ApixFormModel<T = any> {
|
|
|
25
25
|
/** @internal */ _snapshot: any;
|
|
26
26
|
/** @internal */ _snapshotLocked: boolean;
|
|
27
27
|
/** @internal */ _proxy: ApixModel<T>;
|
|
28
|
-
/** @internal */
|
|
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;
|
|
35
37
|
/** @internal */ _transformRequest: ((data: any) => any) | null;
|
|
38
|
+
/**
|
|
39
|
+
* @internal Set only when `watch` must wait for the automatic initial fill
|
|
40
|
+
* to settle — called once, by createModel(), right after it does. Registers
|
|
41
|
+
* the Vue watch() only once the first merge has already happened, so that
|
|
42
|
+
* merge's own data reassignment is never mistaken for a user-driven change
|
|
43
|
+
* in the first place (nothing to de-dupe — the watcher simply doesn't exist
|
|
44
|
+
* yet while the initial fill is in flight).
|
|
45
|
+
*/
|
|
46
|
+
_deferredWatchSetup: (() => void) | null;
|
|
36
47
|
constructor(apix: Apix, options?: FormOptions<T>, source?: FillSource | null);
|
|
37
48
|
get data(): T | null;
|
|
38
49
|
set data(value: T | null);
|
|
@@ -62,22 +73,24 @@ export declare class ApixFormModel<T = any> {
|
|
|
62
73
|
/**
|
|
63
74
|
* Restore data to the snapshot: the first server response, or `default()`
|
|
64
75
|
* if nothing was loaded yet. Pass keys to reset only those dot-paths.
|
|
65
|
-
* An active watch
|
|
76
|
+
* An active `watch` reacts to the change as usual (the request is re-sent).
|
|
66
77
|
*/
|
|
67
78
|
reset(keys?: string | string[]): ApixModel<T>;
|
|
68
79
|
post(url?: string, options?: SubmitOptions): Promise<any>;
|
|
69
80
|
put(url?: string, options?: SubmitOptions): Promise<any>;
|
|
70
81
|
patch(url?: string, options?: SubmitOptions): Promise<any>;
|
|
71
82
|
delete(url?: string, options?: SubmitOptions): Promise<any>;
|
|
72
|
-
/** Re-run the fill request (or set a new source URL and run it). */
|
|
83
|
+
/** Re-run the fill request (or set a new source URL and run it). Resets the view — no ignore/lock applied. */
|
|
73
84
|
reload(url?: string): Promise<any>;
|
|
74
85
|
/**
|
|
75
|
-
* Re-send the fill request with the CURRENT state — a manual
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
* pending debounce is cancelled.
|
|
86
|
+
* Re-send the fill request with the CURRENT state — a manual trigger for a
|
|
87
|
+
* "Search" button. Sends every watched field except `ignore`, and protects
|
|
88
|
+
* `lock` fields from being overwritten by the response, exactly like an
|
|
89
|
+
* auto watch-triggered request; any pending debounce is cancelled.
|
|
90
|
+
* `options.ignore`/`options.lock` extend the form-level lists for this one
|
|
91
|
+
* call only. Without `watch` configured, this equals `reload()`.
|
|
79
92
|
*/
|
|
80
|
-
refresh(): Promise<any>;
|
|
93
|
+
refresh(options?: RefreshOptions): Promise<any>;
|
|
81
94
|
/**
|
|
82
95
|
* Map server data into the model shape. Runs on every fill (initial, reload,
|
|
83
96
|
* watch) AFTER path extraction and BEFORE the reactive data is touched — so it
|
|
@@ -91,15 +104,6 @@ export declare class ApixFormModel<T = any> {
|
|
|
91
104
|
* watch payloads. Receives a detached clone — mutations never touch the model.
|
|
92
105
|
*/
|
|
93
106
|
transformRequest(transformer: ((data: any) => any) | null): ApixModel<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): ApixModel<T>;
|
|
102
|
-
unwatch(): ApixModel<T>;
|
|
103
107
|
/** @internal */
|
|
104
108
|
_fill(extra?: {
|
|
105
109
|
params?: Record<string, unknown>;
|
|
@@ -109,10 +113,18 @@ export declare class ApixFormModel<T = any> {
|
|
|
109
113
|
private _applyFill;
|
|
110
114
|
private _applyError;
|
|
111
115
|
private _submit;
|
|
116
|
+
/**
|
|
117
|
+
* @internal Computes the trigger/send field sets and registers the Vue
|
|
118
|
+
* watch(). Called either synchronously from the constructor (no automatic
|
|
119
|
+
* initial fill to wait for) or once that fill has settled (see
|
|
120
|
+
* `_deferredWatchSetup`) — `initial` is always `default()`'s shape, since
|
|
121
|
+
* that's what determines which fields exist, regardless of timing.
|
|
122
|
+
*/
|
|
123
|
+
private _setupWatch;
|
|
112
124
|
private _onWatchTrigger;
|
|
113
125
|
private _sendWatchRequest;
|
|
114
|
-
/** Build the fill() extra for a watch
|
|
115
|
-
private
|
|
126
|
+
/** Build the fill() extra for a watch/refresh request from the current state. */
|
|
127
|
+
private _buildFillExtra;
|
|
116
128
|
private _payloadJson;
|
|
117
129
|
private _syncLastSent;
|
|
118
130
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -73,20 +73,54 @@ export interface FormOptions<T = any> {
|
|
|
73
73
|
transformResponse?: (data: any, response: any) => any;
|
|
74
74
|
/** See model.transformRequest(). */
|
|
75
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;
|
|
76
98
|
}
|
|
77
|
-
export interface
|
|
78
|
-
/**
|
|
79
|
-
|
|
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[];
|
|
80
110
|
/** Debounce in milliseconds before sending the request (default: 0). */
|
|
81
111
|
debounce?: number;
|
|
82
112
|
/**
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
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.
|
|
86
116
|
*/
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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[];
|
|
90
124
|
}
|
|
91
125
|
export interface SubmitOptions {
|
|
92
126
|
/** Explicit body; overrides model data. */
|
package/dist/utils.d.ts
CHANGED
|
@@ -22,6 +22,18 @@ 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
39
|
*
|
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 g(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function O(i,t){if(!g(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!g(i))return i;for(const e of Object.keys(t))i[e]=e in i?O(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){return t&&i&&typeof i=="object"?f(i,t):i}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 b=c(p);p=this._transformResponse(b,l)??b}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=O(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 A(i={}){return new v(i)}const q=A();exports.Apix=v;exports.ApixError=y;exports.ApixFormModel=R;exports.apix=q;exports.createApix=A;exports.default=q;
|
|
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 m(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function k(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?k(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 _(i){return i&&typeof i=="object"&&typeof i.message=="string"?i.message:null}function E(i,t){return t.some(e=>e===i||i.startsWith(`${e}.`))}function R(i,t,e=""){if(e&&E(e,t))return[];if(m(i)){const s=[];for(const r of Object.keys(i))s.push(...R(i[r],t,e?`${e}.${r}`:r));return s}return Array.isArray(i)||!e?[]:[e]}function q(i,t){return t&&i&&typeof i=="object"?f(i,t):i}class g 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 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._deferredWatchSetup=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;if(this._state=d.reactive({data:r,errors:{},message:null,processing:!1}),this._snapshot=c(r),this._ignore=e.ignore??[],this._lock=e.lock??[],e.watch){const o=e.watch;if(!this._source)console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");else if(e.immediate===!1)this._setupWatch(o,r);else{const n=d.getCurrentScope();this._deferredWatchSetup=()=>{n?n.run(()=>this._setupWatch(o,r)):this._setupWatch(o,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 p=q(u,this._options.path);if(this._transformResponse){const b=c(p);p=this._transformResponse(b,u)??b}return this._applyFill(p,t.preserve??null),this._state.message=_(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=k(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=_(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=_(a),a}catch(a){throw this._applyError(a),a}finally{this._state.processing=!1}}_setupWatch(t,e){const s=t===!0?{}:t,r=s.fields;this._sendFields=R(e??{},this._ignore);const o=r??this._sendFields;this._triggerFields=o,this._debounce=s.debounce??0,this._syncLastSent();const n=o.map(h=>()=>f(this._state.data,h)),a=r?s.deep??!1:!0;d.watch(n,()=>this._onWatchTrigger(),{deep:a})}_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=>!E(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 w(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().finally(()=>{var o;(o=s._deferredWatchSetup)==null||o.call(s),s._deferredWatchSetup=null}).catch(()=>{}),r}class S{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 w(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 w(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 v(i={}){return new S(i)}const O=v();exports.Apix=S;exports.ApixError=g;exports.ApixFormModel=A;exports.apix=O;exports.createApix=v;exports.default=O;
|
package/dist/vue-apix.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { toRaw as
|
|
1
|
+
import { toRaw as F, reactive as O, getCurrentScope as S, watch as q } from "vue";
|
|
2
2
|
function c(i) {
|
|
3
|
-
const t =
|
|
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
|
|
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 (!
|
|
21
|
+
if (!p(t))
|
|
22
22
|
return i === void 0 ? c(t) : i;
|
|
23
23
|
if (i == null) return c(t);
|
|
24
|
-
if (!
|
|
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,38 +35,51 @@ function f(i, t) {
|
|
|
35
35
|
}
|
|
36
36
|
return e;
|
|
37
37
|
}
|
|
38
|
-
function
|
|
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
|
|
43
|
-
(r[
|
|
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
|
}
|
|
47
|
-
function
|
|
47
|
+
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 &&
|
|
51
|
+
r !== void 0 && m(e, s, c(r));
|
|
52
52
|
}
|
|
53
53
|
return e;
|
|
54
54
|
}
|
|
55
|
-
function
|
|
55
|
+
function b(i) {
|
|
56
56
|
const t = {};
|
|
57
57
|
for (const [e, s] of Object.entries(i ?? {}))
|
|
58
58
|
s != null && (t[e] = Array.isArray(s) ? String(s[0]) : String(s));
|
|
59
59
|
return t;
|
|
60
60
|
}
|
|
61
|
-
function
|
|
61
|
+
function d(i) {
|
|
62
62
|
return i && typeof i == "object" && typeof i.message == "string" ? i.message : null;
|
|
63
63
|
}
|
|
64
|
-
function
|
|
64
|
+
function w(i, t) {
|
|
65
|
+
return t.some((e) => e === i || i.startsWith(`${e}.`));
|
|
66
|
+
}
|
|
67
|
+
function k(i, t, e = "") {
|
|
68
|
+
if (e && w(e, t)) return [];
|
|
69
|
+
if (p(i)) {
|
|
70
|
+
const s = [];
|
|
71
|
+
for (const r of Object.keys(i))
|
|
72
|
+
s.push(...k(i[r], t, e ? `${e}.${r}` : r));
|
|
73
|
+
return s;
|
|
74
|
+
}
|
|
75
|
+
return Array.isArray(i) || !e ? [] : [e];
|
|
76
|
+
}
|
|
77
|
+
function v(i, t) {
|
|
65
78
|
return t && i && typeof i == "object" ? f(i, t) : i;
|
|
66
79
|
}
|
|
67
|
-
class
|
|
80
|
+
class R extends Error {
|
|
68
81
|
constructor(t, e, s) {
|
|
69
|
-
super(
|
|
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 : {};
|
|
70
83
|
}
|
|
71
84
|
/**
|
|
72
85
|
* True for any 4xx response whose body carries an `errors` object
|
|
@@ -77,7 +90,7 @@ class j extends Error {
|
|
|
77
90
|
return this.status >= 400 && this.status < 500 && Object.keys(this.errors).length > 0;
|
|
78
91
|
}
|
|
79
92
|
}
|
|
80
|
-
function
|
|
93
|
+
function E(i) {
|
|
81
94
|
return i instanceof Error && i.name === "AbortError";
|
|
82
95
|
}
|
|
83
96
|
function A(i) {
|
|
@@ -88,11 +101,11 @@ function A(i) {
|
|
|
88
101
|
if (typeof r == "boolean") return e(o, r ? "1" : "0");
|
|
89
102
|
if (r instanceof Date) return e(o, r.toISOString());
|
|
90
103
|
if (Array.isArray(r)) {
|
|
91
|
-
r.forEach((
|
|
104
|
+
r.forEach((n, a) => s(n, `${o}[${a}]`));
|
|
92
105
|
return;
|
|
93
106
|
}
|
|
94
107
|
if (typeof r == "object") {
|
|
95
|
-
for (const [
|
|
108
|
+
for (const [n, a] of Object.entries(r)) s(a, `${o}[${n}]`);
|
|
96
109
|
return;
|
|
97
110
|
}
|
|
98
111
|
e(o, String(r));
|
|
@@ -111,11 +124,23 @@ async function T(i) {
|
|
|
111
124
|
return t;
|
|
112
125
|
}
|
|
113
126
|
}
|
|
114
|
-
class
|
|
127
|
+
class U {
|
|
115
128
|
constructor(t, e = {}, s = null) {
|
|
116
|
-
this._snapshot = null, this._snapshotLocked = !1, this.
|
|
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._deferredWatchSetup = null, this._apix = t, this._options = e, this._source = s, this._transformResponse = e.transformResponse ?? null, this._transformRequest = e.transformRequest ?? null;
|
|
117
130
|
const r = e.default ? e.default() : null;
|
|
118
|
-
this._state =
|
|
131
|
+
if (this._state = O({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r), this._ignore = e.ignore ?? [], this._lock = e.lock ?? [], e.watch) {
|
|
132
|
+
const o = e.watch;
|
|
133
|
+
if (!this._source)
|
|
134
|
+
console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");
|
|
135
|
+
else if (e.immediate === !1)
|
|
136
|
+
this._setupWatch(o, r);
|
|
137
|
+
else {
|
|
138
|
+
const n = S();
|
|
139
|
+
this._deferredWatchSetup = () => {
|
|
140
|
+
n ? n.run(() => this._setupWatch(o, r)) : this._setupWatch(o, r);
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
}
|
|
119
144
|
}
|
|
120
145
|
// --- reactive state ---------------------------------------------------------
|
|
121
146
|
get data() {
|
|
@@ -166,7 +191,7 @@ class S {
|
|
|
166
191
|
if (r.startsWith(s)) return e[r];
|
|
167
192
|
}
|
|
168
193
|
setErrors(t) {
|
|
169
|
-
return this._state.errors =
|
|
194
|
+
return this._state.errors = b(t), this._proxy;
|
|
170
195
|
}
|
|
171
196
|
/** Clear all errors, or only the given keys (including their `key.*` sub-errors). */
|
|
172
197
|
clearErrors(t) {
|
|
@@ -182,7 +207,7 @@ class S {
|
|
|
182
207
|
/**
|
|
183
208
|
* Restore data to the snapshot: the first server response, or `default()`
|
|
184
209
|
* if nothing was loaded yet. Pass keys to reset only those dot-paths.
|
|
185
|
-
* An active watch
|
|
210
|
+
* An active `watch` reacts to the change as usual (the request is re-sent).
|
|
186
211
|
*/
|
|
187
212
|
reset(t) {
|
|
188
213
|
if (t === void 0 || Array.isArray(t) && t.length === 0)
|
|
@@ -190,7 +215,7 @@ class S {
|
|
|
190
215
|
const e = Array.isArray(t) ? t : [t];
|
|
191
216
|
if (this._state.data && typeof this._state.data == "object")
|
|
192
217
|
for (const s of e)
|
|
193
|
-
|
|
218
|
+
m(this._state.data, s, c(f(this._snapshot, s)));
|
|
194
219
|
return this.clearErrors(e), this._proxy;
|
|
195
220
|
}
|
|
196
221
|
// --- HTTP ------------------------------------------------------------------------
|
|
@@ -206,7 +231,7 @@ class S {
|
|
|
206
231
|
delete(t, e) {
|
|
207
232
|
return this._submit("delete", t, e);
|
|
208
233
|
}
|
|
209
|
-
/** Re-run the fill request (or set a new source URL and run it). */
|
|
234
|
+
/** Re-run the fill request (or set a new source URL and run it). Resets the view — no ignore/lock applied. */
|
|
210
235
|
reload(t) {
|
|
211
236
|
var e;
|
|
212
237
|
return t && (this._source = { url: t, method: ((e = this._source) == null ? void 0 : e.method) ?? "get" }), this._source ? this._fill() : Promise.reject(
|
|
@@ -214,15 +239,22 @@ class S {
|
|
|
214
239
|
);
|
|
215
240
|
}
|
|
216
241
|
/**
|
|
217
|
-
* Re-send the fill request with the CURRENT state — a manual
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
* pending debounce is cancelled.
|
|
242
|
+
* Re-send the fill request with the CURRENT state — a manual trigger for a
|
|
243
|
+
* "Search" button. Sends every watched field except `ignore`, and protects
|
|
244
|
+
* `lock` fields from being overwritten by the response, exactly like an
|
|
245
|
+
* auto watch-triggered request; any pending debounce is cancelled.
|
|
246
|
+
* `options.ignore`/`options.lock` extend the form-level lists for this one
|
|
247
|
+
* call only. Without `watch` configured, this equals `reload()`.
|
|
221
248
|
*/
|
|
222
|
-
refresh() {
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
249
|
+
refresh(t = {}) {
|
|
250
|
+
if (!this._source)
|
|
251
|
+
return Promise.reject(
|
|
252
|
+
new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url).")
|
|
253
|
+
);
|
|
254
|
+
if (this._triggerFields === null) return this._fill();
|
|
255
|
+
this._debounceTimer && (clearTimeout(this._debounceTimer), this._debounceTimer = null);
|
|
256
|
+
const e = this._buildFillExtra(t);
|
|
257
|
+
return this._lastSent = this._payloadJson(), this._fill(e);
|
|
226
258
|
}
|
|
227
259
|
// --- transformers -------------------------------------------------------------------
|
|
228
260
|
/**
|
|
@@ -242,30 +274,10 @@ class S {
|
|
|
242
274
|
transformRequest(t) {
|
|
243
275
|
return this._transformRequest = t, this._proxy;
|
|
244
276
|
}
|
|
245
|
-
// --- watch ------------------------------------------------------------------------
|
|
246
|
-
/**
|
|
247
|
-
* Re-send the fill request whenever data changes.
|
|
248
|
-
* `paths` limits both what is observed and what is sent
|
|
249
|
-
* (GET → PHP-style query params, POST → JSON body).
|
|
250
|
-
* The response updates everything except the watched paths (see WatchOptions).
|
|
251
|
-
* A new trigger aborts the previous in-flight watch request.
|
|
252
|
-
*/
|
|
253
|
-
watch(t, e) {
|
|
254
|
-
let s = null, r;
|
|
255
|
-
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();
|
|
256
|
-
const o = s && s.length ? s.map((a) => () => f(this._state.data, a)) : () => this._state.data;
|
|
257
|
-
return this._stopWatch = v(o, () => this._onWatchTrigger(), {
|
|
258
|
-
deep: r.deep ?? !0
|
|
259
|
-
}), this._proxy;
|
|
260
|
-
}
|
|
261
|
-
unwatch() {
|
|
262
|
-
var t;
|
|
263
|
-
return (t = this._stopWatch) == null || t.call(this), this._stopWatch = null, this._debounceTimer && (clearTimeout(this._debounceTimer), this._debounceTimer = null), this._proxy;
|
|
264
|
-
}
|
|
265
277
|
// --- internals ----------------------------------------------------------------------
|
|
266
278
|
/** @internal */
|
|
267
279
|
async _fill(t = {}) {
|
|
268
|
-
var o,
|
|
280
|
+
var o, n, a, h, l;
|
|
269
281
|
const e = this._source;
|
|
270
282
|
(o = this._fillAbort) == null || o.abort();
|
|
271
283
|
const s = new AbortController();
|
|
@@ -273,15 +285,15 @@ class S {
|
|
|
273
285
|
const r = { signal: s.signal };
|
|
274
286
|
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);
|
|
275
287
|
try {
|
|
276
|
-
const
|
|
277
|
-
let
|
|
288
|
+
const u = await this._apix.request(e.method, e.url, r);
|
|
289
|
+
let _ = v(u, this._options.path);
|
|
278
290
|
if (this._transformResponse) {
|
|
279
|
-
const
|
|
280
|
-
|
|
291
|
+
const y = c(_);
|
|
292
|
+
_ = this._transformResponse(y, u) ?? y;
|
|
281
293
|
}
|
|
282
|
-
return this._applyFill(
|
|
283
|
-
} catch (
|
|
284
|
-
throw
|
|
294
|
+
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;
|
|
295
|
+
} catch (u) {
|
|
296
|
+
throw E(u) || (this._applyError(u), (l = (h = this._options).onError) == null || l.call(h, u, this._proxy)), u;
|
|
285
297
|
} finally {
|
|
286
298
|
this._fillAbort === s && (this._fillAbort = null, this._state.processing = !1);
|
|
287
299
|
}
|
|
@@ -292,86 +304,99 @@ class S {
|
|
|
292
304
|
const r = this._snapshotLocked ? null : c(s);
|
|
293
305
|
if (e && e.length && s && typeof s == "object" && this._state.data && typeof this._state.data == "object")
|
|
294
306
|
for (const o of e) {
|
|
295
|
-
const
|
|
296
|
-
|
|
307
|
+
const n = f(this._state.data, o);
|
|
308
|
+
n !== void 0 && m(s, o, c(n));
|
|
297
309
|
}
|
|
298
310
|
this._state.data = s, this._snapshotLocked || (this._snapshot = r, this._snapshotLocked = !0), this._syncLastSent();
|
|
299
311
|
}
|
|
300
312
|
_applyError(t) {
|
|
301
|
-
t instanceof
|
|
313
|
+
t instanceof R && (this._state.message = d(t.body) ?? t.message, t.isValidationError && (this._state.errors = b(t.errors)));
|
|
302
314
|
}
|
|
303
315
|
async _submit(t, e, s = {}) {
|
|
304
|
-
var
|
|
305
|
-
const r = e ?? ((
|
|
316
|
+
var n;
|
|
317
|
+
const r = e ?? ((n = this._source) == null ? void 0 : n.url);
|
|
306
318
|
if (!r)
|
|
307
319
|
throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);
|
|
308
|
-
let o = s.data !== void 0 ? s.data : s.only ?
|
|
320
|
+
let o = s.data !== void 0 ? s.data : s.only ? g(this._state.data, s.only) : this._state.data ?? void 0;
|
|
309
321
|
if (s.data === void 0 && this._transformRequest && o !== void 0) {
|
|
310
|
-
const
|
|
311
|
-
o = this._transformRequest(
|
|
322
|
+
const a = c(o);
|
|
323
|
+
o = this._transformRequest(a) ?? a;
|
|
312
324
|
}
|
|
313
325
|
this._state.processing = !0, this._state.errors = {}, this._state.message = null;
|
|
314
326
|
try {
|
|
315
|
-
const
|
|
327
|
+
const a = await this._apix.request(t, r, {
|
|
316
328
|
data: o,
|
|
317
329
|
params: s.params,
|
|
318
330
|
headers: s.headers
|
|
319
331
|
});
|
|
320
|
-
return this._state.message =
|
|
321
|
-
} catch (
|
|
322
|
-
throw this._applyError(
|
|
332
|
+
return this._state.message = d(a), a;
|
|
333
|
+
} catch (a) {
|
|
334
|
+
throw this._applyError(a), a;
|
|
323
335
|
} finally {
|
|
324
336
|
this._state.processing = !1;
|
|
325
337
|
}
|
|
326
338
|
}
|
|
339
|
+
/**
|
|
340
|
+
* @internal Computes the trigger/send field sets and registers the Vue
|
|
341
|
+
* watch(). Called either synchronously from the constructor (no automatic
|
|
342
|
+
* initial fill to wait for) or once that fill has settled (see
|
|
343
|
+
* `_deferredWatchSetup`) — `initial` is always `default()`'s shape, since
|
|
344
|
+
* that's what determines which fields exist, regardless of timing.
|
|
345
|
+
*/
|
|
346
|
+
_setupWatch(t, e) {
|
|
347
|
+
const s = t === !0 ? {} : t, r = s.fields;
|
|
348
|
+
this._sendFields = k(e ?? {}, this._ignore);
|
|
349
|
+
const o = r ?? this._sendFields;
|
|
350
|
+
this._triggerFields = o, this._debounce = s.debounce ?? 0, this._syncLastSent();
|
|
351
|
+
const n = o.map((h) => () => f(this._state.data, h)), a = r ? s.deep ?? !1 : !0;
|
|
352
|
+
q(n, () => this._onWatchTrigger(), { deep: a });
|
|
353
|
+
}
|
|
327
354
|
_onWatchTrigger() {
|
|
328
|
-
|
|
329
|
-
this._debounceTimer && clearTimeout(this._debounceTimer);
|
|
330
|
-
const t = this._watchOptions.debounce ?? 0;
|
|
331
|
-
t > 0 ? this._debounceTimer = setTimeout(() => this._sendWatchRequest(), t) : this._sendWatchRequest();
|
|
355
|
+
this._payloadJson() !== this._lastSent && (this._debounceTimer && clearTimeout(this._debounceTimer), this._debounce > 0 ? this._debounceTimer = setTimeout(() => this._sendWatchRequest(), this._debounce) : this._sendWatchRequest());
|
|
332
356
|
}
|
|
333
357
|
_sendWatchRequest() {
|
|
334
|
-
this._debounceTimer = null, this._source && (this._lastSent = this._payloadJson(), this._fill(this.
|
|
358
|
+
this._debounceTimer = null, this._source && (this._lastSent = this._payloadJson(), this._fill(this._buildFillExtra()).catch(() => {
|
|
335
359
|
}));
|
|
336
360
|
}
|
|
337
|
-
/** Build the fill() extra for a watch
|
|
338
|
-
|
|
339
|
-
const
|
|
340
|
-
let
|
|
341
|
-
this._transformRequest && (
|
|
342
|
-
const r = this._watchOptions.refreshWatched ? null : t;
|
|
343
|
-
return this._source.method === "get" ? { params: s, preserve: r } : { data: s, preserve: r };
|
|
361
|
+
/** Build the fill() extra for a watch/refresh request from the current state. */
|
|
362
|
+
_buildFillExtra(t = {}) {
|
|
363
|
+
const e = t.lock ? [...this._lock, ...t.lock] : this._lock, s = t.ignore ? (this._sendFields ?? []).filter((o) => !w(o, t.ignore)) : this._sendFields ?? [];
|
|
364
|
+
let r = g(this._state.data, s);
|
|
365
|
+
return this._transformRequest && (r = this._transformRequest(r) ?? r), this._source.method === "get" ? { params: r, preserve: e } : { data: r, preserve: e };
|
|
344
366
|
}
|
|
345
367
|
_payloadJson() {
|
|
346
|
-
const
|
|
368
|
+
const e = (this._triggerFields ?? []).map((s) => f(this._state.data, s));
|
|
347
369
|
return JSON.stringify(e) ?? "undefined";
|
|
348
370
|
}
|
|
349
371
|
_syncLastSent() {
|
|
350
372
|
this._lastSent = this._payloadJson();
|
|
351
373
|
}
|
|
352
374
|
}
|
|
353
|
-
function
|
|
354
|
-
const s = new
|
|
355
|
-
get(o,
|
|
356
|
-
if (typeof
|
|
357
|
-
const
|
|
358
|
-
if (
|
|
375
|
+
function j(i, t = {}, e = null) {
|
|
376
|
+
const s = new U(i, t, e), r = new Proxy(s, {
|
|
377
|
+
get(o, n) {
|
|
378
|
+
if (typeof n == "symbol" || n in o) return Reflect.get(o, n);
|
|
379
|
+
const a = o._state.data;
|
|
380
|
+
if (a && typeof a == "object") return a[n];
|
|
359
381
|
},
|
|
360
|
-
set(o,
|
|
361
|
-
if (typeof
|
|
382
|
+
set(o, n, a) {
|
|
383
|
+
if (typeof n == "symbol" || n in o) return Reflect.set(o, n, a);
|
|
362
384
|
const h = o._state.data;
|
|
363
|
-
return h && typeof h == "object" ? (h[
|
|
385
|
+
return h && typeof h == "object" ? (h[n] = a, !0) : (o._state.data = { [n]: a }, !0);
|
|
364
386
|
},
|
|
365
|
-
has(o,
|
|
366
|
-
if (
|
|
367
|
-
const
|
|
368
|
-
return !!
|
|
387
|
+
has(o, n) {
|
|
388
|
+
if (n in o) return !0;
|
|
389
|
+
const a = o._state.data;
|
|
390
|
+
return !!a && typeof a == "object" && n in a;
|
|
369
391
|
}
|
|
370
392
|
});
|
|
371
|
-
return s._proxy = r, e && t.immediate !== !1 && r.reload().
|
|
393
|
+
return s._proxy = r, e && t.immediate !== !1 && r.reload().finally(() => {
|
|
394
|
+
var o;
|
|
395
|
+
(o = s._deferredWatchSetup) == null || o.call(s), s._deferredWatchSetup = null;
|
|
396
|
+
}).catch(() => {
|
|
372
397
|
}), r;
|
|
373
398
|
}
|
|
374
|
-
class
|
|
399
|
+
class W {
|
|
375
400
|
constructor(t = {}) {
|
|
376
401
|
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);
|
|
377
402
|
}
|
|
@@ -421,23 +446,23 @@ class k {
|
|
|
421
446
|
accept: "application/json",
|
|
422
447
|
"x-requested-with": "XMLHttpRequest"
|
|
423
448
|
};
|
|
424
|
-
for (const [h,
|
|
425
|
-
const
|
|
426
|
-
|
|
449
|
+
for (const [h, l] of Object.entries(this.headers)) {
|
|
450
|
+
const u = typeof l == "function" ? l() : l;
|
|
451
|
+
u != null && (o[h.toLowerCase()] = u);
|
|
427
452
|
}
|
|
428
|
-
for (const [h,
|
|
429
|
-
o[h.toLowerCase()] =
|
|
430
|
-
const
|
|
431
|
-
this.credentials && (
|
|
432
|
-
const
|
|
453
|
+
for (const [h, l] of Object.entries(s.headers ?? {}))
|
|
454
|
+
o[h.toLowerCase()] = l;
|
|
455
|
+
const n = { method: t.toUpperCase(), headers: o, signal: s.signal };
|
|
456
|
+
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)));
|
|
457
|
+
const a = { method: t, url: r, options: s };
|
|
433
458
|
this.trackStart();
|
|
434
459
|
try {
|
|
435
|
-
const h = await fetch(r,
|
|
436
|
-
let
|
|
437
|
-
if (this.bodyTransformer && (
|
|
438
|
-
return
|
|
460
|
+
const h = await fetch(r, n);
|
|
461
|
+
let l = await T(h);
|
|
462
|
+
if (this.bodyTransformer && (l = this.bodyTransformer(l, a) ?? l), !h.ok) throw new R(h.status, l, h);
|
|
463
|
+
return l;
|
|
439
464
|
} catch (h) {
|
|
440
|
-
throw
|
|
465
|
+
throw E(h) ? h : this.emitError(h, a);
|
|
441
466
|
} finally {
|
|
442
467
|
this.trackEnd();
|
|
443
468
|
}
|
|
@@ -461,7 +486,7 @@ class k {
|
|
|
461
486
|
// --- form models -----------------------------------------------------------
|
|
462
487
|
/** Create a form model without any request (like Inertia's useForm). */
|
|
463
488
|
form(t, e = {}) {
|
|
464
|
-
return
|
|
489
|
+
return j(this, { ...e, default: typeof t == "function" ? t : () => c(t) });
|
|
465
490
|
}
|
|
466
491
|
/** Create a form model and fill it with a GET request. */
|
|
467
492
|
getForm(t, e) {
|
|
@@ -473,7 +498,7 @@ class k {
|
|
|
473
498
|
}
|
|
474
499
|
createFormModel(t, e, s) {
|
|
475
500
|
const r = typeof s == "string" ? { path: s } : { ...s ?? {} };
|
|
476
|
-
return
|
|
501
|
+
return j(this, r, { url: e, method: t });
|
|
477
502
|
}
|
|
478
503
|
// --- internals --------------------------------------------------------------
|
|
479
504
|
trackStart() {
|
|
@@ -501,15 +526,15 @@ class k {
|
|
|
501
526
|
return s;
|
|
502
527
|
}
|
|
503
528
|
}
|
|
504
|
-
function
|
|
505
|
-
return new
|
|
529
|
+
function L(i = {}) {
|
|
530
|
+
return new W(i);
|
|
506
531
|
}
|
|
507
|
-
const
|
|
532
|
+
const P = L();
|
|
508
533
|
export {
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
534
|
+
W as Apix,
|
|
535
|
+
R as ApixError,
|
|
536
|
+
U as ApixFormModel,
|
|
537
|
+
P as apix,
|
|
538
|
+
L as createApix,
|
|
539
|
+
P as default
|
|
515
540
|
};
|