r-agency-mesh-client-v1 1.0.21 → 1.0.23

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "r-agency-mesh-client-v1",
3
3
  "author": "Jonny Becker",
4
- "version": "1.0.21",
4
+ "version": "1.0.23",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "dev": "vite",
package/release/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6;var _zod = require('zod');var _axios = require('axios'); var _axios2 = _interopRequireDefault(_axios);var R={connect:"connect",execute:"runtime/action/v2"},M=(r,e)=>{let t=_nullishCoalesce(R[e], () => (void 0));if(t)return new URL([r,t].join("/"))};var g=()=>!!window.localStorage.getItem("mesh-client-id"),x=r=>{let e={id:r,date:new Date().getTime()};window.localStorage.setItem("mesh-client-id",JSON.stringify(e))},p=()=>{try{let r=window.localStorage.getItem("mesh-client-id");return r?JSON.parse(r):void 0}catch (e2){return}};var f= (_class =class{constructor() { _class.prototype.__init.call(this); }__init() {this.listeners={}}on(e,t){return this.listeners[e]??=[],_optionalChain([this, 'access', _2 => _2.listeners, 'access', _3 => _3[e], 'optionalAccess', _4 => _4.push, 'call', _5 => _5(t)]),()=>{this.off(e,t)}}off(e,t){this.listeners[e]??=[],this.listeners[e]=_optionalChain([this, 'access', _6 => _6.listeners, 'access', _7 => _7[e], 'optionalAccess', _8 => _8.filter, 'call', _9 => _9(s=>s!==t)])}emit(e,t){this.listeners[e]??=[],_optionalChain([this, 'access', _10 => _10.listeners, 'access', _11 => _11[e], 'optionalAccess', _12 => _12.forEach, 'call', _13 => _13(s=>s(t))])}}, _class);var y=r=>{let e=Object.prototype.toString.call(r.data);try{switch(e){case"[object ArrayBuffer]":return{type:e,data:JSON.parse(new TextDecoder().decode(r.data))}}return{type:e}}catch(t){return{type:e,error:t}}};var u= (_class2 =class{constructor(e){;_class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);this.events=e}__init2() {this.websocket=void 0}__init3() {this.state={connected:!1}}disconnect(){this.websocket&&this.websocket.close()}connect(e,t){try{let s=new URL(e.websocket.url);s.searchParams.set("token",JSON.stringify({version:"1.0",clientId:t}));let n=new WebSocket(s.toString());n.binaryType="arraybuffer",n.addEventListener("open",this.open.bind(this)),n.addEventListener("close",this.close.bind(this)),n.addEventListener("message",this.message.bind(this)),this.websocket=n}catch(s){let n=s;this.events.emit("websocket:error",{error:n.message})}}send(e){try{let s=new TextEncoder().encode(JSON.stringify(e));_optionalChain([this, 'access', _14 => _14.websocket, 'optionalAccess', _15 => _15.send, 'call', _16 => _16(s)])}catch(t){let s=t;this.events.emit("websocket:error",{error:s.message})}}message(e){let s=_nullishCoalesce(y(e).data, () => ({}));if(s.ping)return this.events.emit("websocket:ping",{message:s}),this.send({pong:!0});s.emits&&s.emits.map(n=>{this.events.emit(n.event,_nullishCoalesce(n.payload, () => ({})))})}open(){this.state.connected=!0,this.events.emit("websocket:connected",{client:this,state:this.state})}close(){this.state.connected=!1,this.events.emit("websocket:disconnected",{state:this.state})}}, _class2);var c= (_class3 =class{constructor() { _class3.prototype.__init4.call(this); }__init4() {this.headers={}}assign(e){this.headers=Object.assign(e,this.headers)}getAll(){return this.headers}}, _class3);var h=class{constructor(e){this.raw=e;this._data=e.data}data(){return this.export().data}code(){return this.raw.status}statusText(){return this.raw.statusText}config(){return this.raw.config}headers(){return{...this.raw.headers}}export(){return this.raw.data}errors(){return _nullishCoalesce(this._data.errors, () => ([]))}};var l=class extends h{constructor(e){super(e)}};var I= (_class4 =class{constructor(e,t){;_class4.prototype.__init5.call(this);_class4.prototype.__init6.call(this);_class4.prototype.__init7.call(this);_class4.prototype.__init8.call(this);_class4.prototype.__init9.call(this);_class4.prototype.__init10.call(this);this.action=e;this.events=t}__init5() {this._headers={}}__init6() {this._params={}}__init7() {this._payload={}}__init8() {this._onSuccess=[]}__init9() {this._onError=[]}__init10() {this._onHttpError=[]}onSuccess(e){return this._onSuccess.push(e),this}onError(e){return this._onError.push(e),this}onHttpError(e){return this._onHttpError.push(e),this}headers(e){return this._headers=e,this}params(e){return this._params=e,this}payload(e){return this._payload=e,this}send(e={}){try{let t=new c;this.events.emit("before:send:action",{headers:t,action:this.action}),this.events.emit("modify:headers",{headers:t}),t.assign({"x-mesh-action-id":this.action.id,"x-mesh-client-id":_optionalChain([p, 'call', _17 => _17(), 'optionalAccess', _18 => _18.id])}),e.headers&&t.assign(e.headers),t.assign(this._headers),_axios2.default.request({url:this.action.url,method:this.action.method,headers:t.getAll(),params:{...e.params,...this._params},data:{payload:{..._nullishCoalesce(e.payload, () => ({})),...this._payload}}}).then(s=>{this.response(e,s)}).catch(s=>{this.axiosError(e,s)})}catch(t){this.error(t)}}response(e,t){let s=t.status;e.codes&&e.codes[s]&&e.codes[s]();let n=new l(t);this.events.emit("action:sender:response",{response:n,code:t.status}),this._onSuccess.map(i=>i(n))}error(e){this.events.emit("action:sender:error",{error:e}),this._onError.map(t=>t(e))}axiosError(e,t){let s=t.response,n=new l(s),i=t.status;i&&e.codes&&e.codes[i]&&e.codes[i](),this.events.emit("action:sender:axios:error",{error:t,response:n}),this._onHttpError.map(a=>a(n,t))}}, _class4);var _core = require('@apollo/client/core');var E="x-mesh-client-id",S= exports.X_MESH_HOST_KEY ="x-mesh-host";var m=class extends h{constructor(e){super(e)}};var v= (_class5 =class{constructor(e,t){;_class5.prototype.__init11.call(this);_class5.prototype.__init12.call(this);_class5.prototype.__init13.call(this);_class5.prototype.__init14.call(this);_class5.prototype.__init15.call(this);this.schema=e;this.events=t;this.endpoint=_optionalChain([window, 'access', _19 => _19.MeshClientConfig, 'optionalAccess', _20 => _20.endpoint])}__init11() {this._headers={}}__init12() {this._params={}}__init13() {this._payload={}}__init14() {this._onSuccess=[]}__init15() {this._onHttpError=[]}onSuccess(e){return this._onSuccess.push(e),this}onHttpError(e){return this._onHttpError.push(e),this}headers(e){return this._headers=e,this}params(e){return this._params=e,this}payload(e){return this._payload=e,this}send(){if(!this.endpoint)return;let e=M(this.endpoint,"execute");if(!e)return;let t=new c;this.events.emit("modify:headers",{headers:t}),t.assign(this._headers);try{_axios2.default.request({url:e.toString(),method:"POST",headers:t.getAll(),params:this._params,data:{action:this.schema,payload:this._payload}}).then(this.response.bind(this)).catch(this.error.bind(this))}catch(s){let n=s;this.error(n)}}response(e){let t=new m(e);this._onSuccess.map(s=>s(t))}error(e){let t=e.response,s=new m(t);this._onHttpError.map(n=>n(s,e))}}, _class5);var C= (_class6 =class{__init16() {this.events=new f}__init17() {this.state={connected:!1}}__init18() {this.config=void 0}__init19() {this.actions={}}constructor(){;_class6.prototype.__init16.call(this);_class6.prototype.__init17.call(this);_class6.prototype.__init18.call(this);_class6.prototype.__init19.call(this);this.websocket=new u(this.events),this.events.on("websocket:connected",this._connected.bind(this)),this.events.on("websocket:disconnected",this._disconnected.bind(this)),this.events.on("connect:error",this._error.bind(this)),this.events.on("websocket:error",this._error.bind(this))}createExecute(e){return new v(e,this.events)}createGraphqlSender(e){let t=new c;this.events.emit("create:graphql:sender",{headers:t}),this.events.emit("modify:headers",{headers:t}),e.headers&&t.assign(e.headers),t.assign({[E]:_optionalChain([p, 'call', _21 => _21(), 'optionalAccess', _22 => _22.id])});let s=new (0, _core.HttpLink)({uri:_optionalChain([this, 'access', _23 => _23.config, 'optionalAccess', _24 => _24.graphql, 'access', _25 => _25.url]),headers:t.getAll()}),n=new (0, _core.ApolloLink)((i,a)=>a(i).map(o=>(_optionalChain([o, 'access', _26 => _26.errors, 'optionalAccess', _27 => _27.map, 'call', _28 => _28(d=>{this.events.emit("graphql:sender:error",{error:d})})]),o)));return new (0, _core.ApolloClient)({link:n.concat(_core.from.call(void 0, [s])),cache:new (0, _core.InMemoryCache)({resultCaching:_nullishCoalesce(e.resultCaching, () => (!1))}),headers:t.getAll()})}createActionSender(e){let t=_nullishCoalesce(this.actions[e], () => (this.actions["mesh-fallback-action"]));return new I(t,this.events)}disconnected(){this.websocket.disconnect()}connect(){return new Promise(e=>{let t=window.MeshClientConfig;if(this.state.connected||!t)return e({success:!0,actions:{}});if(!_zod.z.object({endpoint:_zod.z.string().url()}).safeParse({endpoint:t.endpoint}).success)return this.events.emit("connect:error",{error:"invalid mesh config schema!"}),e({success:!1,actions:{}});let n=M(t.endpoint,"connect");if(!n)return this.events.emit("connect:error",{error:"mesh connect url not found!"}),e({success:!1,actions:{}});_axios2.default.request({method:"post",url:n.toString(),headers:{..._nullishCoalesce(t.headers, () => ({})),[S]:new URL(t.endpoint).host,[E]:_optionalChain([p, 'call', _29 => _29(), 'optionalAccess', _30 => _30.id])}}).then(i=>{this.connected(i.data,e)}).catch(()=>(this.events.emit("connect:error",{error:"connection to mesh-server failed!"}),e({success:!1,actions:{}})))})}connected(e,t){let s=_nullishCoalesce(e.success, () => (!1)),n=e.config,i=e.clientId,a=e.actions;if(!s||!n||!i||!a)return this.events.emit("connect:error",{error:"mesh client config not loaded!"}),t({success:!1,actions:{}});g()||x(i),this.config=n,this.actions=a,this.events.emit("connected",{config:n,actions:a}),this.websocket.connect(n,i),t({success:!0,actions:a})}_connected(){this.state.connected=!0}_disconnected(){this.events.emit("disconnected"),this.state.connected=!1}_error(e){console.error(e)}}, _class6);var Be=()=>(window.MeshClient||(window.MeshClient=new C),{config:o=>{window.MeshClientConfig=o},action:o=>window.MeshClient.createActionSender(o),graphql:o=>window.MeshClient.createGraphqlSender(_nullishCoalesce(o, () => ({}))),connect:o=>{window.MeshClient.connect().then(d=>{o&&o(d)})},onEvent:(o,d)=>{window.MeshClient.events.on(o,d)},execute:o=>window.MeshClient.createExecute(o),events:()=>window.MeshClient.events});exports.X_MESH_CLIENT_ID_KEY = E; exports.X_MESH_HOST_KEY = S; exports.useMesh = Be;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6;var _zod = require('zod');var _axios = require('axios'); var _axios2 = _interopRequireDefault(_axios);var R={connect:"connect",execute:"runtime/action/v2"},M=(r,e)=>{let t=_nullishCoalesce(R[e], () => (void 0));if(t)return new URL([r,t].join("/"))};var g=()=>!!window.localStorage.getItem("mesh-client-id"),x=r=>{let e={id:r,date:new Date().getTime()};window.localStorage.setItem("mesh-client-id",JSON.stringify(e))},p=()=>{try{let r=window.localStorage.getItem("mesh-client-id");return r?JSON.parse(r):void 0}catch (e2){return}};var u= (_class =class{constructor() { _class.prototype.__init.call(this); }__init() {this.listeners={}}on(e,t){return this.listeners[e]??=[],_optionalChain([this, 'access', _2 => _2.listeners, 'access', _3 => _3[e], 'optionalAccess', _4 => _4.push, 'call', _5 => _5(t)]),()=>{this.off(e,t)}}off(e,t){this.listeners[e]??=[],this.listeners[e]=_optionalChain([this, 'access', _6 => _6.listeners, 'access', _7 => _7[e], 'optionalAccess', _8 => _8.filter, 'call', _9 => _9(s=>s!==t)])}emit(e,t){this.listeners[e]??=[],_optionalChain([this, 'access', _10 => _10.listeners, 'access', _11 => _11[e], 'optionalAccess', _12 => _12.forEach, 'call', _13 => _13(s=>s(t))])}}, _class);var y=r=>{let e=Object.prototype.toString.call(r.data);try{switch(e){case"[object ArrayBuffer]":return{type:e,data:JSON.parse(new TextDecoder().decode(r.data))}}return{type:e}}catch(t){return{type:e,error:t}}};var f= (_class2 =class{constructor(e){;_class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);this.events=e}__init2() {this.websocket=void 0}__init3() {this.state={connected:!1}}disconnect(){this.websocket&&this.websocket.close()}connect(e,t){try{let s=new URL(e.websocket.url);s.searchParams.set("token",JSON.stringify({version:"1.0",clientId:t}));let n=new WebSocket(s.toString());n.binaryType="arraybuffer",n.addEventListener("open",this.open.bind(this)),n.addEventListener("close",this.close.bind(this)),n.addEventListener("message",this.message.bind(this)),this.websocket=n}catch(s){let n=s;this.events.emit("websocket:error",{error:n.message})}}send(e){try{let s=new TextEncoder().encode(JSON.stringify(e));_optionalChain([this, 'access', _14 => _14.websocket, 'optionalAccess', _15 => _15.send, 'call', _16 => _16(s)])}catch(t){let s=t;this.events.emit("websocket:error",{error:s.message})}}message(e){let s=_nullishCoalesce(y(e).data, () => ({}));if(s.ping)return this.events.emit("websocket:ping",{message:s}),this.send({pong:!0});s.emits&&s.emits.map(n=>{this.events.emit(n.event,_nullishCoalesce(n.payload, () => ({})))})}open(){this.state.connected=!0,this.events.emit("websocket:connected",{client:this,state:this.state})}close(){this.state.connected=!1,this.events.emit("websocket:disconnected",{state:this.state})}}, _class2);var c= (_class3 =class{constructor() { _class3.prototype.__init4.call(this); }__init4() {this.headers={}}assign(e){this.headers=Object.assign(e,this.headers)}getAll(){return this.headers}}, _class3);var h=class{constructor(e){this.raw=e;this._data=e.data}data(){return this.export().data}code(){return this.raw.status}statusText(){return this.raw.statusText}config(){return this.raw.config}headers(){return{...this.raw.headers}}export(){return this.raw.data}errors(){return _nullishCoalesce(this._data.errors, () => ([]))}};var l=class extends h{constructor(e){super(e)}};var C= (_class4 =class{constructor(e,t){;_class4.prototype.__init5.call(this);_class4.prototype.__init6.call(this);_class4.prototype.__init7.call(this);_class4.prototype.__init8.call(this);_class4.prototype.__init9.call(this);_class4.prototype.__init10.call(this);this.action=e;this.events=t}__init5() {this._headers={}}__init6() {this._params={}}__init7() {this._payload={}}__init8() {this._onSuccess=[]}__init9() {this._onError=[]}__init10() {this._onHttpError=[]}onSuccess(e){return this._onSuccess.push(e),this}onError(e){return this._onError.push(e),this}onHttpError(e){return this._onHttpError.push(e),this}headers(e){return this._headers=e,this}params(e){return this._params=e,this}payload(e){return this._payload=e,this}send(e={}){try{let t=new c;this.events.emit("before:send:action",{headers:t,action:this.action}),this.events.emit("modify:headers",{headers:t}),t.assign({"x-mesh-action-id":this.action.id,"x-mesh-client-id":_optionalChain([p, 'call', _17 => _17(), 'optionalAccess', _18 => _18.id])}),e.headers&&t.assign(e.headers),t.assign(this._headers),_axios2.default.request({url:this.action.url,method:this.action.method,headers:t.getAll(),params:{...e.params,...this._params},data:{payload:{..._nullishCoalesce(e.payload, () => ({})),...this._payload}}}).then(s=>{this.response(e,s)}).catch(s=>{this.axiosError(e,s)})}catch(t){this.error(t)}}response(e,t){let s=t.status;e.codes&&e.codes[s]&&e.codes[s]();let n=new l(t);this.events.emit("action:sender:response",{response:n,code:t.status}),this._onSuccess.map(i=>i(n))}error(e){this.events.emit("action:sender:error",{error:e}),this._onError.map(t=>t(e))}axiosError(e,t){let s=t.response,n=new l(s),i=t.status;i&&e.codes&&e.codes[i]&&e.codes[i](),this.events.emit("action:sender:axios:error",{error:t,response:n}),this._onHttpError.map(a=>a(n,t))}}, _class4);var _core = require('@apollo/client/core');var E="x-mesh-client-id",S= exports.X_MESH_HOST_KEY ="x-mesh-host";var m=class extends h{constructor(e){super(e)}};var I= (_class5 =class{constructor(e,t){;_class5.prototype.__init11.call(this);_class5.prototype.__init12.call(this);_class5.prototype.__init13.call(this);_class5.prototype.__init14.call(this);_class5.prototype.__init15.call(this);this.schema=e;this.events=t;this.endpoint=_optionalChain([window, 'access', _19 => _19.MeshClientConfig, 'optionalAccess', _20 => _20.endpoint])}__init11() {this._headers={}}__init12() {this._params={}}__init13() {this._payload={}}__init14() {this._onSuccess=[]}__init15() {this._onHttpError=[]}onSuccess(e){return this._onSuccess.push(e),this}onHttpError(e){return this._onHttpError.push(e),this}headers(e){return this._headers=e,this}params(e){return this._params=e,this}payload(e){return this._payload=e,this}send(){if(!this.endpoint)return;let e=M(this.endpoint,"execute");if(!e)return;let t=new c;this.events.emit("modify:headers",{headers:t}),t.assign(this._headers);try{_axios2.default.request({url:e.toString(),method:"POST",headers:t.getAll(),params:this._params,data:{action:this.schema,payload:this._payload}}).then(this.response.bind(this)).catch(this.error.bind(this))}catch(s){let n=s;this.error(n)}}response(e){let t=new m(e);this._onSuccess.map(s=>s(t))}error(e){let t=e.response,s=new m(t);this._onHttpError.map(n=>n(s,e))}}, _class5);var v= (_class6 =class{__init16() {this.events=new u}__init17() {this.state={connected:!1,status:"disconnected"}}__init18() {this.config=void 0}__init19() {this.actions={}}constructor(){;_class6.prototype.__init16.call(this);_class6.prototype.__init17.call(this);_class6.prototype.__init18.call(this);_class6.prototype.__init19.call(this);this.websocket=new f(this.events),this.events.on("websocket:connected",this._connected.bind(this)),this.events.on("websocket:disconnected",this._disconnected.bind(this)),this.events.on("connect:error",this._error.bind(this)),this.events.on("websocket:error",this._error.bind(this))}status(){return this.state.status}createExecute(e){return new I(e,this.events)}createGraphqlSender(e){let t=new c;this.events.emit("create:graphql:sender",{headers:t}),this.events.emit("modify:headers",{headers:t}),e.headers&&t.assign(e.headers),t.assign({[E]:_optionalChain([p, 'call', _21 => _21(), 'optionalAccess', _22 => _22.id])});let s=new (0, _core.HttpLink)({uri:_optionalChain([this, 'access', _23 => _23.config, 'optionalAccess', _24 => _24.graphql, 'access', _25 => _25.url]),headers:t.getAll()}),n=new (0, _core.ApolloLink)((i,a)=>a(i).map(o=>(_optionalChain([o, 'access', _26 => _26.errors, 'optionalAccess', _27 => _27.map, 'call', _28 => _28(d=>{this.events.emit("graphql:sender:error",{error:d})})]),o)));return new (0, _core.ApolloClient)({link:n.concat(_core.from.call(void 0, [s])),cache:new (0, _core.InMemoryCache)({resultCaching:_nullishCoalesce(e.resultCaching, () => (!1))}),headers:t.getAll()})}createActionSender(e){let t=_nullishCoalesce(this.actions[e], () => (this.actions["mesh-fallback-action"]));return new C(t,this.events)}disconnected(){this.websocket.disconnect()}connect(){return new Promise(e=>{let t=window.MeshClientConfig;if(this.state.connected||!t)return e({success:!0,actions:{}});if(!_zod.z.object({endpoint:_zod.z.string().url()}).safeParse({endpoint:t.endpoint}).success)return this.events.emit("connect:error",{error:"invalid mesh config schema!"}),e({success:!1,actions:{}});let n=M(t.endpoint,"connect");if(!n)return this.events.emit("connect:error",{error:"mesh connect url not found!"}),e({success:!1,actions:{}});_axios2.default.request({method:"post",url:n.toString(),headers:{..._nullishCoalesce(t.headers, () => ({})),[S]:new URL(t.endpoint).host,[E]:_optionalChain([p, 'call', _29 => _29(), 'optionalAccess', _30 => _30.id])}}).then(i=>{this.connected(i.data,e)}).catch(()=>(this.events.emit("connect:error",{error:"connection to mesh-server failed!"}),e({success:!1,actions:{}})))})}connected(e,t){let s=_nullishCoalesce(e.success, () => (!1)),n=e.config,i=e.clientId,a=e.actions;if(!s||!n||!i||!a)return this.events.emit("connect:error",{error:"mesh client config not loaded!"}),t({success:!1,actions:{}});g()||x(i),this.config=n,this.actions=a,this.websocket.connect(n,i),t({success:!0,actions:a})}_connected(){this.state.status="connected",this.events.emit("connected",{actions:this.actions,config:this.config}),this.state.connected=!0}_disconnected(){this.state.status="disconnected",this.events.emit("disconnected"),this.state.connected=!1}_error(e){console.error(e)}}, _class6);var je=()=>(window.MeshClient||(window.MeshClient=new v),{config:o=>{window.MeshClientConfig=o},action:o=>window.MeshClient.createActionSender(o),graphql:o=>window.MeshClient.createGraphqlSender(_nullishCoalesce(o, () => ({}))),connect:o=>{window.MeshClient.connect().then(d=>{o&&o(d)})},onEvent:(o,d)=>{window.MeshClient.events.on(o,d)},execute:o=>window.MeshClient.createExecute(o),events:()=>window.MeshClient.events,is(){return window.MeshClient.status()}});exports.X_MESH_CLIENT_ID_KEY = E; exports.X_MESH_HOST_KEY = S; exports.useMesh = je;
@@ -74,8 +74,8 @@ type MeshClientEvents = {
74
74
  orderId: string;
75
75
  };
