@diephp/vue-apix 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -494,12 +494,16 @@ model.refresh({ ignore: ['paginator.page'], lock: ['trackingNumber'] });
494
494
 
495
495
  ### Cleanup — no `unwatch()` needed inside a component
496
496
 
497
- Vue automatically stops a `watch()` effect created synchronously inside a component's
498
- `setup()` (which is exactly when `apix.getForm(...)` runs in `<script setup>`) once that
497
+ Vue automatically stops a `watch()` effect created inside a component's `setup()` once that
499
498
  component unmounts — no manual cleanup call exists or is needed. This only matters if you
500
499
  create a `watch`-enabled model **outside** any component (e.g. a module-level store shared
501
500
  across the whole app) — there it lives for as long as the module does, by design.
502
501
 
502
+ With an automatic initial fill (`immediate` not `false`), the underlying `watch()` is
503
+ registered only once that fill settles — not at construction — so its own response is
504
+ never mistaken for a change to react to. The component's effect scope is still captured
505
+ synchronously at construction, so auto-cleanup on unmount works exactly the same either way.
506
+
503
507
  ### Live search (minimal)
504
508
 
505
509
  ```ts
package/dist/model.d.ts CHANGED
@@ -35,6 +35,15 @@ export declare class ApixFormModel<T = any> {
35
35
  /** @internal */ _fillAbort: AbortController | null;
36
36
  /** @internal */ _transformResponse: ((data: any, response: any) => any) | null;
37
37
  /** @internal */ _transformRequest: ((data: any) => any) | null;
38
+ /**
39
+ * @internal Set only when `watch` must wait for the automatic initial fill
40
+ * to settle — called once, by createModel(), right after it does. Registers
41
+ * the Vue watch() only once the first merge has already happened, so that
42
+ * merge's own data reassignment is never mistaken for a user-driven change
43
+ * in the first place (nothing to de-dupe — the watcher simply doesn't exist
44
+ * yet while the initial fill is in flight).
45
+ */
46
+ _deferredWatchSetup: (() => void) | null;
38
47
  constructor(apix: Apix, options?: FormOptions<T>, source?: FillSource | null);
39
48
  get data(): T | null;
40
49
  set data(value: T | null);
@@ -104,7 +113,13 @@ export declare class ApixFormModel<T = any> {
104
113
  private _applyFill;
105
114
  private _applyError;
106
115
  private _submit;
107
- /** @internal Configures auto-refetch-on-change, once, at construction time. */
116
+ /**
117
+ * @internal Computes the trigger/send field sets and registers the Vue
118
+ * watch(). Called either synchronously from the constructor (no automatic
119
+ * initial fill to wait for) or once that fill has settled (see
120
+ * `_deferredWatchSetup`) — `initial` is always `default()`'s shape, since
121
+ * that's what determines which fields exist, regardless of timing.
122
+ */
108
123
  private _setupWatch;
109
124
  private _onWatchTrigger;
110
125
  private _sendWatchRequest;
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(i){const t=p.toRaw(i);if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(s=>c(s));if(t instanceof Date)return new Date(t.getTime());const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const s={};for(const r of Object.keys(t))s[r]=c(t[r]);return s}return t}function m(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function E(i,t){if(!m(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!m(i))return i;for(const e of Object.keys(t))i[e]=e in i?E(i[e],t[e]):c(t[e]);return i}function f(i,t){if(i==null)return;let e=i;for(const s of t.split(".")){if(e==null)return;e=e[s]}return e}function y(i,t,e){const s=t.split(".");let r=i;for(let o=0;o<s.length-1;o++){const n=s[o];(r[n]===null||typeof r[n]!="object")&&(r[n]={}),r=r[n]}r[s[s.length-1]]=e}function x(i,t){const e={};for(const s of t){const r=f(i,s);r!==void 0&&y(e,s,c(r))}return e}function j(i){const t={};for(const[e,s]of Object.entries(i??{}))s!=null&&(t[e]=Array.isArray(s)?String(s[0]):String(s));return t}function d(i){return i&&typeof i=="object"&&typeof i.message=="string"?i.message:null}function R(i,t){return t.some(e=>e===i||i.startsWith(`${e}.`))}function w(i,t,e=""){if(e&&R(e,t))return[];if(m(i)){const s=[];for(const r of Object.keys(i))s.push(...w(i[r],t,e?`${e}.${r}`:r));return s}return Array.isArray(i)||!e?[]:[e]}function S(i,t){return t&&i&&typeof i=="object"?f(i,t):i}class g extends Error{constructor(t,e,s){super(d(e)??`Request failed with status ${t}`),this.name="ApixError",this.status=t,this.body=e,this.response=s,this.errors=e&&typeof e=="object"&&e.errors&&typeof e.errors=="object"?e.errors:{}}get isValidationError(){return this.status>=400&&this.status<500&&Object.keys(this.errors).length>0}}function F(i){return i instanceof Error&&i.name==="AbortError"}function T(i){const t=[],e=(r,o)=>{t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`)},s=(r,o)=>{if(r!=null){if(typeof r=="boolean")return e(o,r?"1":"0");if(r instanceof Date)return e(o,r.toISOString());if(Array.isArray(r)){r.forEach((n,a)=>s(n,`${o}[${a}]`));return}if(typeof r=="object"){for(const[n,a]of Object.entries(r))s(a,`${o}[${n}]`);return}e(o,String(r))}};for(const[r,o]of Object.entries(i))s(o,r);return t.join("&")}async function U(i){if(i.status===204)return null;const t=await i.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}class A{constructor(t,e={},s=null){this._snapshot=null,this._snapshotLocked=!1,this._ignore=[],this._lock=[],this._triggerFields=null,this._sendFields=null,this._debounce=0,this._debounceTimer=null,this._lastSent=null,this._fillAbort=null,this._transformResponse=null,this._transformRequest=null,this._apix=t,this._options=e,this._source=s,this._transformResponse=e.transformResponse??null,this._transformRequest=e.transformRequest??null;const r=e.default?e.default():null;this._state=p.reactive({data:r,errors:{},message:null,processing:!1}),this._snapshot=c(r),this._ignore=e.ignore??[],this._lock=e.lock??[],this._setupWatch(e.watch,r)}get data(){return this._state.data}set data(t){this._state.data=t}get errors(){return this._state.errors}get message(){return this._state.message}get processing(){return this._state.processing}get hasErrors(){return Object.keys(this._state.errors).length>0}get isDirty(){return JSON.stringify(this._state.data)!==JSON.stringify(this._snapshot)}get(t){return c(f(this._state.data,t))}setData(t){return this._state.data=c(t),this._proxy}error(t){const e=this._state.errors;if(e[t]!==void 0)return e[t];const s=`${t}.`;for(const r of Object.keys(e))if(r.startsWith(s))return e[r]}setErrors(t){return this._state.errors=j(t),this._proxy}clearErrors(t){if(!t)return this._state.errors={},this._proxy;for(const e of t){const s=`${e}.`;for(const r of Object.keys(this._state.errors))(r===e||r.startsWith(s))&&delete this._state.errors[r]}return this._proxy}reset(t){if(t===void 0||Array.isArray(t)&&t.length===0)return this._state.data=c(this._snapshot),this._state.errors={},this._state.message=null,this._proxy;const e=Array.isArray(t)?t:[t];if(this._state.data&&typeof this._state.data=="object")for(const s of e)y(this._state.data,s,c(f(this._snapshot,s)));return this.clearErrors(e),this._proxy}post(t,e){return this._submit("post",t,e)}put(t,e){return this._submit("put",t,e)}patch(t,e){return this._submit("patch",t,e)}delete(t,e){return this._submit("delete",t,e)}reload(t){var e;return t&&(this._source={url:t,method:((e=this._source)==null?void 0:e.method)??"get"}),this._source?this._fill():Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."))}refresh(t={}){if(!this._source)return Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."));if(this._triggerFields===null)return this._fill();this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null);const e=this._buildFillExtra(t);return this._lastSent=this._payloadJson(),this._fill(e)}transformResponse(t){return this._transformResponse=t,this._proxy}transformRequest(t){return this._transformRequest=t,this._proxy}async _fill(t={}){var o,n,a,h,l;const e=this._source;(o=this._fillAbort)==null||o.abort();const s=new AbortController;this._fillAbort=s,this._state.processing=!0;const r={signal:s.signal};e.method==="get"?r.params={...this._options.params,...t.params}:(r.params=this._options.params,r.data=t.data!==void 0?t.data:this._options.data);try{const u=await this._apix.request(e.method,e.url,r);let _=S(u,this._options.path);if(this._transformResponse){const b=c(_);_=this._transformResponse(b,u)??b}return this._applyFill(_,t.preserve??null),this._state.message=d(u),this._state.errors={},(a=(n=this._options).onSuccess)==null||a.call(n,u,this._proxy),u}catch(u){throw F(u)||(this._applyError(u),(l=(h=this._options).onError)==null||l.call(h,u,this._proxy)),u}finally{this._fillAbort===s&&(this._fillAbort=null,this._state.processing=!1)}}_applyFill(t,e){let s=c(t);this._options.mergeDefaults!==!1&&this._options.default&&(s=E(s,this._options.default()));const r=this._snapshotLocked?null:c(s);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const o of e){const n=f(this._state.data,o);n!==void 0&&y(s,o,c(n))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof g&&(this._state.message=d(t.body)??t.message,t.isValidationError&&(this._state.errors=j(t.errors)))}async _submit(t,e,s={}){var n;const r=e??((n=this._source)==null?void 0:n.url);if(!r)throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);let o=s.data!==void 0?s.data:s.only?x(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&o!==void 0){const a=c(o);o=this._transformRequest(a)??a}this._state.processing=!0,this._state.errors={},this._state.message=null;try{const a=await this._apix.request(t,r,{data:o,params:s.params,headers:s.headers});return this._state.message=d(a),a}catch(a){throw this._applyError(a),a}finally{this._state.processing=!1}}_setupWatch(t,e){if(!t)return;if(!this._source){console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");return}const s=t===!0?{}:t,r=s.fields;this._sendFields=w(e??{},this._ignore),this._triggerFields=r??this._sendFields,this._debounce=s.debounce??0,this._syncLastSent();const o=this._triggerFields.map(a=>()=>f(this._state.data,a)),n=r?s.deep??!1:!0;p.watch(o,()=>this._onWatchTrigger(),{deep:n})}_onWatchTrigger(){this._payloadJson()!==this._lastSent&&(this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounce>0?this._debounceTimer=setTimeout(()=>this._sendWatchRequest(),this._debounce):this._sendWatchRequest())}_sendWatchRequest(){this._debounceTimer=null,this._source&&(this._lastSent=this._payloadJson(),this._fill(this._buildFillExtra()).catch(()=>{}))}_buildFillExtra(t={}){const e=t.lock?[...this._lock,...t.lock]:this._lock,s=t.ignore?(this._sendFields??[]).filter(o=>!R(o,t.ignore)):this._sendFields??[];let r=x(this._state.data,s);return this._transformRequest&&(r=this._transformRequest(r)??r),this._source.method==="get"?{params:r,preserve:e}:{data:r,preserve:e}}_payloadJson(){const e=(this._triggerFields??[]).map(s=>f(this._state.data,s));return JSON.stringify(e)??"undefined"}_syncLastSent(){this._lastSent=this._payloadJson()}}function k(i,t={},e=null){const s=new A(i,t,e),r=new Proxy(s,{get(o,n){if(typeof n=="symbol"||n in o)return Reflect.get(o,n);const a=o._state.data;if(a&&typeof a=="object")return a[n]},set(o,n,a){if(typeof n=="symbol"||n in o)return Reflect.set(o,n,a);const h=o._state.data;return h&&typeof h=="object"?(h[n]=a,!0):(o._state.data={[n]:a},!0)},has(o,n){if(n in o)return!0;const a=o._state.data;return!!a&&typeof a=="object"&&n in a}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().catch(()=>{}),r}class v{constructor(t={}){this.baseUrl="",this.headers={},this.processingHooks=[],this.errorHooks=[],this.bodyTransformer=null,this.active=0,t.baseUrl&&this.setBaseUrl(t.baseUrl),t.headers&&this.setHeader(t.headers),t.credentials&&(this.credentials=t.credentials)}setBaseUrl(t){return this.baseUrl=t.replace(/\/+$/,""),this}setHeader(t){return Object.assign(this.headers,t),this}setCredentials(t){return this.credentials=t,this}onProcessing(t){return this.processingHooks.push(t),()=>{this.processingHooks=this.processingHooks.filter(e=>e!==t)}}onError(t){return this.errorHooks.push(t),()=>{this.errorHooks=this.errorHooks.filter(e=>e!==t)}}transformResponse(t){return this.bodyTransformer=t,this}async request(t,e,s={}){let r=/^https?:\/\//i.test(e)?e:this.baseUrl+e;if(s.params){const h=T(s.params);h&&(r+=(r.includes("?")?"&":"?")+h)}const o={accept:"application/json","x-requested-with":"XMLHttpRequest"};for(const[h,l]of Object.entries(this.headers)){const u=typeof l=="function"?l():l;u!=null&&(o[h.toLowerCase()]=u)}for(const[h,l]of Object.entries(s.headers??{}))o[h.toLowerCase()]=l;const n={method:t.toUpperCase(),headers:o,signal:s.signal};this.credentials&&(n.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?(delete o["content-type"],n.body=s.data):(o["content-type"]??(o["content-type"]="application/json"),n.body=JSON.stringify(s.data)));const a={method:t,url:r,options:s};this.trackStart();try{const h=await fetch(r,n);let l=await U(h);if(this.bodyTransformer&&(l=this.bodyTransformer(l,a)??l),!h.ok)throw new g(h.status,l,h);return l}catch(h){throw F(h)?h:this.emitError(h,a)}finally{this.trackEnd()}}get(t,e,s={}){return this.request("get",t,e?{...s,params:e}:s)}post(t,e,s={}){return this.request("post",t,e!==void 0?{...s,data:e}:s)}put(t,e,s={}){return this.request("put",t,e!==void 0?{...s,data:e}:s)}patch(t,e,s={}){return this.request("patch",t,e!==void 0?{...s,data:e}:s)}delete(t,e,s={}){return this.request("delete",t,e!==void 0?{...s,data:e}:s)}form(t,e={}){return k(this,{...e,default:typeof t=="function"?t:()=>c(t)})}getForm(t,e){return this.createFormModel("get",t,e)}postForm(t,e){return this.createFormModel("post",t,e)}createFormModel(t,e,s){const r=typeof s=="string"?{path:s}:{...s??{}};return k(this,r,{url:e,method:t})}trackStart(){++this.active===1&&this.emitProcessing(!0)}trackEnd(){--this.active===0&&this.emitProcessing(!1)}emitProcessing(t){for(const e of this.processingHooks)try{e(t)}catch{}}emitError(t,e){let s=t;for(const r of this.errorHooks)try{const o=r(s,e);o instanceof Error&&(s=o)}catch{}return s}}function O(i={}){return new v(i)}const q=O();exports.Apix=v;exports.ApixError=g;exports.ApixFormModel=A;exports.apix=q;exports.createApix=O;exports.default=q;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const d=require("vue");function c(i){const t=d.toRaw(i);if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(s=>c(s));if(t instanceof Date)return new Date(t.getTime());const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const s={};for(const r of Object.keys(t))s[r]=c(t[r]);return s}return t}function m(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function k(i,t){if(!m(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!m(i))return i;for(const e of Object.keys(t))i[e]=e in i?k(i[e],t[e]):c(t[e]);return i}function f(i,t){if(i==null)return;let e=i;for(const s of t.split(".")){if(e==null)return;e=e[s]}return e}function y(i,t,e){const s=t.split(".");let r=i;for(let o=0;o<s.length-1;o++){const n=s[o];(r[n]===null||typeof r[n]!="object")&&(r[n]={}),r=r[n]}r[s[s.length-1]]=e}function x(i,t){const e={};for(const s of t){const r=f(i,s);r!==void 0&&y(e,s,c(r))}return e}function j(i){const t={};for(const[e,s]of Object.entries(i??{}))s!=null&&(t[e]=Array.isArray(s)?String(s[0]):String(s));return t}function _(i){return i&&typeof i=="object"&&typeof i.message=="string"?i.message:null}function E(i,t){return t.some(e=>e===i||i.startsWith(`${e}.`))}function R(i,t,e=""){if(e&&E(e,t))return[];if(m(i)){const s=[];for(const r of Object.keys(i))s.push(...R(i[r],t,e?`${e}.${r}`:r));return s}return Array.isArray(i)||!e?[]:[e]}function q(i,t){return t&&i&&typeof i=="object"?f(i,t):i}class g extends Error{constructor(t,e,s){super(_(e)??`Request failed with status ${t}`),this.name="ApixError",this.status=t,this.body=e,this.response=s,this.errors=e&&typeof e=="object"&&e.errors&&typeof e.errors=="object"?e.errors:{}}get isValidationError(){return this.status>=400&&this.status<500&&Object.keys(this.errors).length>0}}function F(i){return i instanceof Error&&i.name==="AbortError"}function T(i){const t=[],e=(r,o)=>{t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`)},s=(r,o)=>{if(r!=null){if(typeof r=="boolean")return e(o,r?"1":"0");if(r instanceof Date)return e(o,r.toISOString());if(Array.isArray(r)){r.forEach((n,a)=>s(n,`${o}[${a}]`));return}if(typeof r=="object"){for(const[n,a]of Object.entries(r))s(a,`${o}[${n}]`);return}e(o,String(r))}};for(const[r,o]of Object.entries(i))s(o,r);return t.join("&")}async function U(i){if(i.status===204)return null;const t=await i.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}class A{constructor(t,e={},s=null){this._snapshot=null,this._snapshotLocked=!1,this._ignore=[],this._lock=[],this._triggerFields=null,this._sendFields=null,this._debounce=0,this._debounceTimer=null,this._lastSent=null,this._fillAbort=null,this._transformResponse=null,this._transformRequest=null,this._deferredWatchSetup=null,this._apix=t,this._options=e,this._source=s,this._transformResponse=e.transformResponse??null,this._transformRequest=e.transformRequest??null;const r=e.default?e.default():null;if(this._state=d.reactive({data:r,errors:{},message:null,processing:!1}),this._snapshot=c(r),this._ignore=e.ignore??[],this._lock=e.lock??[],e.watch){const o=e.watch;if(!this._source)console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");else if(e.immediate===!1)this._setupWatch(o,r);else{const n=d.getCurrentScope();this._deferredWatchSetup=()=>{n?n.run(()=>this._setupWatch(o,r)):this._setupWatch(o,r)}}}}get data(){return this._state.data}set data(t){this._state.data=t}get errors(){return this._state.errors}get message(){return this._state.message}get processing(){return this._state.processing}get hasErrors(){return Object.keys(this._state.errors).length>0}get isDirty(){return JSON.stringify(this._state.data)!==JSON.stringify(this._snapshot)}get(t){return c(f(this._state.data,t))}setData(t){return this._state.data=c(t),this._proxy}error(t){const e=this._state.errors;if(e[t]!==void 0)return e[t];const s=`${t}.`;for(const r of Object.keys(e))if(r.startsWith(s))return e[r]}setErrors(t){return this._state.errors=j(t),this._proxy}clearErrors(t){if(!t)return this._state.errors={},this._proxy;for(const e of t){const s=`${e}.`;for(const r of Object.keys(this._state.errors))(r===e||r.startsWith(s))&&delete this._state.errors[r]}return this._proxy}reset(t){if(t===void 0||Array.isArray(t)&&t.length===0)return this._state.data=c(this._snapshot),this._state.errors={},this._state.message=null,this._proxy;const e=Array.isArray(t)?t:[t];if(this._state.data&&typeof this._state.data=="object")for(const s of e)y(this._state.data,s,c(f(this._snapshot,s)));return this.clearErrors(e),this._proxy}post(t,e){return this._submit("post",t,e)}put(t,e){return this._submit("put",t,e)}patch(t,e){return this._submit("patch",t,e)}delete(t,e){return this._submit("delete",t,e)}reload(t){var e;return t&&(this._source={url:t,method:((e=this._source)==null?void 0:e.method)??"get"}),this._source?this._fill():Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."))}refresh(t={}){if(!this._source)return Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."));if(this._triggerFields===null)return this._fill();this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null);const e=this._buildFillExtra(t);return this._lastSent=this._payloadJson(),this._fill(e)}transformResponse(t){return this._transformResponse=t,this._proxy}transformRequest(t){return this._transformRequest=t,this._proxy}async _fill(t={}){var o,n,a,h,l;const e=this._source;(o=this._fillAbort)==null||o.abort();const s=new AbortController;this._fillAbort=s,this._state.processing=!0;const r={signal:s.signal};e.method==="get"?r.params={...this._options.params,...t.params}:(r.params=this._options.params,r.data=t.data!==void 0?t.data:this._options.data);try{const u=await this._apix.request(e.method,e.url,r);let p=q(u,this._options.path);if(this._transformResponse){const b=c(p);p=this._transformResponse(b,u)??b}return this._applyFill(p,t.preserve??null),this._state.message=_(u),this._state.errors={},(a=(n=this._options).onSuccess)==null||a.call(n,u,this._proxy),u}catch(u){throw F(u)||(this._applyError(u),(l=(h=this._options).onError)==null||l.call(h,u,this._proxy)),u}finally{this._fillAbort===s&&(this._fillAbort=null,this._state.processing=!1)}}_applyFill(t,e){let s=c(t);this._options.mergeDefaults!==!1&&this._options.default&&(s=k(s,this._options.default()));const r=this._snapshotLocked?null:c(s);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const o of e){const n=f(this._state.data,o);n!==void 0&&y(s,o,c(n))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof g&&(this._state.message=_(t.body)??t.message,t.isValidationError&&(this._state.errors=j(t.errors)))}async _submit(t,e,s={}){var n;const r=e??((n=this._source)==null?void 0:n.url);if(!r)throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);let o=s.data!==void 0?s.data:s.only?x(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&o!==void 0){const a=c(o);o=this._transformRequest(a)??a}this._state.processing=!0,this._state.errors={},this._state.message=null;try{const a=await this._apix.request(t,r,{data:o,params:s.params,headers:s.headers});return this._state.message=_(a),a}catch(a){throw this._applyError(a),a}finally{this._state.processing=!1}}_setupWatch(t,e){const s=t===!0?{}:t,r=s.fields;this._sendFields=R(e??{},this._ignore);const o=r??this._sendFields;this._triggerFields=o,this._debounce=s.debounce??0,this._syncLastSent();const n=o.map(h=>()=>f(this._state.data,h)),a=r?s.deep??!1:!0;d.watch(n,()=>this._onWatchTrigger(),{deep:a})}_onWatchTrigger(){this._payloadJson()!==this._lastSent&&(this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounce>0?this._debounceTimer=setTimeout(()=>this._sendWatchRequest(),this._debounce):this._sendWatchRequest())}_sendWatchRequest(){this._debounceTimer=null,this._source&&(this._lastSent=this._payloadJson(),this._fill(this._buildFillExtra()).catch(()=>{}))}_buildFillExtra(t={}){const e=t.lock?[...this._lock,...t.lock]:this._lock,s=t.ignore?(this._sendFields??[]).filter(o=>!E(o,t.ignore)):this._sendFields??[];let r=x(this._state.data,s);return this._transformRequest&&(r=this._transformRequest(r)??r),this._source.method==="get"?{params:r,preserve:e}:{data:r,preserve:e}}_payloadJson(){const e=(this._triggerFields??[]).map(s=>f(this._state.data,s));return JSON.stringify(e)??"undefined"}_syncLastSent(){this._lastSent=this._payloadJson()}}function w(i,t={},e=null){const s=new A(i,t,e),r=new Proxy(s,{get(o,n){if(typeof n=="symbol"||n in o)return Reflect.get(o,n);const a=o._state.data;if(a&&typeof a=="object")return a[n]},set(o,n,a){if(typeof n=="symbol"||n in o)return Reflect.set(o,n,a);const h=o._state.data;return h&&typeof h=="object"?(h[n]=a,!0):(o._state.data={[n]:a},!0)},has(o,n){if(n in o)return!0;const a=o._state.data;return!!a&&typeof a=="object"&&n in a}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().finally(()=>{var o;(o=s._deferredWatchSetup)==null||o.call(s),s._deferredWatchSetup=null}).catch(()=>{}),r}class S{constructor(t={}){this.baseUrl="",this.headers={},this.processingHooks=[],this.errorHooks=[],this.bodyTransformer=null,this.active=0,t.baseUrl&&this.setBaseUrl(t.baseUrl),t.headers&&this.setHeader(t.headers),t.credentials&&(this.credentials=t.credentials)}setBaseUrl(t){return this.baseUrl=t.replace(/\/+$/,""),this}setHeader(t){return Object.assign(this.headers,t),this}setCredentials(t){return this.credentials=t,this}onProcessing(t){return this.processingHooks.push(t),()=>{this.processingHooks=this.processingHooks.filter(e=>e!==t)}}onError(t){return this.errorHooks.push(t),()=>{this.errorHooks=this.errorHooks.filter(e=>e!==t)}}transformResponse(t){return this.bodyTransformer=t,this}async request(t,e,s={}){let r=/^https?:\/\//i.test(e)?e:this.baseUrl+e;if(s.params){const h=T(s.params);h&&(r+=(r.includes("?")?"&":"?")+h)}const o={accept:"application/json","x-requested-with":"XMLHttpRequest"};for(const[h,l]of Object.entries(this.headers)){const u=typeof l=="function"?l():l;u!=null&&(o[h.toLowerCase()]=u)}for(const[h,l]of Object.entries(s.headers??{}))o[h.toLowerCase()]=l;const n={method:t.toUpperCase(),headers:o,signal:s.signal};this.credentials&&(n.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?(delete o["content-type"],n.body=s.data):(o["content-type"]??(o["content-type"]="application/json"),n.body=JSON.stringify(s.data)));const a={method:t,url:r,options:s};this.trackStart();try{const h=await fetch(r,n);let l=await U(h);if(this.bodyTransformer&&(l=this.bodyTransformer(l,a)??l),!h.ok)throw new g(h.status,l,h);return l}catch(h){throw F(h)?h:this.emitError(h,a)}finally{this.trackEnd()}}get(t,e,s={}){return this.request("get",t,e?{...s,params:e}:s)}post(t,e,s={}){return this.request("post",t,e!==void 0?{...s,data:e}:s)}put(t,e,s={}){return this.request("put",t,e!==void 0?{...s,data:e}:s)}patch(t,e,s={}){return this.request("patch",t,e!==void 0?{...s,data:e}:s)}delete(t,e,s={}){return this.request("delete",t,e!==void 0?{...s,data:e}:s)}form(t,e={}){return w(this,{...e,default:typeof t=="function"?t:()=>c(t)})}getForm(t,e){return this.createFormModel("get",t,e)}postForm(t,e){return this.createFormModel("post",t,e)}createFormModel(t,e,s){const r=typeof s=="string"?{path:s}:{...s??{}};return w(this,r,{url:e,method:t})}trackStart(){++this.active===1&&this.emitProcessing(!0)}trackEnd(){--this.active===0&&this.emitProcessing(!1)}emitProcessing(t){for(const e of this.processingHooks)try{e(t)}catch{}}emitError(t,e){let s=t;for(const r of this.errorHooks)try{const o=r(s,e);o instanceof Error&&(s=o)}catch{}return s}}function v(i={}){return new S(i)}const O=v();exports.Apix=S;exports.ApixError=g;exports.ApixFormModel=A;exports.apix=O;exports.createApix=v;exports.default=O;
package/dist/vue-apix.js CHANGED
@@ -1,4 +1,4 @@
1
- import { toRaw as F, reactive as O, watch as q } from "vue";
1
+ import { toRaw as F, reactive as O, getCurrentScope as S, watch as q } from "vue";
2
2
  function c(i) {
3
3
  const t = F(i);
4
4
  if (t === null || typeof t != "object") return t;
@@ -61,15 +61,15 @@ function b(i) {
61
61
  function d(i) {
62
62
  return i && typeof i == "object" && typeof i.message == "string" ? i.message : null;
63
63
  }
64
- function k(i, t) {
64
+ function w(i, t) {
65
65
  return t.some((e) => e === i || i.startsWith(`${e}.`));
66
66
  }
67
- function R(i, t, e = "") {
68
- if (e && k(e, t)) return [];
67
+ function k(i, t, e = "") {
68
+ if (e && w(e, t)) return [];
69
69
  if (p(i)) {
70
70
  const s = [];
71
71
  for (const r of Object.keys(i))
72
- s.push(...R(i[r], t, e ? `${e}.${r}` : r));
72
+ s.push(...k(i[r], t, e ? `${e}.${r}` : r));
73
73
  return s;
74
74
  }
75
75
  return Array.isArray(i) || !e ? [] : [e];
@@ -77,7 +77,7 @@ function R(i, t, e = "") {
77
77
  function v(i, t) {
78
78
  return t && i && typeof i == "object" ? f(i, t) : i;
79
79
  }
80
- class w extends Error {
80
+ class R extends Error {
81
81
  constructor(t, e, s) {
82
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 : {};
83
83
  }
@@ -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 S(i) {
117
+ async function T(i) {
118
118
  if (i.status === 204) return null;
119
119
  const t = await i.text();
120
120
  if (!t) return null;
@@ -124,11 +124,23 @@ async function S(i) {
124
124
  return t;
125
125
  }
126
126
  }
127
- class T {
127
+ class U {
128
128
  constructor(t, e = {}, s = null) {
129
- this._snapshot = null, this._snapshotLocked = !1, this._ignore = [], this._lock = [], this._triggerFields = null, this._sendFields = null, this._debounce = 0, this._debounceTimer = null, this._lastSent = null, this._fillAbort = null, this._transformResponse = null, this._transformRequest = null, this._apix = t, this._options = e, this._source = s, this._transformResponse = e.transformResponse ?? null, this._transformRequest = e.transformRequest ?? null;
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
- this._state = O({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r), this._ignore = e.ignore ?? [], this._lock = e.lock ?? [], this._setupWatch(e.watch, r);
131
+ if (this._state = O({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r), this._ignore = e.ignore ?? [], this._lock = e.lock ?? [], e.watch) {
132
+ const o = e.watch;
133
+ if (!this._source)
134
+ console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");
135
+ else if (e.immediate === !1)
136
+ this._setupWatch(o, r);
137
+ else {
138
+ const n = S();
139
+ this._deferredWatchSetup = () => {
140
+ n ? n.run(() => this._setupWatch(o, r)) : this._setupWatch(o, r);
141
+ };
142
+ }
143
+ }
132
144
  }
133
145
  // --- reactive state ---------------------------------------------------------
134
146
  get data() {
@@ -298,7 +310,7 @@ class T {
298
310
  this._state.data = s, this._snapshotLocked || (this._snapshot = r, this._snapshotLocked = !0), this._syncLastSent();
299
311
  }
300
312
  _applyError(t) {
301
- t instanceof w && (this._state.message = d(t.body) ?? t.message, t.isValidationError && (this._state.errors = b(t.errors)));
313
+ t instanceof R && (this._state.message = d(t.body) ?? t.message, t.isValidationError && (this._state.errors = b(t.errors)));
302
314
  }
303
315
  async _submit(t, e, s = {}) {
304
316
  var n;
@@ -324,17 +336,20 @@ class T {
324
336
  this._state.processing = !1;
325
337
  }
326
338
  }
327
- /** @internal Configures auto-refetch-on-change, once, at construction time. */
339
+ /**
340
+ * @internal Computes the trigger/send field sets and registers the Vue
341
+ * watch(). Called either synchronously from the constructor (no automatic
342
+ * initial fill to wait for) or once that fill has settled (see
343
+ * `_deferredWatchSetup`) — `initial` is always `default()`'s shape, since
344
+ * that's what determines which fields exist, regardless of timing.
345
+ */
328
346
  _setupWatch(t, e) {
329
- if (!t) return;
330
- if (!this._source) {
331
- console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");
332
- return;
333
- }
334
347
  const s = t === !0 ? {} : t, r = s.fields;
335
- this._sendFields = R(e ?? {}, this._ignore), this._triggerFields = r ?? this._sendFields, this._debounce = s.debounce ?? 0, this._syncLastSent();
336
- const o = this._triggerFields.map((a) => () => f(this._state.data, a)), n = r ? s.deep ?? !1 : !0;
337
- q(o, () => this._onWatchTrigger(), { deep: n });
348
+ this._sendFields = k(e ?? {}, this._ignore);
349
+ const o = r ?? this._sendFields;
350
+ this._triggerFields = o, this._debounce = s.debounce ?? 0, this._syncLastSent();
351
+ const n = o.map((h) => () => f(this._state.data, h)), a = r ? s.deep ?? !1 : !0;
352
+ q(n, () => this._onWatchTrigger(), { deep: a });
338
353
  }
339
354
  _onWatchTrigger() {
340
355
  this._payloadJson() !== this._lastSent && (this._debounceTimer && clearTimeout(this._debounceTimer), this._debounce > 0 ? this._debounceTimer = setTimeout(() => this._sendWatchRequest(), this._debounce) : this._sendWatchRequest());
@@ -345,7 +360,7 @@ class T {
345
360
  }
346
361
  /** Build the fill() extra for a watch/refresh request from the current state. */
347
362
  _buildFillExtra(t = {}) {
348
- const e = t.lock ? [...this._lock, ...t.lock] : this._lock, s = t.ignore ? (this._sendFields ?? []).filter((o) => !k(o, t.ignore)) : this._sendFields ?? [];
363
+ const e = t.lock ? [...this._lock, ...t.lock] : this._lock, s = t.ignore ? (this._sendFields ?? []).filter((o) => !w(o, t.ignore)) : this._sendFields ?? [];
349
364
  let r = g(this._state.data, s);
350
365
  return this._transformRequest && (r = this._transformRequest(r) ?? r), this._source.method === "get" ? { params: r, preserve: e } : { data: r, preserve: e };
351
366
  }
@@ -358,7 +373,7 @@ class T {
358
373
  }
359
374
  }
360
375
  function j(i, t = {}, e = null) {
361
- const s = new T(i, t, e), r = new Proxy(s, {
376
+ const s = new U(i, t, e), r = new Proxy(s, {
362
377
  get(o, n) {
363
378
  if (typeof n == "symbol" || n in o) return Reflect.get(o, n);
364
379
  const a = o._state.data;
@@ -375,10 +390,13 @@ function j(i, t = {}, e = null) {
375
390
  return !!a && typeof a == "object" && n in a;
376
391
  }
377
392
  });
378
- return s._proxy = r, e && t.immediate !== !1 && r.reload().catch(() => {
393
+ return s._proxy = r, e && t.immediate !== !1 && r.reload().finally(() => {
394
+ var o;
395
+ (o = s._deferredWatchSetup) == null || o.call(s), s._deferredWatchSetup = null;
396
+ }).catch(() => {
379
397
  }), r;
380
398
  }
381
- class U {
399
+ class W {
382
400
  constructor(t = {}) {
383
401
  this.baseUrl = "", this.headers = {}, this.processingHooks = [], this.errorHooks = [], this.bodyTransformer = null, this.active = 0, t.baseUrl && this.setBaseUrl(t.baseUrl), t.headers && this.setHeader(t.headers), t.credentials && (this.credentials = t.credentials);
384
402
  }
@@ -440,8 +458,8 @@ class U {
440
458
  this.trackStart();
441
459
  try {
442
460
  const h = await fetch(r, n);
443
- let l = await S(h);
444
- if (this.bodyTransformer && (l = this.bodyTransformer(l, a) ?? l), !h.ok) throw new w(h.status, l, h);
461
+ let l = await T(h);
462
+ if (this.bodyTransformer && (l = this.bodyTransformer(l, a) ?? l), !h.ok) throw new R(h.status, l, h);
445
463
  return l;
446
464
  } catch (h) {
447
465
  throw E(h) ? h : this.emitError(h, a);
@@ -509,13 +527,13 @@ class U {
509
527
  }
510
528
  }
511
529
  function L(i = {}) {
512
- return new U(i);
530
+ return new W(i);
513
531
  }
514
532
  const P = L();
515
533
  export {
516
- U as Apix,
517
- w as ApixError,
518
- T as ApixFormModel,
534
+ W as Apix,
535
+ R as ApixError,
536
+ U as ApixFormModel,
519
537
  P as apix,
520
538
  L as createApix,
521
539
  P as default
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diephp/vue-apix",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Tiny form/model/api toolkit for Vue 3 — fetch-based, Laravel-friendly, zero dependencies",
5
5
  "type": "module",
6
6
  "license": "MIT",