@diephp/vue-apix 0.1.0 → 0.1.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 CHANGED
@@ -1,68 +1,89 @@
1
1
  # @diephp/vue-apix
2
2
 
3
3
  Tiny form / model / api toolkit for Vue 3. Fetch data, edit it, send it back — with reactive
4
- `processing`, Laravel-style validation errors and auto-refetch on change. No axios, zero
5
- runtime dependencies, only Vue 3 as a peer.
4
+ `processing`, Laravel-style validation errors and auto-refetch on change. Built on native
5
+ `fetch`, zero runtime dependencies, only Vue 3 as a peer.
6
6
 
7
7
  The closest relative is Inertia's `useForm`, but vue-apix works with any JSON API and also
8
8
  covers "load → edit → submit" and "filters + pagination" flows.
9
9
 
10
+ ## Installation
11
+
10
12
  ```bash
11
13
  npm i @diephp/vue-apix
12
14
  ```
13
15
 
16
+ ```bash
17
+ yarn add @diephp/vue-apix
18
+ ```
19
+
20
+ ```bash
21
+ pnpm add @diephp/vue-apix
22
+ ```
23
+
24
+ Requires Vue `^3.3`. TypeScript definitions are bundled.
25
+
14
26
  ## Setup
15
27
 
16
- Create your own configured instance (e.g. `src/api.ts`) and import it everywhere:
28
+ Create your own configured instance once (e.g. `src/api.ts`) and import it everywhere:
17
29
 
18
30
  ```ts
31
+ // src/api.ts
19
32
  import apix from '@diephp/vue-apix';
20
33
 
21
- apix.setBaseUrl('https://api.domain.com/v1'); // all request URLs then start with /
22
- apix.setHeader({
23
- 'x-auth-token': () => localStorage.getItem('token'), // lazy: resolved on every request
24
- 'x-app': 'admin', // static
25
- });
34
+ // all relative request URLs are prefixed with this, so they must start with /
35
+ apix.setBaseUrl('https://api.domain.com/v1');
26
36
 
27
- apix.onProcessing((active) => progressBar.toggle(active)); // any request in flight
28
- apix.onError((error, ctx) => { // any failed request
29
- if (error instanceof ApixError && error.status === 401) redirectToLogin();
37
+ apix.setHeader({
38
+ // lazy value: the callback is resolved on every request
39
+ 'x-auth-token': () => localStorage.getItem('token'),
40
+ // static value
41
+ 'x-app': 'admin',
30
42
  });
31
43
 
32
- // onError may RETURN an Error to replace the original one — the replacement goes
33
- // to the next hooks, to model.errors/message and to the rejected promise.
34
- // Handy for normalizing non-Laravel validation formats:
35
- apix.onError((error) => {
36
- if (error instanceof ApixError && error.status === 400 && error.body?.details) {
37
- return new ApixError(422, { message: error.body.error_text, errors: error.body.details });
38
- }
39
- });
44
+ // fires with true when the first request starts, false when the last one ends —
45
+ // perfect for a global progress bar / spinner
46
+ apix.onProcessing((active) => progressBar.toggle(active));
40
47
 
41
- // Global body transformer: applied to EVERY parsed response body (success and
42
- // error statuses) before it is used anywhere — ApixError.message/errors included.
43
- // Return a new body, or mutate in place and return nothing.
44
- apix.transformResponse((body) => {
45
- if (body?.messages?.[0]?.message) body.message = body.messages[0].message;
48
+ // fires on every failed request
49
+ apix.onError((error, ctx) => {
50
+ if (error instanceof ApixError && error.status === 401) redirectToLogin();
46
51
  });
47
52
 
48
53
  export default apix;
49
54
  ```
50
55
 
51
- Or create isolated instances: `const other = createApix({ baseUrl, headers, credentials: 'include' })`.
56
+ ```ts
57
+ // any component / store
58
+ import apix from '@/api';
59
+ ```
60
+
61
+ Need an isolated instance (a second API with different auth)? Create one:
62
+
63
+ ```ts
64
+ import { createApix } from '@diephp/vue-apix';
65
+
66
+ // credentials: 'include' — for cookie-based auth like Laravel Sanctum
67
+ const other = createApix({ baseUrl: 'https://other.api', credentials: 'include' });
68
+ ```
52
69
 
53
70
  ## Plain requests (Promise, no model)
54
71
 
55
72
  ```ts
56
- apix.get('/users', { filters: { name: 'x' }, page: 2 }); // → /users?filters[name]=x&page=2
73
+ // GET /users?filters[name]=x&page=2
74
+ apix.get('/users', { filters: { name: 'x' }, page: 2 });
75
+
57
76
  apix.post('/users', { name: 'a' });
58
77
  apix.put('/users/1', { name: 'b' });
59
78
  apix.patch('/users/1', { name: 'c' });
60
- apix.delete('/users', { ids: [1, 2] }); // DELETE with a body is allowed
79
+
80
+ // DELETE with a body is allowed
81
+ apix.delete('/users', { ids: [1, 2] });
61
82
  ```
62
83
 
63
84
  Query params are serialized PHP-style (`filters[name]=x`), booleans become `1/0`,
64
85
  `null`/`undefined` are skipped. Non-2xx responses reject with `ApixError`
65
- (`status`, `body`, `errors`, `isValidationError`).
86
+ (`status`, `body`, `message`, `errors`, `isValidationError`).
66
87
 
67
88
  ## Forms
68
89
 
@@ -70,53 +91,117 @@ Query params are serialized PHP-style (`filters[name]=x`), booleans become `1/0`
70
91
 
71
92
  ```ts
72
93
  const model = apix.form({ name: null, description: null });
73
- model.name = 'tosic'; // magic prop ≡ model.data.name, fully reactive
94
+
95
+ // magic prop ≡ model.data.name, fully reactive
96
+ model.name = 'tosic';
97
+
74
98
  model.post('/api/attribute').then(({ message }) => alert(message));
75
99
  ```
76
100
 
77
101
  ### Filled from the API
78
102
 
79
103
  ```ts
80
- interface AttrDto { id: number | null; name: string | null; description: string | null }
104
+ interface AttrDto {
105
+ id: number | null;
106
+ name: string | null;
107
+ description: string | null;
108
+ }
81
109
 
82
110
  // response: {data: {item: {...}}} → model.data = item
83
111
  const model = apix.getForm<AttrDto>('/api/attribute/123', 'item');
112
+ ```
113
+
114
+ Full options:
84
115
 
