@diephp/vue-apix 0.3.3 → 0.3.4

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
@@ -138,6 +138,9 @@ const model = apix.getForm<AttrDto>('/api/attribute/123', {
138
138
  onSuccess: (response, model) => {},
139
139
  // called after every failed fill; aborted (superseded) requests are ignored
140
140
  onError: (error, model) => {},
141
+ // called after every fill settles, success or failure — like Promise.finally();
142
+ // aborted (superseded) requests are ignored, same as onSuccess/onError
143
+ onFinish: (model) => {},
141
144
  // never sent by a watch-triggered request or refresh() — see "watch" below
142
145
  ignore: ['items'],
143
146
  // this field's value survives every watch/refresh response — see "watch" below
package/dist/types.d.ts CHANGED
@@ -69,6 +69,12 @@ export interface FormOptions<T = any> {
69
69
  onSuccess?: (response: any, model: ApixModel<T>) => void;
70
70
  /** Called after every failed fill request. Aborted (superseded) requests are ignored. */
71
71
  onError?: (error: unknown, model: ApixModel<T>) => void;
72
+ /**
73
+ * Called after every fill request settles, success or failure alike —
74
+ * like Promise.finally(), for turning off local UI state regardless of the
75
+ * outcome. Aborted (superseded) requests are ignored, same as onSuccess/onError.
76
+ */
77
+ onFinish?: (model: ApixModel<T>) => void;
72
78
  /** See model.transformResponse(). */
73
79
  transformResponse?: (data: any, response: any) => any;
74
80
  /** See model.transformRequest(). */
package/dist/vue-apix.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const d=require("vue");function c(i){const t=d.toRaw(i);if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(s=>c(s));if(t instanceof Date)return new Date(t.getTime());const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const s={};for(const r of Object.keys(t))s[r]=c(t[r]);return s}return t}function m(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function E(i,t){if(!m(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!m(i))return i;for(const e of Object.keys(t))i[e]=e in i?E(i[e],t[e]):c(t[e]);return i}function f(i,t){if(i==null)return;let e=i;for(const s of t.split(".")){if(e==null)return;e=e[s]}return e}function y(i,t,e){const s=t.split(".");let r=i;for(let o=0;o<s.length-1;o++){const n=s[o];(r[n]===null||typeof r[n]!="object")&&(r[n]={}),r=r[n]}r[s[s.length-1]]=e}function j(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 w(i){const t={};for(const[e,s]of Object.entries(i??{}))s!=null&&(t[e]=Array.isArray(s)?String(s[0]):String(s));return t}function _(i){return i&&typeof i=="object"&&typeof i.message=="string"?i.message:null}function R(i,t){return t.some(e=>e===i||i.startsWith(`${e}.`))}function g(i,t,e=""){if(e&&R(e,t))return[];if(m(i)){const s=[];for(const r of Object.keys(i))s.push(...g(i[r],t,e?`${e}.${r}`:r));return s}return Array.isArray(i)||!e?[]:[e]}function q(i,t){return t&&i&&typeof i=="object"?f(i,t):i}class b extends Error{constructor(t,e,s){super(_(e)??`Request failed with status ${t}`),this.name="ApixError",this.status=t,this.body=e,this.response=s,this.errors=e&&typeof e=="object"&&e.errors&&typeof e.errors=="object"?e.errors:{}}get isValidationError(){return this.status>=400&&this.status<500&&Object.keys(this.errors).length>0}}function A(i){return i instanceof Error&&i.name==="AbortError"}function T(i){const t=[],e=(r,o)=>{t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`)},s=(r,o)=>{if(r!=null){if(typeof r=="boolean")return e(o,r?"1":"0");if(r instanceof Date)return e(o,r.toISOString());if(Array.isArray(r)){r.forEach((n,a)=>s(n,`${o}[${a}]`));return}if(typeof r=="object"){for(const[n,a]of Object.entries(r))s(a,`${o}[${n}]`);return}e(o,String(r))}};for(const[r,o]of Object.entries(i))s(o,r);return t.join("&")}async function U(i){if(i.status===204)return null;const t=await i.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}class F{constructor(t,e={},s=null){this._snapshot=null,this._snapshotLocked=!1,this._ignore=[],this._lock=[],this._triggerFields=null,this._sendFields=null,this._debounce=0,this._debounceTimer=null,this._lastSent=null,this._fillAbort=null,this._transformResponse=null,this._transformRequest=null,this._deferredWatchSetup=null,this._apix=t,this._options=e,this._source=s,this._transformResponse=e.transformResponse??null,this._transformRequest=e.transformRequest??null;const r=e.default?e.default():null;if(this._state=d.reactive({data:r,errors:{},message:null,processing:!1}),this._snapshot=c(r),this._ignore=e.ignore??[],this._lock=e.lock??[],this._sendFields=g(r??{},this._ignore),e.watch){const o=e.watch;if(!this._source)console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");else if(e.immediate===!1)this._setupWatch(o,r);else{const n=d.getCurrentScope();this._deferredWatchSetup=()=>{n?n.run(()=>this._setupWatch(o,r)):this._setupWatch(o,r)}}}}get data(){return this._state.data}set data(t){this._state.data=t}get errors(){return this._state.errors}get message(){return this._state.message}get processing(){return this._state.processing}get hasErrors(){return Object.keys(this._state.errors).length>0}get isDirty(){return JSON.stringify(this._state.data)!==JSON.stringify(this._snapshot)}get(t){return c(f(this._state.data,t))}setData(t){return this._state.data=c(t),this._proxy}error(t){const e=this._state.errors;if(e[t]!==void 0)return e[t];const s=`${t}.`;for(const r of Object.keys(e))if(r.startsWith(s))return e[r]}setErrors(t){return this._state.errors=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)y(this._state.data,s,c(f(this._snapshot,s)));return this.clearErrors(e),this._proxy}post(t,e){return this._submit("post",t,e)}put(t,e){return this._submit("put",t,e)}patch(t,e){return this._submit("patch",t,e)}delete(t,e){return this._submit("delete",t,e)}reload(t){var e;return t&&(this._source={url:t,method:((e=this._source)==null?void 0:e.method)??"get"}),this._source?this._fill():Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."))}refresh(t={}){if(!this._source)return Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."));this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null);const e=this._buildFillExtra(t);return this._lastSent=this._payloadJson(),this._fill(e)}transformResponse(t){return this._transformResponse=t,this._proxy}transformRequest(t){return this._transformRequest=t,this._proxy}async _fill(t={}){var o,n,a,h,u;const e=this._source;(o=this._fillAbort)==null||o.abort();const s=new AbortController;this._fillAbort=s,this._state.processing=!0;const r={signal:s.signal};e.method==="get"?r.params={...this._options.params,...t.params}:(r.params=this._options.params,r.data=t.data!==void 0?t.data:this._options.data);try{const l=await this._apix.request(e.method,e.url,r);let p=q(l,this._options.path);if(this._transformResponse){const x=c(p);p=this._transformResponse(x,l)??x}return this._applyFill(p,t.preserve??null),this._state.message=_(l),this._state.errors={},(a=(n=this._options).onSuccess)==null||a.call(n,l,this._proxy),l}catch(l){throw A(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=E(s,this._options.default()));const r=this._snapshotLocked?null:c(s);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const o of e){const n=f(this._state.data,o);n!==void 0&&y(s,o,c(n))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof b&&(this._state.message=_(t.body)??t.message,t.isValidationError&&(this._state.errors=w(t.errors)))}async _submit(t,e,s={}){var n;const r=e??((n=this._source)==null?void 0:n.url);if(!r)throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);let o=s.data!==void 0?s.data:s.only?j(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&o!==void 0){const a=c(o);o=this._transformRequest(a)??a}this._state.processing=!0,this._state.errors={},this._state.message=null;try{const a=await this._apix.request(t,r,{data:o,params:s.params,headers:s.headers});return this._state.message=_(a),a}catch(a){throw this._applyError(a),a}finally{this._state.processing=!1}}_setupWatch(t,e){const s=t===!0?{}:t,r=s.fields,o=r??this._sendFields??g(e??{},this._ignore);this._triggerFields=o,this._debounce=s.debounce??0,this._syncLastSent();const n=o.map(h=>()=>f(this._state.data,h)),a=r?s.deep??!1:!0;d.watch(n,()=>this._onWatchTrigger(),{deep:a})}_onWatchTrigger(){this._payloadJson()!==this._lastSent&&(this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounce>0?this._debounceTimer=setTimeout(()=>this._sendWatchRequest(),this._debounce):this._sendWatchRequest())}_sendWatchRequest(){this._debounceTimer=null,this._source&&(this._lastSent=this._payloadJson(),this._fill(this._buildFillExtra()).catch(()=>{}))}_buildFillExtra(t={}){const e=t.lock?[...this._lock,...t.lock]:this._lock,s=t.ignore?(this._sendFields??[]).filter(o=>!R(o,t.ignore)):this._sendFields??[];let r=j(this._state.data,s);return this._transformRequest&&(r=this._transformRequest(r)??r),this._source.method==="get"?{params:r,preserve:e}:{data:r,preserve:e}}_payloadJson(){const e=(this._triggerFields??[]).map(s=>f(this._state.data,s));return JSON.stringify(e)??"undefined"}_syncLastSent(){this._lastSent=this._payloadJson()}}function k(i,t={},e=null){const s=new F(i,t,e),r=new Proxy(s,{get(o,n){if(typeof n=="symbol"||n in o)return Reflect.get(o,n);const a=o._state.data;if(a&&typeof a=="object")return a[n]},set(o,n,a){if(typeof n=="symbol"||n in o)return Reflect.set(o,n,a);const h=o._state.data;return h&&typeof h=="object"?(h[n]=a,!0):(o._state.data={[n]:a},!0)},has(o,n){if(n in o)return!0;const a=o._state.data;return!!a&&typeof a=="object"&&n in a}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().finally(()=>{var o;(o=s._deferredWatchSetup)==null||o.call(s),s._deferredWatchSetup=null}).catch(()=>{}),r}class S{constructor(t={}){this.baseUrl="",this.headers={},this.processingHooks=[],this.errorHooks=[],this.bodyTransformer=null,this.active=0,t.baseUrl&&this.setBaseUrl(t.baseUrl),t.headers&&this.setHeader(t.headers),t.credentials&&(this.credentials=t.credentials)}setBaseUrl(t){return this.baseUrl=t.replace(/\/+$/,""),this}setHeader(t){return Object.assign(this.headers,t),this}setCredentials(t){return this.credentials=t,this}onProcessing(t){return this.processingHooks.push(t),()=>{this.processingHooks=this.processingHooks.filter(e=>e!==t)}}onError(t){return this.errorHooks.push(t),()=>{this.errorHooks=this.errorHooks.filter(e=>e!==t)}}transformResponse(t){return this.bodyTransformer=t,this}async request(t,e,s={}){let r=/^https?:\/\//i.test(e)?e:this.baseUrl+e;if(s.params){const h=T(s.params);h&&(r+=(r.includes("?")?"&":"?")+h)}const o={accept:"application/json","x-requested-with":"XMLHttpRequest"};for(const[h,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 n={method:t.toUpperCase(),headers:o,signal:s.signal};this.credentials&&(n.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?(delete o["content-type"],n.body=s.data):(o["content-type"]??(o["content-type"]="application/json"),n.body=JSON.stringify(s.data)));const a={method:t,url:r,options:s};this.trackStart();try{const h=await fetch(r,n);let u=await U(h);if(this.bodyTransformer&&(u=this.bodyTransformer(u,a)??u),!h.ok)throw new b(h.status,u,h);return u}catch(h){throw A(h)?h:this.emitError(h,a)}finally{this.trackEnd()}}get(t,e,s={}){return this.request("get",t,e?{...s,params:e}:s)}post(t,e,s={}){return this.request("post",t,e!==void 0?{...s,data:e}:s)}put(t,e,s={}){return this.request("put",t,e!==void 0?{...s,data:e}:s)}patch(t,e,s={}){return this.request("patch",t,e!==void 0?{...s,data:e}:s)}delete(t,e,s={}){return this.request("delete",t,e!==void 0?{...s,data:e}:s)}form(t,e={}){return k(this,{...e,default:typeof t=="function"?t:()=>c(t)})}getForm(t,e){return this.createFormModel("get",t,e)}postForm(t,e){return this.createFormModel("post",t,e)}createFormModel(t,e,s){const r=typeof s=="string"?{path:s}:{...s??{}};return k(this,r,{url:e,method:t})}trackStart(){++this.active===1&&this.emitProcessing(!0)}trackEnd(){--this.active===0&&this.emitProcessing(!1)}emitProcessing(t){for(const e of this.processingHooks)try{e(t)}catch{}}emitError(t,e){let s=t;for(const r of this.errorHooks)try{const o=r(s,e);o instanceof Error&&(s=o)}catch{}return s}}function v(i={}){return new S(i)}const O=v();exports.Apix=S;exports.ApixError=b;exports.ApixFormModel=F;exports.apix=O;exports.createApix=v;exports.default=O;
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 y(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function F(i,t){if(!y(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!y(i))return i;for(const e of Object.keys(t))i[e]=e in i?F(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 g(i,t,e){const s=t.split(".");let r=i;for(let o=0;o<s.length-1;o++){const n=s[o];(r[n]===null||typeof r[n]!="object")&&(r[n]={}),r=r[n]}r[s[s.length-1]]=e}function k(i,t){const e={};for(const s of t){const r=f(i,s);r!==void 0&&g(e,s,c(r))}return e}function E(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 A(i,t){return t.some(e=>e===i||i.startsWith(`${e}.`))}function b(i,t,e=""){if(e&&A(e,t))return[];if(y(i)){const s=[];for(const r of Object.keys(i))s.push(...b(i[r],t,e?`${e}.${r}`:r));return s}return Array.isArray(i)||!e?[]:[e]}function U(i,t){return t&&i&&typeof i=="object"?f(i,t):i}class x 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 S(i){return i instanceof Error&&i.name==="AbortError"}function W(i){const t=[],e=(r,o)=>{t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`)},s=(r,o)=>{if(r!=null){if(typeof r=="boolean")return e(o,r?"1":"0");if(r instanceof Date)return e(o,r.toISOString());if(Array.isArray(r)){r.forEach((n,a)=>s(n,`${o}[${a}]`));return}if(typeof r=="object"){for(const[n,a]of Object.entries(r))s(a,`${o}[${n}]`);return}e(o,String(r))}};for(const[r,o]of Object.entries(i))s(o,r);return t.join("&")}async function L(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._ignore=[],this._lock=[],this._triggerFields=null,this._sendFields=null,this._debounce=0,this._debounceTimer=null,this._lastSent=null,this._fillAbort=null,this._transformResponse=null,this._transformRequest=null,this._deferredWatchSetup=null,this._apix=t,this._options=e,this._source=s,this._transformResponse=e.transformResponse??null,this._transformRequest=e.transformRequest??null;const r=e.default?e.default():null;if(this._state=_.reactive({data:r,errors:{},message:null,processing:!1}),this._snapshot=c(r),this._ignore=e.ignore??[],this._lock=e.lock??[],this._sendFields=b(r??{},this._ignore),e.watch){const o=e.watch;if(!this._source)console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");else if(e.immediate===!1)this._setupWatch(o,r);else{const n=_.getCurrentScope();this._deferredWatchSetup=()=>{n?n.run(()=>this._setupWatch(o,r)):this._setupWatch(o,r)}}}}get data(){return this._state.data}set data(t){this._state.data=t}get errors(){return this._state.errors}get message(){return this._state.message}get processing(){return this._state.processing}get hasErrors(){return Object.keys(this._state.errors).length>0}get isDirty(){return JSON.stringify(this._state.data)!==JSON.stringify(this._snapshot)}get(t){return c(f(this._state.data,t))}setData(t){return this._state.data=c(t),this._proxy}error(t){const e=this._state.errors;if(e[t]!==void 0)return e[t];const s=`${t}.`;for(const r of Object.keys(e))if(r.startsWith(s))return e[r]}setErrors(t){return this._state.errors=E(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)g(this._state.data,s,c(f(this._snapshot,s)));return this.clearErrors(e),this._proxy}post(t,e){return this._submit("post",t,e)}put(t,e){return this._submit("put",t,e)}patch(t,e){return this._submit("patch",t,e)}delete(t,e){return this._submit("delete",t,e)}reload(t){var e;return t&&(this._source={url:t,method:((e=this._source)==null?void 0:e.method)??"get"}),this._source?this._fill():Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."))}refresh(t={}){if(!this._source)return Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."));this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null);const e=this._buildFillExtra(t);return this._lastSent=this._payloadJson(),this._fill(e)}transformResponse(t){return this._transformResponse=t,this._proxy}transformRequest(t){return this._transformRequest=t,this._proxy}async _fill(t={}){var o,n,a,h,u,d,j;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 m=U(l,this._options.path);if(this._transformResponse){const w=c(m);m=this._transformResponse(w,l)??w}return this._applyFill(m,t.preserve??null),this._state.message=p(l),this._state.errors={},(a=(n=this._options).onSuccess)==null||a.call(n,l,this._proxy),l}catch(l){throw S(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,(j=(d=this._options).onFinish)==null||j.call(d,this._proxy))}}_applyFill(t,e){let s=c(t);this._options.mergeDefaults!==!1&&this._options.default&&(s=F(s,this._options.default()));const r=this._snapshotLocked?null:c(s);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const o of e){const n=f(this._state.data,o);n!==void 0&&g(s,o,c(n))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof x&&(this._state.message=p(t.body)??t.message,t.isValidationError&&(this._state.errors=E(t.errors)))}async _submit(t,e,s={}){var n;const r=e??((n=this._source)==null?void 0:n.url);if(!r)throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);let o=s.data!==void 0?s.data:s.only?k(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&o!==void 0){const a=c(o);o=this._transformRequest(a)??a}this._state.processing=!0,this._state.errors={},this._state.message=null;try{const a=await this._apix.request(t,r,{data:o,params:s.params,headers:s.headers});return this._state.message=p(a),a}catch(a){throw this._applyError(a),a}finally{this._state.processing=!1}}_setupWatch(t,e){const s=t===!0?{}:t,r=s.fields,o=r??this._sendFields??b(e??{},this._ignore);this._triggerFields=o,this._debounce=s.debounce??0,this._syncLastSent();const n=o.map(h=>()=>f(this._state.data,h)),a=r?s.deep??!1:!0;_.watch(n,()=>this._onWatchTrigger(),{deep:a})}_onWatchTrigger(){this._payloadJson()!==this._lastSent&&(this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounce>0?this._debounceTimer=setTimeout(()=>this._sendWatchRequest(),this._debounce):this._sendWatchRequest())}_sendWatchRequest(){this._debounceTimer=null,this._source&&(this._lastSent=this._payloadJson(),this._fill(this._buildFillExtra()).catch(()=>{}))}_buildFillExtra(t={}){const e=t.lock?[...this._lock,...t.lock]:this._lock,s=t.ignore?(this._sendFields??[]).filter(o=>!A(o,t.ignore)):this._sendFields??[];let r=k(this._state.data,s);return this._transformRequest&&(r=this._transformRequest(r)??r),this._source.method==="get"?{params:r,preserve:e}:{data:r,preserve:e}}_payloadJson(){const e=(this._triggerFields??[]).map(s=>f(this._state.data,s));return JSON.stringify(e)??"undefined"}_syncLastSent(){this._lastSent=this._payloadJson()}}function R(i,t={},e=null){const s=new v(i,t,e),r=new Proxy(s,{get(o,n){if(typeof n=="symbol"||n in o)return Reflect.get(o,n);const a=o._state.data;if(a&&typeof a=="object")return a[n]},set(o,n,a){if(typeof n=="symbol"||n in o)return Reflect.set(o,n,a);const h=o._state.data;return h&&typeof h=="object"?(h[n]=a,!0):(o._state.data={[n]:a},!0)},has(o,n){if(n in o)return!0;const a=o._state.data;return!!a&&typeof a=="object"&&n in a}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().finally(()=>{var o;(o=s._deferredWatchSetup)==null||o.call(s),s._deferredWatchSetup=null}).catch(()=>{}),r}class O{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=W(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 d=typeof u=="function"?u():u;d!=null&&(o[h.toLowerCase()]=d)}for(const[h,u]of Object.entries(s.headers??{}))o[h.toLowerCase()]=u;const n={method:t.toUpperCase(),headers:o,signal:s.signal};this.credentials&&(n.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?(delete o["content-type"],n.body=s.data):(o["content-type"]??(o["content-type"]="application/json"),n.body=JSON.stringify(s.data)));const a={method:t,url:r,options:s};this.trackStart();try{const h=await fetch(r,n);let u=await L(h);if(this.bodyTransformer&&(u=this.bodyTransformer(u,a)??u),!h.ok)throw new x(h.status,u,h);return u}catch(h){throw S(h)?h:this.emitError(h,a)}finally{this.trackEnd()}}get(t,e,s={}){return this.request("get",t,e?{...s,params:e}:s)}post(t,e,s={}){return this.request("post",t,e!==void 0?{...s,data:e}:s)}put(t,e,s={}){return this.request("put",t,e!==void 0?{...s,data:e}:s)}patch(t,e,s={}){return this.request("patch",t,e!==void 0?{...s,data:e}:s)}delete(t,e,s={}){return this.request("delete",t,e!==void 0?{...s,data:e}:s)}form(t,e={}){return R(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 R(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 q(i={}){return new O(i)}const T=q();exports.Apix=O;exports.ApixError=x;exports.ApixFormModel=v;exports.apix=T;exports.createApix=q;exports.default=T;
package/dist/vue-apix.js CHANGED
@@ -1,6 +1,6 @@
1
- import { toRaw as F, reactive as O, getCurrentScope as S, watch as q } from "vue";
1
+ import { toRaw as S, reactive as q, getCurrentScope as v, watch as A } from "vue";
2
2
  function c(i) {
3
- const t = F(i);
3
+ const t = S(i);
4
4
  if (t === null || typeof t != "object") return t;
5
5
  if (Array.isArray(t)) return t.map((s) => c(s));
6
6
  if (t instanceof Date) return new Date(t.getTime());
@@ -12,18 +12,18 @@ function c(i) {
12
12
  }
13
13
  return t;
14
14
  }
15
- function p(i) {
15
+ function m(i) {
16
16
  if (i === null || typeof i != "object") return !1;
17
17
  const t = Object.getPrototypeOf(i);
18
18
  return t === Object.prototype || t === null;
19
19
  }
20
- function w(i, t) {
21
- if (!p(t))
20
+ function R(i, t) {
21
+ if (!m(t))
22
22
  return i === void 0 ? c(t) : i;
23
23
  if (i == null) return c(t);
24
- if (!p(i)) return i;
24
+ if (!m(i)) return i;
25
25
  for (const e of Object.keys(t))
26
- i[e] = e in i ? w(i[e], t[e]) : c(t[e]);
26
+ i[e] = e in i ? R(i[e], t[e]) : c(t[e]);
27
27
  return i;
28
28
  }
29
29
  function f(i, t) {
@@ -35,7 +35,7 @@ function f(i, t) {
35
35
  }
36
36
  return e;
37
37
  }
38
- function m(i, t, e) {
38
+ function y(i, t, e) {
39
39
  const s = t.split(".");
40
40
  let r = i;
41
41
  for (let o = 0; o < s.length - 1; o++) {
@@ -44,42 +44,42 @@ function m(i, t, e) {
44
44
  }
45
45
  r[s[s.length - 1]] = e;
46
46
  }
47
- function b(i, t) {
47
+ function x(i, t) {
48
48
  const e = {};
49
49
  for (const s of t) {
50
50
  const r = f(i, s);
51
- r !== void 0 && m(e, s, c(r));
51
+ r !== void 0 && y(e, s, c(r));
52
52
  }
53
53
  return e;
54
54
  }
55
- function j(i) {
55
+ function w(i) {
56
56
  const t = {};
57
57
  for (const [e, s] of Object.entries(i ?? {}))
58
58
  s != null && (t[e] = Array.isArray(s) ? String(s[0]) : String(s));
59
59
  return t;
60
60
  }
61
- function d(i) {
61
+ function _(i) {
62
62
  return i && typeof i == "object" && typeof i.message == "string" ? i.message : null;
63
63
  }
64
- function k(i, t) {
64
+ function E(i, t) {
65
65
  return t.some((e) => e === i || i.startsWith(`${e}.`));
66
66
  }
67
- function y(i, t, e = "") {
68
- if (e && k(e, t)) return [];
69
- if (p(i)) {
67
+ function g(i, t, e = "") {
68
+ if (e && E(e, t)) return [];
69
+ if (m(i)) {
70
70
  const s = [];
71
71
  for (const r of Object.keys(i))
72
- s.push(...y(i[r], t, e ? `${e}.${r}` : r));
72
+ s.push(...g(i[r], t, e ? `${e}.${r}` : r));
73
73
  return s;
74
74
  }
75
75
  return Array.isArray(i) || !e ? [] : [e];
76
76
  }
77
- function v(i, t) {
77
+ function T(i, t) {
78
78
  return t && i && typeof i == "object" ? f(i, t) : i;
79
79
  }
80
- class R extends Error {
80
+ class F extends Error {
81
81
  constructor(t, e, s) {
82
- super(d(e) ?? `Request failed with status ${t}`), this.name = "ApixError", this.status = t, this.body = e, this.response = s, this.errors = e && typeof e == "object" && e.errors && typeof e.errors == "object" ? e.errors : {};
82
+ super(_(e) ?? `Request failed with status ${t}`), this.name = "ApixError", this.status = t, this.body = e, this.response = s, this.errors = e && typeof e == "object" && e.errors && typeof e.errors == "object" ? e.errors : {};
83
83
  }
84
84
  /**
85
85
  * True for any 4xx response whose body carries an `errors` object
@@ -90,10 +90,10 @@ class R extends Error {
90
90
  return this.status >= 400 && this.status < 500 && Object.keys(this.errors).length > 0;
91
91
  }
92
92
  }
93
- function E(i) {
93
+ function O(i) {
94
94
  return i instanceof Error && i.name === "AbortError";
95
95
  }
96
- function A(i) {
96
+ function U(i) {
97
97
  const t = [], e = (r, o) => {
98
98
  t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`);
99
99
  }, s = (r, o) => {
@@ -114,7 +114,7 @@ function A(i) {
114
114
  for (const [r, o] of Object.entries(i)) s(o, r);
115
115
  return t.join("&");
116
116
  }
117
- async function T(i) {
117
+ async function W(i) {
118
118
  if (i.status === 204) return null;
119
119
  const t = await i.text();
120
120
  if (!t) return null;
@@ -124,18 +124,18 @@ async function T(i) {
124
124
  return t;
125
125
  }
126
126
  }
127
- class U {
127
+ class L {
128
128
  constructor(t, e = {}, s = null) {
129
129
  this._snapshot = null, this._snapshotLocked = !1, this._ignore = [], this._lock = [], this._triggerFields = null, this._sendFields = null, this._debounce = 0, this._debounceTimer = null, this._lastSent = null, this._fillAbort = null, this._transformResponse = null, this._transformRequest = null, this._deferredWatchSetup = null, this._apix = t, this._options = e, this._source = s, this._transformResponse = e.transformResponse ?? null, this._transformRequest = e.transformRequest ?? null;
130
130
  const r = e.default ? e.default() : null;
131
- if (this._state = O({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r), this._ignore = e.ignore ?? [], this._lock = e.lock ?? [], this._sendFields = y(r ?? {}, this._ignore), e.watch) {
131
+ if (this._state = q({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r), this._ignore = e.ignore ?? [], this._lock = e.lock ?? [], this._sendFields = g(r ?? {}, this._ignore), e.watch) {
132
132
  const o = e.watch;
133
133
  if (!this._source)
134
134
  console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");
135
135
  else if (e.immediate === !1)
136
136
  this._setupWatch(o, r);
137
137
  else {
138
- const n = S();
138
+ const n = v();
139
139
  this._deferredWatchSetup = () => {
140
140
  n ? n.run(() => this._setupWatch(o, r)) : this._setupWatch(o, r);
141
141
  };
@@ -191,7 +191,7 @@ class U {
191
191
  if (r.startsWith(s)) return e[r];
192
192
  }
193
193
  setErrors(t) {
194
- return this._state.errors = j(t), this._proxy;
194
+ return this._state.errors = w(t), this._proxy;
195
195
  }
196
196
  /** Clear all errors, or only the given keys (including their `key.*` sub-errors). */
197
197
  clearErrors(t) {
@@ -215,7 +215,7 @@ class U {
215
215
  const e = Array.isArray(t) ? t : [t];
216
216
  if (this._state.data && typeof this._state.data == "object")
217
217
  for (const s of e)
218
- m(this._state.data, s, c(f(this._snapshot, s)));
218
+ y(this._state.data, s, c(f(this._snapshot, s)));
219
219
  return this.clearErrors(e), this._proxy;
220
220
  }
221
221
  // --- HTTP ------------------------------------------------------------------------
@@ -276,7 +276,7 @@ class U {
276
276
  // --- internals ----------------------------------------------------------------------
277
277
  /** @internal */
278
278
  async _fill(t = {}) {
279
- var o, n, a, h, u;
279
+ var o, n, a, h, u, d, b;
280
280
  const e = this._source;
281
281
  (o = this._fillAbort) == null || o.abort();
282
282
  const s = new AbortController();
@@ -285,38 +285,38 @@ class U {
285
285
  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);
286
286
  try {
287
287
  const l = await this._apix.request(e.method, e.url, r);
288
- let _ = v(l, this._options.path);
288
+ let p = T(l, this._options.path);
289
289
  if (this._transformResponse) {
290
- const g = c(_);
291
- _ = this._transformResponse(g, l) ?? g;
290
+ const j = c(p);
291
+ p = this._transformResponse(j, l) ?? j;
292
292
  }
293
- return this._applyFill(_, t.preserve ?? null), this._state.message = d(l), this._state.errors = {}, (a = (n = this._options).onSuccess) == null || a.call(n, l, this._proxy), l;
293
+ return this._applyFill(p, t.preserve ?? null), this._state.message = _(l), this._state.errors = {}, (a = (n = this._options).onSuccess) == null || a.call(n, l, this._proxy), l;
294
294
  } catch (l) {
295
- throw E(l) || (this._applyError(l), (u = (h = this._options).onError) == null || u.call(h, l, this._proxy)), l;
295
+ throw O(l) || (this._applyError(l), (u = (h = this._options).onError) == null || u.call(h, l, this._proxy)), l;
296
296
  } finally {
297
- this._fillAbort === s && (this._fillAbort = null, this._state.processing = !1);
297
+ this._fillAbort === s && (this._fillAbort = null, this._state.processing = !1, (b = (d = this._options).onFinish) == null || b.call(d, this._proxy));
298
298
  }
299
299
  }
300
300
  _applyFill(t, e) {
301
301
  let s = c(t);
302
- this._options.mergeDefaults !== !1 && this._options.default && (s = w(s, this._options.default()));
302
+ this._options.mergeDefaults !== !1 && this._options.default && (s = R(s, this._options.default()));
303
303
  const r = this._snapshotLocked ? null : c(s);
304
304
  if (e && e.length && s && typeof s == "object" && this._state.data && typeof this._state.data == "object")
305
305
  for (const o of e) {
306
306
  const n = f(this._state.data, o);
307
- n !== void 0 && m(s, o, c(n));
307
+ n !== void 0 && y(s, o, c(n));
308
308
  }
309
309
  this._state.data = s, this._snapshotLocked || (this._snapshot = r, this._snapshotLocked = !0), this._syncLastSent();
310
310
  }
311
311
  _applyError(t) {
312
- t instanceof R && (this._state.message = d(t.body) ?? t.message, t.isValidationError && (this._state.errors = j(t.errors)));
312
+ t instanceof F && (this._state.message = _(t.body) ?? t.message, t.isValidationError && (this._state.errors = w(t.errors)));
313
313
  }
314
314
  async _submit(t, e, s = {}) {
315
315
  var n;
316
316
  const r = e ?? ((n = this._source) == null ? void 0 : n.url);
317
317
  if (!r)
318
318
  throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);
319
- let o = s.data !== void 0 ? s.data : s.only ? b(this._state.data, s.only) : this._state.data ?? void 0;
319
+ let o = s.data !== void 0 ? s.data : s.only ? x(this._state.data, s.only) : this._state.data ?? void 0;
320
320
  if (s.data === void 0 && this._transformRequest && o !== void 0) {
321
321
  const a = c(o);
322
322
  o = this._transformRequest(a) ?? a;
@@ -328,7 +328,7 @@ class U {
328
328
  params: s.params,
329
329
  headers: s.headers
330
330
  });
331
- return this._state.message = d(a), a;
331
+ return this._state.message = _(a), a;
332
332
  } catch (a) {
333
333
  throw this._applyError(a), a;
334
334
  } finally {
@@ -343,10 +343,10 @@ class U {
343
343
  * that's what determines which fields exist, regardless of timing.
344
344
  */
345
345
  _setupWatch(t, e) {
346
- const s = t === !0 ? {} : t, r = s.fields, o = r ?? this._sendFields ?? y(e ?? {}, this._ignore);
346
+ const s = t === !0 ? {} : t, r = s.fields, o = r ?? this._sendFields ?? g(e ?? {}, this._ignore);
347
347
  this._triggerFields = o, this._debounce = s.debounce ?? 0, this._syncLastSent();
348
348
  const n = o.map((h) => () => f(this._state.data, h)), a = r ? s.deep ?? !1 : !0;
349
- q(n, () => this._onWatchTrigger(), { deep: a });
349
+ A(n, () => this._onWatchTrigger(), { deep: a });
350
350
  }
351
351
  _onWatchTrigger() {
352
352
  this._payloadJson() !== this._lastSent && (this._debounceTimer && clearTimeout(this._debounceTimer), this._debounce > 0 ? this._debounceTimer = setTimeout(() => this._sendWatchRequest(), this._debounce) : this._sendWatchRequest());
@@ -357,8 +357,8 @@ class U {
357
357
  }
358
358
  /** Build the fill() extra for a watch/refresh request from the current state. */
359
359
  _buildFillExtra(t = {}) {
360
- const e = t.lock ? [...this._lock, ...t.lock] : this._lock, s = t.ignore ? (this._sendFields ?? []).filter((o) => !k(o, t.ignore)) : this._sendFields ?? [];
361
- let r = b(this._state.data, s);
360
+ const e = t.lock ? [...this._lock, ...t.lock] : this._lock, s = t.ignore ? (this._sendFields ?? []).filter((o) => !E(o, t.ignore)) : this._sendFields ?? [];
361
+ let r = x(this._state.data, s);
362
362
  return this._transformRequest && (r = this._transformRequest(r) ?? r), this._source.method === "get" ? { params: r, preserve: e } : { data: r, preserve: e };
363
363
  }
364
364
  _payloadJson() {
@@ -369,8 +369,8 @@ class U {
369
369
  this._lastSent = this._payloadJson();
370
370
  }
371
371
  }
372
- function x(i, t = {}, e = null) {
373
- const s = new U(i, t, e), r = new Proxy(s, {
372
+ function k(i, t = {}, e = null) {
373
+ const s = new L(i, t, e), r = new Proxy(s, {
374
374
  get(o, n) {
375
375
  if (typeof n == "symbol" || n in o) return Reflect.get(o, n);
376
376
  const a = o._state.data;
@@ -393,7 +393,7 @@ function x(i, t = {}, e = null) {
393
393
  }).catch(() => {
394
394
  }), r;
395
395
  }
396
- class W {
396
+ class H {
397
397
  constructor(t = {}) {
398
398
  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);
399
399
  }
@@ -436,7 +436,7 @@ class W {
436
436
  async request(t, e, s = {}) {
437
437
  let r = /^https?:\/\//i.test(e) ? e : this.baseUrl + e;
438
438
  if (s.params) {
439
- const h = A(s.params);
439
+ const h = U(s.params);
440
440
  h && (r += (r.includes("?") ? "&" : "?") + h);
441
441
  }
442
442
  const o = {
@@ -444,8 +444,8 @@ class W {
444
444
  "x-requested-with": "XMLHttpRequest"
445
445
  };
446
446
  for (const [h, u] of Object.entries(this.headers)) {
447
- const l = typeof u == "function" ? u() : u;
448
- l != null && (o[h.toLowerCase()] = l);
447
+ const d = typeof u == "function" ? u() : u;
448
+ d != null && (o[h.toLowerCase()] = d);
449
449
  }
450
450
  for (const [h, u] of Object.entries(s.headers ?? {}))
451
451
  o[h.toLowerCase()] = u;
@@ -455,11 +455,11 @@ class W {
455
455
  this.trackStart();
456
456
  try {
457
457
  const h = await fetch(r, n);
458
- let u = await T(h);
459
- if (this.bodyTransformer && (u = this.bodyTransformer(u, a) ?? u), !h.ok) throw new R(h.status, u, h);
458
+ let u = await W(h);
459
+ if (this.bodyTransformer && (u = this.bodyTransformer(u, a) ?? u), !h.ok) throw new F(h.status, u, h);
460
460
  return u;
461
461
  } catch (h) {
462
- throw E(h) ? h : this.emitError(h, a);
462
+ throw O(h) ? h : this.emitError(h, a);
463
463
  } finally {
464
464
  this.trackEnd();
465
465
  }
@@ -483,7 +483,7 @@ class W {
483
483
  // --- form models -----------------------------------------------------------
484
484
  /** Create a form model without any request (like Inertia's useForm). */
485
485
  form(t, e = {}) {
486
- return x(this, { ...e, default: typeof t == "function" ? t : () => c(t) });
486
+ return k(this, { ...e, default: typeof t == "function" ? t : () => c(t) });
487
487
  }
488
488
  /** Create a form model and fill it with a GET request. */
489
489
  getForm(t, e) {
@@ -495,7 +495,7 @@ class W {
495
495
  }
496
496
  createFormModel(t, e, s) {
497
497
  const r = typeof s == "string" ? { path: s } : { ...s ?? {} };
498
- return x(this, r, { url: e, method: t });
498
+ return k(this, r, { url: e, method: t });
499
499
  }
500
500
  // --- internals --------------------------------------------------------------
501
501
  trackStart() {
@@ -523,15 +523,15 @@ class W {
523
523
  return s;
524
524
  }
525
525
  }
526
- function L(i = {}) {
527
- return new W(i);
526
+ function P(i = {}) {
527
+ return new H(i);
528
528
  }
529
- const P = L();
529
+ const C = P();
530
530
  export {
531
- W as Apix,
532
- R as ApixError,
533
- U as ApixFormModel,
534
- P as apix,
535
- L as createApix,
536
- P as default
531
+ H as Apix,
532
+ F as ApixError,
533
+ L as ApixFormModel,
534
+ C as apix,
535
+ P as createApix,
536
+ C as default
537
537
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diephp/vue-apix",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
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",