@diephp/vue-apix 0.2.0 → 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 +127 -44
- package/dist/index.d.ts +1 -1
- package/dist/model.d.ts +20 -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 +132 -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,104 @@ 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 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.
|
|
418
502
|
|
|
419
503
|
### Live search (minimal)
|
|
420
504
|
|
|
@@ -424,13 +508,12 @@ interface SearchDto {
|
|
|
424
508
|
query: string | null;
|
|
425
509
|
}
|
|
426
510
|
|
|
427
|
-
const search = apix
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
.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
|
+
});
|
|
434
517
|
|
|
435
518
|
// template: <input v-model="search.query" /> — that's the whole feature
|
|
436
519
|
```
|
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,10 +25,12 @@ 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;
|
|
@@ -62,22 +64,24 @@ export declare class ApixFormModel<T = any> {
|
|
|
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
|
|
67
|
+
* An active `watch` reacts to the change as usual (the request is re-sent).
|
|
66
68
|
*/
|
|
67
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
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
* pending debounce is cancelled.
|
|
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
|
|
@@ -91,15 +95,6 @@ export declare class ApixFormModel<T = any> {
|
|
|
91
95
|
* watch payloads. Receives a detached clone — mutations never touch the model.
|
|
92
96
|
*/
|
|
93
97
|
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
98
|
/** @internal */
|
|
104
99
|
_fill(extra?: {
|
|
105
100
|
params?: Record<string, unknown>;
|
|
@@ -109,10 +104,12 @@ export declare class ApixFormModel<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
|
|
115
|
-
private
|
|
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
|
}
|
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 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
|
|
1
|
+
import { toRaw as F, reactive as O, 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 k(i, t) {
|
|
65
|
+
return t.some((e) => e === i || i.startsWith(`${e}.`));
|
|
66
|
+
}
|
|
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) {
|
|
65
78
|
return t && i && typeof i == "object" ? f(i, t) : i;
|
|
66
79
|
}
|
|
67
|
-
class
|
|
80
|
+
class w 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));
|
|
@@ -101,7 +114,7 @@ function A(i) {
|
|
|
101
114
|
for (const [r, o] of Object.entries(i)) s(o, r);
|
|
102
115
|
return t.join("&");
|
|
103
116
|
}
|
|
104
|
-
async function
|
|
117
|
+
async function S(i) {
|
|
105
118
|
if (i.status === 204) return null;
|
|
106
119
|
const t = await i.text();
|
|
107
120
|
if (!t) return null;
|
|
@@ -111,11 +124,11 @@ async function T(i) {
|
|
|
111
124
|
return t;
|
|
112
125
|
}
|
|
113
126
|
}
|
|
114
|
-
class
|
|
127
|
+
class T {
|
|
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._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
|
+
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);
|
|
119
132
|
}
|
|
120
133
|
// --- reactive state ---------------------------------------------------------
|
|
121
134
|
get data() {
|
|
@@ -166,7 +179,7 @@ class S {
|
|
|
166
179
|
if (r.startsWith(s)) return e[r];
|
|
167
180
|
}
|
|
168
181
|
setErrors(t) {
|
|
169
|
-
return this._state.errors =
|
|
182
|
+
return this._state.errors = b(t), this._proxy;
|
|
170
183
|
}
|
|
171
184
|
/** Clear all errors, or only the given keys (including their `key.*` sub-errors). */
|
|
172
185
|
clearErrors(t) {
|
|
@@ -182,7 +195,7 @@ class S {
|
|
|
182
195
|
/**
|
|
183
196
|
* Restore data to the snapshot: the first server response, or `default()`
|
|
184
197
|
* if nothing was loaded yet. Pass keys to reset only those dot-paths.
|
|
185
|
-
* An active watch
|
|
198
|
+
* An active `watch` reacts to the change as usual (the request is re-sent).
|
|
186
199
|
*/
|
|
187
200
|
reset(t) {
|
|
188
201
|
if (t === void 0 || Array.isArray(t) && t.length === 0)
|
|
@@ -190,7 +203,7 @@ class S {
|
|
|
190
203
|
const e = Array.isArray(t) ? t : [t];
|
|
191
204
|
if (this._state.data && typeof this._state.data == "object")
|
|
192
205
|
for (const s of e)
|
|
193
|
-
|
|
206
|
+
m(this._state.data, s, c(f(this._snapshot, s)));
|
|
194
207
|
return this.clearErrors(e), this._proxy;
|
|
195
208
|
}
|
|
196
209
|
// --- HTTP ------------------------------------------------------------------------
|
|
@@ -206,7 +219,7 @@ class S {
|
|
|
206
219
|
delete(t, e) {
|
|
207
220
|
return this._submit("delete", t, e);
|
|
208
221
|
}
|
|
209
|
-
/** 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. */
|
|
210
223
|
reload(t) {
|
|
211
224
|
var e;
|
|
212
225
|
return t && (this._source = { url: t, method: ((e = this._source) == null ? void 0 : e.method) ?? "get" }), this._source ? this._fill() : Promise.reject(
|
|
@@ -214,15 +227,22 @@ class S {
|
|
|
214
227
|
);
|
|
215
228
|
}
|
|
216
229
|
/**
|
|
217
|
-
* Re-send the fill request with the CURRENT state — a manual
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
* pending debounce is cancelled.
|
|
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()`.
|
|
221
236
|
*/
|
|
222
|
-
refresh() {
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
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);
|
|
226
246
|
}
|
|
227
247
|
// --- transformers -------------------------------------------------------------------
|
|
228
248
|
/**
|
|
@@ -242,30 +262,10 @@ class S {
|
|
|
242
262
|
transformRequest(t) {
|
|
243
263
|
return this._transformRequest = t, this._proxy;
|
|
244
264
|
}
|
|
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
265
|
// --- internals ----------------------------------------------------------------------
|
|
266
266
|
/** @internal */
|
|
267
267
|
async _fill(t = {}) {
|
|
268
|
-
var o,
|
|
268
|
+
var o, n, a, h, l;
|
|
269
269
|
const e = this._source;
|
|
270
270
|
(o = this._fillAbort) == null || o.abort();
|
|
271
271
|
const s = new AbortController();
|
|
@@ -273,15 +273,15 @@ class S {
|
|
|
273
273
|
const r = { signal: s.signal };
|
|
274
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);
|
|
275
275
|
try {
|
|
276
|
-
const
|
|
277
|
-
let
|
|
276
|
+
const u = await this._apix.request(e.method, e.url, r);
|
|
277
|
+
let _ = v(u, this._options.path);
|
|
278
278
|
if (this._transformResponse) {
|
|
279
|
-
const
|
|
280
|
-
|
|
279
|
+
const y = c(_);
|
|
280
|
+
_ = this._transformResponse(y, u) ?? y;
|
|
281
281
|
}
|
|
282
|
-
return this._applyFill(
|
|
283
|
-
} catch (
|
|
284
|
-
throw
|
|
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;
|
|
285
285
|
} finally {
|
|
286
286
|
this._fillAbort === s && (this._fillAbort = null, this._state.processing = !1);
|
|
287
287
|
}
|
|
@@ -292,86 +292,93 @@ class S {
|
|
|
292
292
|
const r = this._snapshotLocked ? null : c(s);
|
|
293
293
|
if (e && e.length && s && typeof s == "object" && this._state.data && typeof this._state.data == "object")
|
|
294
294
|
for (const o of e) {
|
|
295
|
-
const
|
|
296
|
-
|
|
295
|
+
const n = f(this._state.data, o);
|
|
296
|
+
n !== void 0 && m(s, o, c(n));
|
|
297
297
|
}
|
|
298
298
|
this._state.data = s, this._snapshotLocked || (this._snapshot = r, this._snapshotLocked = !0), this._syncLastSent();
|
|
299
299
|
}
|
|
300
300
|
_applyError(t) {
|
|
301
|
-
t instanceof
|
|
301
|
+
t instanceof w && (this._state.message = d(t.body) ?? t.message, t.isValidationError && (this._state.errors = b(t.errors)));
|
|
302
302
|
}
|
|
303
303
|
async _submit(t, e, s = {}) {
|
|
304
|
-
var
|
|
305
|
-
const r = e ?? ((
|
|
304
|
+
var n;
|
|
305
|
+
const r = e ?? ((n = this._source) == null ? void 0 : n.url);
|
|
306
306
|
if (!r)
|
|
307
307
|
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 ?
|
|
308
|
+
let o = s.data !== void 0 ? s.data : s.only ? g(this._state.data, s.only) : this._state.data ?? void 0;
|
|
309
309
|
if (s.data === void 0 && this._transformRequest && o !== void 0) {
|
|
310
|
-
const
|
|
311
|
-
o = this._transformRequest(
|
|
310
|
+
const a = c(o);
|
|
311
|
+
o = this._transformRequest(a) ?? a;
|
|
312
312
|
}
|
|
313
313
|
this._state.processing = !0, this._state.errors = {}, this._state.message = null;
|
|
314
314
|
try {
|
|
315
|
-
const
|
|
315
|
+
const a = await this._apix.request(t, r, {
|
|
316
316
|
data: o,
|
|
317
317
|
params: s.params,
|
|
318
318
|
headers: s.headers
|
|
319
319
|
});
|
|
320
|
-
return this._state.message =
|
|
321
|
-
} catch (
|
|
322
|
-
throw this._applyError(
|
|
320
|
+
return this._state.message = d(a), a;
|
|
321
|
+
} catch (a) {
|
|
322
|
+
throw this._applyError(a), a;
|
|
323
323
|
} finally {
|
|
324
324
|
this._state.processing = !1;
|
|
325
325
|
}
|
|
326
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
|
+
}
|
|
327
339
|
_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();
|
|
340
|
+
this._payloadJson() !== this._lastSent && (this._debounceTimer && clearTimeout(this._debounceTimer), this._debounce > 0 ? this._debounceTimer = setTimeout(() => this._sendWatchRequest(), this._debounce) : this._sendWatchRequest());
|
|
332
341
|
}
|
|
333
342
|
_sendWatchRequest() {
|
|
334
|
-
this._debounceTimer = null, this._source && (this._lastSent = this._payloadJson(), this._fill(this.
|
|
343
|
+
this._debounceTimer = null, this._source && (this._lastSent = this._payloadJson(), this._fill(this._buildFillExtra()).catch(() => {
|
|
335
344
|
}));
|
|
336
345
|
}
|
|
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 };
|
|
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 };
|
|
344
351
|
}
|
|
345
352
|
_payloadJson() {
|
|
346
|
-
const
|
|
353
|
+
const e = (this._triggerFields ?? []).map((s) => f(this._state.data, s));
|
|
347
354
|
return JSON.stringify(e) ?? "undefined";
|
|
348
355
|
}
|
|
349
356
|
_syncLastSent() {
|
|
350
357
|
this._lastSent = this._payloadJson();
|
|
351
358
|
}
|
|
352
359
|
}
|
|
353
|
-
function
|
|
354
|
-
const s = new
|
|
355
|
-
get(o,
|
|
356
|
-
if (typeof
|
|
357
|
-
const
|
|
358
|
-
if (
|
|
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];
|
|
359
366
|
},
|
|
360
|
-
set(o,
|
|
361
|
-
if (typeof
|
|
367
|
+
set(o, n, a) {
|
|
368
|
+
if (typeof n == "symbol" || n in o) return Reflect.set(o, n, a);
|
|
362
369
|
const h = o._state.data;
|
|
363
|
-
return h && typeof h == "object" ? (h[
|
|
370
|
+
return h && typeof h == "object" ? (h[n] = a, !0) : (o._state.data = { [n]: a }, !0);
|
|
364
371
|
},
|
|
365
|
-
has(o,
|
|
366
|
-
if (
|
|
367
|
-
const
|
|
368
|
-
return !!
|
|
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;
|
|
369
376
|
}
|
|
370
377
|
});
|
|
371
378
|
return s._proxy = r, e && t.immediate !== !1 && r.reload().catch(() => {
|
|
372
379
|
}), r;
|
|
373
380
|
}
|
|
374
|
-
class
|
|
381
|
+
class U {
|
|
375
382
|
constructor(t = {}) {
|
|
376
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);
|
|
377
384
|
}
|
|
@@ -421,23 +428,23 @@ class k {
|
|
|
421
428
|
accept: "application/json",
|
|
422
429
|
"x-requested-with": "XMLHttpRequest"
|
|
423
430
|
};
|
|
424
|
-
for (const [h,
|
|
425
|
-
const
|
|
426
|
-
|
|
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);
|
|
427
434
|
}
|
|
428
|
-
for (const [h,
|
|
429
|
-
o[h.toLowerCase()] =
|
|
430
|
-
const
|
|
431
|
-
this.credentials && (
|
|
432
|
-
const
|
|
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 };
|
|
433
440
|
this.trackStart();
|
|
434
441
|
try {
|
|
435
|
-
const h = await fetch(r,
|
|
436
|
-
let
|
|
437
|
-
if (this.bodyTransformer && (
|
|
438
|
-
return
|
|
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;
|
|
439
446
|
} catch (h) {
|
|
440
|
-
throw
|
|
447
|
+
throw E(h) ? h : this.emitError(h, a);
|
|
441
448
|
} finally {
|
|
442
449
|
this.trackEnd();
|
|
443
450
|
}
|
|
@@ -461,7 +468,7 @@ class k {
|
|
|
461
468
|
// --- form models -----------------------------------------------------------
|
|
462
469
|
/** Create a form model without any request (like Inertia's useForm). */
|
|
463
470
|
form(t, e = {}) {
|
|
464
|
-
return
|
|
471
|
+
return j(this, { ...e, default: typeof t == "function" ? t : () => c(t) });
|
|
465
472
|
}
|
|
466
473
|
/** Create a form model and fill it with a GET request. */
|
|
467
474
|
getForm(t, e) {
|
|
@@ -473,7 +480,7 @@ class k {
|
|
|
473
480
|
}
|
|
474
481
|
createFormModel(t, e, s) {
|
|
475
482
|
const r = typeof s == "string" ? { path: s } : { ...s ?? {} };
|
|
476
|
-
return
|
|
483
|
+
return j(this, r, { url: e, method: t });
|
|
477
484
|
}
|
|
478
485
|
// --- internals --------------------------------------------------------------
|
|
479
486
|
trackStart() {
|
|
@@ -501,15 +508,15 @@ class k {
|
|
|
501
508
|
return s;
|
|
502
509
|
}
|
|
503
510
|
}
|
|
504
|
-
function
|
|
505
|
-
return new
|
|
511
|
+
function L(i = {}) {
|
|
512
|
+
return new U(i);
|
|
506
513
|
}
|
|
507
|
-
const
|
|
514
|
+
const P = L();
|
|
508
515
|
export {
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
516
|
+
U as Apix,
|
|
517
|
+
w as ApixError,
|
|
518
|
+
T as ApixFormModel,
|
|
519
|
+
P as apix,
|
|
520
|
+
L as createApix,
|
|
521
|
+
P as default
|
|
515
522
|
};
|