85
- // full options:
116
+ ```ts
86
117
  const model = apix.getForm<AttrDto>('/api/attribute/123', {
87
- path: 'item', // dot-path inside body.data (or body if no data wrapper)
88
- default: () => ({ id: null, name: null, description: null }), // used while loading
89
- immediate: true, // default; false = wait for reload()/watch trigger
90
- params: { with: 'labels' }, // extra query params for every fill request
91
- onSuccess: (response, model) => {}, // every successful fill (initial, reload, watch)
118
+ // dot-path inside body.data (or inside body when there is no data wrapper)
119
+ path: 'item',
120
+ // used while the request is in flight, and as the reset() fallback
121
+ default: () => ({ id: null, name: null, description: null }),
122
+ // default is true; false = no request until reload() or a watch trigger
123
+ immediate: true,
124
+ // default is true: every fill response is deep-merged over default(),
125
+ // so keys the backend didn't return keep their default values
126
+ mergeDefaults: true,
127
+ // extra query params added to every fill request
128
+ params: { with: 'labels' },
129
+ // called after every successful fill (initial, reload(), watch-triggered)
130
+ onSuccess: (response, model) => {},
131
+ // called after every failed fill; aborted (superseded) requests are ignored
92
132
  onError: (error, model) => {},
93
133
  });
94
134
  ```
95
135
 
96
136
  While the request is in flight `model.processing === true` and `model.data` is
97
137
  `default()` (or `null` without a default). `apix.postForm(url, options)` is the same,
98
- but fills via POST (complex search endpoints).
138
+ but fills via POST — for complex search endpoints.
139
+
140
+ **Responses are merged over `default()`.** `default()` describes the shape of your model;
141
+ a fill response is deep-merged on top of it, so keys the backend didn't return keep their
142
+ default values and nested `v-model` targets like `model.filter.name` never disappear:
99
143
 
100
- ### In a component
144
+ ```ts
145
+ const model = apix.getForm('/api/data', {
146
+ default: () => ({
147
+ filter: { name: null, hub_id: null },
148
+ items: [],
149
+ }),
150
+ });
151
+
152
+ // backend returned only {items: [...]} → model.filter is still {name: null, hub_id: null},
153
+ // so <el-input v-model="model.filter.name" /> keeps working
154
+ ```
155
+
156
+ The merge is deep (a partial `filter` object is completed key by key), a `null` where the
157
+ default has an object falls back to the default object, explicit scalar `null`s from the
158
+ response are respected, and arrays are always replaced — never merged. The `reset()`
159
+ snapshot stores the merged state. Opt out with `mergeDefaults: false`.
160
+
161
+ ### Edit form — full component
101
162
 
102
163
  ```vue
103
164
  <script setup lang="ts">
104
- const model = apix.getForm<AttrDto>('/api/attribute/1', { path: 'item', default: () => ({ name: null, description: null }) });
165
+ import apix from '@/api';
166
+
167
+ interface AttrDto {
168
+ id: number | null;
169
+ name: string | null;
170
+ description: string | null;
171
+ }
172
+
173
+ const model = apix.getForm<AttrDto>('/api/attribute/1', {
174
+ path: 'item',
175
+ default: () => ({ id: null, name: null, description: null }),
176
+ });
105
177
 
106
178
  // NOTE: wrap in a function! `model.put(...)` directly in setup would fire immediately.
107
- const submit = () => model.put('/api/attribute/1').then(({ message }) => alert(message));
179
+ const submit = () =>
180
+ model
181
+ .put('/api/attribute/1')
182
+ .then(({ message }) => alert(message))
183
+ .catch(() => {
184
+ // validation errors are already in model.errors — nothing to do here
185
+ });
108
186
  </script>
109
187
 
110
188
  <template>
111
- <form v-loading="model.processing" @submit.prevent="submit">
112
- <input v-model="model.name" />
189
+ <form @submit.prevent="submit">
190
+ <!-- magic prop: model.name ≡ model.data.name -->
191
+ <input v-model="model.name" :disabled="model.processing" />
113
192
  <span v-if="model.errors.name">{{ model.errors.name }}</span>
114
193
 
115
- <input v-model="model.data.description" />
194
+ <!-- explicit path works too -->
195
+ <input v-model="model.data.description" :disabled="model.processing" />
116
196
  <span v-if="model.error('description')">{{ model.error('description') }}</span>
117
197
 
118
198
  <button type="submit" :disabled="model.processing">Save</button>
199
+
200
+ <!-- restore the first server response -->
119
201
  <button type="button" @click="model.reset()">Reset</button>
202
+
203
+ <!-- or reset specific fields only -->
204
+ <button type="button" @click="model.reset(['name'])">Reset name</button>
120
205
  </form>
121
206
  </template>
122
207
  ```