76
76
  connected: {
77
- config: IMeshClientConfig;
78
- actions: MeshActions;
77
+ config?: IMeshClientConfig;
78
+ actions?: MeshActions;
79
79
  };
80
80
  disconnected: any;
81
81
  "connect:error": {
@@ -222,8 +222,10 @@ interface IMeshClientExecute {
222
222
  onHttpError(fn: MeshExecuteOnHttpErrorFn): IMeshClientExecute;
223
223
  }
224
224
 
225
+ type MeshClientStatus = 'connected' | 'disconnected';
225
226
  interface IMeshClient {
226
227
  events: EventManagerInt<MeshClientEvents>;
228
+ status(): MeshClientStatus;
227
229
  disconnected(): void;
228
230
  connect(): Promise<IMeshConnectResult>;
229
231
  createActionSender<Alias extends keyof IMeshGenerated['actions']>(alias: Alias): IMeshClientSender;
@@ -249,6 +251,7 @@ declare global {
249
251
  }
250
252
  }
251
253
  interface IMesh {
254
+ is(): MeshClientStatus;
252
255
  events(): EventManagerInt<MeshClientEvents>;
253
256
  connect(callback?: (result: IMeshConnectResult) => void): void;
254
257
  config(config: IMeshClientCreateConfig): void;
@@ -74,8 +74,8 @@ type MeshClientEvents = {
74
74
  orderId: string;
75
75
  };
76
76
  connected: {
77
- config: IMeshClientConfig;
78
- actions: MeshActions;
77
+ config?: IMeshClientConfig;
78
+ actions?: MeshActions;
79
79
  };
80
80
  disconnected: any;
81
81
  "connect:error": {
@@ -222,8 +222,10 @@ interface IMeshClientExecute {
222
222
  onHttpError(fn: MeshExecuteOnHttpErrorFn): IMeshClientExecute;
223
223
  }
224
224
 
225
+ type MeshClientStatus = 'connected' | 'disconnected';
225
226
  interface IMeshClient {
226
227
  events: EventManagerInt<MeshClientEvents>;
228
+ status(): MeshClientStatus;
227
229
  disconnected(): void;
228
230
  connect(): Promise<IMeshConnectResult>;
229
231
  createActionSender<Alias extends keyof IMeshGenerated['actions']>(alias: Alias): IMeshClientSender;
@@ -249,6 +251,7 @@ declare global {
249
251
  }
250
252
  }
251
253
  interface IMesh {
254
+ is(): MeshClientStatus;
252
255
  events(): EventManagerInt<MeshClientEvents>;
253
256
  connect(callback?: (result: IMeshConnectResult) => void): void;
254
257
  config(config: IMeshClientCreateConfig): void;
package/release/index.js CHANGED
@@ -1 +1 @@
1
- import{z as w}from"zod";import b from"axios";var R={connect:"connect",execute:"runtime/action/v2"},M=(r,e)=>{let t=R[e]??void 0;if(t)return new URL([r,t].join("/"))};var g=()=>!!window.localStorage.getItem("mesh-client-id"),x=r=>{let e={id:r,date:new Date().getTime()};window.localStorage.setItem("mesh-client-id",JSON.stringify(e))},p=()=>{try{let r=window.localStorage.getItem("mesh-client-id");return r?JSON.parse(r):void 0}catch{return}};var f=class{listeners={};on(e,t){return this.listeners[e]??=[],this.listeners[e]?.push(t),()=>{this.off(e,t)}}off(e,t){this.listeners[e]??=[],this.listeners[e]=this.listeners[e]?.filter(s=>s!==t)}emit(e,t){this.listeners[e]??=[],this.listeners[e]?.forEach(s=>s(t))}};var y=r=>{let e=Object.prototype.toString.call(r.data);try{switch(e){case"[object ArrayBuffer]":return{type:e,data:JSON.parse(new TextDecoder().decode(r.data))}}return{type:e}}catch(t){return{type:e,error:t}}};var u=class{constructor(e){this.events=e}websocket=void 0;state={connected:!1};disconnect(){this.websocket&&this.websocket.close()}connect(e,t){try{let s=new URL(e.websocket.url);s.searchParams.set("token",JSON.stringify({version:"1.0",clientId:t}));let n=new WebSocket(s.toString());n.binaryType="arraybuffer",n.addEventListener("open",this.open.bind(this)),n.addEventListener("close",this.close.bind(this)),n.addEventListener("message",this.message.bind(this)),this.websocket=n}catch(s){let n=s;this.events.emit("websocket:error",{error:n.message})}}send(e){try{let s=new TextEncoder().encode(JSON.stringify(e));this.websocket?.send(s)}catch(t){let s=t;this.events.emit("websocket:error",{error:s.message})}}message(e){let s=y(e).data??{};if(s.ping)return this.events.emit("websocket:ping",{message:s}),this.send({pong:!0});s.emits&&s.emits.map(n=>{this.events.emit(n.event,n.payload??{})})}open(){this.state.connected=!0,this.events.emit("websocket:connected",{client:this,state:this.state})}close(){this.state.connected=!1,this.events.emit("websocket:disconnected",{state:this.state})}};import _ from"axios";var c=class{headers={};assign(e){this.headers=Object.assign(e,this.headers)}getAll(){return this.headers}};var h=class{constructor(e){this.raw=e;this._data=e.data}_data;data(){return this.export().data}code(){return this.raw.status}statusText(){return this.raw.statusText}config(){return this.raw.config}headers(){return{...this.raw.headers}}export(){return this.raw.data}errors(){return this._data.errors??[]}};var l=class extends h{constructor(e){super(e)}};var I=class{constructor(e,t){this.action=e;this.events=t}_headers={};_params={};_payload={};_onSuccess=[];_onError=[];_onHttpError=[];onSuccess(e){return this._onSuccess.push(e),this}onError(e){return this._onError.push(e),this}onHttpError(e){return this._onHttpError.push(e),this}headers(e){return this._headers=e,this}params(e){return this._params=e,this}payload(e){return this._payload=e,this}send(e={}){try{let t=new c;this.events.emit("before:send:action",{headers:t,action:this.action}),this.events.emit("modify:headers",{headers:t}),t.assign({"x-mesh-action-id":this.action.id,"x-mesh-client-id":p()?.id}),e.headers&&t.assign(e.headers),t.assign(this._headers),_.request({url:this.action.url,method:this.action.method,headers:t.getAll(),params:{...e.params,...this._params},data:{payload:{...e.payload??{},...this._payload}}}).then(s=>{this.response(e,s)}).catch(s=>{this.axiosError(e,s)})}catch(t){this.error(t)}}response(e,t){let s=t.status;e.codes&&e.codes[s]&&e.codes[s]();let n=new l(t);this.events.emit("action:sender:response",{response:n,code:t.status}),this._onSuccess.map(i=>i(n))}error(e){this.events.emit("action:sender:error",{error:e}),this._onError.map(t=>t(e))}axiosError(e,t){let s=t.response,n=new l(s),i=t.status;i&&e.codes&&e.codes[i]&&e.codes[i](),this.events.emit("action:sender:axios:error",{error:t,response:n}),this._onHttpError.map(a=>a(n,t))}};import{ApolloClient as k,ApolloLink as H,from as O,HttpLink as q,InMemoryCache as K}from"@apollo/client/core";var E="x-mesh-client-id",S="x-mesh-host";import A from"axios";var m=class extends h{constructor(e){super(e)}};var v=class{constructor(e,t){this.schema=e;this.events=t;this.endpoint=window.MeshClientConfig?.endpoint}endpoint;_headers={};_params={};_payload={};_onSuccess=[];_onHttpError=[];onSuccess(e){return this._onSuccess.push(e),this}onHttpError(e){return this._onHttpError.push(e),this}headers(e){return this._headers=e,this}params(e){return this._params=e,this}payload(e){return this._payload=e,this}send(){if(!this.endpoint)return;let e=M(this.endpoint,"execute");if(!e)return;let t=new c;this.events.emit("modify:headers",{headers:t}),t.assign(this._headers);try{A.request({url:e.toString(),method:"POST",headers:t.getAll(),params:this._params,data:{action:this.schema,payload:this._payload}}).then(this.response.bind(this)).catch(this.error.bind(this))}catch(s){let n=s;this.error(n)}}response(e){let t=new m(e);this._onSuccess.map(s=>s(t))}error(e){let t=e.response,s=new m(t);this._onHttpError.map(n=>n(s,e))}};var C=class{events=new f;websocket;state={connected:!1};config=void 0;actions={};constructor(){this.websocket=new u(this.events),this.events.on("websocket:connected",this._connected.bind(this)),this.events.on("websocket:disconnected",this._disconnected.bind(this)),this.events.on("connect:error",this._error.bind(this)),this.events.on("websocket:error",this._error.bind(this))}createExecute(e){return new v(e,this.events)}createGraphqlSender(e){let t=new c;this.events.emit("create:graphql:sender",{headers:t}),this.events.emit("modify:headers",{headers:t}),e.headers&&t.assign(e.headers),t.assign({[E]:p()?.id});let s=new q({uri:this.config?.graphql.url,headers:t.getAll()}),n=new H((i,a)=>a(i).map(o=>(o.errors?.map(d=>{this.events.emit("graphql:sender:error",{error:d})}),o)));return new k({link:n.concat(O([s])),cache:new K({resultCaching:e.resultCaching??!1}),headers:t.getAll()})}createActionSender(e){let t=this.actions[e]??this.actions["mesh-fallback-action"];return new I(t,this.events)}disconnected(){this.websocket.disconnect()}connect(){return new Promise(e=>{let t=window.MeshClientConfig;if(this.state.connected||!t)return e({success:!0,actions:{}});if(!w.object({endpoint:w.string().url()}).safeParse({endpoint:t.endpoint}).success)return this.events.emit("connect:error",{error:"invalid mesh config schema!"}),e({success:!1,actions:{}});let n=M(t.endpoint,"connect");if(!n)return this.events.emit("connect:error",{error:"mesh connect url not found!"}),e({success:!1,actions:{}});b.request({method:"post",url:n.toString(),headers:{...t.headers??{},[S]:new URL(t.endpoint).host,[E]:p()?.id}}).then(i=>{this.connected(i.data,e)}).catch(()=>(this.events.emit("connect:error",{error:"connection to mesh-server failed!"}),e({success:!1,actions:{}})))})}connected(e,t){let s=e.success??!1,n=e.config,i=e.clientId,a=e.actions;if(!s||!n||!i||!a)return this.events.emit("connect:error",{error:"mesh client config not loaded!"}),t({success:!1,actions:{}});g()||x(i),this.config=n,this.actions=a,this.events.emit("connected",{config:n,actions:a}),this.websocket.connect(n,i),t({success:!0,actions:a})}_connected(){this.state.connected=!0}_disconnected(){this.events.emit("disconnected"),this.state.connected=!1}_error(e){console.error(e)}};var Be=()=>(window.MeshClient||(window.MeshClient=new C),{config:o=>{window.MeshClientConfig=o},action:o=>window.MeshClient.createActionSender(o),graphql:o=>window.MeshClient.createGraphqlSender(o??{}),connect:o=>{window.MeshClient.connect().then(d=>{o&&o(d)})},onEvent:(o,d)=>{window.MeshClient.events.on(o,d)},execute:o=>window.MeshClient.createExecute(o),events:()=>window.MeshClient.events});export{E as X_MESH_CLIENT_ID_KEY,S as X_MESH_HOST_KEY,Be as useMesh};
1
+ import{z as w}from"zod";import b from"axios";var R={connect:"connect",execute:"runtime/action/v2"},M=(r,e)=>{let t=R[e]??void 0;if(t)return new URL([r,t].join("/"))};var g=()=>!!window.localStorage.getItem("mesh-client-id"),x=r=>{let e={id:r,date:new Date().getTime()};window.localStorage.setItem("mesh-client-id",JSON.stringify(e))},p=()=>{try{let r=window.localStorage.getItem("mesh-client-id");return r?JSON.parse(r):void 0}catch{return}};var u=class{listeners={};on(e,t){return this.listeners[e]??=[],this.listeners[e]?.push(t),()=>{this.off(e,t)}}off(e,t){this.listeners[e]??=[],this.listeners[e]=this.listeners[e]?.filter(s=>s!==t)}emit(e,t){this.listeners[e]??=[],this.listeners[e]?.forEach(s=>s(t))}};var y=r=>{let e=Object.prototype.toString.call(r.data);try{switch(e){case"[object ArrayBuffer]":return{type:e,data:JSON.parse(new TextDecoder().decode(r.data))}}return{type:e}}catch(t){return{type:e,error:t}}};var f=class{constructor(e){this.events=e}websocket=void 0;state={connected:!1};disconnect(){this.websocket&&this.websocket.close()}connect(e,t){try{let s=new URL(e.websocket.url);s.searchParams.set("token",JSON.stringify({version:"1.0",clientId:t}));let n=new WebSocket(s.toString());n.binaryType="arraybuffer",n.addEventListener("open",this.open.bind(this)),n.addEventListener("close",this.close.bind(this)),n.addEventListener("message",this.message.bind(this)),this.websocket=n}catch(s){let n=s;this.events.emit("websocket:error",{error:n.message})}}send(e){try{let s=new TextEncoder().encode(JSON.stringify(e));this.websocket?.send(s)}catch(t){let s=t;this.events.emit("websocket:error",{error:s.message})}}message(e){let s=y(e).data??{};if(s.ping)return this.events.emit("websocket:ping",{message:s}),this.send({pong:!0});s.emits&&s.emits.map(n=>{this.events.emit(n.event,n.payload??{})})}open(){this.state.connected=!0,this.events.emit("websocket:connected",{client:this,state:this.state})}close(){this.state.connected=!1,this.events.emit("websocket:disconnected",{state:this.state})}};import _ from"axios";var c=class{headers={};assign(e){this.headers=Object.assign(e,this.headers)}getAll(){return this.headers}};var h=class{constructor(e){this.raw=e;this._data=e.data}_data;data(){return this.export().data}code(){return this.raw.status}statusText(){return this.raw.statusText}config(){return this.raw.config}headers(){return{...this.raw.headers}}export(){return this.raw.data}errors(){return this._data.errors??[]}};var l=class extends h{constructor(e){super(e)}};var C=class{constructor(e,t){this.action=e;this.events=t}_headers={};_params={};_payload={};_onSuccess=[];_onError=[];_onHttpError=[];onSuccess(e){return this._onSuccess.push(e),this}onError(e){return this._onError.push(e),this}onHttpError(e){return this._onHttpError.push(e),this}headers(e){return this._headers=e,this}params(e){return this._params=e,this}payload(e){return this._payload=e,this}send(e={}){try{let t=new c;this.events.emit("before:send:action",{headers:t,action:this.action}),this.events.emit("modify:headers",{headers:t}),t.assign({"x-mesh-action-id":this.action.id,"x-mesh-client-id":p()?.id}),e.headers&&t.assign(e.headers),t.assign(this._headers),_.request({url:this.action.url,method:this.action.method,headers:t.getAll(),params:{...e.params,...this._params},data:{payload:{...e.payload??{},...this._payload}}}).then(s=>{this.response(e,s)}).catch(s=>{this.axiosError(e,s)})}catch(t){this.error(t)}}response(e,t){let s=t.status;e.codes&&e.codes[s]&&e.codes[s]();let n=new l(t);this.events.emit("action:sender:response",{response:n,code:t.status}),this._onSuccess.map(i=>i(n))}error(e){this.events.emit("action:sender:error",{error:e}),this._onError.map(t=>t(e))}axiosError(e,t){let s=t.response,n=new l(s),i=t.status;i&&e.codes&&e.codes[i]&&e.codes[i](),this.events.emit("action:sender:axios:error",{error:t,response:n}),this._onHttpError.map(a=>a(n,t))}};import{ApolloClient as k,ApolloLink as H,from as O,HttpLink as q,InMemoryCache as K}from"@apollo/client/core";var E="x-mesh-client-id",S="x-mesh-host";import A from"axios";var m=class extends h{constructor(e){super(e)}};var I=class{constructor(e,t){this.schema=e;this.events=t;this.endpoint=window.MeshClientConfig?.endpoint}endpoint;_headers={};_params={};_payload={};_onSuccess=[];_onHttpError=[];onSuccess(e){return this._onSuccess.push(e),this}onHttpError(e){return this._onHttpError.push(e),this}headers(e){return this._headers=e,this}params(e){return this._params=e,this}payload(e){return this._payload=e,this}send(){if(!this.endpoint)return;let e=M(this.endpoint,"execute");if(!e)return;let t=new c;this.events.emit("modify:headers",{headers:t}),t.assign(this._headers);try{A.request({url:e.toString(),method:"POST",headers:t.getAll(),params:this._params,data:{action:this.schema,payload:this._payload}}).then(this.response.bind(this)).catch(this.error.bind(this))}catch(s){let n=s;this.error(n)}}response(e){let t=new m(e);this._onSuccess.map(s=>s(t))}error(e){let t=e.response,s=new m(t);this._onHttpError.map(n=>n(s,e))}};var v=class{events=new u;websocket;state={connected:!1,status:"disconnected"};config=void 0;actions={};constructor(){this.websocket=new f(this.events),this.events.on("websocket:connected",this._connected.bind(this)),this.events.on("websocket:disconnected",this._disconnected.bind(this)),this.events.on("connect:error",this._error.bind(this)),this.events.on("websocket:error",this._error.bind(this))}status(){return this.state.status}createExecute(e){return new I(e,this.events)}createGraphqlSender(e){let t=new c;this.events.emit("create:graphql:sender",{headers:t}),this.events.emit("modify:headers",{headers:t}),e.headers&&t.assign(e.headers),t.assign({[E]:p()?.id});let s=new q({uri:this.config?.graphql.url,headers:t.getAll()}),n=new H((i,a)=>a(i).map(o=>(o.errors?.map(d=>{this.events.emit("graphql:sender:error",{error:d})}),o)));return new k({link:n.concat(O([s])),cache:new K({resultCaching:e.resultCaching??!1}),headers:t.getAll()})}createActionSender(e){let t=this.actions[e]??this.actions["mesh-fallback-action"];return new C(t,this.events)}disconnected(){this.websocket.disconnect()}connect(){return new Promise(e=>{let t=window.MeshClientConfig;if(this.state.connected||!t)return e({success:!0,actions:{}});if(!w.object({endpoint:w.string().url()}).safeParse({endpoint:t.endpoint}).success)return this.events.emit("connect:error",{error:"invalid mesh config schema!"}),e({success:!1,actions:{}});let n=M(t.endpoint,"connect");if(!n)return this.events.emit("connect:error",{error:"mesh connect url not found!"}),e({success:!1,actions:{}});b.request({method:"post",url:n.toString(),headers:{...t.headers??{},[S]:new URL(t.endpoint).host,[E]:p()?.id}}).then(i=>{this.connected(i.data,e)}).catch(()=>(this.events.emit("connect:error",{error:"connection to mesh-server failed!"}),e({success:!1,actions:{}})))})}connected(e,t){let s=e.success??!1,n=e.config,i=e.clientId,a=e.actions;if(!s||!n||!i||!a)return this.events.emit("connect:error",{error:"mesh client config not loaded!"}),t({success:!1,actions:{}});g()||x(i),this.config=n,this.actions=a,this.websocket.connect(n,i),t({success:!0,actions:a})}_connected(){this.state.status="connected",this.events.emit("connected",{actions:this.actions,config:this.config}),this.state.connected=!0}_disconnected(){this.state.status="disconnected",this.events.emit("disconnected"),this.state.connected=!1}_error(e){console.error(e)}};var je=()=>(window.MeshClient||(window.MeshClient=new v),{config:o=>{window.MeshClientConfig=o},action:o=>window.MeshClient.createActionSender(o),graphql:o=>window.MeshClient.createGraphqlSender(o??{}),connect:o=>{window.MeshClient.connect().then(d=>{o&&o(d)})},onEvent:(o,d)=>{window.MeshClient.events.on(o,d)},execute:o=>window.MeshClient.createExecute(o),events:()=>window.MeshClient.events,is(){return window.MeshClient.status()}});export{E as X_MESH_CLIENT_ID_KEY,S as X_MESH_HOST_KEY,je as useMesh};