@diephp/vue-apix 0.1.1 → 0.1.3

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
@@ -41,6 +41,12 @@ apix.setHeader({
41
41
  'x-app': 'admin',
42
42
  });
43
43
 
44
+ // Header names are case-insensitive ('Content-Type' and 'content-type' are the same key).
45
+ // Content-Type is auto-set to application/json only when a request has a JSON body and
46
+ // you haven't configured it yourself; configure it explicitly to send it on every request
47
+ // (including GET). For FormData bodies any content-type is dropped so the browser can
48
+ // set the multipart boundary.
49
+
44
50
  // fires with true when the first request starts, false when the last one ends —
45
51
  // perfect for a global progress bar / spinner
46
52
  apix.onProcessing((active) => progressBar.toggle(active));
@@ -121,6 +127,9 @@ const model = apix.getForm<AttrDto>('/api/attribute/123', {
121
127
  default: () => ({ id: null, name: null, description: null }),
122
128
  // default is true; false = no request until reload() or a watch trigger
123
129
  immediate: true,
130
+ // default is true: every fill response is deep-merged over default(),
131
+ // so keys the backend didn't return keep their default values
132
+ mergeDefaults: true,
124
133
  // extra query params added to every fill request
125
134
  params: { with: 'labels' },
126
135
  // called after every successful fill (initial, reload(), watch-triggered)
@@ -134,6 +143,27 @@ While the request is in flight `model.processing === true` and `model.data` is
134
143
  `default()` (or `null` without a default). `apix.postForm(url, options)` is the same,
135
144
  but fills via POST — for complex search endpoints.
136
145
 
146
+ **Responses are merged over `default()`.** `default()` describes the shape of your model;
147
+ a fill response is deep-merged on top of it, so keys the backend didn't return keep their
148
+ default values and nested `v-model` targets like `model.filter.name` never disappear:
149
+
150
+ ```ts
151
+ const model = apix.getForm('/api/data', {
152
+ default: () => ({
153
+ filter: { name: null, hub_id: null },
154
+ items: [],
155
+ }),
156
+ });
157
+
158
+ // backend returned only {items: [...]} → model.filter is still {name: null, hub_id: null},
159
+ // so <el-input v-model="model.filter.name" /> keeps working
160
+ ```
161
+
162
+ The merge is deep (a partial `filter` object is completed key by key), a `null` where the
163
+ default has an object falls back to the default object, explicit scalar `null`s from the
164
+ response are respected, and arrays are always replaced — never merged. The `reset()`
165
+ snapshot stores the merged state. Opt out with `mergeDefaults: false`.
166
+
137
167
  ### Edit form — full component
138
168
 
139
169
  ```vue
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 y(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&&y(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 m 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 k(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 T(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)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)."))}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,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 d=S(l,this._options.path);if(this._transformResponse){const g=c(d);d=this._transformResponse(g,l)??g}return this._applyFill(d,t.preserve??null),this._state.message=p(l),this._state.errors={},(n=(a=this._options).onSuccess)==null||n.call(a,l,this._proxy),l}catch(l){throw R(l)||(this._applyError(l),(u=(h=this._options).onError)==null||u.call(h,l,this._proxy)),l}finally{this._fillAbort===s&&(this._fillAbort=null,this._state.processing=!1)}}_applyFill(t,e){let s=c(t);this._options.mergeDefaults!==!1&&this._options.default&&(s=A(s,this._options.default()));const r=this._snapshotLocked?null:c(s);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const o of e){const a=f(this._state.data,o);a!==void 0&&y(s,o,c(a))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof m&&(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=k(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 T(h);if(this.bodyTransformer&&(u=this.bodyTransformer(u,n)??u),!h.ok)throw new m(h.status,u,h);return u}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=m;exports.ApixModel=v;exports.apix=q;exports.createApix=O;exports.default=q;
package/dist/vue-apix.js CHANGED
@@ -1,59 +1,73 @@
1
- import { toRaw as R, reactive as j, watch as A } from "vue";
1
+ import { toRaw as A, reactive as v, watch as E } from "vue";
2
2
  function c(o) {
3
- const t = R(o);
3
+ const t = A(o);
4
4
  if (t === null || typeof t != "object") return t;
5
- if (Array.isArray(t)) return t.map((e) => c(e));
5
+ if (Array.isArray(t)) return t.map((s) => c(s));
6
6
  if (t instanceof Date) return new Date(t.getTime());
7
- const s = Object.getPrototypeOf(t);
8
- if (s === Object.prototype || s === null) {
9
- const e = {};
10
- for (const r of Object.keys(t)) e[r] = c(t[r]);
11
- return e;
7
+ const e = Object.getPrototypeOf(t);
8
+ if (e === Object.prototype || e === null) {
9
+ const s = {};
10
+ for (const r of Object.keys(t)) s[r] = c(t[r]);
11
+ return s;
12
12
  }
13
13
  return t;
14
14
  }
15
+ function y(o) {
16
+ if (o === null || typeof o != "object") return !1;
17
+ const t = Object.getPrototypeOf(o);
18
+ return t === Object.prototype || t === null;
19
+ }
20
+ function x(o, t) {
21
+ if (!y(t))
22
+ return o === void 0 ? c(t) : o;
23
+ if (o == null) return c(t);
24
+ if (!y(o)) return o;
25
+ for (const e of Object.keys(t))
26
+ o[e] = e in o ? x(o[e], t[e]) : c(t[e]);
27
+ return o;
28
+ }
15
29
  function f(o, t) {
16
30
  if (o == null) return;
17
- let s = o;
18
- for (const e of t.split(".")) {
19
- if (s == null) return;
20
- s = s[e];
31
+ let e = o;
32
+ for (const s of t.split(".")) {
33
+ if (e == null) return;
34
+ e = e[s];
21
35
  }
22
- return s;
36
+ return e;
23
37
  }
24
- function p(o, t, s) {
25
- const e = t.split(".");
38
+ function d(o, t, e) {
39
+ const s = t.split(".");
26
40
  let r = o;
27
- for (let i = 0; i < e.length - 1; i++) {
28
- const a = e[i];
41
+ for (let i = 0; i < s.length - 1; i++) {
42
+ const a = s[i];
29
43
  (r[a] === null || typeof r[a] != "object") && (r[a] = {}), r = r[a];
30
44
  }
31
- r[e[e.length - 1]] = s;
45
+ r[s[s.length - 1]] = e;
32
46
  }
33
- function y(o, t) {
34
- const s = {};
35
- for (const e of t) {
36
- const r = f(o, e);
37
- r !== void 0 && p(s, e, c(r));
47
+ function g(o, t) {
48
+ const e = {};
49
+ for (const s of t) {
50
+ const r = f(o, s);
51
+ r !== void 0 && d(e, s, c(r));
38
52
  }
39
- return s;
53
+ return e;
40
54
  }
41
- function g(o) {
55
+ function b(o) {
42
56
  const t = {};
43
- for (const [s, e] of Object.entries(o ?? {}))
44
- e != null && (t[s] = Array.isArray(e) ? String(e[0]) : String(e));
57
+ for (const [e, s] of Object.entries(o ?? {}))
58
+ s != null && (t[e] = Array.isArray(s) ? String(s[0]) : String(s));
45
59
  return t;
46
60
  }
47
- function d(o) {
61
+ function p(o) {
48
62
  return o && typeof o == "object" && typeof o.message == "string" ? o.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;
52
- return t ? f(s, t) : s;
64
+ function O(o, t) {
65
+ const e = o && typeof o == "object" && !Array.isArray(o) && "data" in o ? o.data : o;
66
+ return t ? f(e, t) : e;
53
67
  }
54
- class w extends Error {
55
- 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 : {};
68
+ class j extends Error {
69
+ constructor(t, e, s) {
70
+ 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 : {};
57
71
  }
58
72
  /**
59
73
  * True for any 4xx response whose body carries an `errors` object
@@ -64,31 +78,31 @@ 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) {
81
+ function R(o) {
68
82
  return o instanceof Error && o.name === "AbortError";
69
83
  }
70
84
  function q(o) {
71
- const t = [], s = (r, i) => {
85
+ const t = [], e = (r, i) => {
72
86
  t.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`);
73
- }, e = (r, i) => {
87
+ }, s = (r, i) => {
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 e(i, r ? "1" : "0");
90
+ if (r instanceof Date) return e(i, r.toISOString());
77
91
  if (Array.isArray(r)) {
78
- r.forEach((a, n) => e(a, `${i}[${n}]`));
92
+ r.forEach((a, n) => s(a, `${i}[${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)) s(n, `${i}[${a}]`);
83
97
  return;
84
98
  }
85
- s(i, String(r));
99
+ e(i, String(r));
86
100
  }
87
101
  };
88
- for (const [r, i] of Object.entries(o)) e(i, r);
102
+ for (const [r, i] of Object.entries(o)) s(i, r);
89
103
  return t.join("&");
90
104
  }
91
- async function v(o) {
105
+ async function k(o) {
92
106
  if (o.status === 204) return null;
93
107
  const t = await o.text();
94
108
  if (!t) return null;
@@ -98,11 +112,11 @@ async function v(o) {
98
112
  return t;
99
113
  }
100
114
  }
101
- class O {
102
- constructor(t, s = {}, e = null) {
103
- 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
- const r = s.default ? s.default() : null;
105
- this._state = j({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r);
115
+ class S {
116
+ constructor(t, e = {}, s = null) {
117
+ this._snapshot = null, this._snapshotLocked = !1, this._stopWatch = null, this._debounceTimer = null, this._watched = null, this._watchOptions = {}, this._lastSent = null, this._fillAbort = null, this._transformResponse = null, this._transformRequest = null, this._apix = t, this._options = e, this._source = s, this._transformResponse = e.transformResponse ?? null, this._transformRequest = e.transformRequest ?? null;
118
+ const r = e.default ? e.default() : null;
119
+ this._state = v({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r);
106
120
  }
107
121
  // --- reactive state ---------------------------------------------------------
108
122
  get data() {
@@ -146,23 +160,23 @@ class O {
146
160
  * so `error('name')` also surfaces `name.en.label` messages.
147
161
  */
148
162
  error(t) {
149
- const s = this._state.errors;
150
- if (s[t] !== void 0) return s[t];
151
- const e = `${t}.`;
152
- for (const r of Object.keys(s))
153
- if (r.startsWith(e)) return s[r];
163
+ const e = this._state.errors;
164
+ if (e[t] !== void 0) return e[t];
165
+ const s = `${t}.`;
166
+ for (const r of Object.keys(e))
167
+ if (r.startsWith(s)) return e[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) {
160
174
  if (!t)
161
175
  return this._state.errors = {}, this._proxy;
162
- for (const s of t) {
163
- const e = `${s}.`;
176
+ for (const e of t) {
177
+ const s = `${e}.`;
164
178
  for (const r of Object.keys(this._state.errors))
165
- (r === s || r.startsWith(e)) && delete this._state.errors[r];
179
+ (r === e || r.startsWith(s)) && delete this._state.errors[r];
166
180
  }
167
181
  return this._proxy;
168
182
  }
@@ -174,29 +188,29 @@ class O {
174
188
  reset(t) {
175
189
  if (t === void 0 || Array.isArray(t) && t.length === 0)
176
190
  return this._state.data = c(this._snapshot), this._state.errors = {}, this._state.message = null, this._proxy;
177
- const s = Array.isArray(t) ? t : [t];
191
+ const e = Array.isArray(t) ? t : [t];
178
192
  if (this._state.data && typeof this._state.data == "object")
179
- for (const e of s)
180
- p(this._state.data, e, c(f(this._snapshot, e)));
181
- return this.clearErrors(s), this._proxy;
193
+ for (const s of e)
194
+ d(this._state.data, s, c(f(this._snapshot, s)));
195
+ return this.clearErrors(e), this._proxy;
182
196
  }
183
197
  // --- HTTP ------------------------------------------------------------------------
184
- post(t, s) {
185
- return this._submit("post", t, s);
198
+ post(t, e) {
199
+ return this._submit("post", t, e);
186
200
  }
187
- put(t, s) {
188
- return this._submit("put", t, s);
201
+ put(t, e) {
202
+ return this._submit("put", t, e);
189
203
  }
190
- patch(t, s) {
191
- return this._submit("patch", t, s);
204
+ patch(t, e) {
205
+ return this._submit("patch", t, e);
192
206
  }
193
- delete(t, s) {
194
- return this._submit("delete", t, s);
207
+ delete(t, e) {
208
+ return this._submit("delete", t, e);
195
209
  }
196
210
  /** Re-run the fill request (or set a new source URL and run it). */
197
211
  reload(t) {
198
- var s;
199
- return t && (this._source = { url: t, method: ((s = this._source) == null ? void 0 : s.method) ?? "get" }), this._source ? this._fill() : Promise.reject(
212
+ var e;
213
+ return t && (this._source = { url: t, method: ((e = this._source) == null ? void 0 : e.method) ?? "get" }), this._source ? this._fill() : Promise.reject(
200
214
  new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url).")
201
215
  );
202
216
  }
@@ -226,11 +240,11 @@ class O {
226
240
  * The response updates everything except the watched paths (see WatchOptions).
227
241
  * A new trigger aborts the previous in-flight watch request.
228
242
  */
229
- watch(t, s) {
230
- let e = null, r;
231
- 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(), {
243
+ watch(t, e) {
244
+ let s = null, r;
245
+ 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();
246
+ const i = s && s.length ? s.map((a) => () => f(this._state.data, a)) : () => this._state.data;
247
+ return this._stopWatch = E(i, () => this._onWatchTrigger(), {
234
248
  deep: r.deep ?? !0
235
249
  }), this._proxy;
236
250
  }
@@ -241,46 +255,48 @@ class O {
241
255
  // --- internals ----------------------------------------------------------------------
242
256
  /** @internal */
243
257
  async _fill(t = {}) {
244
- var i, a, n, h, l;
245
- const s = this._source;
258
+ var i, a, n, h, u;
259
+ const e = this._source;
246
260
  (i = this._fillAbort) == null || i.abort();
247
- const e = new AbortController();
248
- this._fillAbort = e, this._state.processing = !0;
249
- const r = { signal: e.signal };
250
- 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);
261
+ const s = new AbortController();
262
+ this._fillAbort = s, this._state.processing = !0;
263
+ const r = { signal: s.signal };
264
+ 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);
251
265
  try {
252
- const u = await this._apix.request(s.method, s.url, r);
253
- let _ = E(u, this._options.path);
266
+ const l = await this._apix.request(e.method, e.url, r);
267
+ let _ = O(l, this._options.path);
254
268
  if (this._transformResponse) {
255
269
  const m = c(_);
256
- _ = this._transformResponse(m, u) ?? m;
270
+ _ = this._transformResponse(m, l) ?? 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;
259
- } catch (u) {
260
- throw x(u) || (this._applyError(u), (l = (h = this._options).onError) == null || l.call(h, u, this._proxy)), u;
272
+ return this._applyFill(_, t.preserve ?? null), this._state.message = p(l), this._state.errors = {}, (n = (a = this._options).onSuccess) == null || n.call(a, l, this._proxy), l;
273
+ } catch (l) {
274
+ throw R(l) || (this._applyError(l), (u = (h = this._options).onError) == null || u.call(h, l, this._proxy)), l;
261
275
  } finally {
262
- this._fillAbort === e && (this._fillAbort = null, this._state.processing = !1);
276
+ this._fillAbort === s && (this._fillAbort = null, this._state.processing = !1);
263
277
  }
264
278
  }
265
- _applyFill(t, s) {
266
- const e = c(t);
267
- 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));
279
+ _applyFill(t, e) {
280
+ let s = c(t);
281
+ this._options.mergeDefaults !== !1 && this._options.default && (s = x(s, this._options.default()));
282
+ const r = this._snapshotLocked ? null : c(s);
283
+ if (e && e.length && s && typeof s == "object" && this._state.data && typeof this._state.data == "object")
284
+ for (const i of e) {
285
+ const a = f(this._state.data, i);
286
+ a !== void 0 && d(s, i, c(a));
271
287
  }
272
- this._state.data = e, this._snapshotLocked || (this._snapshot = c(t), this._snapshotLocked = !0), this._syncLastSent();
288
+ this._state.data = s, 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
- async _submit(t, s, e = {}) {
293
+ async _submit(t, e, s = {}) {
278
294
  var a;
279
- const r = s ?? ((a = this._source) == null ? void 0 : a.url);
295
+ const r = e ?? ((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) {
298
+ let i = s.data !== void 0 ? s.data : s.only ? g(this._state.data, s.only) : this._state.data ?? void 0;
299
+ if (s.data === void 0 && this._transformRequest && i !== void 0) {
284
300
  const n = c(i);
285
301
  i = this._transformRequest(n) ?? n;
286
302
  }
@@ -288,10 +304,10 @@ class O {
288
304
  try {
289
305
  const n = await this._apix.request(t, r, {
290
306
  data: i,
291
- params: e.params,
292
- headers: e.headers
307
+ params: s.params,
308
+ headers: s.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 {
@@ -306,23 +322,23 @@ class O {
306
322
  }
307
323
  _sendWatchRequest() {
308
324
  if (this._debounceTimer = null, !this._source) return;
309
- const t = this._watched, s = this._watchOptions.payload ?? t;
310
- let e = s && s.length ? y(this._state.data, s) : c(this._state.data);
311
- 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 };
325
+ const t = this._watched, e = this._watchOptions.payload ?? t;
326
+ let s = e && e.length ? g(this._state.data, e) : c(this._state.data);
327
+ this._transformRequest && (s = this._transformRequest(s) ?? s), this._lastSent = this._payloadJson();
328
+ const r = this._watchOptions.refreshWatched ? null : t, i = this._source.method === "get" ? { params: s, preserve: r } : { data: s, preserve: r };
313
329
  this._fill(i).catch(() => {
314
330
  });
315
331
  }
316
332
  _payloadJson() {
317
- const t = this._watched, s = t && t.length ? t.map((e) => f(this._state.data, e)) : this._state.data;
318
- return JSON.stringify(s) ?? "undefined";
333
+ const t = this._watched, e = t && t.length ? t.map((s) => f(this._state.data, s)) : this._state.data;
334
+ return JSON.stringify(e) ?? "undefined";
319
335
  }
320
336
  _syncLastSent() {
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, {
340
+ function w(o, t = {}, e = null) {
341
+ const s = new S(o, t, e), r = new Proxy(s, {
326
342
  get(i, a) {
327
343
  if (typeof a == "symbol" || a in i) return Reflect.get(i, a);
328
344
  const n = i._state.data;
@@ -339,10 +355,10 @@ function b(o, t = {}, s = null) {
339
355
  return !!n && typeof n == "object" && a in n;
340
356
  }
341
357
  });
342
- return e._proxy = r, s && t.immediate !== !1 && r.reload().catch(() => {
358
+ return s._proxy = r, e && t.immediate !== !1 && r.reload().catch(() => {
343
359
  }), r;
344
360
  }
345
- class S {
361
+ class T {
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
  }
@@ -359,7 +375,7 @@ class S {
359
375
  /** Global hook: fires with true when the first request starts, false when the last one ends. */
360
376
  onProcessing(t) {
361
377
  return this.processingHooks.push(t), () => {
362
- this.processingHooks = this.processingHooks.filter((s) => s !== t);
378
+ this.processingHooks = this.processingHooks.filter((e) => e !== t);
363
379
  };
364
380
  }
365
381
  /**
@@ -369,7 +385,7 @@ class S {
369
385
  */
370
386
  onError(t) {
371
387
  return this.errorHooks.push(t), () => {
372
- this.errorHooks = this.errorHooks.filter((s) => s !== t);
388
+ this.errorHooks = this.errorHooks.filter((e) => e !== t);
373
389
  };
374
390
  }
375
391
  /**
@@ -382,68 +398,69 @@ class S {
382
398
  return this.bodyTransformer = t, this;
383
399
  }
384
400
  // --- plain requests (Promise, no model) -----------------------------------
385
- async request(t, s, e = {}) {
386
- let r = /^https?:\/\//i.test(s) ? s : this.baseUrl + s;
387
- if (e.params) {
388
- const h = q(e.params);
401
+ async request(t, e, s = {}) {
402
+ let r = /^https?:\/\//i.test(e) ? e : this.baseUrl + e;
403
+ if (s.params) {
404
+ const h = q(s.params);
389
405
  h && (r += (r.includes("?") ? "&" : "?") + h);
390
406
  }
391
407
  const i = {
392
- Accept: "application/json",
393
- "X-Requested-With": "XMLHttpRequest"
408
+ accept: "application/json",
409
+ "x-requested-with": "XMLHttpRequest"
394
410
  };
395
- for (const [h, l] of Object.entries(this.headers)) {
396
- const u = typeof l == "function" ? l() : l;
397
- u != null && (i[h] = u);
411
+ for (const [h, u] of Object.entries(this.headers)) {
412
+ const l = typeof u == "function" ? u() : u;
413
+ l != null && (i[h.toLowerCase()] = l);
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)));
402
- const n = { method: t, url: r, options: e };
415
+ for (const [h, u] of Object.entries(s.headers ?? {}))
416
+ i[h.toLowerCase()] = u;
417
+ const a = { method: t.toUpperCase(), headers: i, signal: s.signal };
418
+ this.credentials && (a.credentials = this.credentials), s.data !== void 0 && t !== "get" && (typeof FormData < "u" && s.data instanceof FormData ? (delete i["content-type"], a.body = s.data) : (i["content-type"] ?? (i["content-type"] = "application/json"), a.body = JSON.stringify(s.data)));
419
+ const n = { method: t, url: r, options: s };
403
420
  this.trackStart();
404
421
  try {
405
422
  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);
408
- return l;
423
+ let u = await k(h);
424
+ if (this.bodyTransformer && (u = this.bodyTransformer(u, n) ?? u), !h.ok) throw new j(h.status, u, h);
425
+ return u;
409
426
  } catch (h) {
410
- throw x(h) ? h : this.emitError(h, n);
427
+ throw R(h) ? h : this.emitError(h, n);
411
428
  } finally {
412
429
  this.trackEnd();
413
430
  }
414
431
  }
415
- get(t, s, e = {}) {
416
- return this.request("get", t, s ? { ...e, params: s } : e);
432
+ get(t, e, s = {}) {
433
+ return this.request("get", t, e ? { ...s, params: e } : s);
417
434
  }
418
- post(t, s, e = {}) {
419
- return this.request("post", t, s !== void 0 ? { ...e, data: s } : e);
435
+ post(t, e, s = {}) {
436
+ return this.request("post", t, e !== void 0 ? { ...s, data: e } : s);
420
437
  }
421
- put(t, s, e = {}) {
422
- return this.request("put", t, s !== void 0 ? { ...e, data: s } : e);
438
+ put(t, e, s = {}) {
439
+ return this.request("put", t, e !== void 0 ? { ...s, data: e } : s);
423
440
  }
424
- patch(t, s, e = {}) {
425
- return this.request("patch", t, s !== void 0 ? { ...e, data: s } : e);
441
+ patch(t, e, s = {}) {
442
+ return this.request("patch", t, e !== void 0 ? { ...s, data: e } : s);
426
443
  }
427
444
  /** DELETE with an optional body. */
428
- delete(t, s, e = {}) {
429
- return this.request("delete", t, s !== void 0 ? { ...e, data: s } : e);
445
+ delete(t, e, s = {}) {
446
+ return this.request("delete", t, e !== void 0 ? { ...s, data: e } : s);
430
447
  }
431
448
  // --- form models -----------------------------------------------------------
432
449
  /** Create a form model without any request (like Inertia's useForm). */
433
- form(t, s = {}) {
434
- return b(this, { ...s, default: typeof t == "function" ? t : () => c(t) });
450
+ form(t, e = {}) {
451
+ return w(this, { ...e, default: typeof t == "function" ? t : () => c(t) });
435
452
  }
436
453
  /** Create a form model and fill it with a GET request. */
437
- getForm(t, s) {
438
- return this.createFormModel("get", t, s);
454
+ getForm(t, e) {
455
+ return this.createFormModel("get", t, e);
439
456
  }
440
457
  /** Same as getForm, but the fill request is a POST (complex search endpoints etc.). */
441
- postForm(t, s) {
442
- return this.createFormModel("post", t, s);
458
+ postForm(t, e) {
459
+ return this.createFormModel("post", t, e);
443
460
  }
444
- createFormModel(t, s, e) {
445
- const r = typeof e == "string" ? { path: e } : { ...e ?? {} };
446
- return b(this, r, { url: s, method: t });
461
+ createFormModel(t, e, s) {
462
+ const r = typeof s == "string" ? { path: s } : { ...s ?? {} };
463
+ return w(this, r, { url: e, method: t });
447
464
  }
448
465
  // --- internals --------------------------------------------------------------
449
466
  trackStart() {
@@ -453,33 +470,33 @@ class S {
453
470
  --this.active === 0 && this.emitProcessing(!1);
454
471
  }
455
472
  emitProcessing(t) {
456
- for (const s of this.processingHooks)
473
+ for (const e of this.processingHooks)
457
474
  try {
458
- s(t);
475
+ e(t);
459
476
  } catch {
460
477
  }
461
478
  }
462
479
  /** Runs the hooks; a hook returning an Error replaces it for the rest of the chain. */
463
- emitError(t, s) {
464
- let e = t;
480
+ emitError(t, e) {
481
+ let s = t;
465
482
  for (const r of this.errorHooks)
466
483
  try {
467
- const i = r(e, s);
468
- i instanceof Error && (e = i);
484
+ const i = r(s, e);
485
+ i instanceof Error && (s = i);
469
486
  } catch {
470
487
  }
471
- return e;
488
+ return s;
472
489
  }
473
490
  }
474
- function T(o = {}) {
475
- return new S(o);
491
+ function U(o = {}) {
492
+ return new T(o);
476
493
  }
477
- const U = T();
494
+ const L = U();
478
495
  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
496
+ T as Apix,
497
+ j as ApixError,
498
+ S as ApixModel,
499
+ L as apix,
500
+ U as createApix,
501
+ L as default
485
502
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diephp/vue-apix",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
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",