@@ -139,6 +224,7 @@ const submit = () => model.put('/api/attribute/1').then(({ message }) => alert(m
139
224
  | `model.post/put/patch/delete(url?, opts?)` | submit `model.data` (or `opts.data` / `opts.only: ['name']`), returns the response Promise |
140
225
  | `model.reload(url?)` | re-run the fill request |
141
226
  | `model.watch(paths?, opts?)` / `model.unwatch()` | auto-refetch on change, see below |
227
+ | `model.transformResponse(fn)` / `model.transformRequest(fn)` | reshape server data ↔ model data, see below |
142
228
 
143
229
  Submitting clears previous errors; any **4xx** response carrying an `errors` object in the
144
230
  body (Laravel's 422, or any backend using the same shape on 400-499) fills `model.errors`
@@ -150,20 +236,166 @@ treated as validation errors — only `model.message` is surfaced.
150
236
  clearErrors, reset, post, put, patch, delete, reload, watch, unwatch, transformRequest,
151
237
  transformResponse`. A data field with such a name is still there — via `model.data.<key>`.
152
238
 
239
+ ## watch() — filters, pagination, live search
240
+
241
+ The classic SPA page: a table, a filter form and a paginator. One model holds all of it,
242
+ `watch()` re-sends the request whenever the watched paths change:
243
+
244
+ ```vue
245
+ <script setup lang="ts">
246
+ import apix from '@/api';
247
+
248
+ interface ItemDto {
249
+ id: number;
250
+ name: string;
251
+ description: string;
252
+ }
253
+
254
+ interface PageDto {
255
+ items: ItemDto[];
256
+ filters: { name: string | null; status: string | null };
257
+ paginator: { page: number; total: number; per_page: number };
258
+ }
259
+
260
+ const table = apix
261
+ .getForm<PageDto>('/api/attribute', {
262
+ default: () => ({
263
+ items: [],
264
+ filters: { name: null, status: null },
265
+ paginator: { page: 1, total: 0, per_page: 15 },
266
+ }),
267
+ })
268
+ // watch paginator.page (not the whole paginator!) so the server-owned
269
+ // `total` keeps updating from responses — see the note below
270
+ .watch(['filters', 'paginator.page'], { debounce: 300 });
271
+
272
+ const lastPage = () => Math.max(1, Math.ceil(table.paginator.total / table.paginator.per_page));
273
+
274
+ // changing a filter should always jump back to the first page
275
+ const applyFilter = () => (table.paginator.page = 1);
276
+ </script>
277
+
278
+ <template>
279
+ <div>
280
+ <!-- typing here fires ONE debounced request: GET /api/attribute?filters[name]=...&paginator[page]=1 -->
281
+ <input v-model="table.filters.name" placeholder="Search…" @input="applyFilter" />
282
+
283
+ <select v-model="table.filters.status" @change="applyFilter">
284
+ <option :value="null">All</option>
285
+ <option value="active">Active</option>
286
+ <option value="archived">Archived</option>
287
+ </select>
288
+
289
+ <span v-if="table.processing">Loading…</span>
290
+
291
+ <table>
292
+ <tr v-for="item in table.items" :key="item.id">
293
+ <td>{{ item.id }}</td>
294
+ <td>{{ item.name }}</td>
295
+ </tr>
296
+ </table>
297
+
298
+ <!-- pagination: just mutate the watched path, the table refetches itself -->
299
+ <button :disabled="table.paginator.page <= 1" @click="table.paginator.page--">Prev</button>
300
+ <span>{{ table.paginator.page }} / {{ lastPage() }} · total {{ table.paginator.total }}</span>
301
+ <button :disabled="table.paginator.page >= lastPage()" @click="table.paginator.page++">Next</button>
302
+
303
+ <!-- back to the first-response state; the watcher notices and refetches clean data -->
304
+ <button @click="table.reset()">Reset filters</button>
305
+ </div>
306
+ </template>
307
+ ```
308
+
309
+ Expected server response shape for the example above (Laravel-style):
310
+
311
+ ```json
312
+ {
313
+ "data": {
314
+ "items": [{ "id": 1, "name": "Attribute 1", "description": "..." }],
315
+ "filters": { "name": null, "status": null },
316
+ "paginator": { "page": 1, "total": 42, "per_page": 15 }
317
+ }
318
+ }
319
+ ```
320
+
321
+ How `watch()` behaves:
322
+
323
+ - **Only the watched paths are sent.** GET → PHP-style query
324
+ (`filters[name]=x&paginator[page]=2`), postForm → JSON body. Override with `payload: [...]`.
325
+ - **The response updates everything except the watched paths**, so a slow response never
326
+ clobbers what the user is typing. Opt out with `refreshWatched: true`.
327
+ - **A new trigger aborts the previous in-flight request** (AbortController) — the last
328
+ change wins, out-of-order responses can't overwrite fresh data.
329
+ - **Debounce** (`debounce: 300`) collapses fast typing into one request.
330
+ - `reset()` restores the first-response snapshot; if that actually changes watched data,
331
+ the request is re-sent — reset filters, the table refreshes itself.
332
+ - **Watch server-owned fields precisely**: `['filters', 'paginator.page']`, not
333
+ `['paginator']` — a watched path is preserved from responses, so watching the whole
334
+ `paginator` would freeze `paginator.total` at its first value.
335
+ - Created inside `setup()`, the watcher is bound to the component scope and stops on
336
+ unmount. Module-level models live until `model.unwatch()`.
337
+
338
+ ### Live search (minimal)
339
+
340
+ ```ts
341
+ interface SearchDto {
342
+ results: Array<{ id: number; title: string }>;
343
+ query: string | null;
344
+ }
345
+
346
+ const search = apix
347
+ .getForm<SearchDto>('/api/search', {
348
+ default: () => ({ results: [], query: null }),
349
+ // don't hit the API until the user types something
350
+ immediate: false,
351
+ })
352
+ .watch(['query'], { debounce: 400 });
353
+
354
+ // template: <input v-model="search.query" /> — that's the whole feature
355
+ ```
356
+
357
+ ## Global hooks and error normalization
358
+
359
+ ```ts
360
+ // onError may RETURN an Error to replace the original one — the replacement goes
361
+ // to the next hooks, to model.errors/message and to the rejected promise.
362
+ // Handy when a backend uses its own validation format:
363
+ apix.onError((error) => {
364
+ if (error instanceof ApixError && error.status === 400 && error.body?.details) {
365
+ return new ApixError(422, {
366
+ message: error.body.error_text,
367
+ errors: error.body.details,
368
+ });
369
+ }
370
+ });
371
+ ```
372
+
373
+ ```ts
374
+ // Global body transformer: applied to EVERY parsed response body (success and
375
+ // error statuses) before it is used anywhere — ApixError.message/errors included.
376
+ // Return a new body, or mutate it in place and return nothing.
377
+ apix.transformResponse((body) => {
378
+ // example: the backend sends messages as an array — lift the first one to body.message
379
+ if (body?.messages?.[0]?.message) body.message = body.messages[0].message;
380
+ });
381
+ ```
382
+
153
383
  ## Model transformers — reshape server data
154
384
 
155
385
  When the API shape is awkward (nested, legacy), unwrap it into a comfortable model
156
386
  shape and wrap it back on submit:
157
387
 
158
388
  ```ts
159
- // server: {attr: {name: {value: 'x'}}} ↔ model: {name: 'x'}
389
+ // server shape: {attr: {name: {value: 'x'}}} ↔ model shape: {name: 'x'}
160
390
  const model = apix
161
391
  .getForm<{ name: string | null }>('/api/attribute/1', 'item')
162
392
  .transformResponse((data) => ({ name: data?.attr?.name?.value ?? null }))
163
393
  .transformRequest((data) => ({ attr: { name: { value: data.name } } }));
164
394
 
165
395
  model.name = 'edited';
166
- model.put(); // body: {attr: {name: {value: 'edited'}}}
396
+
397
+ // body sent: {attr: {name: {value: 'edited'}}}
398
+ model.put();
167
399
  ```
168
400
 
169
401
  - `transformResponse(data, response)` runs on every fill (initial, `reload()`, watch) after
@@ -174,48 +406,21 @@ model.put(); // body: {attr: {name: {value: 'edited'}}}
174
406
  mutations never touch the model.
175
407
  - Both are also accepted as `getForm`/`postForm`/`form` options.
176
408
 
177
- ## watch() — filters, pagination, live search
178
-
179
- ```ts
180
- interface PageDto {
181
- items: ItemDto[];
182
- filters: { name: string | null };
183
- paginator: { page: number; total: number; per_page: number };
184
- }
185
-
186
- const table = apix
187
- .getForm<PageDto>('/api/fetch/data', {
188
- default: () => ({ items: [], filters: { name: null }, paginator: { page: 1, total: 0, per_page: 15 } }),
189
- })
190
- .watch(['filters', 'paginator.page'], { debounce: 300 });
191
-
192
- // template: v-model="table.filters.name", @click="table.paginator.page++" — the table refetches itself
193
- ```
194
-
195
- How it behaves:
196
-
197
- - **Only the watched paths are sent** — GET → PHP-style query (`filters[name]=x&paginator[page]=2`),
198
- postForm → JSON body. Override with `payload: [...]`.
199
- - **The response updates everything except the watched paths**, so a slow response never
200
- clobbers what the user is typing. Opt out with `refreshWatched: true`.
201
- - **A new trigger aborts the previous in-flight request** (AbortController) — the last change wins.
202
- - **Debounce** (`debounce: 300`) collapses fast typing into one request.
203
- - `reset()` restores the first-response snapshot; if that actually changes watched data,
204
- the request is re-sent — reset filters, table refreshes.
205
- - Watch server-owned fields precisely: `['filters', 'paginator.page']`, not `['paginator']` —
206
- otherwise `paginator.total` from the response would be preserved away too.
207
- - Created inside `setup()`, the watcher is bound to the component scope and stops on unmount.
208
- Module-level models live until `model.unwatch()`.
209
-
210
409
  ## TypeScript
211
410
 
212
411
  ```ts
213
412
  const model = apix.getForm<AttrDto>('/api/attribute/1', 'item');
214
- model.name; // typed via magic props: Model<AttrDto> = ApixModel<AttrDto> & AttrDto
215
- model.data?.description; // full escape hatch
413
+
414
+ // typed via magic props: Model<AttrDto> = ApixModel<AttrDto> & AttrDto
415
+ model.name;
416
+
417
+ // full escape hatch
418
+ model.data?.description;
216
419
 
217
420
  const list = apix.getForm<ItemDto[]>('/api/attribute', 'items');
218
- list.data?.map((item) => item.name); // arrays: no magic props, use .data
421
+
422
+ // arrays: no magic props, iterate .data directly
423
+ list.data?.map((item) => item.name);
219
424
  ```
220
425
 
221
426
  ## License
package/dist/types.d.ts CHANGED
@@ -50,6 +50,14 @@ export interface FormOptions<T = any> {
50
50
  default?: () => T;
51
51
  /** Send the fill request immediately (default: true). */
52
52
  immediate?: boolean;
53
+ /**
54
+ * Deep-merge every fill response over `default()` (default: true).
55
+ * Keys the backend didn't return keep their default values, so nested
56
+ * v-model targets (e.g. `model.filter.name`) never disappear.
57
+ * Arrays are never merged — a response array replaces the default one.
58
+ * Set false to use the response as-is.
59
+ */
60
+ mergeDefaults?: boolean;
53
61
  /** Extra query params sent with every fill request (initial, reload, watch). */
54
62
  params?: Record<string, unknown>;
55
63
  /** Body for `postForm` fill requests. */
package/dist/utils.d.ts CHANGED
@@ -4,6 +4,17 @@
4
4
  * (File, Blob, class instances) is kept by reference.
5
5
  */
6
6
  export declare function deepClone<T>(value: T): T;
7
+ export declare function isPlainObject(value: unknown): value is Record<string, any>;
8
+ /**
9
+ * Fill gaps in `incoming` using `defaults`:
10
+ * - keys missing in the response fall back to the default value;
11
+ * - where defaults have a nested plain object but the response has null/undefined,
12
+ * the default object is used (keeps deep v-model targets alive);
13
+ * - present response values always win (including explicit scalar nulls);
14
+ * - arrays are never merged — a response array replaces the default one.
15
+ * `incoming` must be a detached clone — it is mutated in place.
16
+ */
17
+ export declare function mergeDefaults(incoming: any, defaults: any): any;
7
18
  export declare function pathGet(target: any, path: string): any;
8
19
  export declare function pathSet(target: any, path: string, value: any): void;
9
20
  /** Build a plain object holding deep clones of the given dot-paths. */
package/dist/vue-apix.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const p=require("vue");function c(o){const t=p.toRaw(o);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 f(o,t){if(o==null)return;let e=o;for(const s of t.split(".")){if(e==null)return;e=e[s]}return e}function m(o,t,e){const s=t.split(".");let r=o;for(let i=0;i<s.length-1;i++){const a=s[i];(r[a]===null||typeof r[a]!="object")&&(r[a]={}),r=r[a]}r[s[s.length-1]]=e}function b(o,t){const e={};for(const s of t){const r=f(o,s);r!==void 0&&m(e,s,c(r))}return e}function w(o){const t={};for(const[e,s]of Object.entries(o??{}))s!=null&&(t[e]=Array.isArray(s)?String(s[0]):String(s));return t}function d(o){return o&&typeof o=="object"&&typeof o.message=="string"?o.message:null}function q(o,t){const e=o&&typeof o=="object"&&!Array.isArray(o)&&"data"in o?o.data:o;return t?f(e,t):e}class y 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 A(o){return o instanceof Error&&o.name==="AbortError"}function S(o){const t=[],e=(r,i)=>{t.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`)},s=(r,i)=>{if(r!=null){if(typeof r=="boolean")return e(i,r?"1":"0");if(r instanceof Date)return e(i,r.toISOString());if(Array.isArray(r)){r.forEach((a,n)=>s(a,`${i}[${n}]`));return}if(typeof r=="object"){for(const[a,n]of Object.entries(r))s(n,`${i}[${a}]`);return}e(i,String(r))}};for(const[r,i]of Object.entries(o))s(i,r);return t.join("&")}async function O(o){if(o.status===204)return null;const t=await o.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}class j{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=p.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=w(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)."))}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 i=s&&s.length?s.map(a=>()=>f(this._state.data,a)):()=>this._state.data;return this._stopWatch=p.watch(i,()=>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 i,a,n,h,l;const e=this._source;(i=this._fillAbort)==null||i.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 _=q(u,this._options.path);if(this._transformResponse){const g=c(_);_=this._transformResponse(g,u)??g}return this._applyFill(_,t.preserve??null),this._state.message=d(u),this._state.errors={},(n=(a=this._options).onSuccess)==null||n.call(a,u,this._proxy),u}catch(u){throw A(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){const s=c(t);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const r of e){const i=f(this._state.data,r);i!==void 0&&m(s,r,c(i))}this._state.data=s,this._snapshotLocked||(this._snapshot=c(t),this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof y&&(this._state.message=d(t.body)??t.message,t.isValidationError&&(this._state.errors=w(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 i=s.data!==void 0?s.data:s.only?b(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&i!==void 0){const n=c(i);i=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:i,params:s.params,headers:s.headers});return this._state.message=d(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(){if(this._debounceTimer=null,!this._source)return;const t=this._watched,e=this._watchOptions.payload??t;let s=e&&e.length?b(this._state.data,e):c(this._state.data);this._transformRequest&&(s=this._transformRequest(s)??s),this._lastSent=this._payloadJson();const r=this._watchOptions.refreshWatched?null:t,i=this._source.method==="get"?{params:s,preserve:r}:{data:s,preserve:r};this._fill(i).catch(()=>{})}_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 x(o,t={},e=null){const s=new j(o,t,e),r=new Proxy(s,{get(i,a){if(typeof a=="symbol"||a in i)return Reflect.get(i,a);const n=i._state.data;if(n&&typeof n=="object")return n[a]},set(i,a,n){if(typeof a=="symbol"||a in i)return Reflect.set(i,a,n);const h=i._state.data;return h&&typeof h=="object"?(h[a]=n,!0):(i._state.data={[a]:n},!0)},has(i,a){if(a in i)return!0;const n=i._state.data;return!!n&&typeof n=="object"&&a in n}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().catch(()=>{}),r}class R{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 i={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&&(i[h]=u)}Object.assign(i,s.headers);const a={method:t.toUpperCase(),headers:i,signal:s.signal};this.credentials&&(a.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?a.body=s.data:(i["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 l=await O(h);if(this.bodyTransformer&&(l=this.bodyTransformer(l,n)??l),!h.ok)throw new y(h.status,l,h);return l}catch(h){throw A(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 x(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 x(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 i=r(s,e);i instanceof Error&&(s=i)}catch{}return s}}function v(o={}){return new R(o)}const E=v();exports.Apix=R;exports.ApixError=y;exports.ApixModel=j;exports.apix=E;exports.createApix=v;exports.default=E;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const _=require("vue");function c(i){const t=_.toRaw(i);if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(s=>c(s));if(t instanceof Date)return new Date(t.getTime());const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const s={};for(const r of Object.keys(t))s[r]=c(t[r]);return s}return t}function b(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function A(i,t){if(!b(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!b(i))return i;for(const e of Object.keys(t))i[e]=e in i?A(i[e],t[e]):c(t[e]);return i}function f(i,t){if(i==null)return;let e=i;for(const s of t.split(".")){if(e==null)return;e=e[s]}return e}function m(i,t,e){const s=t.split(".");let r=i;for(let o=0;o<s.length-1;o++){const a=s[o];(r[a]===null||typeof r[a]!="object")&&(r[a]={}),r=r[a]}r[s[s.length-1]]=e}function w(i,t){const e={};for(const s of t){const r=f(i,s);r!==void 0&&m(e,s,c(r))}return e}function x(i){const t={};for(const[e,s]of Object.entries(i??{}))s!=null&&(t[e]=Array.isArray(s)?String(s[0]):String(s));return t}function p(i){return i&&typeof i=="object"&&typeof i.message=="string"?i.message:null}function S(i,t){const e=i&&typeof i=="object"&&!Array.isArray(i)&&"data"in i?i.data:i;return t?f(e,t):e}class y extends Error{constructor(t,e,s){super(p(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 R(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((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 v{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=_.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)."))}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=_.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,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 d=S(u,this._options.path);if(this._transformResponse){const g=c(d);d=this._transformResponse(g,u)??g}return this._applyFill(d,t.preserve??null),this._state.message=p(u),this._state.errors={},(n=(a=this._options).onSuccess)==null||n.call(a,u,this._proxy),u}catch(u){throw R(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=A(s,this._options.default()));const r=this._snapshotLocked?null:c(s);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const o of e){const a=f(this._state.data,o);a!==void 0&&m(s,o,c(a))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof y&&(this._state.message=p(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=p(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(){if(this._debounceTimer=null,!this._source)return;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),this._lastSent=this._payloadJson();const r=this._watchOptions.refreshWatched?null:t,o=this._source.method==="get"?{params:s,preserve:r}:{data:s,preserve:r};this._fill(o).catch(()=>{})}_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 v(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 E{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]=u)}Object.assign(o,s.headers);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?a.body=s.data:(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 l=await k(h);if(this.bodyTransformer&&(l=this.bodyTransformer(l,n)??l),!h.ok)throw new y(h.status,l,h);return l}catch(h){throw R(h)?h:this.emitError(h,n)}finally{this.trackEnd()}}get(t,e,s={}){return this.request("get",t,e?{...s,params:e}:s)}post(t,e,s={}){return this.request("post",t,e!==void 0?{...s,data:e}:s)}put(t,e,s={}){return this.request("put",t,e!==void 0?{...s,data:e}:s)}patch(t,e,s={}){return this.request("patch",t,e!==void 0?{...s,data:e}:s)}delete(t,e,s={}){return this.request("delete",t,e!==void 0?{...s,data:e}:s)}form(t,e={}){return j(this,{...e,default:typeof t=="function"?t:()=>c(t)})}getForm(t,e){return this.createFormModel("get",t,e)}postForm(t,e){return this.createFormModel("post",t,e)}createFormModel(t,e,s){const r=typeof s=="string"?{path:s}:{...s??{}};return j(this,r,{url:e,method:t})}trackStart(){++this.active===1&&this.emitProcessing(!0)}trackEnd(){--this.active===0&&this.emitProcessing(!1)}emitProcessing(t){for(const e of this.processingHooks)try{e(t)}catch{}}emitError(t,e){let s=t;for(const r of this.errorHooks)try{const o=r(s,e);o instanceof Error&&(s=o)}catch{}return s}}function O(i={}){return new E(i)}const q=O();exports.Apix=E;exports.ApixError=y;exports.ApixModel=v;exports.apix=q;exports.createApix=O;exports.default=q;
package/dist/vue-apix.js CHANGED
@@ -1,6 +1,6 @@
1
- import { toRaw as R, reactive as j, watch as A } from "vue";
2
- function c(o) {
3
- const t = R(o);
1
+ import { toRaw as A, reactive as E, watch as O } from "vue";
2
+ function c(i) {
3
+ const t = A(i);
4
4
  if (t === null || typeof t != "object") return t;
5
5
  if (Array.isArray(t)) return t.map((e) => c(e));
6
6
  if (t instanceof Date) return new Date(t.getTime());
@@ -12,48 +12,62 @@ function c(o) {
12
12
  }
13
13
  return t;
14
14
  }
15
- function f(o, t) {
16
- if (o == null) return;
17
- let s = o;
15
+ function y(i) {
16
+ if (i === null || typeof i != "object") return !1;
17
+ const t = Object.getPrototypeOf(i);
18
+ return t === Object.prototype || t === null;
19
+ }
20
+ function x(i, t) {
21
+ if (!y(t))
22
+ return i === void 0 ? c(t) : i;
23
+ if (i == null) return c(t);
24
+ if (!y(i)) return i;
25
+ for (const s of Object.keys(t))
26
+ i[s] = s in i ? x(i[s], t[s]) : c(t[s]);
27
+ return i;
28
+ }
29
+ function f(i, t) {
30
+ if (i == null) return;
31
+ let s = i;
18
32
  for (const e of t.split(".")) {
19
33
  if (s == null) return;
20
34
  s = s[e];
21
35
  }
22
36
  return s;
23
37
  }
24
- function p(o, t, s) {
38
+ function d(i, t, s) {
25
39
  const e = t.split(".");
26
- let r = o;
27
- for (let i = 0; i < e.length - 1; i++) {
28
- const a = e[i];
40
+ let r = i;
41
+ for (let o = 0; o < e.length - 1; o++) {
42
+ const a = e[o];
29
43
  (r[a] === null || typeof r[a] != "object") && (r[a] = {}), r = r[a];
30
44
  }
31
45
  r[e[e.length - 1]] = s;
32
46
  }
33
- function y(o, t) {
47
+ function g(i, t) {
34
48
  const s = {};
35
49
  for (const e of t) {
36
- const r = f(o, e);
37
- r !== void 0 && p(s, e, c(r));
50
+ const r = f(i, e);
51
+ r !== void 0 && d(s, e, c(r));
38
52
  }
39
53
  return s;
40
54
  }
41
- function g(o) {
55
+ function b(i) {
42
56
  const t = {};
43
- for (const [s, e] of Object.entries(o ?? {}))
57
+ for (const [s, e] of Object.entries(i ?? {}))
44
58
  e != null && (t[s] = Array.isArray(e) ? String(e[0]) : String(e));
45
59
  return t;
46
60
  }
47
- function d(o) {
48
- return o && typeof o == "object" && typeof o.message == "string" ? o.message : null;
61
+ function p(i) {
62
+ return i && typeof i == "object" && typeof i.message == "string" ? i.message : null;
49
63
  }
50
- function E(o, t) {
51
- const s = o && typeof o == "object" && !Array.isArray(o) && "data" in o ? o.data : o;
64
+ function q(i, t) {
65
+ const s = i && typeof i == "object" && !Array.isArray(i) && "data" in i ? i.data : i;
52
66
  return t ? f(s, t) : s;
53
67
  }
54
- class w extends Error {
68
+ class j extends Error {
55
69
  constructor(t, s, e) {
56
- super(d(s) ?? `Request failed with status ${t}`), this.name = "ApixError", this.status = t, this.body = s, this.response = e, this.errors = s && typeof s == "object" && s.errors && typeof s.errors == "object" ? s.errors : {};
70
+ super(p(s) ?? `Request failed with status ${t}`), this.name = "ApixError", this.status = t, this.body = s, this.response = e, this.errors = s && typeof s == "object" && s.errors && typeof s.errors == "object" ? s.errors : {};
57
71
  }
58
72
  /**
59
73
  * True for any 4xx response whose body carries an `errors` object
@@ -64,33 +78,33 @@ class w extends Error {
64
78
  return this.status >= 400 && this.status < 500 && Object.keys(this.errors).length > 0;
65
79
  }
66
80
  }
67
- function x(o) {
68
- return o instanceof Error && o.name === "AbortError";
81
+ function R(i) {
82
+ return i instanceof Error && i.name === "AbortError";
69
83
  }
70
- function q(o) {
71
- const t = [], s = (r, i) => {
72
- t.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`);
73
- }, e = (r, i) => {
84
+ function v(i) {
85
+ const t = [], s = (r, o) => {
86
+ t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`);
87
+ }, e = (r, o) => {
74
88
  if (r != null) {
75
- if (typeof r == "boolean") return s(i, r ? "1" : "0");
76
- if (r instanceof Date) return s(i, r.toISOString());
89
+ if (typeof r == "boolean") return s(o, r ? "1" : "0");
90
+ if (r instanceof Date) return s(o, r.toISOString());
77
91
  if (Array.isArray(r)) {
78
- r.forEach((a, n) => e(a, `${i}[${n}]`));
92
+ r.forEach((a, n) => e(a, `${o}[${n}]`));
79
93
  return;
80
94
  }
81
95
  if (typeof r == "object") {
82
- for (const [a, n] of Object.entries(r)) e(n, `${i}[${a}]`);
96
+ for (const [a, n] of Object.entries(r)) e(n, `${o}[${a}]`);
83
97
  return;
84
98
  }
85
- s(i, String(r));
99
+ s(o, String(r));
86
100
  }
87
101
  };
88
- for (const [r, i] of Object.entries(o)) e(i, r);
102
+ for (const [r, o] of Object.entries(i)) e(o, r);
89
103
  return t.join("&");
90
104
  }
91
- async function v(o) {
92
- if (o.status === 204) return null;
93
- const t = await o.text();
105
+ async function S(i) {
106
+ if (i.status === 204) return null;
107
+ const t = await i.text();
94
108
  if (!t) return null;
95
109
  try {
96
110
  return JSON.parse(t);
@@ -98,11 +112,11 @@ async function v(o) {
98
112
  return t;
99
113
  }
100
114
  }
101
- class O {
115
+ class T {
102
116
  constructor(t, s = {}, e = null) {
103
117
  this._snapshot = null, this._snapshotLocked = !1, this._stopWatch = null, this._debounceTimer = null, this._watched = null, this._watchOptions = {}, this._lastSent = null, this._fillAbort = null, this._transformResponse = null, this._transformRequest = null, this._apix = t, this._options = s, this._source = e, this._transformResponse = s.transformResponse ?? null, this._transformRequest = s.transformRequest ?? null;
104
118
  const r = s.default ? s.default() : null;
105
- this._state = j({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r);
119
+ this._state = E({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r);
106
120
  }
107
121
  // --- reactive state ---------------------------------------------------------
108
122
  get data() {
@@ -153,7 +167,7 @@ class O {
153
167
  if (r.startsWith(e)) return s[r];
154
168
  }
155
169
  setErrors(t) {
156
- return this._state.errors = g(t), this._proxy;
170
+ return this._state.errors = b(t), this._proxy;
157
171
  }
158
172
  /** Clear all errors, or only the given keys (including their `key.*` sub-errors). */
159
173
  clearErrors(t) {
@@ -177,7 +191,7 @@ class O {
177
191
  const s = Array.isArray(t) ? t : [t];
178
192
  if (this._state.data && typeof this._state.data == "object")
179
193
  for (const e of s)
180
- p(this._state.data, e, c(f(this._snapshot, e)));
194
+ d(this._state.data, e, c(f(this._snapshot, e)));
181
195
  return this.clearErrors(s), this._proxy;
182
196
  }
183
197
  // --- HTTP ------------------------------------------------------------------------
@@ -229,8 +243,8 @@ class O {
229
243
  watch(t, s) {
230
244
  let e = null, r;
231
245
  Array.isArray(t) ? (e = t, r = s ?? {}) : r = t ?? s ?? {}, 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 = e, this._watchOptions = r, this._syncLastSent();
232
- const i = e && e.length ? e.map((a) => () => f(this._state.data, a)) : () => this._state.data;
233
- return this._stopWatch = A(i, () => this._onWatchTrigger(), {
246
+ const o = e && e.length ? e.map((a) => () => f(this._state.data, a)) : () => this._state.data;
247
+ return this._stopWatch = O(o, () => this._onWatchTrigger(), {
234
248
  deep: r.deep ?? !0
235
249
  }), this._proxy;
236
250
  }
@@ -241,57 +255,59 @@ class O {
241
255
  // --- internals ----------------------------------------------------------------------
242
256
  /** @internal */
243
257
  async _fill(t = {}) {
244
- var i, a, n, h, l;
258
+ var o, a, n, h, l;
245
259
  const s = this._source;
246
- (i = this._fillAbort) == null || i.abort();
260
+ (o = this._fillAbort) == null || o.abort();
247
261
  const e = new AbortController();
248
262
  this._fillAbort = e, this._state.processing = !0;
249
263
  const r = { signal: e.signal };
250
264
  s.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);
251
265
  try {
252
266
  const u = await this._apix.request(s.method, s.url, r);
253
- let _ = E(u, this._options.path);
267
+ let _ = q(u, this._options.path);
254
268
  if (this._transformResponse) {
255
269
  const m = c(_);
256
270
  _ = this._transformResponse(m, u) ?? m;
257
271
  }
258
- return this._applyFill(_, t.preserve ?? null), this._state.message = d(u), this._state.errors = {}, (n = (a = this._options).onSuccess) == null || n.call(a, u, this._proxy), u;
272
+ return this._applyFill(_, t.preserve ?? null), this._state.message = p(u), this._state.errors = {}, (n = (a = this._options).onSuccess) == null || n.call(a, u, this._proxy), u;
259
273
  } catch (u) {
260
- throw x(u) || (this._applyError(u), (l = (h = this._options).onError) == null || l.call(h, u, this._proxy)), u;
274
+ throw R(u) || (this._applyError(u), (l = (h = this._options).onError) == null || l.call(h, u, this._proxy)), u;
261
275
  } finally {
262
276
  this._fillAbort === e && (this._fillAbort = null, this._state.processing = !1);
263
277
  }
264
278
  }
265
279
  _applyFill(t, s) {
266
- const e = c(t);
280
+ let e = c(t);
281
+ this._options.mergeDefaults !== !1 && this._options.default && (e = x(e, this._options.default()));
282
+ const r = this._snapshotLocked ? null : c(e);
267
283
  if (s && s.length && e && typeof e == "object" && this._state.data && typeof this._state.data == "object")
268
- for (const r of s) {
269
- const i = f(this._state.data, r);
270
- i !== void 0 && p(e, r, c(i));
284
+ for (const o of s) {
285
+ const a = f(this._state.data, o);
286
+ a !== void 0 && d(e, o, c(a));
271
287
  }
272
- this._state.data = e, this._snapshotLocked || (this._snapshot = c(t), this._snapshotLocked = !0), this._syncLastSent();
288
+ this._state.data = e, this._snapshotLocked || (this._snapshot = r, this._snapshotLocked = !0), this._syncLastSent();
273
289
  }
274
290
  _applyError(t) {
275
- t instanceof w && (this._state.message = d(t.body) ?? t.message, t.isValidationError && (this._state.errors = g(t.errors)));
291
+ t instanceof j && (this._state.message = p(t.body) ?? t.message, t.isValidationError && (this._state.errors = b(t.errors)));
276
292
  }
277
293
  async _submit(t, s, e = {}) {
278
294
  var a;
279
295
  const r = s ?? ((a = this._source) == null ? void 0 : a.url);
280
296
  if (!r)
281
297
  throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);
282
- let i = e.data !== void 0 ? e.data : e.only ? y(this._state.data, e.only) : this._state.data ?? void 0;
283
- if (e.data === void 0 && this._transformRequest && i !== void 0) {
284
- const n = c(i);
285
- i = this._transformRequest(n) ?? n;
298
+ let o = e.data !== void 0 ? e.data : e.only ? g(this._state.data, e.only) : this._state.data ?? void 0;
299
+ if (e.data === void 0 && this._transformRequest && o !== void 0) {
300
+ const n = c(o);
301
+ o = this._transformRequest(n) ?? n;
286
302
  }
287
303
  this._state.processing = !0, this._state.errors = {}, this._state.message = null;
288
304
  try {
289
305
  const n = await this._apix.request(t, r, {
290
- data: i,
306
+ data: o,
291
307
  params: e.params,
292
308
  headers: e.headers
293
309
  });
294
- return this._state.message = d(n), n;
310
+ return this._state.message = p(n), n;
295
311
  } catch (n) {
296
312
  throw this._applyError(n), n;
297
313
  } finally {
@@ -307,10 +323,10 @@ class O {
307
323
  _sendWatchRequest() {
308
324
  if (this._debounceTimer = null, !this._source) return;
309
325
  const t = this._watched, s = this._watchOptions.payload ?? t;
310
- let e = s && s.length ? y(this._state.data, s) : c(this._state.data);
326
+ let e = s && s.length ? g(this._state.data, s) : c(this._state.data);
311
327
  this._transformRequest && (e = this._transformRequest(e) ?? e), this._lastSent = this._payloadJson();
312
- const r = this._watchOptions.refreshWatched ? null : t, i = this._source.method === "get" ? { params: e, preserve: r } : { data: e, preserve: r };
313
- this._fill(i).catch(() => {
328
+ const r = this._watchOptions.refreshWatched ? null : t, o = this._source.method === "get" ? { params: e, preserve: r } : { data: e, preserve: r };
329
+ this._fill(o).catch(() => {
314
330
  });
315
331
  }
316
332
  _payloadJson() {
@@ -321,28 +337,28 @@ class O {
321
337
  this._lastSent = this._payloadJson();
322
338
  }
323
339
  }
324
- function b(o, t = {}, s = null) {
325
- const e = new O(o, t, s), r = new Proxy(e, {
326
- get(i, a) {
327
- if (typeof a == "symbol" || a in i) return Reflect.get(i, a);
328
- const n = i._state.data;
340
+ function w(i, t = {}, s = null) {
341
+ const e = new T(i, t, s), r = new Proxy(e, {
342
+ get(o, a) {
343
+ if (typeof a == "symbol" || a in o) return Reflect.get(o, a);
344
+ const n = o._state.data;
329
345
  if (n && typeof n == "object") return n[a];
330
346
  },
331
- set(i, a, n) {
332
- if (typeof a == "symbol" || a in i) return Reflect.set(i, a, n);
333
- const h = i._state.data;
334
- return h && typeof h == "object" ? (h[a] = n, !0) : (i._state.data = { [a]: n }, !0);
347
+ set(o, a, n) {
348
+ if (typeof a == "symbol" || a in o) return Reflect.set(o, a, n);
349
+ const h = o._state.data;
350
+ return h && typeof h == "object" ? (h[a] = n, !0) : (o._state.data = { [a]: n }, !0);
335
351
  },
336
- has(i, a) {
337
- if (a in i) return !0;
338
- const n = i._state.data;
352
+ has(o, a) {
353
+ if (a in o) return !0;
354
+ const n = o._state.data;
339
355
  return !!n && typeof n == "object" && a in n;
340
356
  }
341
357
  });
342
358
  return e._proxy = r, s && t.immediate !== !1 && r.reload().catch(() => {
343
359
  }), r;
344
360
  }
345
- class S {
361
+ class k {
346
362
  constructor(t = {}) {
347
363
  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);
348
364
  }
@@ -385,29 +401,29 @@ class S {
385
401
  async request(t, s, e = {}) {
386
402
  let r = /^https?:\/\//i.test(s) ? s : this.baseUrl + s;
387
403
  if (e.params) {
388
- const h = q(e.params);
404
+ const h = v(e.params);
389
405
  h && (r += (r.includes("?") ? "&" : "?") + h);
390
406
  }
391
- const i = {
407
+ const o = {
392
408
  Accept: "application/json",
393
409
  "X-Requested-With": "XMLHttpRequest"
394
410
  };
395
411
  for (const [h, l] of Object.entries(this.headers)) {
396
412
  const u = typeof l == "function" ? l() : l;
397
- u != null && (i[h] = u);
413
+ u != null && (o[h] = u);
398
414
  }
399
- Object.assign(i, e.headers);
400
- const a = { method: t.toUpperCase(), headers: i, signal: e.signal };
401
- this.credentials && (a.credentials = this.credentials), e.data !== void 0 && t !== "get" && (typeof FormData < "u" && e.data instanceof FormData ? a.body = e.data : (i["Content-Type"] = "application/json", a.body = JSON.stringify(e.data)));
415
+ Object.assign(o, e.headers);
416
+ const a = { method: t.toUpperCase(), headers: o, signal: e.signal };
417
+ this.credentials && (a.credentials = this.credentials), e.data !== void 0 && t !== "get" && (typeof FormData < "u" && e.data instanceof FormData ? a.body = e.data : (o["Content-Type"] = "application/json", a.body = JSON.stringify(e.data)));
402
418
  const n = { method: t, url: r, options: e };
403
419
  this.trackStart();
404
420
  try {
405
421
  const h = await fetch(r, a);
406
- let l = await v(h);
407
- if (this.bodyTransformer && (l = this.bodyTransformer(l, n) ?? l), !h.ok) throw new w(h.status, l, h);
422
+ let l = await S(h);
423
+ if (this.bodyTransformer && (l = this.bodyTransformer(l, n) ?? l), !h.ok) throw new j(h.status, l, h);
408
424
  return l;
409
425
  } catch (h) {
410
- throw x(h) ? h : this.emitError(h, n);
426
+ throw R(h) ? h : this.emitError(h, n);
411
427
  } finally {
412
428
  this.trackEnd();
413
429
  }
@@ -431,7 +447,7 @@ class S {
431
447
  // --- form models -----------------------------------------------------------
432
448
  /** Create a form model without any request (like Inertia's useForm). */
433
449
  form(t, s = {}) {
434
- return b(this, { ...s, default: typeof t == "function" ? t : () => c(t) });
450
+ return w(this, { ...s, default: typeof t == "function" ? t : () => c(t) });
435
451
  }
436
452
  /** Create a form model and fill it with a GET request. */
437
453
  getForm(t, s) {
@@ -443,7 +459,7 @@ class S {
443
459
  }
444
460
  createFormModel(t, s, e) {
445
461
  const r = typeof e == "string" ? { path: e } : { ...e ?? {} };
446
- return b(this, r, { url: s, method: t });
462
+ return w(this, r, { url: s, method: t });
447
463
  }
448
464
  // --- internals --------------------------------------------------------------
449
465
  trackStart() {
@@ -464,22 +480,22 @@ class S {
464
480
  let e = t;
465
481
  for (const r of this.errorHooks)
466
482
  try {
467
- const i = r(e, s);
468
- i instanceof Error && (e = i);
483
+ const o = r(e, s);
484
+ o instanceof Error && (e = o);
469
485
  } catch {
470
486
  }
471
487
  return e;
472
488
  }
473
489
  }
474
- function T(o = {}) {
475
- return new S(o);
490
+ function U(i = {}) {
491
+ return new k(i);
476
492
  }
477
- const U = T();
493
+ const W = U();
478
494
  export {
479
- S as Apix,
480
- w as ApixError,
481
- O as ApixModel,
482
- U as apix,
483
- T as createApix,
484
- U as default
495
+ k as Apix,
496
+ j as ApixError,
497
+ T as ApixModel,
498
+ W as apix,
499
+ U as createApix,
500
+ W as default
485
501
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diephp/vue-apix",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Tiny form/model/api toolkit for Vue 3 — fetch-based, Laravel-friendly, zero dependencies",
5
5
  "type": "module",
6
6
  "license": "MIT",