@machinemetrics/mm-react-tools 3.2.5-0 → 3.2.5-1

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.
@@ -31397,23 +31397,21 @@ const xb = (r, e) => {
31397
31397
  h.current,
31398
31398
  () => xb(h, f)
31399
31399
  ];
31400
- }, lq = nI(
31401
- ({ href: r, asFlyout: e, flyoutTitle: t, children: n, ...i }, a) => {
31402
- const { isEmbedded: u, navigateParent: c } = ai(qa);
31403
- return /* @__PURE__ */ sr.jsx(
31404
- "a",
31405
- {
31406
- ...i,
31407
- ref: a,
31408
- href: r,
31409
- onClick: (f) => {
31410
- !u || f.metaKey || f.ctrlKey || f.shiftKey || (f.preventDefault(), f.stopPropagation(), c(r, { asFlyout: e, flyoutTitle: t }));
31411
- },
31412
- children: n
31413
- }
31414
- );
31415
- }
31416
- );
31400
+ }, lq = nI(({ href: r, asFlyout: e, children: t, ...n }, i) => {
31401
+ const { isEmbedded: a, navigateParent: u } = ai(qa);
31402
+ return /* @__PURE__ */ sr.jsx(
31403
+ "a",
31404
+ {
31405
+ ...n,
31406
+ ref: i,
31407
+ href: r,
31408
+ onClick: (c) => {
31409
+ !a || c.metaKey || c.ctrlKey || c.shiftKey || (c.preventDefault(), c.stopPropagation(), u(r, { asFlyout: e }));
31410
+ },
31411
+ children: t
31412
+ }
31413
+ );
31414
+ });
31417
31415
  export {
31418
31416
  lq as Link,
31419
31417
  oq as MMProvider,
@@ -162,4 +162,4 @@ ${f}`),y(b);return}c(null,I),n.strategy===ri.Count&&(h--,h===0&&y()),n.strategy=
162
162
 
163
163
  ${c.stack}`),f.unsubscribe(),u.reject(h)):(h=Vb(d),h?(c&&(h.stack+=`
164
164
 
165
- ${c.stack}`),u.reject(h)):u.resolve(d))}});return f.requestSubject=e,this.protocol.publish(e,t,{reply:a,headers:n.headers}),u}else{const a=new Xb(this.protocol.muxSubscriptions,e,n,i);this.protocol.request(a);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${a.token}`,headers:n.headers})}catch(c){a.cancel(c)}const u=Promise.race([a.timer,a.deferred]);return u.catch(()=>{a.cancel()}),u}}flush(){return this.isClosed()?Promise.reject(Ce.errorForCode(we.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(Ce.errorForCode(we.ConnectionClosed)):this.isDraining()?Promise.reject(Ce.errorForCode(we.ConnectionDraining)):(this.draining=!0,this.protocol.drain())}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){const e=this.protocol.getServer();return e?e.listen:""}status(){const e=new Mr;return e.iterClosed.then(()=>{const t=this.listeners.indexOf(e);this.listeners.splice(t,1)}),this.listeners.push(e),e}get info(){return this.protocol.isClosed()?void 0:this.protocol.info}async context(){return(await this.request("$SYS.REQ.USER.INFO")).json((t,n)=>t==="time"?new Date(Date.parse(n)):n)}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(e={}){const t=new lP(this,e);if(e.checkAPI!==!1)try{await t.getAccountInfo()}catch(n){const i=n;throw i.code===we.NoResponders&&(i.code=we.JetStreamNotEnabled),i}return t}jetstream(e={}){return new Fd(this,e)}getServerVersion(){const e=this.info;return e?Cs(e.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw Ce.errorForCode(we.Disconnect);const e=Date.now();return await this.flush(),Date.now()-e}get features(){return this.protocol.features}get services(){return this._services||(this._services=new pP(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(Ce.errorForCode(we.ConnectionClosed)):this.isDraining()?Promise.reject(Ce.errorForCode(we.ConnectionDraining)):this.protocol.reconnect()}}class pP{constructor(e){E(this,"nc");this.nc=e}add(e){try{return new No(this.nc,e).start()}catch(t){return Promise.reject(t)}}client(e,t){return new GC(this.nc,e,t)}}class mP{constructor(e,t,n){E(this,"bucket");E(this,"sm");E(this,"prefixLen");this.bucket=e,this.prefixLen=t,this.sm=n}get key(){return this.sm.subject.substring(this.prefixLen)}get value(){return this.sm.data}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){return this.sm.header.get(gc)||"PUT"}get length(){const e=this.sm.header.get(en.MessageSizeHdr)||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class yP{constructor(e,t,n){E(this,"bucket");E(this,"key");E(this,"sm");this.bucket=e,this.key=t,this.sm=n}get value(){return this.sm.data}get created(){return new Date(hd(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var e;return((e=this.sm.headers)==null?void 0:e.get(gc))||"PUT"}get delta(){return this.sm.info.pending}get length(){var t;const e=((t=this.sm.headers)==null?void 0:t.get(en.MessageSizeHdr))||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Ew extends zI{constructor(t,n,i){super(t.nc,n,i);E(this,"js");E(this,"monitor");this.js=t,this.monitor=null,this.sub.closed.then(()=>{this.monitor&&this.monitor.cancel()})}set info(t){this.sub.info=t}get info(){return this.sub.info}_resetOrderedConsumer(t){if(this.info===null||this.sub.isClosed())return;const n=Ei(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,n);const a=this.info;a.config.name=Is.next(),a.ordered_consumer_sequence.delivery_seq=0,a.flow_control.heartbeat_count=0,a.flow_control.fc_count=0,a.flow_control.consumer_restarts++,a.deliver=n,a.config.deliver_subject=n,a.config.deliver_policy=yr.StartSequence,a.config.opt_start_seq=t;const u={};u.stream_name=this.info.stream,u.config=a.config;const c=`${a.api.prefix}.CONSUMER.CREATE.${a.stream}`;this.js._request(c,u,{retries:-1}).then(f=>{const h=f,d=this.sub.info;d.last=h,this.info.config=h.config,this.info.name=h.name}).catch(f=>{const h=new Ce(`unable to recreate ordered consumer ${a.stream} at seq ${t}`,we.RequestError,f);this.sub.callback(h,{})})}_maybeSetupHbMonitoring(){var n,i;const t=((i=(n=this.info)==null?void 0:n.config)==null?void 0:i.idle_heartbeat)||0;t&&this._setupHbMonitoring(hd(t))}_setupHbMonitoring(t,n=0){const i={cancelAfter:0,maxOut:2};n&&(i.cancelAfter=n);const a=this.sub,u=c=>{var d,y,g,m;const f=AI(409,`${qn.IdleHeartbeatMissed}: ${c}`,this.sub.subject);if(!((d=this.info)==null?void 0:d.ordered))this.sub.callback(null,f);else{if(!this.js.nc.protocol.connected)return!1;const b=((g=(y=this.info)==null?void 0:y.ordered_consumer_sequence)==null?void 0:g.stream_seq)||0;return this._resetOrderedConsumer(b+1),(m=this.monitor)==null||m.restart(),!1}return!a.noIterator};this.monitor=new gd(t,u,i)}_checkHbOrderConsumer(t){const n=t.headers.get(en.ConsumerStalledHdr);n!==""&&this.js.nc.publish(n);const i=parseInt(t.headers.get(en.LastConsumerSeqHdr),10),a=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,i!==a.delivery_seq&&this._resetOrderedConsumer(a.stream_seq+1),!1}_checkOrderedConsumer(t){const n=this.info.ordered_consumer_sequence,i=t.info.streamSequence,a=t.info.deliverySequence;return a!=n.delivery_seq+1?(this._resetOrderedConsumer(n.stream_seq+1),!1):(n.delivery_seq=a,n.stream_seq=i,!0)}async destroy(){this.isClosed()||await this.drain();const t=this.sub.info,n=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.DELETE.${t.stream}.${n}`;await t.api._request(i)}async consumerInfo(){const t=this.sub.info,n=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.INFO.${t.stream}.${n}`,a=await t.api._request(i);return t.last=a,a}}class gP extends Ew{constructor(e,t,n){super(e,t,n)}pull(e={batch:1}){const{stream:t,config:n,name:i}=this.sub.info,a=n.durable_name??i,u={};if(u.batch=e.batch||1,u.no_wait=e.no_wait||!1,(e.max_bytes??0)>0){const h=this.js.nc.features.get(kt.JS_PULL_MAX_BYTES);if(!h.ok)throw new Error(`max_bytes is only supported on servers ${h.min} or better`);u.max_bytes=e.max_bytes}let c=0;e.expires&&e.expires>0&&(c=e.expires,u.expires=cr(c));let f=0;if(e.idle_heartbeat&&e.idle_heartbeat>0&&(f=e.idle_heartbeat,u.idle_heartbeat=cr(f)),f&&c===0)throw new Error("idle_heartbeat requires expires");if(f>c)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),c&&f&&(this.monitor?this.monitor._change(f,c):this._setupHbMonitoring(f,c));const h=this.info.api,d=`${h.prefix}.CONSUMER.MSG.NEXT.${t}.${a}`,y=this.sub.subject;h.nc.publish(d,h.jc.encode(u),{reply:y})}}}function vP(r,e){return r?wP(e):bP(e)}function bP(r){return(e,t)=>e?[e,null]:(e=va(t),e?[e,null]:[null,Do(t,r)])}function wP(r){return(e,t)=>{if(e)return[e,null];const n=va(t);return n!==null?[Ow(n),null]:[null,Do(t,r)]}}function Ow(r){if(r!==null)switch(r.code){case we.JetStream404NoMessages:case we.JetStream408RequestTimeout:return null;case we.JetStream409:return kI(r)?r:null;default:return r}return null}function _P(r){r&&r.ack()}function xP(r){const e=r.split(".");if(e.length===9&&e.splice(2,0,"_",""),e.length<11||e[0]!=="$JS"||e[1]!=="ACK")throw new Error("not js message");const t={};return t.domain=e[2]==="_"?"":e[2],t.account_hash=e[3],t.stream=e[4],t.consumer=e[5],t.redeliveryCount=parseInt(e[6],10),t.redelivered=t.redeliveryCount>1,t.streamSequence=parseInt(e[7],10),t.deliverySequence=parseInt(e[8],10),t.timestampNanos=parseInt(e[9],10),t.pending=parseInt(e[10],10),t}class SP{constructor(e,t){E(this,"msg");E(this,"di");E(this,"didAck");E(this,"timeout");this.msg=e,this.didAck=!1,this.timeout=t}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){return this.di||(this.di=xP(this.reply)),this.di}get redelivered(){return this.info.redeliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}doAck(e){this.didAck||(this.didAck=!this.isWIP(e),this.msg.respond(e))}isWIP(e){return e.length===4&&e[0]===Mo[0]&&e[1]===Mo[1]&&e[2]===Mo[2]&&e[3]===Mo[3]}async ackAck(e){var n;e=e||{},e.timeout=e.timeout||this.timeout;const t=ir();if(this.didAck)t.resolve(!1);else if(this.didAck=!0,this.msg.reply){const a=this.msg.publisher,u=!((n=a.options)!=null&&n.noAsyncTraces),c=new Xb(a.muxSubscriptions,this.msg.reply,{timeout:e.timeout},u);a.request(c);try{a.publish(this.msg.reply,bw,{reply:`${a.muxSubscriptions.baseInbox}${c.token}`})}catch(f){c.cancel(f)}try{await Promise.race([c.timer,c.deferred]),t.resolve(!0)}catch(f){c.cancel(f),t.reject(f)}}else t.resolve(!1);return t}ack(){this.doAck(bw)}nak(e){let t=nP;e&&(t=Bb().encode(`-NAK ${JSON.stringify({delay:cr(e)})}`)),this.doAck(t)}working(){this.doAck(Mo)}next(e,t={batch:1}){const n={};n.batch=t.batch||1,n.no_wait=t.no_wait||!1,t.expires&&t.expires>0&&(n.expires=cr(t.expires));const i=Ln().encode(n),a=_a.concat(iP,aP,i),u=e?{reply:e}:void 0;this.msg.respond(a,u)}term(e=""){let t=sP;(e==null?void 0:e.length)>0&&(t=Bb().encode(`+TERM ${e}`)),this.doAck(t)}json(){return this.msg.json()}string(){return this.msg.string()}}const EP="1.29.2",OP="nats.ws";class TP{constructor(){E(this,"version");E(this,"lang");E(this,"closeError");E(this,"connected");E(this,"done");E(this,"socket");E(this,"options");E(this,"socketClosed");E(this,"encrypted");E(this,"peeked");E(this,"yields");E(this,"signal");E(this,"closedNotification");this.version=EP,this.lang=OP,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=ir(),this.closedNotification=ir()}async connect(e,t){const n=ir();if(t.tls)return n.reject(new Ce("tls",we.InvalidOption)),n;this.options=t;const i=e.src;if(t.wsFactory){const{socket:a,encrypted:u}=await t.wsFactory(e.src,t);this.socket=a,this.encrypted=u}else this.encrypted=i.indexOf("wss://")===0,this.socket=new WebSocket(i);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=a=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(a.data)),this.peeked){this.signal.resolve();return}const u=_a.concat(...this.yields),c=KI(u);if(c!==""){const f=jC.exec(c);if(!f){t.debug&&console.error("!!!",oc(u)),n.reject(new Error("unexpected response from server"));return}try{const h=JSON.parse(f[1]);LC(h,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),n.resolve()}catch(h){n.reject(h);return}}},this.socket.onclose=a=>{if(this.isDiscarded())return;this.socketClosed=!0;let u;this.done||(a.wasClean||(u=new Error(a.reason)),this._closed(u))},this.socket.onerror=a=>{if(this.isDiscarded())return;const u=a,c=new Ce(u.message,we.Unknown,new Error(u.error));n.reject(c)},n}disconnect(){this._closed(void 0,!0)}async _closed(e,t=!0){if(!this.isDiscarded()&&this.connected&&!this.done){if(this.closeError=e,!e)for(;!this.socketClosed&&this.socket.bufferedAmount>0;)await ya(100);this.done=!0;try{this.socket.close(e?1002:1e3,e?e.message:void 0)}catch{}t&&this.closedNotification.resolve(e)}}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){for(;;){if(this.isDiscarded())return;this.yields.length===0&&await this.signal;const e=this.yields;this.yields=[];for(let t=0;t<e.length;t++)this.options.debug&&console.info(`> ${oc(e[t])}`),yield e[t];if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=ir())}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(!this.isDiscarded())try{this.socket.send(e.buffer),this.options.debug&&console.info(`< ${oc(e)}`);return}catch(t){this.options.debug&&console.error(`!!! ${oc(e)}: ${t}`)}}close(e){return this._closed(e,!1)}closed(){return this.closedNotification}isDiscarded(){return this.done?(this.discard(),!0):!1}discard(){var e;this.done=!0;try{(e=this.socket)==null||e.close()}catch{}}}function AP(r,e){/^(.*:\/\/)(.*)/.test(r)||(typeof e=="boolean"?r=`${e===!0?"https":"http"}://${r}`:r=`https://${r}`);let n=new URL(r);const i=n.protocol.toLowerCase();i==="ws:"&&(e=!1),i==="wss:"&&(e=!0),i!=="https:"&&i!=="http"&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2"),n=new URL(`http://${r}`));let a,u;const c=n.hostname,f=n.pathname,h=n.search||"";switch(i){case"http:":case"ws:":case"nats:":u=n.port||"80",a="ws:";break;case"https:":case"wss:":case"tls:":u=n.port||"443",a="wss:";break;default:u=n.port||e===!0?"443":"80",a=e===!0?"wss:":"ws:";break}return`${a}//${c}:${u}${f}${h}`}function kP(r={}){return HI({defaultPort:443,urlParseFn:AP,factory:()=>new TP}),Ld.connect(r)}const Tw=["new","last","last_per_subject"],IP=async(r,e)=>(console.info(`Connecting to server ${r}`),await kP({servers:[r],authenticator:NC(new TextEncoder().encode(e))}));async function*CP(r){const e=Ln();for await(const t of r)try{yield e.decode(t.data)}catch(n){console.warn(`Skipping event: ${n}`)}}const Aw=(r,e)=>{r.current&&(r.current=void 0),e.current&&(e.current.close(),e.current=void 0)},kw={scada:"mm.0.[location-ref].[machine-ref].[qualifier].[data-category].[metric-key].[message-type]","machine-service":"mm.2.[location-ref].[machine-ref].[service-name].[qualifier].[data-category].[metric-key].[message-type]","edge-service":"mm.3.[location-ref].[edge-ref].[service-name].[data-category].[metric-key].[message-type]","machine-source-service":"mm.4.[location-ref].[machine-ref].[machine-source-ref].[service-name].[data-category].[metric-key].[message-type]",edge:"mm.7.[location-ref].[edge-ref].[data-category].[metric-key].[message-type]"},PP={undefined:0,event:1,eventset:2,quantity:3,state:4,count:5,info:6,beat:7},NP=(r,e,t)=>{if(!kw[r])throw new Error("Unknown stream name");const n=kw[r].split(".");let i="";return n.forEach((a,u)=>{switch(a){case"[location-ref]":i+="."+e;break;case"[machine-ref]":i+="."+((t==null?void 0:t.machineRef)||"*");break;case"[qualifier]":i+="."+((t==null?void 0:t.qualifier)||"0");break;case"[data-category]":i+="."+(PP[t==null?void 0:t.dataCategory]||"*");break;case"[metric-key]":i+="."+(t!=null&&t.metricKey?t==null?void 0:t.metricKey.toLowerCase().replace(/[^a-zA-Z0-9_\\-]/gi,"-"):"*");break;case"[message-type]":i+="."+((t==null?void 0:t.messageType)||"0");break;case"[edge-ref]":i+="."+((t==null?void 0:t.edgeRef)||"*");break;case"[service-name]":i+="."+((t==null?void 0:t.serviceName)||"*");break;case"[machine-source-ref]":i+="."+((t==null?void 0:t.machineSourceRef)||"*");break;default:u>0&&(i+="."),i+=a;break}}),i},RP=r=>{const{streamName:e,locationRef:t,filters:n,deliverPolicy:i="new",dispatch:a}=r;if(!Tw.includes(i))throw new Error(`Invalid deliverPolicy "${i}" specified. Valid options are: ${Tw.join(", ")}`);n&&n.length>1&&console.warn("Multiple filters are not supported. Only the first filter will be used.");const{urls:u,natsCredsRef:c}=ti(),f=me.useRef(),h=me.useRef();return me.useEffect(()=>!u.natsUrl||!c.current||!e||!t?void 0:((async()=>{try{const y=await IP(u.natsUrl,c.current);f.current=y;const g=NP(e,t,n==null?void 0:n[0]);console.info(`Consuming events from stream ${e} filtering by subject ${g}`);const b=await(await y.jetstream().consumers.get(e,{deliver_policy:i,filterSubjects:g})).consume({max_messages:1e3}),I=CP(b);if(h.current=I,typeof a=="function")for await(const S of I)a(S)}catch(y){console.error(`Error setting up event stream. ${y}`)}})(),()=>Aw(h,f)),[e,t,i,u.natsUrl,c]),[h.current,()=>Aw(h,f)]},MP=me.forwardRef(({href:r,asFlyout:e,flyoutTitle:t,children:n,...i},a)=>{const{isEmbedded:u,navigateParent:c}=me.useContext(fa);return nr.jsx("a",{...i,ref:a,href:r,onClick:f=>{!u||f.metaKey||f.ctrlKey||f.shiftKey||(f.preventDefault(),f.stopPropagation(),c(r,{asFlyout:e,flyoutTitle:t}))},children:n})});Ot.Link=MP,Ot.MMProvider=yI,Ot.PrivateLayout=tk,Ot._useMMApolloLinkContext=ek,Ot.useApiRequest=f0,Ot.useAsyncEffect=bo,Ot.useAsyncInterval=wo,Ot.useDowntimeQuery=GA,Ot.useEventStream=RP,Ot.useMMAppContext=ZA,Ot.useMMAppSetting=XA,Ot.useMMAppTools=KA,Ot.useMMAuth=ti,Ot.useMMEmbeddedApp=YA,Ot.useMMHash=JA,Ot.useMMTemplates=QA,Ot.useProductionQuery=zA,Ot.useQuantityStream=HA,Ot.useSearchParamsState=VA,Ot.useThrottleEffect=WA,Object.defineProperty(Ot,Symbol.toStringTag,{value:"Module"})});
165
+ ${c.stack}`),u.reject(h)):u.resolve(d))}});return f.requestSubject=e,this.protocol.publish(e,t,{reply:a,headers:n.headers}),u}else{const a=new Xb(this.protocol.muxSubscriptions,e,n,i);this.protocol.request(a);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${a.token}`,headers:n.headers})}catch(c){a.cancel(c)}const u=Promise.race([a.timer,a.deferred]);return u.catch(()=>{a.cancel()}),u}}flush(){return this.isClosed()?Promise.reject(Ce.errorForCode(we.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(Ce.errorForCode(we.ConnectionClosed)):this.isDraining()?Promise.reject(Ce.errorForCode(we.ConnectionDraining)):(this.draining=!0,this.protocol.drain())}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){const e=this.protocol.getServer();return e?e.listen:""}status(){const e=new Mr;return e.iterClosed.then(()=>{const t=this.listeners.indexOf(e);this.listeners.splice(t,1)}),this.listeners.push(e),e}get info(){return this.protocol.isClosed()?void 0:this.protocol.info}async context(){return(await this.request("$SYS.REQ.USER.INFO")).json((t,n)=>t==="time"?new Date(Date.parse(n)):n)}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(e={}){const t=new lP(this,e);if(e.checkAPI!==!1)try{await t.getAccountInfo()}catch(n){const i=n;throw i.code===we.NoResponders&&(i.code=we.JetStreamNotEnabled),i}return t}jetstream(e={}){return new Fd(this,e)}getServerVersion(){const e=this.info;return e?Cs(e.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw Ce.errorForCode(we.Disconnect);const e=Date.now();return await this.flush(),Date.now()-e}get features(){return this.protocol.features}get services(){return this._services||(this._services=new pP(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(Ce.errorForCode(we.ConnectionClosed)):this.isDraining()?Promise.reject(Ce.errorForCode(we.ConnectionDraining)):this.protocol.reconnect()}}class pP{constructor(e){E(this,"nc");this.nc=e}add(e){try{return new No(this.nc,e).start()}catch(t){return Promise.reject(t)}}client(e,t){return new GC(this.nc,e,t)}}class mP{constructor(e,t,n){E(this,"bucket");E(this,"sm");E(this,"prefixLen");this.bucket=e,this.prefixLen=t,this.sm=n}get key(){return this.sm.subject.substring(this.prefixLen)}get value(){return this.sm.data}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){return this.sm.header.get(gc)||"PUT"}get length(){const e=this.sm.header.get(en.MessageSizeHdr)||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class yP{constructor(e,t,n){E(this,"bucket");E(this,"key");E(this,"sm");this.bucket=e,this.key=t,this.sm=n}get value(){return this.sm.data}get created(){return new Date(hd(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var e;return((e=this.sm.headers)==null?void 0:e.get(gc))||"PUT"}get delta(){return this.sm.info.pending}get length(){var t;const e=((t=this.sm.headers)==null?void 0:t.get(en.MessageSizeHdr))||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Ew extends zI{constructor(t,n,i){super(t.nc,n,i);E(this,"js");E(this,"monitor");this.js=t,this.monitor=null,this.sub.closed.then(()=>{this.monitor&&this.monitor.cancel()})}set info(t){this.sub.info=t}get info(){return this.sub.info}_resetOrderedConsumer(t){if(this.info===null||this.sub.isClosed())return;const n=Ei(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,n);const a=this.info;a.config.name=Is.next(),a.ordered_consumer_sequence.delivery_seq=0,a.flow_control.heartbeat_count=0,a.flow_control.fc_count=0,a.flow_control.consumer_restarts++,a.deliver=n,a.config.deliver_subject=n,a.config.deliver_policy=yr.StartSequence,a.config.opt_start_seq=t;const u={};u.stream_name=this.info.stream,u.config=a.config;const c=`${a.api.prefix}.CONSUMER.CREATE.${a.stream}`;this.js._request(c,u,{retries:-1}).then(f=>{const h=f,d=this.sub.info;d.last=h,this.info.config=h.config,this.info.name=h.name}).catch(f=>{const h=new Ce(`unable to recreate ordered consumer ${a.stream} at seq ${t}`,we.RequestError,f);this.sub.callback(h,{})})}_maybeSetupHbMonitoring(){var n,i;const t=((i=(n=this.info)==null?void 0:n.config)==null?void 0:i.idle_heartbeat)||0;t&&this._setupHbMonitoring(hd(t))}_setupHbMonitoring(t,n=0){const i={cancelAfter:0,maxOut:2};n&&(i.cancelAfter=n);const a=this.sub,u=c=>{var d,y,g,m;const f=AI(409,`${qn.IdleHeartbeatMissed}: ${c}`,this.sub.subject);if(!((d=this.info)==null?void 0:d.ordered))this.sub.callback(null,f);else{if(!this.js.nc.protocol.connected)return!1;const b=((g=(y=this.info)==null?void 0:y.ordered_consumer_sequence)==null?void 0:g.stream_seq)||0;return this._resetOrderedConsumer(b+1),(m=this.monitor)==null||m.restart(),!1}return!a.noIterator};this.monitor=new gd(t,u,i)}_checkHbOrderConsumer(t){const n=t.headers.get(en.ConsumerStalledHdr);n!==""&&this.js.nc.publish(n);const i=parseInt(t.headers.get(en.LastConsumerSeqHdr),10),a=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,i!==a.delivery_seq&&this._resetOrderedConsumer(a.stream_seq+1),!1}_checkOrderedConsumer(t){const n=this.info.ordered_consumer_sequence,i=t.info.streamSequence,a=t.info.deliverySequence;return a!=n.delivery_seq+1?(this._resetOrderedConsumer(n.stream_seq+1),!1):(n.delivery_seq=a,n.stream_seq=i,!0)}async destroy(){this.isClosed()||await this.drain();const t=this.sub.info,n=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.DELETE.${t.stream}.${n}`;await t.api._request(i)}async consumerInfo(){const t=this.sub.info,n=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.INFO.${t.stream}.${n}`,a=await t.api._request(i);return t.last=a,a}}class gP extends Ew{constructor(e,t,n){super(e,t,n)}pull(e={batch:1}){const{stream:t,config:n,name:i}=this.sub.info,a=n.durable_name??i,u={};if(u.batch=e.batch||1,u.no_wait=e.no_wait||!1,(e.max_bytes??0)>0){const h=this.js.nc.features.get(kt.JS_PULL_MAX_BYTES);if(!h.ok)throw new Error(`max_bytes is only supported on servers ${h.min} or better`);u.max_bytes=e.max_bytes}let c=0;e.expires&&e.expires>0&&(c=e.expires,u.expires=cr(c));let f=0;if(e.idle_heartbeat&&e.idle_heartbeat>0&&(f=e.idle_heartbeat,u.idle_heartbeat=cr(f)),f&&c===0)throw new Error("idle_heartbeat requires expires");if(f>c)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),c&&f&&(this.monitor?this.monitor._change(f,c):this._setupHbMonitoring(f,c));const h=this.info.api,d=`${h.prefix}.CONSUMER.MSG.NEXT.${t}.${a}`,y=this.sub.subject;h.nc.publish(d,h.jc.encode(u),{reply:y})}}}function vP(r,e){return r?wP(e):bP(e)}function bP(r){return(e,t)=>e?[e,null]:(e=va(t),e?[e,null]:[null,Do(t,r)])}function wP(r){return(e,t)=>{if(e)return[e,null];const n=va(t);return n!==null?[Ow(n),null]:[null,Do(t,r)]}}function Ow(r){if(r!==null)switch(r.code){case we.JetStream404NoMessages:case we.JetStream408RequestTimeout:return null;case we.JetStream409:return kI(r)?r:null;default:return r}return null}function _P(r){r&&r.ack()}function xP(r){const e=r.split(".");if(e.length===9&&e.splice(2,0,"_",""),e.length<11||e[0]!=="$JS"||e[1]!=="ACK")throw new Error("not js message");const t={};return t.domain=e[2]==="_"?"":e[2],t.account_hash=e[3],t.stream=e[4],t.consumer=e[5],t.redeliveryCount=parseInt(e[6],10),t.redelivered=t.redeliveryCount>1,t.streamSequence=parseInt(e[7],10),t.deliverySequence=parseInt(e[8],10),t.timestampNanos=parseInt(e[9],10),t.pending=parseInt(e[10],10),t}class SP{constructor(e,t){E(this,"msg");E(this,"di");E(this,"didAck");E(this,"timeout");this.msg=e,this.didAck=!1,this.timeout=t}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){return this.di||(this.di=xP(this.reply)),this.di}get redelivered(){return this.info.redeliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}doAck(e){this.didAck||(this.didAck=!this.isWIP(e),this.msg.respond(e))}isWIP(e){return e.length===4&&e[0]===Mo[0]&&e[1]===Mo[1]&&e[2]===Mo[2]&&e[3]===Mo[3]}async ackAck(e){var n;e=e||{},e.timeout=e.timeout||this.timeout;const t=ir();if(this.didAck)t.resolve(!1);else if(this.didAck=!0,this.msg.reply){const a=this.msg.publisher,u=!((n=a.options)!=null&&n.noAsyncTraces),c=new Xb(a.muxSubscriptions,this.msg.reply,{timeout:e.timeout},u);a.request(c);try{a.publish(this.msg.reply,bw,{reply:`${a.muxSubscriptions.baseInbox}${c.token}`})}catch(f){c.cancel(f)}try{await Promise.race([c.timer,c.deferred]),t.resolve(!0)}catch(f){c.cancel(f),t.reject(f)}}else t.resolve(!1);return t}ack(){this.doAck(bw)}nak(e){let t=nP;e&&(t=Bb().encode(`-NAK ${JSON.stringify({delay:cr(e)})}`)),this.doAck(t)}working(){this.doAck(Mo)}next(e,t={batch:1}){const n={};n.batch=t.batch||1,n.no_wait=t.no_wait||!1,t.expires&&t.expires>0&&(n.expires=cr(t.expires));const i=Ln().encode(n),a=_a.concat(iP,aP,i),u=e?{reply:e}:void 0;this.msg.respond(a,u)}term(e=""){let t=sP;(e==null?void 0:e.length)>0&&(t=Bb().encode(`+TERM ${e}`)),this.doAck(t)}json(){return this.msg.json()}string(){return this.msg.string()}}const EP="1.29.2",OP="nats.ws";class TP{constructor(){E(this,"version");E(this,"lang");E(this,"closeError");E(this,"connected");E(this,"done");E(this,"socket");E(this,"options");E(this,"socketClosed");E(this,"encrypted");E(this,"peeked");E(this,"yields");E(this,"signal");E(this,"closedNotification");this.version=EP,this.lang=OP,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=ir(),this.closedNotification=ir()}async connect(e,t){const n=ir();if(t.tls)return n.reject(new Ce("tls",we.InvalidOption)),n;this.options=t;const i=e.src;if(t.wsFactory){const{socket:a,encrypted:u}=await t.wsFactory(e.src,t);this.socket=a,this.encrypted=u}else this.encrypted=i.indexOf("wss://")===0,this.socket=new WebSocket(i);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=a=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(a.data)),this.peeked){this.signal.resolve();return}const u=_a.concat(...this.yields),c=KI(u);if(c!==""){const f=jC.exec(c);if(!f){t.debug&&console.error("!!!",oc(u)),n.reject(new Error("unexpected response from server"));return}try{const h=JSON.parse(f[1]);LC(h,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),n.resolve()}catch(h){n.reject(h);return}}},this.socket.onclose=a=>{if(this.isDiscarded())return;this.socketClosed=!0;let u;this.done||(a.wasClean||(u=new Error(a.reason)),this._closed(u))},this.socket.onerror=a=>{if(this.isDiscarded())return;const u=a,c=new Ce(u.message,we.Unknown,new Error(u.error));n.reject(c)},n}disconnect(){this._closed(void 0,!0)}async _closed(e,t=!0){if(!this.isDiscarded()&&this.connected&&!this.done){if(this.closeError=e,!e)for(;!this.socketClosed&&this.socket.bufferedAmount>0;)await ya(100);this.done=!0;try{this.socket.close(e?1002:1e3,e?e.message:void 0)}catch{}t&&this.closedNotification.resolve(e)}}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){for(;;){if(this.isDiscarded())return;this.yields.length===0&&await this.signal;const e=this.yields;this.yields=[];for(let t=0;t<e.length;t++)this.options.debug&&console.info(`> ${oc(e[t])}`),yield e[t];if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=ir())}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(!this.isDiscarded())try{this.socket.send(e.buffer),this.options.debug&&console.info(`< ${oc(e)}`);return}catch(t){this.options.debug&&console.error(`!!! ${oc(e)}: ${t}`)}}close(e){return this._closed(e,!1)}closed(){return this.closedNotification}isDiscarded(){return this.done?(this.discard(),!0):!1}discard(){var e;this.done=!0;try{(e=this.socket)==null||e.close()}catch{}}}function AP(r,e){/^(.*:\/\/)(.*)/.test(r)||(typeof e=="boolean"?r=`${e===!0?"https":"http"}://${r}`:r=`https://${r}`);let n=new URL(r);const i=n.protocol.toLowerCase();i==="ws:"&&(e=!1),i==="wss:"&&(e=!0),i!=="https:"&&i!=="http"&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2"),n=new URL(`http://${r}`));let a,u;const c=n.hostname,f=n.pathname,h=n.search||"";switch(i){case"http:":case"ws:":case"nats:":u=n.port||"80",a="ws:";break;case"https:":case"wss:":case"tls:":u=n.port||"443",a="wss:";break;default:u=n.port||e===!0?"443":"80",a=e===!0?"wss:":"ws:";break}return`${a}//${c}:${u}${f}${h}`}function kP(r={}){return HI({defaultPort:443,urlParseFn:AP,factory:()=>new TP}),Ld.connect(r)}const Tw=["new","last","last_per_subject"],IP=async(r,e)=>(console.info(`Connecting to server ${r}`),await kP({servers:[r],authenticator:NC(new TextEncoder().encode(e))}));async function*CP(r){const e=Ln();for await(const t of r)try{yield e.decode(t.data)}catch(n){console.warn(`Skipping event: ${n}`)}}const Aw=(r,e)=>{r.current&&(r.current=void 0),e.current&&(e.current.close(),e.current=void 0)},kw={scada:"mm.0.[location-ref].[machine-ref].[qualifier].[data-category].[metric-key].[message-type]","machine-service":"mm.2.[location-ref].[machine-ref].[service-name].[qualifier].[data-category].[metric-key].[message-type]","edge-service":"mm.3.[location-ref].[edge-ref].[service-name].[data-category].[metric-key].[message-type]","machine-source-service":"mm.4.[location-ref].[machine-ref].[machine-source-ref].[service-name].[data-category].[metric-key].[message-type]",edge:"mm.7.[location-ref].[edge-ref].[data-category].[metric-key].[message-type]"},PP={undefined:0,event:1,eventset:2,quantity:3,state:4,count:5,info:6,beat:7},NP=(r,e,t)=>{if(!kw[r])throw new Error("Unknown stream name");const n=kw[r].split(".");let i="";return n.forEach((a,u)=>{switch(a){case"[location-ref]":i+="."+e;break;case"[machine-ref]":i+="."+((t==null?void 0:t.machineRef)||"*");break;case"[qualifier]":i+="."+((t==null?void 0:t.qualifier)||"0");break;case"[data-category]":i+="."+(PP[t==null?void 0:t.dataCategory]||"*");break;case"[metric-key]":i+="."+(t!=null&&t.metricKey?t==null?void 0:t.metricKey.toLowerCase().replace(/[^a-zA-Z0-9_\\-]/gi,"-"):"*");break;case"[message-type]":i+="."+((t==null?void 0:t.messageType)||"0");break;case"[edge-ref]":i+="."+((t==null?void 0:t.edgeRef)||"*");break;case"[service-name]":i+="."+((t==null?void 0:t.serviceName)||"*");break;case"[machine-source-ref]":i+="."+((t==null?void 0:t.machineSourceRef)||"*");break;default:u>0&&(i+="."),i+=a;break}}),i},RP=r=>{const{streamName:e,locationRef:t,filters:n,deliverPolicy:i="new",dispatch:a}=r;if(!Tw.includes(i))throw new Error(`Invalid deliverPolicy "${i}" specified. Valid options are: ${Tw.join(", ")}`);n&&n.length>1&&console.warn("Multiple filters are not supported. Only the first filter will be used.");const{urls:u,natsCredsRef:c}=ti(),f=me.useRef(),h=me.useRef();return me.useEffect(()=>!u.natsUrl||!c.current||!e||!t?void 0:((async()=>{try{const y=await IP(u.natsUrl,c.current);f.current=y;const g=NP(e,t,n==null?void 0:n[0]);console.info(`Consuming events from stream ${e} filtering by subject ${g}`);const b=await(await y.jetstream().consumers.get(e,{deliver_policy:i,filterSubjects:g})).consume({max_messages:1e3}),I=CP(b);if(h.current=I,typeof a=="function")for await(const S of I)a(S)}catch(y){console.error(`Error setting up event stream. ${y}`)}})(),()=>Aw(h,f)),[e,t,i,u.natsUrl,c]),[h.current,()=>Aw(h,f)]},MP=me.forwardRef(({href:r,asFlyout:e,children:t,...n},i)=>{const{isEmbedded:a,navigateParent:u}=me.useContext(fa);return nr.jsx("a",{...n,ref:i,href:r,onClick:c=>{!a||c.metaKey||c.ctrlKey||c.shiftKey||(c.preventDefault(),c.stopPropagation(),u(r,{asFlyout:e}))},children:t})});Ot.Link=MP,Ot.MMProvider=yI,Ot.PrivateLayout=tk,Ot._useMMApolloLinkContext=ek,Ot.useApiRequest=f0,Ot.useAsyncEffect=bo,Ot.useAsyncInterval=wo,Ot.useDowntimeQuery=GA,Ot.useEventStream=RP,Ot.useMMAppContext=ZA,Ot.useMMAppSetting=XA,Ot.useMMAppTools=KA,Ot.useMMAuth=ti,Ot.useMMEmbeddedApp=YA,Ot.useMMHash=JA,Ot.useMMTemplates=QA,Ot.useProductionQuery=zA,Ot.useQuantityStream=HA,Ot.useSearchParamsState=VA,Ot.useThrottleEffect=WA,Object.defineProperty(Ot,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@machinemetrics/mm-react-tools",
3
- "version": "3.2.5-0",
3
+ "version": "3.2.5-1",
4
4
  "description": "Components, hooks, and helper functions for writing React apps using MachineMetrics APIs.",
5
5
  "author": "machinemetrics",
6
6
  "license": "MIT",