@trimjs/web-app 0.1.4 → 0.1.6

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.
@@ -1,3 +1,3 @@
1
- (function(h,u){typeof exports=="object"&&typeof module!="undefined"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(h=typeof globalThis!="undefined"?globalThis:h||self,u(h.TrimApp={}))})(this,function(h){"use strict";var at=Object.defineProperty,lt=Object.defineProperties;var ut=Object.getOwnPropertyDescriptors;var Te=Object.getOwnPropertySymbols;var ft=Object.prototype.hasOwnProperty,pt=Object.prototype.propertyIsEnumerable;var ae=(h,u,a)=>u in h?at(h,u,{enumerable:!0,configurable:!0,writable:!0,value:a}):h[u]=a,W=(h,u)=>{for(var a in u||(u={}))ft.call(u,a)&&ae(h,a,u[a]);if(Te)for(var a of Te(u))pt.call(u,a)&&ae(h,a,u[a]);return h},H=(h,u)=>lt(h,ut(u));var M=(h,u,a)=>ae(h,typeof u!="symbol"?u+"":u,a);var v=(h,u,a)=>new Promise((X,k)=>{var K=C=>{try{U(a.next(C))}catch(B){k(B)}},Z=C=>{try{U(a.throw(C))}catch(B){k(B)}},U=C=>C.done?X(C.value):Promise.resolve(C.value).then(K,Z);U((a=a.apply(h,u)).next())});class u{constructor(){M(this,"debug",!1)}setDebug(e){this.debug=e}isDebug(){return this.debug}log(){if(this.debug){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];console.log("[Trim App]",...t)}}warn(){if(this.debug){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];console.warn("[Trim App]",...t)}}error(){if(this.debug){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];console.error("[Trim App]",...t)}}info(){if(this.debug){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];console.info("[Trim App]",...t)}}}const a=new u;function X(n){const e=/FNOS\/([\d.]+)|FNAppType\/(\w+)|FNAppVer\/([\d.]+)/g,t={};let r;for(;(r=e.exec(n))!==null;)r[1]&&(t.fnOSVersion=r[1]),r[2]&&(t.fnAppType=r[2]),r[3]&&(t.fnAppVersion=r[3]);return t}const k=()=>X(navigator.userAgent).fnAppVersion;let K=!1;window.addEventListener("flutterInAppWebViewPlatformReady",()=>{K=!0});const Z=()=>new Promise(n=>{var e;K||(e=window.flutter_inappwebview)!=null&&e._platformReady?(a.log("flutter_inappwebview is ready"),n(window.flutter_inappwebview)):window.addEventListener("flutterInAppWebViewPlatformReady",()=>{a.log("flutter_inappwebview is ready"),n(window.flutter_inappwebview)})}),U=(n,e,t)=>v(this,null,function*(){a.log(`callHandler: ${e}, params: ${t}`);const r=yield n.callHandler(e,t);if(r)try{const o=JSON.parse(r);a.log(`messageData: ${JSON.stringify(o)}`);const i=JSON.parse(o.result);return a.log(`appMessage: ${JSON.stringify(i)}`),i}catch(o){return a.error(`error: ${o}`),null}return null}),C=new Map;function B(){window.fnAppMessage=n=>{a.log("app-message",n);const e=JSON.parse(n),t=C.get(e.reqId);t&&(t(e),C.delete(e.reqId))}}k()&&B();var _=(n=>(n.Call="call",n.Reply="reply",n.Syn="syn",n.SynAck="synAck",n.Ack="ack",n))(_||{}),N=(n=>(n.Fulfilled="fulfilled",n.Rejected="rejected",n))(N||{}),ee=(n=>(n.ConnectionDestroyed="ConnectionDestroyed",n.ConnectionTimeout="ConnectionTimeout",n.NoIframeSrc="NoIframeSrc",n))(ee||{}),le=(n=>(n.DataCloneError="DataCloneError",n))(le||{}),j=(n=>(n.Message="message",n))(j||{});const _e=(n,e)=>{const t=[];let r=!1;return{destroy(o){r||(r=!0,e(`${n}: Destroying connection`),t.forEach(i=>{i(o)}))},onDestroy(o){r?o():t.push(o)}}},Fe=n=>(...e)=>{n&&console.log("[Penpal]",...e)},ue=({name:n,message:e,stack:t})=>({name:n,message:e,stack:t}),Oe=n=>{const e=new Error;return Object.keys(n).forEach(t=>e[t]=n[t]),e},Re=(n,e,t)=>{const{localName:r,local:o,remote:i,originForSending:s,originForReceiving:c}=n;let d=!1;const S=E=>{if(E.source!==i||E.data.penpal!==_.Call)return;if(c!=="*"&&E.origin!==c){t(`${r} received message from origin ${E.origin} which did not match expected origin ${c}`);return}const $=E.data,{methodName:y,args:g,id:b}=$;t(`${r}: Received ${y}() call`);const l=m=>P=>{if(t(`${r}: Sending ${y}() reply`),d){t(`${r}: Unable to send ${y}() reply due to destroyed connection`);return}const T={penpal:_.Reply,id:b,resolution:m,returnValue:P};m===N.Rejected&&P instanceof Error&&(T.returnValue=ue(P),T.returnValueIsError=!0);try{i.postMessage(T,s)}catch(O){if(O.name===le.DataCloneError){const R={penpal:_.Reply,id:b,resolution:N.Rejected,returnValue:ue(O),returnValueIsError:!0};i.postMessage(R,s)}throw O}};new Promise(m=>m(e[y].apply(e,g))).then(l(N.Fulfilled),l(N.Rejected))};return o.addEventListener(j.Message,S),()=>{d=!0,o.removeEventListener(j.Message,S)}};let xe=0;const De=()=>++xe,fe=".",pe=n=>n?n.split(fe):[],Ie=n=>n.join(fe),je=(n,e)=>{const t=pe(e||"");return t.push(n),Ie(t)},Ve=(n,e,t)=>{const r=pe(e);return r.reduce((o,i,s)=>(typeof o[i]=="undefined"&&(o[i]={}),s===r.length-1&&(o[i]=t),o[i]),n),n},de=(n,e)=>{const t={};return Object.keys(n).forEach(r=>{const o=n[r],i=je(r,e);typeof o=="object"&&Object.assign(t,de(o,i)),typeof o=="function"&&(t[i]=o)}),t},We=n=>{const e={};for(const t in n)Ve(e,t,n[t]);return e},qe=(n,e,t,r,o)=>{const{localName:i,local:s,remote:c,originForSending:d,originForReceiving:S}=e;let E=!1;o(`${i}: Connecting call sender`);const $=g=>(...b)=>{o(`${i}: Sending ${g}() call`);let l;try{c.closed&&(l=!0)}catch(m){l=!0}if(l&&r(),E){const m=new Error(`Unable to send ${g}() call due to destroyed connection`);throw m.code=ee.ConnectionDestroyed,m}return new Promise((m,P)=>{const T=De(),O=x=>{if(x.source!==c||x.data.penpal!==_.Reply||x.data.id!==T)return;if(S!=="*"&&x.origin!==S){o(`${i} received message from origin ${x.origin} which did not match expected origin ${S}`);return}const Y=x.data;o(`${i}: Received ${g}() reply`),s.removeEventListener(j.Message,O);let z=Y.returnValue;Y.returnValueIsError&&(z=Oe(z)),(Y.resolution===N.Fulfilled?m:P)(z)};s.addEventListener(j.Message,O);const R={penpal:_.Call,id:T,methodName:g,args:b};c.postMessage(R,d)})},y=t.reduce((g,b)=>(g[b]=$(b),g),{});return Object.assign(n,We(y)),()=>{E=!0}},Ne=(n,e)=>{let t;return n!==void 0&&(t=window.setTimeout(()=>{const r=new Error(`Connection timed out after ${n}ms`);r.code=ee.ConnectionTimeout,e(r)},n)),()=>{clearTimeout(t)}},Le={name:"@fn/micro-app-postmate",version:"0.1.2",type:"module",main:"src/index.ts",scripts:{dev:"vite",build:"tsc -b && vite build",lint:"eslint ."},files:["src","dist"],peerDependencies:{"@fn/micro-app-event":"^0.0.1",rxjs:"^7.8.0"},devDependencies:{"@eslint/js":"^9.13.0","@fn/micro-app-event":"workspace:*",eslint:"^9.13.0",globals:"^15.11.0",typescript:"~5.6.2","typescript-eslint":"^8.11.0",rxjs:"^7.8.0",vite:"^5.4.10"},publishConfig:{registry:"http://verdaccio.teiron-inc.cn:4873"}},He=(n,e,t,r,o)=>{const{destroy:i,onDestroy:s}=r;return c=>{if(!(n instanceof RegExp?n.test(c.origin):n==="*"||n===c.origin)){o(`Child: Handshake - Received SYN-ACK from origin ${c.origin} which did not match expected origin ${n}`);return}o("Child: Handshake - Received SYN-ACK, responding with ACK");const S=c.origin==="null"?"*":c.origin,E={penpal:_.Ack,methodNames:Object.keys(e),config:t};window.parent.postMessage(E,S);const $={localName:"Child",local:window,remote:window.parent,originForSending:S,originForReceiving:c.origin},y=Re($,e,o);s(y);const g={},b=qe(g,$,c.data.methodNames,i,o);return s(b),g}};function he(n,e){console==null||console.warn(`[fnApp warn]: ${n}`,e)}function ge(n,e){console==null||console.error(`[fnApp error]: ${n}`,e)}const L="_fn_all_event",ye="事件订阅数量为空",J=window.__POWERED_BY_FNAPP__?window.__FNAPP.inject.appEventObjMap:new Map;class me{constructor(e,t){M(this,"id");M(this,"appName");M(this,"eventObj");M(this,"getEventCallBackLength",e=>{var t;return((t=this.eventObj[e])==null?void 0:t.length)||0});this.id=e,this.appName=t,this.$clear(),J.get(this.id)||J.set(this.id,{}),this.eventObj=J.get(this.id)}$on(e,t){const r=this.eventObj[e];return r?(r.includes(t)||r.push(t),this):(this.eventObj[e]=[t],this)}$onAll(e){return this.$on(L,e)}$once(e,t){t.$__once=!0,this.$on(e,t)}$off(e,t){const r=this.eventObj[e];if(!e||!r||!r.length)return he(`${e} ${ye}`),this;let o,i=r.length;for(;i--;)if(o=r[i],o===t){r.splice(i,1);break}return this}$offAll(e){return this.$off(L,e)}$emit(e,...t){return e=`${this.appName}/${e}`,this.$pureEmit(e,...t)}$pureEmit(e,...t){let r=0,o=0;return J.forEach(i=>{if(i[e])for(let s=i[e].length-1;s>=0;s--){r++;const c=i[e][s];c.$__once&&i[e].splice(s,1);try{c(...t)}catch(d){ge(d)}}if(i[L])for(let s=i[L].length-1;s>=0;s--){r++;const c=i[L][s];c.$__once&&i[L].splice(s,1);try{c(...t)}catch(d){ge(d)}}}),(!e||r===0&&o===0)&&he(`${e} ${ye}`),this}$clear(){const e=J.get(this.id)||{};return Object.keys(e).forEach(r=>delete e[r]),this}}var te=function(n,e){return te=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o])},te(n,e)};function be(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");te(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function we(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function ne(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(c){s={error:c}}finally{try{o&&!o.done&&(t=r.return)&&t.call(r)}finally{if(s)throw s.error}}return i}function re(n,e,t){if(t||arguments.length===2)for(var r=0,o=e.length,i;r<o;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return n.concat(i||Array.prototype.slice.call(e))}typeof SuppressedError=="function"&&SuppressedError;function F(n){return typeof n=="function"}function ke(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var ie=ke(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
2
- `+t.map(function(r,o){return o+1+") "+r.toString()}).join(`
3
- `):"",this.name="UnsubscriptionError",this.errors=t}});function ve(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var oe=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var c=we(s),d=c.next();!d.done;d=c.next()){var S=d.value;S.remove(this)}}catch(l){e={error:l}}finally{try{d&&!d.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else s.remove(this);var E=this.initialTeardown;if(F(E))try{E()}catch(l){i=l instanceof ie?l.errors:[l]}var $=this._finalizers;if($){this._finalizers=null;try{for(var y=we($),g=y.next();!g.done;g=y.next()){var b=g.value;try{Ae(b)}catch(l){i=i!=null?i:[],l instanceof ie?i=re(re([],ne(i)),ne(l.errors)):i.push(l)}}}catch(l){r={error:l}}finally{try{g&&!g.done&&(o=y.return)&&o.call(y)}finally{if(r)throw r.error}}}if(i)throw new ie(i)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Ae(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&ve(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&ve(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}();oe.EMPTY;function Ee(n){return n instanceof oe||n&&"closed"in n&&F(n.remove)&&F(n.add)&&F(n.unsubscribe)}function Ae(n){F(n)?n():n.unsubscribe()}var Se={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Ue={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,re([n,e],ne(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Be(n){Ue.setTimeout(function(){throw n})}function $e(){}function Je(n){n()}var Pe=function(n){be(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,Ee(t)&&t.add(r)):r.destination=Qe,r}return e.create=function(t,r,o){return new ce(t,r,o)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(oe),Ye=Function.prototype.bind;function se(n,e){return Ye.call(n,e)}var ze=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){Q(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){Q(r)}else Q(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Q(t)}},n}(),ce=function(n){be(e,n);function e(t,r,o){var i=n.call(this)||this,s;if(F(t)||!t)s={next:t!=null?t:void 0,error:r!=null?r:void 0,complete:o!=null?o:void 0};else{var c;i&&Se.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return i.unsubscribe()},s={next:t.next&&se(t.next,c),error:t.error&&se(t.error,c),complete:t.complete&&se(t.complete,c)}):s=t}return i.destination=new ze(s),i}return e}(Pe);function Q(n){Be(n)}function Ke(n){throw n}var Qe={closed:!0,next:$e,error:Ke,complete:$e},Ge=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Xe(n){return n}function Ze(n){return n.length===0?Xe:n.length===1?n[0]:function(t){return n.reduce(function(r,o){return o(r)},t)}}var et=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var o=this,i=nt(e)?e:new ce(e,t,r);return Je(function(){var s=o,c=s.operator,d=s.source;i.add(c?c.call(i,d):d?o._subscribe(i):o._trySubscribe(i))}),i},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=Me(t),new t(function(o,i){var s=new ce({next:function(c){try{e(c)}catch(d){i(d),s.unsubscribe()}},error:i,complete:o});r.subscribe(s)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[Ge]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ze(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=Me(e),new e(function(r,o){var i;t.subscribe(function(s){return i=s},function(s){return o(s)},function(){return r(i)})})},n.create=function(e){return new n(e)},n}();function Me(n){var e;return(e=n!=null?n:Se.Promise)!==null&&e!==void 0?e:Promise}function tt(n){return n&&F(n.next)&&F(n.error)&&F(n.complete)}function nt(n){return n&&n instanceof Pe||tt(n)&&Ee(n)}const rt=()=>{try{clearTimeout(void 0)}catch(n){return!1}return!0},it=(n={})=>{const{parentOrigin:e="*",timeout:t,debug:r=!1,config:o={}}=n,i=Fe(r),s=_e("App",i),{destroy:c,onDestroy:d}=s,S=()=>{i("Child: Handshake - Sending SYN");const $={penpal:_.Syn},y=e instanceof RegExp?"*":e;window.parent.postMessage($,y)};return{promise:new Promise(($,y)=>{const g=Ne(t,c),b=l=>{if(rt()&&!(l.source!==parent||!l.data)&&l.data.penpal===_.SynAck){const m=l.data,P=new me(m.id,m.appName),T=new me(m.id+"/api",m.appName),O=m.id,R={},x=f=>"api/"+f,Y={$emit:(f,...p)=>{P.getEventCallBackLength(f)>0?P.$pureEmit(f,...p):R==null||R.$off(f,()=>{},!0)},onQueryResult:f=>{T.$pureEmit(x(f.reqid),f)},onOsNotify:f=>{}},z=f=>function(w){const V=x(f);T.$on(V,function I(A){w.next(A),A.reqid&&A.result==="succ"&&(w.complete(),T.$off(V,I))})},st=de(Y),q=He(e,st,H(W({},o),{postmateVersion:Le.version}),s,i)(l),D={},G=q.bus;if(G){const f=(p,w,V)=>{V?(w.$__once=!0,P.$once(p,w)):P.$on(p,w),D[p]?D[p].push(w):(D[p]=[w],G.$on(p,O))};Object.assign(R,G,{$on:f,$off:(p,w,V)=>{var I;if(D[p]){const A=D[p].indexOf(w);A>-1&&(D[p].splice(A,1),P.$off(p,w))}V&&delete D[p],(I=D[p])!=null&&I.length||(G.$off(p,O),delete D[p])},$once:(p,w)=>{f(p,w,!0)}})}const ct=H(W({},q),{bus:R,query:(f,p)=>v(this,null,function*(){const w=(f==null?void 0:f.reqid)||(yield q.genReqId());return new Promise((V,I)=>{q.query(H(W({},f),{reqid:w}),p).then(A=>{(A==null?void 0:A.result)==="succ"?V(A):I(A)})})}),createObservableQuery:(w,...V)=>v(this,[w,...V],function*(f,p={}){const I=(f==null?void 0:f.reqid)||(yield q.genReqId()),A=new et(z(I));return q.query(H(W({},f),{reqid:I}),H(W({},p),{observable:!0})),A})});q&&(window.removeEventListener(j.Message,b),g(),$({methods:ct,config:l.data.config}))}};window.addEventListener(j.Message,b),S(),d(l=>{window.removeEventListener(j.Message,b),l&&y(l)})}),destroy(){c()}}},ot=n=>it({debug:n==null?void 0:n.debug}).promise;class Ce{constructor(){M(this,"options");M(this,"flutterInAppWebView",null);M(this,"osConnector",null);M(this,"initPromise");M(this,"isWeb",!0);let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.options=e,e.debug&&(a.setDebug(!0),a.log("Trim App initialized with debug mode")),a.log("Options:",e),this.initPromise=this.init()}init(){return v(this,null,function*(){return a.log("Starting initialization..."),new Promise(e=>{k()?(this.isWeb=!1,a.log("Initializing mobile platform..."),Z().then(t=>{this.flutterInAppWebView=t,a.log("Mobile platform initialized"),e()})):(this.isWeb=!0,a.log("Initializing web platform..."),ot().then(t=>{this.osConnector=t,a.log("Web platform initialized"),e()}))})})}callAppMethod(e,t){return v(this,null,function*(){return this.flutterInAppWebView?U(this.flutterInAppWebView,e,t):null})}ready(){return v(this,null,function*(){return this.initPromise})}getOptions(){return this.options}setOptions(e){this.options=W(W({},this.options),e),e.debug!==void 0&&a.setDebug(e.debug),a.log("Options updated:",this.options)}getPlatformConfig(){return v(this,null,function*(){var e;if(yield this.initPromise,this.isWeb){const t=yield(e=this.osConnector)==null?void 0:e.methods.getPlatformConfig();if(!t)throw new Error("Failed to get platform config");return t}else{const t=yield this.callAppMethod("getAppMessage");if(!t)throw new Error("Failed to get platform config");return{theme:t.nightMode,language:t.language,appVersion:t.appVersion,systemVersion:t.systemVersion,format:{date:t.dateFormat,time:t.timeFormat}}}})}setTitle(e){return v(this,null,function*(){var t;return yield this.initPromise,a.log("Setting title:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.setTitle(e):this.callAppMethod("updateTitle",e)})}setExitPageTips(e){return v(this,null,function*(){var t;return yield this.initPromise,this.isWeb?(t=this.osConnector)==null?void 0:t.methods.setExitPageTips(e):this.callAppMethod("setExitPageTips",e?JSON.stringify(e):"")})}openFile(e){return v(this,null,function*(){var t;return yield this.initPromise,a.log("Opening file:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.openFile(e):this.callAppMethod("openFile",e)})}openFileManager(e){return v(this,null,function*(){var t;return yield this.initPromise,a.log("Opening file manager:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.openFileManagerApp(e):this.callAppMethod("openFileManager",e)})}close(){return v(this,null,function*(){var e;return yield this.initPromise,this.isWeb?(e=this.osConnector)==null?void 0:e.methods.close():this.callAppMethod("exitPage")})}query(e,t){return v(this,null,function*(){var r;if(yield this.initPromise,this.isWeb){const o=yield(r=this.osConnector)==null?void 0:r.methods.query(e,t);if(!o)throw new Error("Failed to query");return o}else throw new Error("query is not supported on mobile platform")})}pickFile(e){return v(this,null,function*(){var t;return yield this.initPromise,this.isWeb?(t=this.osConnector)==null?void 0:t.methods.pickFile(e):this.callAppMethod("openFolder",JSON.stringify(e))})}}h.TrimApp=Ce,h.default=Ce,Object.defineProperties(h,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
1
+ (function(h,u){typeof exports=="object"&&typeof module!="undefined"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(h=typeof globalThis!="undefined"?globalThis:h||self,u(h.TrimApp={}))})(this,(function(h){"use strict";var st=Object.defineProperty,ct=Object.defineProperties;var at=Object.getOwnPropertyDescriptors;var Me=Object.getOwnPropertySymbols;var lt=Object.prototype.hasOwnProperty,ut=Object.prototype.propertyIsEnumerable;var ce=(h,u,c)=>u in h?st(h,u,{enumerable:!0,configurable:!0,writable:!0,value:c}):h[u]=c,j=(h,u)=>{for(var c in u||(u={}))lt.call(u,c)&&ce(h,c,u[c]);if(Me)for(var c of Me(u))ut.call(u,c)&&ce(h,c,u[c]);return h},H=(h,u)=>ct(h,at(u));var M=(h,u,c)=>ce(h,typeof u!="symbol"?u+"":u,c);var v=(h,u,c)=>new Promise((X,k)=>{var K=O=>{try{U(c.next(O))}catch(B){k(B)}},Z=O=>{try{U(c.throw(O))}catch(B){k(B)}},U=O=>O.done?X(O.value):Promise.resolve(O.value).then(K,Z);U((c=c.apply(h,u)).next())});class u{constructor(){M(this,"debug",!1)}setDebug(e){this.debug=e}isDebug(){return this.debug}log(){if(this.debug){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];console.log("[Trim App]",...t)}}warn(){if(this.debug){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];console.warn("[Trim App]",...t)}}error(){if(this.debug){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];console.error("[Trim App]",...t)}}info(){if(this.debug){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];console.info("[Trim App]",...t)}}}const c=new u;function X(r){const e=/FNOS\/([\d.]+)|FNAppType\/(\w+)|FNAppVer\/([\d.]+)/g,t={};let n;for(;(n=e.exec(r))!==null;)n[1]&&(t.fnOSVersion=n[1]),n[2]&&(t.fnAppType=n[2]),n[3]&&(t.fnAppVersion=n[3]);return t}const k=()=>X(navigator.userAgent).fnAppVersion;let K=!1;window.addEventListener("flutterInAppWebViewPlatformReady",()=>{K=!0});const Z=()=>new Promise(r=>{var e;K||(e=window.flutter_inappwebview)!=null&&e._platformReady?(c.log("flutter_inappwebview is ready"),r(window.flutter_inappwebview)):window.addEventListener("flutterInAppWebViewPlatformReady",()=>{c.log("flutter_inappwebview is ready"),r(window.flutter_inappwebview)})}),U=(r,e,t)=>v(null,null,function*(){c.log(`callHandler: ${e}, params: ${t}`);const n=yield r.callHandler(e,t);if(n)try{const o=JSON.parse(n);c.log(`messageData: ${JSON.stringify(o)}`);const i=JSON.parse(o.result);return c.log(`appMessage: ${JSON.stringify(i)}`),i}catch(o){return c.error(`error: ${o}`),null}return null}),O=new Map;function B(){window.fnAppMessage=r=>{c.log("app-message",r);const e=JSON.parse(r),t=O.get(e.reqId);t&&(t(e),O.delete(e.reqId))}}k()&&B();var _=(r=>(r.Call="call",r.Reply="reply",r.Syn="syn",r.SynAck="synAck",r.Ack="ack",r))(_||{}),D=(r=>(r.Fulfilled="fulfilled",r.Rejected="rejected",r))(D||{}),ee=(r=>(r.ConnectionDestroyed="ConnectionDestroyed",r.ConnectionTimeout="ConnectionTimeout",r.NoIframeSrc="NoIframeSrc",r))(ee||{}),ae=(r=>(r.DataCloneError="DataCloneError",r))(ae||{}),V=(r=>(r.Message="message",r))(V||{});const Oe=(r,e)=>{const t=[];let n=!1;return{destroy(o){n||(n=!0,e(`${r}: Destroying connection`),t.forEach(i=>{i(o)}))},onDestroy(o){n?o():t.push(o)}}},Te=r=>(...e)=>{r&&console.log("[Penpal]",...e)},le=({name:r,message:e,stack:t})=>({name:r,message:e,stack:t}),_e=r=>{const e=new Error;return Object.keys(r).forEach(t=>e[t]=r[t]),e},Ce=(r,e,t)=>{const{localName:n,local:o,remote:i,originForSending:s,originForReceiving:a}=r;let d=!1;const S=A=>{if(A.source!==i||A.data.penpal!==_.Call)return;if(a!=="*"&&A.origin!==a){t(`${n} received message from origin ${A.origin} which did not match expected origin ${a}`);return}const $=A.data,{methodName:y,args:g,id:b}=$;t(`${n}: Received ${y}() call`);const l=m=>P=>{if(t(`${n}: Sending ${y}() reply`),d){t(`${n}: Unable to send ${y}() reply due to destroyed connection`);return}const T={penpal:_.Reply,id:b,resolution:m,returnValue:P};m===D.Rejected&&P instanceof Error&&(T.returnValue=le(P),T.returnValueIsError=!0);try{i.postMessage(T,s)}catch(F){if(F.name===ae.DataCloneError){const R={penpal:_.Reply,id:b,resolution:D.Rejected,returnValue:le(F),returnValueIsError:!0};i.postMessage(R,s)}throw F}};new Promise(m=>m(e[y].apply(e,g))).then(l(D.Fulfilled),l(D.Rejected))};return o.addEventListener(V.Message,S),()=>{d=!0,o.removeEventListener(V.Message,S)}};let Fe=0;const Re=()=>++Fe,ue=".",fe=r=>r?r.split(ue):[],xe=r=>r.join(ue),Ie=(r,e)=>{const t=fe(e||"");return t.push(r),xe(t)},Ne=(r,e,t)=>{const n=fe(e);return n.reduce((o,i,s)=>(typeof o[i]=="undefined"&&(o[i]={}),s===n.length-1&&(o[i]=t),o[i]),r),r},pe=(r,e)=>{const t={};return Object.keys(r).forEach(n=>{const o=r[n],i=Ie(n,e);typeof o=="object"&&Object.assign(t,pe(o,i)),typeof o=="function"&&(t[i]=o)}),t},Ve=r=>{const e={};for(const t in r)Ne(e,t,r[t]);return e},We=(r,e,t,n,o)=>{const{localName:i,local:s,remote:a,originForSending:d,originForReceiving:S}=e;let A=!1;o(`${i}: Connecting call sender`);const $=g=>(...b)=>{o(`${i}: Sending ${g}() call`);let l;try{a.closed&&(l=!0)}catch(m){l=!0}if(l&&n(),A){const m=new Error(`Unable to send ${g}() call due to destroyed connection`);throw m.code=ee.ConnectionDestroyed,m}return new Promise((m,P)=>{const T=Re(),F=x=>{if(x.source!==a||x.data.penpal!==_.Reply||x.data.id!==T)return;if(S!=="*"&&x.origin!==S){o(`${i} received message from origin ${x.origin} which did not match expected origin ${S}`);return}const Y=x.data;o(`${i}: Received ${g}() reply`),s.removeEventListener(V.Message,F);let z=Y.returnValue;Y.returnValueIsError&&(z=_e(z)),(Y.resolution===D.Fulfilled?m:P)(z)};s.addEventListener(V.Message,F);const R={penpal:_.Call,id:T,methodName:g,args:b};a.postMessage(R,d)})},y=t.reduce((g,b)=>(g[b]=$(b),g),{});return Object.assign(r,Ve(y)),()=>{A=!0}},je=(r,e)=>{let t;return r!==void 0&&(t=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${r}ms`);n.code=ee.ConnectionTimeout,e(n)},r)),()=>{clearTimeout(t)}},qe={version:"0.1.2"},De=(r,e,t,n,o)=>{const{destroy:i,onDestroy:s}=n;return a=>{if(!(r instanceof RegExp?r.test(a.origin):r==="*"||r===a.origin)){o(`Child: Handshake - Received SYN-ACK from origin ${a.origin} which did not match expected origin ${r}`);return}o("Child: Handshake - Received SYN-ACK, responding with ACK");const S=a.origin==="null"?"*":a.origin,A={penpal:_.Ack,methodNames:Object.keys(e),config:t};window.parent.postMessage(A,S);const $={localName:"Child",local:window,remote:window.parent,originForSending:S,originForReceiving:a.origin},y=Ce($,e,o);s(y);const g={},b=We(g,$,a.data.methodNames,i,o);return s(b),g}};function de(r,e){console==null||console.warn(`[fnApp warn]: ${r}`,e)}function he(r,e){console==null||console.error(`[fnApp error]: ${r}`,e)}const L="_fn_all_event",ge="事件订阅数量为空",J=window.__POWERED_BY_FNAPP__?window.__FNAPP.inject.appEventObjMap:new Map;class ye{constructor(e,t){M(this,"id");M(this,"appName");M(this,"eventObj");M(this,"getEventCallBackLength",e=>{var t;return((t=this.eventObj[e])==null?void 0:t.length)||0});this.id=e,this.appName=t,this.$clear(),J.get(this.id)||J.set(this.id,{}),this.eventObj=J.get(this.id)}$on(e,t){const n=this.eventObj[e];return n?(n.includes(t)||n.push(t),this):(this.eventObj[e]=[t],this)}$onAll(e){return this.$on(L,e)}$once(e,t){t.$__once=!0,this.$on(e,t)}$off(e,t){const n=this.eventObj[e];if(!e||!n||!n.length)return de(`${e} ${ge}`),this;let o,i=n.length;for(;i--;)if(o=n[i],o===t){n.splice(i,1);break}return this}$offAll(e){return this.$off(L,e)}$emit(e,...t){return e=`${this.appName}/${e}`,this.$pureEmit(e,...t)}$pureEmit(e,...t){let n=0,o=0;return J.forEach(i=>{if(i[e])for(let s=i[e].length-1;s>=0;s--){n++;const a=i[e][s];a.$__once&&i[e].splice(s,1);try{a(...t)}catch(d){he(d)}}if(i[L])for(let s=i[L].length-1;s>=0;s--){n++;const a=i[L][s];a.$__once&&i[L].splice(s,1);try{a(...t)}catch(d){he(d)}}}),(!e||n===0&&o===0)&&de(`${e} ${ge}`),this}$clear(){const e=J.get(this.id)||{};return Object.keys(e).forEach(n=>delete e[n]),this}}var te=function(r,e){return te=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])},te(r,e)};function me(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");te(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function be(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function re(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return i}function ne(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))}typeof SuppressedError=="function"&&SuppressedError;function C(r){return typeof r=="function"}function Le(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var ie=Le(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
2
+ `+t.map(function(n,o){return o+1+") "+n.toString()}).join(`
3
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function we(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var oe=(function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=be(s),d=a.next();!d.done;d=a.next()){var S=d.value;S.remove(this)}}catch(l){e={error:l}}finally{try{d&&!d.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else s.remove(this);var A=this.initialTeardown;if(C(A))try{A()}catch(l){i=l instanceof ie?l.errors:[l]}var $=this._finalizers;if($){this._finalizers=null;try{for(var y=be($),g=y.next();!g.done;g=y.next()){var b=g.value;try{Ae(b)}catch(l){i=i!=null?i:[],l instanceof ie?i=ne(ne([],re(i)),re(l.errors)):i.push(l)}}}catch(l){n={error:l}}finally{try{g&&!g.done&&(o=y.return)&&o.call(y)}finally{if(n)throw n.error}}}if(i)throw new ie(i)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Ae(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&we(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&we(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=(function(){var e=new r;return e.closed=!0,e})(),r})();oe.EMPTY;function ve(r){return r instanceof oe||r&&"closed"in r&&C(r.remove)&&C(r.add)&&C(r.unsubscribe)}function Ae(r){C(r)?r():r.unsubscribe()}var He={Promise:void 0},ke={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,ne([r,e],re(t)))},clearTimeout:function(r){return clearTimeout(r)},delegate:void 0};function Ue(r){ke.setTimeout(function(){throw r})}function Ee(){}function Be(r){r()}var Se=(function(r){me(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,ve(t)&&t.add(n)):n.destination=ze,n}return e.create=function(t,n,o){return new se(t,n,o)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(oe),Je=(function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){Q(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){Q(n)}else Q(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Q(t)}},r})(),se=(function(r){me(e,r);function e(t,n,o){var i=r.call(this)||this,s;return C(t)||!t?s={next:t!=null?t:void 0,error:n!=null?n:void 0,complete:o!=null?o:void 0}:s=t,i.destination=new Je(s),i}return e})(Se);function Q(r){Ue(r)}function Ye(r){throw r}var ze={closed:!0,next:Ee,error:Ye,complete:Ee},Ke=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Qe(r){return r}function Ge(r){return r.length===0?Qe:r.length===1?r[0]:function(t){return r.reduce(function(n,o){return o(n)},t)}}var Xe=(function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var o=this,i=et(e)?e:new se(e,t,n);return Be(function(){var s=o,a=s.operator,d=s.source;i.add(a?a.call(i,d):d?o._subscribe(i):o._trySubscribe(i))}),i},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=$e(t),new t(function(o,i){var s=new se({next:function(a){try{e(a)}catch(d){i(d),s.unsubscribe()}},error:i,complete:o});n.subscribe(s)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Ke]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ge(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=$e(e),new e(function(n,o){var i;t.subscribe(function(s){return i=s},function(s){return o(s)},function(){return n(i)})})},r.create=function(e){return new r(e)},r})();function $e(r){var e;return(e=r!=null?r:He.Promise)!==null&&e!==void 0?e:Promise}function Ze(r){return r&&C(r.next)&&C(r.error)&&C(r.complete)}function et(r){return r&&r instanceof Se||Ze(r)&&ve(r)}const tt=()=>{try{clearTimeout(void 0)}catch(r){return!1}return!0},rt=(r={})=>{const{parentOrigin:e="*",timeout:t,debug:n=!1,config:o={}}=r,i=Te(n),s=Oe("App",i),{destroy:a,onDestroy:d}=s,S=()=>{i("Child: Handshake - Sending SYN");const $={penpal:_.Syn},y=e instanceof RegExp?"*":e;window.parent.postMessage($,y)};return{promise:new Promise(($,y)=>{const g=je(t,a),b=l=>{if(tt()&&!(l.source!==parent||!l.data)&&l.data.penpal===_.SynAck){const m=l.data,P=new ye(m.id,m.appName),T=new ye(m.id+"/api",m.appName),F=m.id,R={},x=f=>"api/"+f,Y={$emit:(f,...p)=>{P.getEventCallBackLength(f)>0?P.$pureEmit(f,...p):R==null||R.$off(f,()=>{},!0)},onQueryResult:f=>{T.$pureEmit(x(f.reqid),f)},onOsNotify:f=>{}},z=f=>function(w){const W=x(f);T.$on(W,function N(E){w.next(E),E.reqid&&E.result==="succ"&&(w.complete(),T.$off(W,N))})},it=pe(Y),q=De(e,it,H(j({},o),{postmateVersion:qe.version}),s,i)(l),I={},G=q.bus;if(G){const f=(p,w,W)=>{W?(w.$__once=!0,P.$once(p,w)):P.$on(p,w),I[p]?I[p].push(w):(I[p]=[w],G.$on(p,F))};Object.assign(R,G,{$on:f,$off:(p,w,W)=>{var N;if(I[p]){const E=I[p].indexOf(w);E>-1&&(I[p].splice(E,1),P.$off(p,w))}W&&delete I[p],(N=I[p])!=null&&N.length||(G.$off(p,F),delete I[p])},$once:(p,w)=>{f(p,w,!0)}})}const ot=H(j({},q),{bus:R,query:(f,p)=>v(null,null,function*(){const w=(f==null?void 0:f.reqid)||(yield q.genReqId());return new Promise((W,N)=>{q.query(H(j({},f),{reqid:w}),p).then(E=>{(E==null?void 0:E.result)==="succ"?W(E):N(E)})})}),createObservableQuery:(w,...W)=>v(null,[w,...W],function*(f,p={}){const N=(f==null?void 0:f.reqid)||(yield q.genReqId()),E=new Xe(z(N));return q.query(H(j({},f),{reqid:N}),H(j({},p),{observable:!0})),E})});q&&(window.removeEventListener(V.Message,b),g(),$({methods:ot,config:l.data.config}))}};window.addEventListener(V.Message,b),S(),d(l=>{window.removeEventListener(V.Message,b),l&&y(l)})}),destroy(){a()}}},nt=r=>rt({debug:r==null?void 0:r.debug}).promise;class Pe{constructor(){M(this,"options");M(this,"flutterInAppWebView",null);M(this,"osConnector",null);M(this,"initPromise");M(this,"isWeb",!0);let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.options=e,e.debug&&(c.setDebug(!0),c.log("Trim App initialized with debug mode")),c.log("Options:",e),this.initPromise=this.init()}init(){return v(this,null,function*(){return c.log("Starting initialization..."),new Promise(e=>{k()?(this.isWeb=!1,c.log("Initializing mobile platform..."),Z().then(t=>{this.flutterInAppWebView=t,c.log("Mobile platform initialized"),e()})):(this.isWeb=!0,c.log("Initializing web platform..."),nt().then(t=>{this.osConnector=t,c.log("Web platform initialized"),e()}))})})}callAppMethod(e,t){return v(this,null,function*(){return this.flutterInAppWebView?U(this.flutterInAppWebView,e,t):null})}ready(){return v(this,null,function*(){return this.initPromise})}getOptions(){return this.options}setOptions(e){this.options=j(j({},this.options),e),e.debug!==void 0&&c.setDebug(e.debug),c.log("Options updated:",this.options)}getPlatformConfig(){return v(this,null,function*(){var e;if(yield this.initPromise,this.isWeb){const t=yield(e=this.osConnector)==null?void 0:e.methods.getPlatformConfig();if(!t)throw new Error("Failed to get platform config");return t}else{const t=yield this.callAppMethod("getAppMessage");if(!t)throw new Error("Failed to get platform config");return{theme:t.nightMode,language:t.language,appVersion:t.appVersion,systemVersion:t.systemVersion,format:{date:t.dateFormat,time:t.timeFormat}}}})}setTitle(e){return v(this,null,function*(){var t;return yield this.initPromise,c.log("Setting title:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.setTitle(e):this.callAppMethod("updateTitle",e)})}setExitPageTips(e){return v(this,null,function*(){var t;return yield this.initPromise,this.isWeb?(t=this.osConnector)==null?void 0:t.methods.setExitPageTips(e):this.callAppMethod("setExitPageTips",e?JSON.stringify(e):"")})}openFile(e){return v(this,null,function*(){var t;return yield this.initPromise,c.log("Opening file:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.openFile(e):this.callAppMethod("openFile",e)})}openFileManager(e){return v(this,null,function*(){var t;return yield this.initPromise,c.log("Opening file manager:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.openFileManagerApp(e):this.callAppMethod("openFileManager",e)})}close(){return v(this,null,function*(){var e;return yield this.initPromise,this.isWeb?(e=this.osConnector)==null?void 0:e.methods.close():this.callAppMethod("exitPage")})}query(e,t){return v(this,null,function*(){var n;if(yield this.initPromise,this.isWeb){const o=yield(n=this.osConnector)==null?void 0:n.methods.query(e,t);if(!o)throw new Error("Failed to query");return o}else throw new Error("query is not supported on mobile platform")})}pickFile(e){return v(this,null,function*(){var t;return yield this.initPromise,this.isWeb?(t=this.osConnector)==null?void 0:t.methods.pickFile(e):this.callAppMethod("openFolder",JSON.stringify(e))})}}h.TrimApp=Pe,h.default=Pe,Object.defineProperties(h,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
package/package.json CHANGED
@@ -1,11 +1,10 @@
1
1
  {
2
2
  "name": "@trimjs/web-app",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "web app sdk for nas",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.js",
8
- "types": "dist/index.d.ts",
9
8
  "scripts": {
10
9
  "dev": "vite",
11
10
  "build": "tsc -b && vite build",
@@ -13,7 +12,6 @@
13
12
  "typecheck": "tsc --noEmit"
14
13
  },
15
14
  "files": [
16
- "src",
17
15
  "dist"
18
16
  ],
19
17
  "devDependencies": {
@@ -24,9 +22,8 @@
24
22
  "@rollup/plugin-babel": "^6.1.0",
25
23
  "eslint": "^9.13.0",
26
24
  "globals": "^15.11.0",
27
- "rollup": "^4.24.0",
28
25
  "typescript": "~5.6.2",
29
26
  "typescript-eslint": "^8.11.0",
30
- "vite": "^5.4.10"
27
+ "vite": "^7.3.1"
31
28
  }
32
29
  }
package/src/index.ts DELETED
@@ -1,257 +0,0 @@
1
- import { logger } from "./logger";
2
- import type { PlatformConfig, TrimAppOptions } from "./types";
3
- import type { FlutterInAppWebView } from "./mobile/index";
4
- import { isFnApp } from "./utils/platform";
5
- import { callHandler, initMobile } from "./mobile/index";
6
- import { initWeb, OSConnection } from "./web/index";
7
- import { AppMessage } from "./mobile/types";
8
- import { type ResponseData } from "@fn/micro-app-postmate/src/child/os-type";
9
- import {
10
- type FilePickerParams,
11
- type QueryConfig,
12
- } from "@fn/micro-app-postmate/src/child/type";
13
-
14
- /**
15
- * @trim/app - NAS 应用 SDK
16
- * @description nas 应用 SDK
17
- */
18
-
19
- // 导出类型
20
- export type { TrimAppOptions } from "./types";
21
-
22
- /**
23
- * Trim App 实例类
24
- */
25
- export class TrimApp {
26
- private options: TrimAppOptions;
27
-
28
- private flutterInAppWebView: FlutterInAppWebView | null = null;
29
- private osConnector: OSConnection | null = null;
30
- private initPromise: Promise<void>;
31
-
32
- public isWeb: boolean = true;
33
-
34
- constructor(options: TrimAppOptions = {}) {
35
- this.options = options;
36
-
37
- // 设置 debug 模式
38
- if (options.debug) {
39
- logger.setDebug(true);
40
- logger.log("Trim App initialized with debug mode");
41
- }
42
-
43
- logger.log("Options:", options);
44
-
45
- // 保存初始化 Promise
46
- this.initPromise = this.init();
47
- }
48
-
49
- private async init(): Promise<void> {
50
- logger.log("Starting initialization...");
51
-
52
- return new Promise((resolve) => {
53
- if (isFnApp()) {
54
- this.isWeb = false;
55
- logger.log("Initializing mobile platform...");
56
- initMobile().then((flutterInAppWebView) => {
57
- this.flutterInAppWebView = flutterInAppWebView;
58
- logger.log("Mobile platform initialized");
59
- resolve();
60
- });
61
- } else {
62
- this.isWeb = true;
63
- logger.log("Initializing web platform...");
64
- initWeb().then((osConnector) => {
65
- this.osConnector = osConnector as OSConnection;
66
- logger.log("Web platform initialized");
67
- resolve();
68
- });
69
- }
70
- });
71
- }
72
-
73
- public async callAppMethod<T>(
74
- fn: string,
75
- params?: string
76
- ): Promise<T | null> {
77
- if (!this.flutterInAppWebView) {
78
- return null;
79
- }
80
- return callHandler<T>(this.flutterInAppWebView, fn, params);
81
- }
82
-
83
- /**
84
- * 等待初始化完成
85
- * @returns Promise
86
- */
87
- async ready(): Promise<void> {
88
- return this.initPromise;
89
- }
90
-
91
- /**
92
- * 获取配置
93
- */
94
- getOptions(): TrimAppOptions {
95
- return this.options;
96
- }
97
-
98
- /**
99
- * 更新配置
100
- */
101
- setOptions(options: Partial<TrimAppOptions>) {
102
- this.options = { ...this.options, ...options };
103
-
104
- // 更新 debug 模式
105
- if (options.debug !== undefined) {
106
- logger.setDebug(options.debug);
107
- }
108
-
109
- logger.log("Options updated:", this.options);
110
- }
111
-
112
- // 调用 app 的方法
113
-
114
- /**
115
- * 获取平台配置
116
- */
117
- async getPlatformConfig(): Promise<PlatformConfig> {
118
- // 等待初始化完成
119
- await this.initPromise;
120
-
121
- if (this.isWeb) {
122
- const config = await this.osConnector?.methods.getPlatformConfig();
123
- if (!config) {
124
- throw new Error("Failed to get platform config");
125
- }
126
- return config;
127
- } else {
128
- const config = await this.callAppMethod<AppMessage>("getAppMessage");
129
- if (!config) {
130
- throw new Error("Failed to get platform config");
131
- }
132
- return {
133
- theme: config.nightMode as "dark" | "light",
134
- language: config.language,
135
- appVersion: config.appVersion,
136
- systemVersion: config.systemVersion,
137
- format: {
138
- date: config.dateFormat,
139
- time: config.timeFormat,
140
- },
141
- };
142
- }
143
- }
144
-
145
- /**
146
- * setTitle - 设置标题
147
- * @param title 标题文本
148
- */
149
- async setTitle(title: string) {
150
- // 等待初始化完成
151
- await this.initPromise;
152
-
153
- logger.log("Setting title:", title);
154
-
155
- if (this.isWeb) {
156
- return this.osConnector?.methods.setTitle(title);
157
- } else {
158
- return this.callAppMethod("updateTitle", title);
159
- }
160
- }
161
-
162
- /**
163
- * setExitPageTips - 设置退出页面提示
164
- * @param params 提示参数
165
- */
166
- async setExitPageTips(params?: { title?: string; content?: string }) {
167
- // 等待初始化完成
168
- await this.initPromise;
169
-
170
- if (this.isWeb) {
171
- return this.osConnector?.methods.setExitPageTips(params);
172
- } else {
173
- return this.callAppMethod(
174
- "setExitPageTips",
175
- params ? JSON.stringify(params) : ""
176
- );
177
- }
178
- }
179
-
180
- /**
181
- * 通过应用打开某个文件
182
- */
183
- async openFile(path: string) {
184
- // 等待初始化完成
185
- await this.initPromise;
186
-
187
- logger.log("Opening file:", path);
188
-
189
- if (this.isWeb) {
190
- return this.osConnector?.methods.openFile(path);
191
- } else {
192
- return this.callAppMethod("openFile", path);
193
- }
194
- }
195
-
196
- /**
197
- * 打开文件管理器
198
- */
199
- async openFileManager(path: string) {
200
- // 等待初始化完成
201
- await this.initPromise;
202
-
203
- logger.log("Opening file manager:", path);
204
-
205
- if (this.isWeb) {
206
- return this.osConnector?.methods.openFileManagerApp(path);
207
- } else {
208
- return this.callAppMethod("openFileManager", path);
209
- }
210
- }
211
-
212
- /**
213
- * 关闭应用
214
- */
215
- async close() {
216
- // 等待初始化完成
217
- await this.initPromise;
218
- if (this.isWeb) {
219
- return this.osConnector?.methods.close();
220
- } else {
221
- return this.callAppMethod("exitPage");
222
- }
223
- }
224
-
225
- /**
226
- * 请求接口
227
- */
228
- async query<T>(params: any, config?: QueryConfig): Promise<ResponseData<T>> {
229
- // 等待初始化完成
230
- await this.initPromise;
231
- if (this.isWeb) {
232
- const result = await this.osConnector?.methods.query<T>(params, config);
233
- if (!result) {
234
- throw new Error("Failed to query");
235
- }
236
- return result;
237
- } else {
238
- throw new Error("query is not supported on mobile platform");
239
- }
240
- }
241
-
242
- /**
243
- * 选择文件
244
- */
245
- async pickFile(params: FilePickerParams) {
246
- // 等待初始化完成
247
- await this.initPromise;
248
- if (this.isWeb) {
249
- return this.osConnector?.methods.pickFile(params);
250
- } else {
251
- return this.callAppMethod("openFolder", JSON.stringify(params));
252
- }
253
- }
254
- }
255
-
256
- // 默认导出
257
- export default TrimApp;
package/src/logger.ts DELETED
@@ -1,65 +0,0 @@
1
- /**
2
- * Logger 工具类
3
- * 只有在 debug 模式下才会输出日志
4
- */
5
- class Logger {
6
- private debug: boolean = false;
7
-
8
- /**
9
- * 设置 debug 模式
10
- * @param enabled 是否启用 debug
11
- */
12
- setDebug(enabled: boolean) {
13
- this.debug = enabled;
14
- }
15
-
16
- /**
17
- * 获取当前 debug 状态
18
- */
19
- isDebug(): boolean {
20
- return this.debug;
21
- }
22
-
23
- /**
24
- * 输出日志(只在 debug 模式下)
25
- * @param args 日志参数
26
- */
27
- log(...args: any[]) {
28
- if (this.debug) {
29
- console.log('[Trim App]', ...args);
30
- }
31
- }
32
-
33
- /**
34
- * 输出警告日志(只在 debug 模式下)
35
- * @param args 日志参数
36
- */
37
- warn(...args: any[]) {
38
- if (this.debug) {
39
- console.warn('[Trim App]', ...args);
40
- }
41
- }
42
-
43
- /**
44
- * 输出错误日志(只在 debug 模式下)
45
- * @param args 日志参数
46
- */
47
- error(...args: any[]) {
48
- if (this.debug) {
49
- console.error('[Trim App]', ...args);
50
- }
51
- }
52
-
53
- /**
54
- * 输出信息日志(只在 debug 模式下)
55
- * @param args 日志参数
56
- */
57
- info(...args: any[]) {
58
- if (this.debug) {
59
- console.info('[Trim App]', ...args);
60
- }
61
- }
62
- }
63
-
64
- // 导出单例
65
- export const logger = new Logger();
@@ -1,112 +0,0 @@
1
- import { logger } from "../logger";
2
- import { isFnApp } from "../utils/platform";
3
-
4
- export interface FlutterInAppWebView {
5
- callHandler: (fn: string, params?: string) => Promise<string>;
6
- _platformReady?: boolean;
7
- }
8
-
9
- declare global {
10
- interface Window {
11
- flutter_inappwebview: FlutterInAppWebView;
12
- fnAppMessage?: (message: string) => void;
13
- onAppHeaderGoBack?: () => boolean | number | string; // 随意返回
14
- }
15
- }
16
-
17
- let isReady = false;
18
- window.addEventListener("flutterInAppWebViewPlatformReady", () => {
19
- isReady = true;
20
- });
21
-
22
- export const initMobile = () => {
23
- /**
24
- * 处理app有回掉的方法消息
25
- */
26
- return new Promise<FlutterInAppWebView>((res) => {
27
- if (isReady || window.flutter_inappwebview?._platformReady) {
28
- logger.log("flutter_inappwebview is ready");
29
- res(window.flutter_inappwebview);
30
- } else {
31
- window.addEventListener("flutterInAppWebViewPlatformReady", () => {
32
- logger.log("flutter_inappwebview is ready");
33
- res(window.flutter_inappwebview);
34
- });
35
- }
36
- });
37
- };
38
-
39
- export interface FnAppMessage<T> {
40
- reqId: string;
41
- method: string;
42
- result: T;
43
- }
44
-
45
- export const callHandler = async <T>(
46
- flutterInAppWebView: FlutterInAppWebView,
47
- fn: string,
48
- params?: string
49
- ): Promise<T | null> => {
50
- logger.log(`callHandler: ${fn}, params: ${params}`);
51
- const res = await flutterInAppWebView.callHandler(fn, params);
52
- if (res) {
53
- try {
54
- const messageData: FnAppMessage<string> = JSON.parse(res);
55
- logger.log(`messageData: ${JSON.stringify(messageData)}`);
56
- const appMessage: T = JSON.parse(messageData.result);
57
- logger.log(`appMessage: ${JSON.stringify(appMessage)}`);
58
- return appMessage;
59
- } catch (error) {
60
- logger.error(`error: ${error}`);
61
- return null;
62
- }
63
- }
64
- return null;
65
- };
66
-
67
- // 存储app消息的回调
68
- const fnAppMessageHandleMap = new Map<
69
- string,
70
- (Response: FnAppMessage<any>) => void
71
- >();
72
-
73
- function initAppMessageEvent() {
74
- window.fnAppMessage = (message: string) => {
75
- logger.log("app-message", message);
76
- const data: FnAppMessage<any> = JSON.parse(message);
77
-
78
- const handle = fnAppMessageHandleMap.get(data.reqId);
79
- if (handle) {
80
- handle(data);
81
- fnAppMessageHandleMap.delete(data.reqId);
82
- }
83
- };
84
- }
85
-
86
- if (isFnApp()) {
87
- initAppMessageEvent();
88
- }
89
-
90
- export async function pickFilePromise(
91
- flutterInAppWebView: FlutterInAppWebView,
92
- params: {
93
- title: string;
94
- multiple: boolean;
95
- directory: boolean;
96
- }
97
- ): Promise<string[] | undefined> {
98
- return new Promise((resolve, reject) => {
99
- flutterInAppWebView
100
- ?.callHandler("openFolder", JSON.stringify(params))
101
- .then((reqId) => {
102
- if (reqId) {
103
- function handle(data: FnAppMessage<string[]>) {
104
- resolve(data.result);
105
- }
106
- fnAppMessageHandleMap.set(reqId, handle);
107
- } else {
108
- reject(new Error("openFolder failed"));
109
- }
110
- });
111
- });
112
- }
@@ -1,9 +0,0 @@
1
- export interface AppMessage {
2
- nightMode: string; // dark | light
3
- language: string;
4
- platform: string;
5
- appVersion?: string;
6
- systemVersion: string;
7
- dateFormat: string; // yyyy-MM-dd
8
- timeFormat: string; // 12h | 24h
9
- }
package/src/types.ts DELETED
@@ -1,18 +0,0 @@
1
- /**
2
- * SDK 配置选项
3
- */
4
- export interface TrimAppOptions {
5
- /** 是否开启 debug 模式,开启后会输出日志 */
6
- debug?: boolean;
7
- }
8
-
9
- export interface PlatformConfig {
10
- theme: "dark" | "light";
11
- language: string; // "zh-CN" | "en-US" ....
12
- appVersion?: string;
13
- systemVersion: string;
14
- format: {
15
- date?: string; // "YYYY-MM-DD" | "MM-DD-YYYY" | "DD-MM-YYYY" | "YYYY/MM/DD" | "MM/DD/YYYY" | "DD/MM/YYYY"
16
- time?: string; // "12h" | "24h"
17
- };
18
- }
@@ -1,17 +0,0 @@
1
- export function fnAppUAMatch(ua: string) {
2
- const regex = /FNOS\/([\d.]+)|FNAppType\/(\w+)|FNAppVer\/([\d.]+)/g;
3
-
4
- const matches: any = {};
5
- let match;
6
- while ((match = regex.exec(ua)) !== null) {
7
- if (match[1]) matches.fnOSVersion = match[1];
8
- if (match[2]) matches.fnAppType = match[2];
9
- if (match[3]) matches.fnAppVersion = match[3];
10
- }
11
-
12
- return matches;
13
- }
14
-
15
- export const isFnApp = () => {
16
- return fnAppUAMatch(navigator.userAgent).fnAppVersion;
17
- };
package/src/web/index.ts DELETED
@@ -1,27 +0,0 @@
1
- import { connectToOS } from "@fn/micro-app-postmate";
2
- import { type OSConfig } from "@fn/micro-app-postmate/src/parent/type";
3
- import {
4
- type OSMethods,
5
- type ConnectionResult,
6
- type AsyncMethodReturns,
7
- } from "@fn/micro-app-postmate/src/types";
8
- import type { PlatformConfig, TrimAppOptions } from "../types";
9
-
10
- export type OSConnection = AsyncMethodReturns<
11
- ConnectionResult<
12
- OSMethods & {
13
- setExitPageTips: (params?: { title?: string; content?: string }) => void;
14
- openFileManagerApp: (path: string) => void;
15
- openFile: (path: string) => void;
16
- getPlatformConfig: () => Promise<PlatformConfig>;
17
- close: () => void;
18
- },
19
- OSConfig
20
- >
21
- >;
22
-
23
- export const initWeb = (options?: TrimAppOptions) => {
24
- return connectToOS({
25
- debug: options?.debug,
26
- }).promise;
27
- };